// screens2.jsx — Courses + Progrès + Compléments
function CoursesScreen({ t, groups, checked, selection, onSetQty, onToggle, onScan, onGoMeals }) {
  const total = groups.reduce((n, r) => n + r.items.length, 0);
  const done = groups.reduce((n, r) => n + r.items.filter(it => checked[r.rayon + '::' + it.key]).length, 0);
  const nbRepas = Object.values(selection || {}).reduce((a, b) => a + b, 0);

  return (
    <div>
      <ScreenHeader t={t} kicker={total ? `${done}/${total} produits récupérés` : 'Choisis tes repas de la semaine'} title="Courses" />

      <button onClick={onScan} style={{
        width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', marginBottom: 18,
        borderRadius: 18, border: `1px dashed ${t.border}`, background: t.surface, cursor: 'pointer', fontFamily: 'inherit' }}>
        <div style={{ width: 40, height: 40, borderRadius: 12, background: `color-mix(in srgb, ${t.blue} 18%, ${t.surface})`,
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="scan" size={21} color={t.blue} />
        </div>
        <div style={{ flex: 1, textAlign: 'left' }}>
          <div style={{ fontWeight: 700, fontSize: 14.5, color: t.text }}>Scanner un produit</div>
          <div style={{ fontSize: 12, color: t.textMuted }}>Vérifie les macros et le sucre ajouté</div>
        </div>
        <Icon name="chevron" size={18} color={t.textFaint} />
      </button>

      {/* SÉLECTION DES REPAS avec compteur */}
      <div style={{ fontSize: 12.5, fontWeight: 700, color: t.textMuted, letterSpacing: 0.3, textTransform: 'uppercase', margin: '0 4px 10px' }}>
        Mes repas de la semaine{nbRepas ? ` · ${nbRepas} sélectionné${nbRepas > 1 ? 's' : ''}` : ''}
      </div>
      <Card t={t} pad={6} style={{ marginBottom: 22 }}>
        {MEALS.map((m, i) => {
          const qty = (selection && selection[m.id]) || 0;
          return (
            <div key={m.id} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 12px', borderTop: i ? `1px solid ${t.borderSoft}` : 'none' }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: qty ? t.text : t.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.name}</div>
                <div style={{ fontSize: 11.5, color: t.textFaint }}>{m.kcal} kcal · {m.prot}g prot</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
                <button onClick={() => onSetQty(m.id, qty - 1)} disabled={!qty} style={{ width: 30, height: 30, borderRadius: 9, cursor: qty ? 'pointer' : 'default',
                  border: `1px solid ${t.border}`, background: t.surface, opacity: qty ? 1 : 0.4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="minus" size={16} color={t.text} sw={2.4} />
                </button>
                <span style={{ minWidth: 22, textAlign: 'center', fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 16, color: qty ? t.green : t.textFaint }}>{qty}</span>
                <button onClick={() => onSetQty(m.id, qty + 1)} style={{ width: 30, height: 30, borderRadius: 9, cursor: 'pointer',
                  border: 'none', background: t.green, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="plus" size={16} color={t.onAccent} sw={2.4} />
                </button>
              </div>
            </div>
          );
        })}
      </Card>

      {/* LISTE DE COURSES GÉNÉRÉE */}
      {groups.length === 0 ? (
        <Card t={t} pad={22} style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 14, color: t.textMuted, lineHeight: 1.5 }}>
            Ajoute des repas ci-dessus (bouton +) pour générer ta liste de courses.
          </div>
        </Card>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: t.textMuted, letterSpacing: 0.3, textTransform: 'uppercase', margin: '0 4px -2px' }}>Ma liste de courses</div>
          {groups.map(rayon => (
            <div key={rayon.rayon}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '0 4px 9px' }}>
                <Icon name={rayon.icon} size={16} color={t.textMuted} />
                <span style={{ fontSize: 12.5, fontWeight: 700, color: t.textMuted, letterSpacing: 0.3, textTransform: 'uppercase' }}>{rayon.rayon}</span>
              </div>
              <Card t={t} pad={4}>
                {rayon.items.map((it, i) => {
                  const key = rayon.rayon + '::' + it.key;
                  const on = !!checked[key];
                  return (
                    <button key={it.key} onClick={() => onToggle(key)} style={{
                      width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '11px 12px', background: 'none',
                      border: 'none', borderTop: i ? `1px solid ${t.borderSoft}` : 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
                      <CheckDot on={on} color={t.green} t={t} size={23} />
                      <span style={{ flex: 1, textAlign: 'left', fontSize: 14.5, color: on ? t.textFaint : t.text,
                        textDecoration: on ? 'line-through' : 'none', fontWeight: 500 }}>{it.label}</span>
                    </button>
                  );
                })}
              </Card>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── PROGRÈS ───────────────────────────────────────────────────
function WeightChart({ t, data }) {
  const W = 320, H = 150, pad = { l: 6, r: 6, t: 14, b: 18 };
  const ys = data.map(d => d.kg);
  const min = Math.min(...ys) - 1.2, max = Math.max(...ys) + 1.2;
  const x = i => pad.l + (i / Math.max(data.length - 1, 1)) * (W - pad.l - pad.r);
  const y = v => pad.t + (1 - (v - min) / (max - min || 1)) * (H - pad.t - pad.b);
  const line = data.map((d, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)} ${y(d.kg).toFixed(1)}`).join(' ');
  const area = `${line} L${x(data.length-1).toFixed(1)} ${H-pad.b} L${x(0).toFixed(1)} ${H-pad.b} Z`;
  // objectif -1kg/sem depuis le départ
  const obj = data.map((d, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)} ${y(ys[0] - i).toFixed(1)}`).join(' ');
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
      <defs>
        <linearGradient id={`wg-${t.key}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={t.green} stopOpacity="0.28" />
          <stop offset="100%" stopColor={t.green} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#wg-${t.key})`} />
      <path d={obj} fill="none" stroke={t.textFaint} strokeWidth="1.6" strokeDasharray="4 4" opacity="0.6" />
      <path d={line} fill="none" stroke={t.green} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" />
      {data.map((d, i) => (
        <g key={i}>
          {i === data.length - 1 && <circle cx={x(i)} cy={y(d.kg)} r="6" fill={t.green} opacity="0.18" />}
          <circle cx={x(i)} cy={y(d.kg)} r={i === data.length - 1 ? 4 : 2.4} fill={t.green} />
          <text x={x(i)} y={H - 4} textAnchor="middle" fontSize="9" fill={t.textFaint} fontFamily="Space Grotesk, sans-serif">{d.label}</text>
        </g>
      ))}
    </svg>
  );
}

function ProgresScreen({ t, weightLog, onLogWeight, onWeeklyPlan, onHistory }) {
  const data = weightLog || [];
  const hasData = data.length >= 1;
  const cur = hasData ? data[data.length - 1].kg : null;
  const start = hasData ? data[0].kg : null;
  const lost = hasData ? (start - cur).toFixed(1) : '0';
  const lastWk = +(data.length >= 2 ? data[data.length - 2].kg - cur : 0).toFixed(1);
  // Calories adaptatives — calcul réel via le backend (utilise les vraies dates de pesée)
  const [adaptData, setAdaptData] = React.useState(null);
  React.useEffect(() => {
    if (!window.FuelFitAPI || data.length < 2) return;
    const hist = data.map((d, i) => ({
      date: d.date || new Date(Date.now() - (data.length - 1 - i) * 7 * 86400000).toISOString().slice(0, 10),
      weight: d.kg,
    }));
    window.FuelFitAPI.computeAdaptive(hist, (TARGETS && TARGETS.kcal) || 1900, 1)
      .then(setAdaptData).catch(() => {});
  }, [weightLog]);

  const adapt = (() => {
    if (adaptData) {
      const tone = adaptData.adjustment < -20 ? t.amber : adaptData.adjustment > 20 ? t.orange : t.green;
      return { msg: <>{adaptData.message}</>, tone };
    }
    // fallback local tant que le backend n'a pas répondu
    if (lastWk >= 0.7 && lastWk <= 1.3) return { msg: <>Rythme parfait (<b style={{ color: t.text }}>−{lastWk.toFixed(1).replace('.', ',')} kg</b>). On maintient ta cible.</>, tone: t.green };
    if (lastWk < 0.7) return { msg: <>Perte plus lente que prévu. On ajustera ta cible à la baisse.</>, tone: t.amber };
    return { msg: <>Perte rapide (<b style={{ color: t.text }}>−{lastWk.toFixed(1).replace('.', ',')} kg</b>). Pour préserver le muscle, on remontera un peu.</>, tone: t.orange };
  })();
  return (
    <div>
      <ScreenHeader t={t} kicker="Ta progression" title="Progrès" />

      <Card t={t} style={{ marginBottom: 14 }}>
        {hasData ? (
          <>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 4 }}>
              <div>
                <div style={{ fontSize: 12.5, color: t.textMuted, fontWeight: 600 }}>Poids actuel</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                  <span style={{ fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 38, color: t.text, letterSpacing: -1 }}>{cur.toFixed(1).replace('.', ',')}</span>
                  <span style={{ fontSize: 15, color: t.textMuted, fontWeight: 600 }}>kg</span>
                </div>
              </div>
              {data.length >= 2 && (
                <div style={{ textAlign: 'right' }}>
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '5px 10px', borderRadius: 99,
                    background: `color-mix(in srgb, ${t.green} 16%, ${t.surface})`, color: t.green, fontWeight: 700, fontSize: 13, fontFamily: 'Space Grotesk, sans-serif' }}>
                    {lastWk >= 0 ? '−' : '+'}{Math.abs(lastWk).toFixed(1).replace('.', ',')} kg récent
                  </div>
                  <div style={{ fontSize: 12, color: t.textFaint, marginTop: 5 }}>−{lost} kg depuis le départ</div>
                </div>
              )}
            </div>
            {data.length >= 2 && <WeightChart t={t} data={data} />}
          </>
        ) : (
          <div style={{ textAlign: 'center', padding: '8px 4px 14px' }}>
            <div style={{ fontSize: 14, color: t.textMuted, lineHeight: 1.5 }}>
              Pèse-toi pour démarrer le suivi.<br />Ta courbe apparaîtra dès la 2ᵉ pesée.
            </div>
          </div>
        )}
        <button onClick={onLogWeight} style={{ width: '100%', marginTop: hasData ? 8 : 14, padding: '12px', borderRadius: 14, border: 'none',
          cursor: 'pointer', background: t.text, color: t.bg, fontWeight: 700, fontSize: 14.5, fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }}>
          <Icon name="scale" size={18} color={t.bg} /> Saisir mon poids
        </button>
      </Card>

      {/* Calories adaptatives — seulement avec assez de données */}
      {data.length >= 2 && (
      <Card t={t} style={{ marginBottom: 14, background: `color-mix(in srgb, ${adapt.tone} 10%, ${t.surface})`, border: `1px solid color-mix(in srgb, ${adapt.tone} 30%, ${t.surface})` }}>
        <div style={{ display: 'flex', gap: 11 }}>
          <div style={{ width: 36, height: 36, borderRadius: 11, flexShrink: 0, background: `color-mix(in srgb, ${adapt.tone} 25%, ${t.surface})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="spark" size={20} color={adapt.tone} fill />
          </div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 14.5, color: t.text, marginBottom: 4 }}>Calories adaptatives</div>
            <div style={{ fontSize: 13, color: t.textMuted, lineHeight: 1.5 }}>{adapt.msg}</div>
          </div>
        </div>
      </Card>

      )}

      {/* Accès au plan de la semaine */}
      <button onClick={onWeeklyPlan} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '15px 16px', marginBottom: 14,
        borderRadius: 18, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
        background: t.green, color: t.onAccent, boxShadow: `0 6px 18px color-mix(in srgb, ${t.green} 40%, transparent)` }}>
        <Icon name="spark" size={22} color={t.onAccent} fill />
        <div style={{ flex: 1, textAlign: 'left' }}>
          <div style={{ fontWeight: 700, fontSize: 14.5 }}>Voir mon plan de la semaine</div>
          <div style={{ fontSize: 12, opacity: 0.85 }}>Bilan + plan repas 7 jours par Hermès</div>
        </div>
        <Icon name="chevron" size={18} color={t.onAccent} />
      </button>

      {/* Historique / journal */}
      <button onClick={onHistory} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', marginBottom: 14,
        borderRadius: 18, border: `1px solid ${t.borderSoft}`, background: t.surface, cursor: 'pointer', fontFamily: 'inherit' }}>
        <div style={{ width: 40, height: 40, borderRadius: 12, background: `color-mix(in srgb, ${t.blue} 16%, ${t.surface})`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="progress" size={20} color={t.blue} />
        </div>
        <div style={{ flex: 1, textAlign: 'left' }}>
          <div style={{ fontWeight: 700, fontSize: 14.5, color: t.text }}>Mon journal de bord</div>
          <div style={{ fontSize: 12, color: t.textMuted }}>Historique jour par jour de ce que tu as mangé</div>
        </div>
        <Icon name="chevron" size={18} color={t.textFaint} />
      </button>

      {/* Stats semaine */}
      {data.length >= 1 && <div style={{ display: 'flex', gap: 12 }}>
        {[
          { label: 'Variation 7 j', val: `−${lastWk.toFixed(1).replace('.', ',')}`, sub: 'kg cette semaine' },
          { label: 'Saisies', val: `${data.length}`, sub: 'points enregistrés' },
        ].map(s => (
          <Card key={s.label} t={t} pad={16} style={{ flex: 1 }}>
            <div style={{ fontSize: 12, color: t.textMuted, fontWeight: 600, marginBottom: 6 }}>{s.label}</div>
            <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 26, color: t.text, letterSpacing: -0.5 }}>{s.val}</div>
            <div style={{ fontSize: 11.5, color: t.textFaint, marginTop: 2 }}>{s.sub}</div>
          </Card>
        ))}
      </div>}
    </div>
  );
}

// ── COMPLÉMENTS ───────────────────────────────────────────────
function SuppCard({ s, t, on, onToggle }) {
  return (
    <Card t={t} pad={15}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ width: 40, height: 40, borderRadius: 12, flexShrink: 0,
          background: `color-mix(in srgb, ${t[s.tint]} 22%, ${t.surface})`,
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="supps" size={21} color={t[s.tint]} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 15, color: t.text, marginBottom: 3 }}>{s.name}</div>
          <div style={{ fontSize: 12.5, color: t.textMuted, lineHeight: 1.45, marginBottom: 9 }}>{s.role}</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 11.5, fontWeight: 600, padding: '4px 9px', borderRadius: 7, background: t.surfaceAlt, color: t.textMuted, whiteSpace: 'nowrap' }}>Dose · {s.dose}</span>
            <span style={{ fontSize: 11.5, fontWeight: 600, padding: '4px 9px', borderRadius: 7, background: t.surfaceAlt, color: t.textMuted, whiteSpace: 'nowrap' }}>{s.moment}</span>
          </div>
        </div>
        <button onClick={onToggle} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}>
          <CheckDot on={on} color={t[s.tint]} t={t} />
        </button>
      </div>
    </Card>
  );
}

function ComplementsScreen({ t, checked, onToggle }) {
  return (
    <div>
      <ScreenHeader t={t} kicker="Prises du jour" title="Compléments" />

      <div style={{ fontSize: 12.5, fontWeight: 700, color: t.textMuted, letterSpacing: 0.3, textTransform: 'uppercase', margin: '0 4px 10px' }}>Essentiels</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 22 }}>
        {SUPPS.essentiels.map(s => <SuppCard key={s.id} s={s} t={t} on={!!checked[s.id]} onToggle={() => onToggle(s.id)} />)}
      </div>

      <div style={{ fontSize: 12.5, fontWeight: 700, color: t.textMuted, letterSpacing: 0.3, textTransform: 'uppercase', margin: '0 4px 10px' }}>Confort & optionnel</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 16 }}>
        {SUPPS.confort.map(s => <SuppCard key={s.id} s={s} t={t} on={!!checked[s.id]} onToggle={() => onToggle(s.id)} />)}
      </div>

      {/* Boissons */}
      <div style={{ fontSize: 12.5, fontWeight: 700, color: t.textMuted, letterSpacing: 0.3, textTransform: 'uppercase', margin: '0 4px 10px' }}>Boissons</div>
      <Card t={t} pad={6} style={{ marginBottom: 14 }}>
        {DRINKS.libres.map((d, i) => (
          <div key={d.name} style={{ display: 'flex', alignItems: 'flex-start', gap: 11, padding: '11px 12px', borderTop: i ? `1px solid ${t.borderSoft}` : 'none' }}>
            <Icon name="check" size={18} color={t.green} sw={2.6} style={{ marginTop: 2, flexShrink: 0 }} />
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{d.name}{d.star ? ' ★' : ''}</div>
              <div style={{ fontSize: 12, color: t.textMuted, lineHeight: 1.4 }}>{d.note}</div>
            </div>
          </div>
        ))}
      </Card>
      <Card t={t} pad={6} style={{ marginBottom: 22 }}>
        {DRINKS.eviter.map((d, i) => (
          <div key={d.name} style={{ display: 'flex', alignItems: 'flex-start', gap: 11, padding: '11px 12px', borderTop: i ? `1px solid ${t.borderSoft}` : 'none' }}>
            <Icon name="close" size={18} color={t.red} sw={2.6} style={{ marginTop: 2, flexShrink: 0 }} />
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: t.textMuted }}>{d.name}</div>
              <div style={{ fontSize: 12, color: t.textFaint, lineHeight: 1.4 }}>{d.note}</div>
            </div>
          </div>
        ))}
      </Card>

      {/* Santé du foie — honnête */}
      <Card t={t} pad={16} style={{ background: t.surfaceAlt }}>
        <div style={{ display: 'flex', gap: 11 }}>
          <Icon name="info" size={20} color={t.textMuted} style={{ marginTop: 1, flexShrink: 0 }} />
          <div>
            <div style={{ fontWeight: 700, fontSize: 14, color: t.text, marginBottom: 4 }}>Santé du foie</div>
            <div style={{ fontSize: 12.5, color: t.textMuted, lineHeight: 1.5 }}>
              Soyons honnêtes : aucune pilule ne « détoxifie » le foie. Ce qui agit vraiment, c’est ton alimentation sans sucre ajouté et la perte de gras. Pas de complément miracle ici.
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { CoursesScreen, ProgresScreen, ComplementsScreen, WeightChart, SuppCard });
