// week.jsx — Écran "Ma semaine" : plan 7 jours généré par Hermès, renouvelé auto.
const { useState: useWk, useEffect: useWkE } = React;

const JOURS = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];

// Index du jour de la semaine (0 = Lundi)
function todayIndex() {
  const d = new Date().getDay(); // 0=dim
  return d === 0 ? 6 : d - 1;
}

function SemaineScreen({ t, plan, status, targets, doneMap, onToggleMeal, onRegenerate }) {
  const tg = targets || TARGETS;
  const todayI = todayIndex();

  if (status === 'loading') {
    return (
      <div>
        <ScreenHeader t={t} kicker="Hermès prépare ta semaine" title="Ma semaine" />
        <div style={{ height: 320, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18 }}>
          <div style={{ width: 60, height: 60, borderRadius: 99, border: `3px solid ${t.ringTrack}`, borderTopColor: t.green, animation: 'spin 0.9s linear infinite' }} />
          <div style={{ fontSize: 14.5, color: t.textMuted, textAlign: 'center', maxWidth: 240 }}>Hermès compose ton plan de la semaine selon tes résultats…</div>
        </div>
      </div>
    );
  }

  if (status === 'error' || !plan) {
    return (
      <div>
        <ScreenHeader t={t} kicker="Plan hebdomadaire" title="Ma semaine" />
        <Card t={t} pad={22} style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 14, color: t.textMuted, lineHeight: 1.5, marginBottom: 16 }}>
            {status === 'error' ? 'Hermès n’a pas pu générer ton plan.' : 'Aucun plan pour le moment.'}
          </div>
          <button onClick={onRegenerate} style={{ padding: '12px 20px', borderRadius: 14, border: 'none', cursor: 'pointer',
            background: t.green, color: t.onAccent, fontWeight: 700, fontSize: 14.5, fontFamily: 'inherit' }}>
            Générer ma semaine
          </button>
        </Card>
      </div>
    );
  }

  return (
    <div>
      <ScreenHeader t={t} kicker="Plan d’Hermès · zéro sucre ajouté" title="Ma semaine" right={
        <button onClick={onRegenerate} aria-label="Regénérer" style={{ width: 40, height: 40, borderRadius: 99, flexShrink: 0, cursor: 'pointer',
          background: t.surface, border: `1px solid ${t.borderSoft}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="spark" size={19} color={t.green} fill />
        </button>
      } />

      {plan.bilan && (
        <Card t={t} style={{ marginBottom: 16, background: `color-mix(in srgb, ${t.green} 10%, ${t.surface})`, border: `1px solid color-mix(in srgb, ${t.green} 28%, ${t.surface})` }}>
          <div style={{ display: 'flex', gap: 11 }}>
            <Icon name="spark" size={20} color={t.green} fill style={{ flexShrink: 0, marginTop: 1 }} />
            <div style={{ fontSize: 13, color: t.text, lineHeight: 1.55 }}>{plan.bilan}</div>
          </div>
        </Card>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {plan.plan.map((day, di) => {
          const isToday = di === todayI;
          return (
            <div key={di}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', margin: '0 4px 8px' }}>
                <span style={{ fontSize: 15, fontWeight: 700, color: isToday ? t.green : t.text }}>
                  {day.day}{isToday ? ' · aujourd’hui' : ''}
                </span>
                <span style={{ fontSize: 12, color: t.textMuted, fontFamily: 'Space Grotesk, sans-serif' }}>{day.totalKcal} kcal · {day.totalProt}g</span>
              </div>
              <Card t={t} pad={6} style={isToday ? { border: `1.5px solid color-mix(in srgb, ${t.green} 45%, ${t.surface})` } : {}}>
                {day.meals.map((m, mi) => {
                  const key = di + ':' + mi;
                  const on = !!doneMap[key];
                  return (
                    <div key={mi} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 12px', borderTop: mi ? `1px solid ${t.borderSoft}` : 'none' }}>
                      <div style={{ width: 74, flexShrink: 0, fontSize: 11, fontWeight: 600, color: t.textFaint }}>{m.slot}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13.5, color: on ? t.textFaint : t.text, textDecoration: on ? 'line-through' : 'none', fontWeight: 500 }}>{m.name}</div>
                        <div style={{ fontSize: 11, color: t.textFaint, fontFamily: 'Space Grotesk, sans-serif' }}>{m.kcal} kcal · {m.prot}g prot</div>
                      </div>
                      <button onClick={() => onToggleMeal(key)} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}>
                        <CheckDot on={on} color={t.green} t={t} size={23} />
                      </button>
                    </div>
                  );
                })}
              </Card>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { SemaineScreen, JOURS, todayIndex });

// ── HISTORIQUE jour par jour ──────────────────────────────────
function HistoryScreen({ t, targets }) {
  const [days, setDays] = React.useState(null); // [{date, items, water, kcal, prot}]
  const [open, setOpen] = React.useState(null);  // date dépliée
  const TG = targets || TARGETS;

  React.useEffect(() => {
    let alive = true;
    (async () => {
      try {
        // Charge les 14 derniers jours
        const today = new Date();
        const dates = Array.from({ length: 14 }, (_, i) => {
          const d = new Date(today.getTime() - i * 86400000);
          return d.toISOString().slice(0, 10);
        });
        const logs = await Promise.all(dates.map(d => window.FuelFitDB.getDayLog(d).then(r => ({ date: d, ...r })).catch(() => null)));
        if (!alive) return;
        const enriched = logs.filter(Boolean).map(l => {
          const kcal = l.items.reduce((s, it) => s + (it.kcal || 0), 0);
          const prot = l.items.reduce((s, it) => s + (it.prot || 0), 0);
          return { date: l.date, items: l.items, water: l.log.water_glasses || 0, weight: l.log.weight, kcal, prot };
        }).filter(d => d.items.length > 0 || d.water > 0 || d.weight); // jours avec activité
        setDays(enriched);
      } catch (e) { setDays([]); }
    })();
    return () => { alive = false; };
  }, []);

  const fmtDate = (iso) => {
    const d = new Date(iso + 'T12:00:00');
    const s = d.toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long' });
    return s.charAt(0).toUpperCase() + s.slice(1);
  };
  const todayIso = new Date().toISOString().slice(0, 10);

  return (
    <div>
      <ScreenHeader t={t} kicker="Ton journal de bord" title="Historique" />
      {days === null ? (
        <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ width: 48, height: 48, borderRadius: 99, border: `3px solid ${t.ringTrack}`, borderTopColor: t.green, animation: 'spin 0.9s linear infinite' }} />
        </div>
      ) : days.length === 0 ? (
        <Card t={t} pad={22} style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 14, color: t.textMuted, lineHeight: 1.5 }}>
            Aucune journée enregistrée pour l’instant.<br />Valide tes repas, ton eau et tes compléments — ils apparaîtront ici.
          </div>
        </Card>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {days.map(day => {
            const isOpen = open === day.date;
            const pctK = Math.min(day.kcal / TG.kcal, 1) * 100;
            return (
              <Card key={day.date} t={t} pad={0} style={{ overflow: 'hidden' }}>
                <button onClick={() => setOpen(isOpen ? null : day.date)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                  background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>
                      {day.date === todayIso ? 'Aujourd’hui' : fmtDate(day.date)}
                    </div>
                    <div style={{ fontSize: 12, color: t.textMuted, fontFamily: 'Space Grotesk, sans-serif', marginTop: 2 }}>
                      {day.kcal} kcal · {day.prot}g prot · {(day.water * 0.25).toFixed(2).replace('.', ',')} L{day.weight ? ` · ${Number(day.weight).toFixed(1).replace('.', ',')} kg` : ''}
                    </div>
                    <div style={{ height: 5, borderRadius: 99, background: t.ringTrack, overflow: 'hidden', marginTop: 7 }}>
                      <div style={{ height: '100%', width: pctK + '%', background: t.green, borderRadius: 99 }} />
                    </div>
                  </div>
                  <Icon name="chevron" size={18} color={t.textFaint} style={{ transform: isOpen ? 'rotate(90deg)' : 'none', transition: 'transform .2s' }} />
                </button>
                {isOpen && (
                  <div style={{ padding: '0 16px 14px' }}>
                    {day.items.length === 0 && <div style={{ fontSize: 13, color: t.textFaint, padding: '6px 0' }}>Aucun repas validé.</div>}
                    {day.items.map(it => (
                      <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: `1px solid ${t.borderSoft}` }}>
                        <Icon name={it.kind === 'supplement' ? 'supps' : it.kind === 'hermes' ? 'camera' : 'check'} size={15} color={t.green} sw={2.2} />
                        <div style={{ flex: 1, fontSize: 13, color: t.text }}>
                          {it.slot ? <span style={{ color: t.textFaint }}>{it.slot} · </span> : null}{it.name}
                        </div>
                        {(it.kcal > 0) && <div style={{ fontSize: 11.5, color: t.textMuted, fontFamily: 'Space Grotesk, sans-serif' }}>{it.kcal} kcal</div>}
                      </div>
                    ))}
                  </div>
                )}
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { HistoryScreen });
