// Healify — AI tool deep flows: Bloodwork, DNA, Meal plan.
// State-machine screens: each tool walks through entry → loading → result → save.
// Requires components.jsx.

const { useState: useStateT1, useEffect: useEffectT1, useRef: useRefT1 } = React;

// ──────────────────────────────────────────────────────────────────────────
// Shared bits used by tool flows
// ──────────────────────────────────────────────────────────────────────────

function HToast({ msg, kind = 'success', onDone }) {
  useEffectT1(() => {
    const t = setTimeout(onDone, 2400);
    return () => clearTimeout(t);
  }, []);
  const bg = kind === 'success' ? 'var(--success-700)' : kind === 'error' ? 'var(--danger)' : 'var(--brand-ink)';
  return (
    <div style={{
      position: 'fixed', left: 20, right: 20, bottom: 120, zIndex: 90,
      background: bg, color: '#fff', padding: '14px 18px', borderRadius: 14,
      fontFamily: H.body, fontWeight: 500, fontSize: 14,
      boxShadow: '0 14px 32px rgba(3,4,13,0.22)',
      animation: 'hToastIn 240ms ease-out',
      display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <style>{`@keyframes hToastIn { from { opacity: 0; transform: translateY(8px); } }`}</style>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>
      <div style={{ flex: 1 }}>{msg}</div>
    </div>
  );
}

function HSpinner({ size = 40, color = '#fff' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ animation: 'hSpin 1.1s linear infinite' }}>
      <circle cx="12" cy="12" r="9" opacity="0.3"/>
      <path d="M12 3a9 9 0 0 1 9 9"/>
      <style>{`@keyframes hSpin { to { transform: rotate(360deg); } }`}</style>
    </svg>
  );
}

// Loading hero card — used across tool generators.
function HToolLoading({ title, sub, hint }) {
  return (
    <HCard style={{ padding: 32, textAlign: 'center', borderRadius: 22 }}>
      <div style={{ width: 120, height: 120, borderRadius: 999, margin: '0 auto', background: H.gradOrange, display: 'grid', placeItems: 'center', boxShadow: '0 10px 30px rgba(255,104,65,0.3)' }}>
        <HSpinner size={40} />
      </div>
      <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, marginTop: 16 }}>{title}</div>
      <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 4, lineHeight: 1.45 }}>{sub}</div>
      {hint && <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 14, fontStyle: 'italic' }}>{hint}</div>}
    </HCard>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// 1. BLOODWORK — upload → scanning → results → save
// ══════════════════════════════════════════════════════════════════════════

function BloodReportScreen({ onNavigate, onBack }) {
  const [stage, setStage] = useStateT1('upload'); // upload | scanning | results | saved
  const [toast, setToast] = useStateT1(null);
  const [scanProgress, setScanProgress] = useStateT1(0);

  useEffectT1(() => {
    if (stage !== 'scanning') return;
    setScanProgress(0);
    const iv = setInterval(() => {
      setScanProgress(p => {
        if (p >= 100) { clearInterval(iv); setStage('results'); return 100; }
        return p + 4;
      });
    }, 70);
    return () => clearInterval(iv);
  }, [stage]);

  const markers = [
    { name: 'Total cholesterol', v: '214 mg/dL', level: 'fair', range: '< 200' },
    { name: 'LDL',               v: '138 mg/dL', level: 'fair', range: '< 100' },
    { name: 'HDL',               v: '58 mg/dL',  level: 'normal', range: '> 50' },
    { name: 'Triglycerides',     v: '118 mg/dL', level: 'normal', range: '< 150' },
    { name: 'Fasting glucose',   v: '92 mg/dL',  level: 'normal', range: '70–99' },
    { name: 'HbA1c',             v: '5.4 %',     level: 'normal', range: '< 5.7' },
    { name: 'Vitamin D',         v: '22 ng/mL',  level: 'bad',    range: '30–80' },
    { name: 'TSH',               v: '2.1 mIU/L', level: 'normal', range: '0.4–4.0' },
  ];

  const onSave = () => {
    setStage('saved');
    setToast({ msg: 'Blood report saved to Health', kind: 'success' });
    setTimeout(() => onNavigate('tab:health'), 1200);
  };

  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Blood report" />

      {stage === 'upload' && (
        <>
          <HCard style={{ padding: 22, textAlign: 'center', borderRadius: 22 }}>
            <div style={{ width: 88, height: 88, borderRadius: 22, background: 'var(--focus-heart-50)', margin: '0 auto', display: 'grid', placeItems: 'center' }}>
              <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke={H.orange} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z"/><path d="M14 3v6h6"/><path d="m9 14 3-3 3 3"/><path d="M12 11v6"/></svg>
            </div>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 20, marginTop: 14 }}>Upload your blood report</div>
            <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 6, lineHeight: 1.5 }}>
              PDF or photo. Anna extracts 40+ markers and compares against optimal ranges for your age group.
            </div>
            <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <HPrimaryButton onClick={() => setStage('scanning')}>Upload PDF</HPrimaryButton>
              <HPrimaryButton type="outline" onClick={() => setStage('scanning')}>Take photo</HPrimaryButton>
            </div>
          </HCard>

          <HSectionLabel style={{ margin: '22px 4px 10px' }}>How it works</HSectionLabel>
          <HCard style={{ padding: 16 }}>
            {['Anna extracts every marker from your report', 'Each value is compared against optimal (not just lab) ranges', 'You get a plain-English breakdown + next steps to chat about'].map((t, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '6px 0' }}>
                <div style={{ width: 22, height: 22, borderRadius: 999, background: H.orange, color: '#fff', display: 'grid', placeItems: 'center', fontFamily: H.body, fontWeight: 500, fontSize: 12, flexShrink: 0 }}>{i + 1}</div>
                <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg1, lineHeight: 1.45 }}>{t}</div>
              </div>
            ))}
          </HCard>

          <HSectionLabel style={{ margin: '22px 4px 10px' }}>Past reports</HSectionLabel>
          <HCard style={{ padding: 0 }}>
            {[
              { lab: 'Quest Diagnostics', when: 'Jan 12', notes: '3 needed attention' },
              { lab: 'LabCorp', when: 'Sep 4 · 2025', notes: 'All optimal' },
            ].map((r, i, arr) => (
              <div key={i} onClick={() => { setToast({ msg: `Opening ${r.lab} · ${r.when}…`, kind: 'success' }); setTimeout(() => setStage('results'), 600); }} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i === arr.length - 1 ? 'none' : '0.5px solid ' + H.border, cursor: 'pointer' }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--bg-app)', display: 'grid', placeItems: 'center' }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg2} strokeWidth="1.8" strokeLinecap="round"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z"/><path d="M14 3v6h6"/></svg>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{r.lab}</div>
                  <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 1 }}>{r.when} · {r.notes}</div>
                </div>
                <HChevron />
              </div>
            ))}
          </HCard>
        </>
      )}

      {stage === 'scanning' && (
        <>
          <HToolLoading title="Scanning your report…" sub="Extracting markers and comparing optimal ranges" hint={scanProgress < 30 ? 'Reading file…' : scanProgress < 60 ? 'Recognizing values…' : scanProgress < 90 ? 'Comparing ranges…' : 'Generating insights…'} />
          <div style={{ height: 6, borderRadius: 999, background: 'var(--bg-app)', overflow: 'hidden', marginTop: 16 }}>
            <div style={{ width: scanProgress + '%', height: '100%', background: H.gradOrange, transition: 'width 70ms linear' }}/>
          </div>
        </>
      )}

      {(stage === 'results' || stage === 'saved') && (
        <>
          <HCard style={{ padding: 18, borderRadius: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: 14, background: 'var(--focus-heart-50)', display: 'grid', placeItems: 'center' }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill={H.orange}><path d="M12 2 5 9c-3 3-3 8 0 11s8 3 11 0 3-8 0-11z"/></svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 17 }}>Quest Diagnostics · Apr 2</div>
                <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2 }}>40 markers analyzed · 3 need attention</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' }}>
              <HBadge title="5 out of range" level="fair" />
              <HBadge title="1 low vitamin D" level="bad" />
              <HBadge title="34 in optimal" level="normal" />
            </div>
          </HCard>

          <HSectionLabel style={{ margin: '22px 4px 10px' }}>Markers</HSectionLabel>
          <div style={{ background: '#fff', borderRadius: 16, overflow: 'hidden', boxShadow: '0 1px 2px rgba(3,4,13,0.04)' }}>
            {markers.map((m, i) => (
              <div key={m.name} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderBottom: i === markers.length - 1 ? 'none' : '0.5px solid ' + H.border }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{m.name}</div>
                  <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3 }}>optimal {m.range}</div>
                </div>
                <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg1 }}>{m.v}</div>
                <HStatusDot level={m.level} />
              </div>
            ))}
          </div>

          <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <HPrimaryButton onClick={() => onNavigate('chat', { topic: 'blood' })}>Chat with Anna about your results</HPrimaryButton>
            <HPrimaryButton type="outline" onClick={onSave}>Save to Health</HPrimaryButton>
          </div>
        </>
      )}

      {toast && <HToast msg={toast.msg} kind={toast.kind} onDone={() => setToast(null)} />}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// 2. DNA — connect/upload → loading → traits → save
// ══════════════════════════════════════════════════════════════════════════

function DNAScreen({ onNavigate, onBack }) {
  const [stage, setStage] = useStateT1('connect'); // connect | uploading | results | saved
  const [toast, setToast] = useStateT1(null);

  useEffectT1(() => {
    if (stage === 'uploading') {
      const t = setTimeout(() => setStage('results'), 1900);
      return () => clearTimeout(t);
    }
  }, [stage]);

  const traits = [
    { k: 'caffeine', name: 'Caffeine metabolism', level: 'fair',   body: 'Slow metabolizer. Cap caffeine at 2pm.', color: 'var(--quartz-150)' },
    { k: 'vit-d',    name: 'Vitamin D absorption', level: 'bad',   body: 'Below avg. Anna suggests 2,000 IU supplement.', color: 'var(--focus-heart-100)' },
    { k: 'lactose',  name: 'Lactose tolerance',    level: 'normal', body: 'Normal. No dairy restriction needed.', color: 'var(--focus-fitness-100)' },
    { k: 'muscle',   name: 'Muscle composition',   level: 'normal', body: 'Mixed type IIa/IIx. Good for strength + endurance.', color: 'var(--focus-sleep-100)' },
    { k: 'sleep',    name: 'Sleep chronotype',     level: 'fair',   body: 'Moderate evening-type. Target lights out 11:15.', color: 'var(--focus-sleep)' },
    { k: 'omega',    name: 'Omega-3 processing',   level: 'fair',   body: 'Benefit from 2g/day EPA+DHA.', color: 'var(--focus-mental-100)' },
  ];

  const onSave = () => {
    setStage('saved');
    setToast({ msg: 'DNA insights saved to your profile', kind: 'success' });
    setTimeout(() => onNavigate('tab:health'), 1200);
  };

  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="DNA insights" />

      {stage === 'connect' && (
        <>
          <HCard style={{ padding: 22, borderRadius: 22, background: 'linear-gradient(135deg, #1A1018 0%, #2A1522 100%)', color: '#fff', textAlign: 'center' }}>
            <div style={{ width: 76, height: 76, borderRadius: 22, background: 'rgba(255,104,65,0.2)', margin: '0 auto', display: 'grid', placeItems: 'center' }}>
              <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke={H.gold} strokeWidth="2" strokeLinecap="round"><path d="M7 3c4 3 6 9 10 14M17 3c-4 3-6 9-10 14M6 6h12M6 18h12M7 10h10M7 14h10"/></svg>
            </div>
            <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, marginTop: 14, letterSpacing: -0.3 }}>Connect your DNA data</div>
            <div style={{ fontFamily: H.body, fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 8, lineHeight: 1.5 }}>
              Anna analyzes 30+ traits across nutrition, fitness, sleep, and longevity.
            </div>
          </HCard>

          <HSectionLabel style={{ margin: '22px 4px 10px' }}>Choose your provider</HSectionLabel>
          <div style={{ background: '#fff', borderRadius: 16, overflow: 'hidden', boxShadow: '0 1px 2px rgba(3,4,13,0.04)' }}>
            {[
              { name: '23andMe',     sub: 'Connect via OAuth',       k: '23' },
              { name: 'Ancestry',    sub: 'Connect via OAuth',       k: 'an' },
              { name: 'MyHeritage',  sub: 'Connect via OAuth',       k: 'mh' },
              { name: 'Upload raw file', sub: '.txt or .vcf · ≤ 50MB', k: 'raw' },
            ].map((p, i, arr) => (
              <div key={p.k} onClick={() => setStage('uploading')} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                borderBottom: i === arr.length - 1 ? 'none' : '0.5px solid ' + H.border, cursor: 'pointer',
              }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--bg-app)', display: 'grid', placeItems: 'center' }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg2} strokeWidth="1.8" strokeLinecap="round"><path d="M7 3c4 3 6 9 10 14M17 3c-4 3-6 9-10 14"/></svg>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{p.name}</div>
                  <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 1 }}>{p.sub}</div>
                </div>
                <HChevron />
              </div>
            ))}
          </div>

          <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 20, lineHeight: 1.5, padding: '0 4px' }}>
            Your raw data is encrypted and stored on-device. Healify never shares genetic data with third parties.
          </div>
        </>
      )}

      {stage === 'uploading' && <HToolLoading title="Reading your DNA…" sub="Mapping 30+ traits to evidence-based recommendations" hint="This usually takes 10–20 seconds" />}

      {(stage === 'results' || stage === 'saved') && (
        <>
          <HCard style={{ padding: 20, borderRadius: 22, background: 'linear-gradient(135deg, #1A1018 0%, #2A1522 100%)', color: '#fff' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 52, height: 52, borderRadius: 14, background: 'rgba(255,104,65,0.2)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={H.gold} strokeWidth="2" strokeLinecap="round"><path d="M7 3c4 3 6 9 10 14M17 3c-4 3-6 9-10 14M6 6h12M6 18h12M7 10h10M7 14h10"/></svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18 }}>Your DNA profile</div>
                <div style={{ fontFamily: H.body, fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 2 }}>23andMe · imported just now</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' }}>
              <HBadge title="30 traits" level="info" />
              <HBadge title="2 high-impact" level="bad" />
              <HBadge title="4 watch points" level="fair" />
            </div>
          </HCard>

          <HSectionLabel style={{ margin: '22px 4px 10px' }}>Traits</HSectionLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {traits.map(t => (
              <HCard key={t.k} onClick={() => onNavigate('chat', { topic: 'dna' })} style={{ padding: '14px 16px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <HIconTile color={t.color} alpha={0.16} size={36}>{HIcons.vitals(t.color)}</HIconTile>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{t.name}</div>
                      <HStatusDot level={t.level} />
                    </div>
                    <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 2, lineHeight: 1.4 }}>{t.body}</div>
                  </div>
                </div>
              </HCard>
            ))}
          </div>

          <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <HPrimaryButton onClick={() => onNavigate('chat', { topic: 'dna' })}>Ask Anna about your DNA</HPrimaryButton>
            <HPrimaryButton type="outline" onClick={onSave}>Save to profile</HPrimaryButton>
          </div>
        </>
      )}

      {toast && <HToast msg={toast.msg} kind={toast.kind} onDone={() => setToast(null)} />}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// 3. MEAL PLAN — preferences → generating → plan → swap → grocery → save
// ══════════════════════════════════════════════════════════════════════════

function MealPlanScreen({ onNavigate, onBack }) {
  const [stage, setStage] = useStateT1('prefs'); // prefs | generating | plan | swap | grocery | saved
  const [prefs, setPrefs] = useStateT1({
    goal: 'longevity', diet: 'omnivore', allergies: ['peanut'], cals: 1830, days: 7,
  });
  const [toast, setToast] = useStateT1(null);
  const [day, setDay] = useStateT1(3);
  const [swapIdx, setSwapIdx] = useStateT1(null);
  const [plan, setPlan] = useStateT1([
    { meal: 'Breakfast', dish: 'Greek yogurt + berries + walnuts', kcal: 410, img: '🥣' },
    { meal: 'Lunch',     dish: 'Salmon + farro + roasted veg',     kcal: 620, img: '🥗' },
    { meal: 'Snack',     dish: 'Apple + almond butter',             kcal: 240, img: '🍎' },
    { meal: 'Dinner',    dish: 'Chicken stir-fry + brown rice',     kcal: 560, img: '🍜' },
  ]);

  useEffectT1(() => {
    if (stage === 'generating') {
      const t = setTimeout(() => setStage('plan'), 2100);
      return () => clearTimeout(t);
    }
  }, [stage]);

  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const toggle = (key, v) => setPrefs(p => {
    const arr = p[key];
    if (Array.isArray(arr)) return { ...p, [key]: arr.includes(v) ? arr.filter(x => x !== v) : [...arr, v] };
    return { ...p, [key]: v };
  });

  const grocery = [
    { cat: 'Produce', items: ['Berries (mixed)', 'Apples · 4', 'Spinach · 1 bag', 'Bell peppers · 3', 'Broccoli · 2 heads', 'Lemon · 2'] },
    { cat: 'Protein', items: ['Salmon · 1.5 lb', 'Chicken thigh · 2 lb', 'Greek yogurt · 32 oz', 'Tofu · 1 block'] },
    { cat: 'Pantry',  items: ['Farro · 1 cup', 'Brown rice · 2 cups', 'Walnuts · 1 cup', 'Almond butter · 8 oz', 'Olive oil', 'Soy sauce'] },
  ];

  const onSave = () => {
    setStage('saved');
    setToast({ msg: '7-day meal plan saved to Nutrition', kind: 'success' });
    setTimeout(() => onNavigate('tab:nutrition'), 1200);
  };

  // ── Preferences
  if (stage === 'prefs') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={onBack} title="Meal plan" />

        <HToolHero kicker="Meal plan · Generator" title="Plan your week with Anna" subtitle="A personalized 7-day plan in under 15 seconds." />

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Goal</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
          {[
            { k: 'longevity', label: 'Longevity' },
            { k: 'lose',      label: 'Lose weight' },
            { k: 'muscle',    label: 'Build muscle' },
            { k: 'energy',    label: 'More energy' },
          ].map(o => (
            <div key={o.k} onClick={() => toggle('goal', o.k)} style={{
              padding: '10px 14px', borderRadius: 999, cursor: 'pointer',
              background: prefs.goal === o.k ? H.black : '#fff', color: prefs.goal === o.k ? '#fff' : H.fg1,
              fontFamily: H.body, fontWeight: 500, fontSize: 13,
              boxShadow: prefs.goal === o.k ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
            }}>{o.label}</div>
          ))}
        </div>

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Diet</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
          {['omnivore', 'pescatarian', 'vegetarian', 'vegan', 'keto'].map(o => (
            <div key={o} onClick={() => toggle('diet', o)} style={{
              padding: '10px 14px', borderRadius: 999, cursor: 'pointer',
              background: prefs.diet === o ? H.black : '#fff', color: prefs.diet === o ? '#fff' : H.fg1,
              fontFamily: H.body, fontWeight: 500, fontSize: 13, textTransform: 'capitalize',
              boxShadow: prefs.diet === o ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
            }}>{o}</div>
          ))}
        </div>

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Allergies & exclusions</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
          {['peanut', 'tree nut', 'gluten', 'dairy', 'shellfish', 'soy', 'egg'].map(o => {
            const on = prefs.allergies.includes(o);
            return (
              <div key={o} onClick={() => toggle('allergies', o)} style={{
                padding: '10px 14px', borderRadius: 999, cursor: 'pointer',
                background: on ? H.orange : '#fff', color: on ? '#fff' : H.fg1,
                fontFamily: H.body, fontWeight: 500, fontSize: 13, textTransform: 'capitalize',
                boxShadow: on ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
              }}>{on ? '✓ ' : ''}{o}</div>
            );
          })}
        </div>

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Daily target</HSectionLabel>
        <HCard style={{ padding: 16, marginBottom: 22 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontFamily: H.body, fontSize: 14 }}>Calories</div>
            <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22 }}>{prefs.cals.toLocaleString()}</div>
          </div>
          <input type="range" min="1200" max="3200" step="50" value={prefs.cals} onChange={e => setPrefs(p => ({ ...p, cals: +e.target.value }))} style={{ width: '100%', marginTop: 10, accentColor: H.orange }}/>
        </HCard>

        <HPrimaryButton onClick={() => setStage('generating')}>Generate plan</HPrimaryButton>
        {toast && <HToast msg={toast.msg} kind={toast.kind} onDone={() => setToast(null)} />}
      </div>
    );
  }

  // ── Generating
  if (stage === 'generating') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={onBack} title="Meal plan" />
        <HToolLoading title="Anna is building your plan…" sub={`7 days · ${prefs.cals} kcal/day · ${prefs.diet}`} hint="Balancing macros, fiber, and prep time" />
      </div>
    );
  }

  // ── Grocery list
  if (stage === 'grocery') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => setStage('plan')} title="Grocery list" />
        <HCard style={{ padding: 16, marginBottom: 18, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--focus-fitness-50)', display: 'grid', placeItems: 'center' }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--focus-fitness-100)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3h2l3 13h12l3-9H6"/><circle cx="9" cy="20" r="1.6"/><circle cx="18" cy="20" r="1.6"/></svg>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>This week · 32 items</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>Estimated cost ≈ $94</div>
          </div>
        </HCard>
        {grocery.map(g => (
          <div key={g.cat} style={{ marginBottom: 18 }}>
            <HSectionLabel style={{ margin: '0 4px 10px' }}>{g.cat}</HSectionLabel>
            <HCard style={{ padding: '4px 16px' }}>
              {g.items.map((it, i) => <GroceryItem key={i} label={it} />)}
            </HCard>
          </div>
        ))}
        <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <HPrimaryButton onClick={() => { setToast({ msg: 'Grocery list shared', kind: 'success' }); }}>Share list</HPrimaryButton>
          <HPrimaryButton type="outline" onClick={() => setStage('plan')}>Back to plan</HPrimaryButton>
        </div>
        {toast && <HToast msg={toast.msg} kind={toast.kind} onDone={() => setToast(null)} />}
      </div>
    );
  }

  // ── Plan view (with swap modal)
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%', position: 'relative' }}>
      <HTopBar onBack={onBack} title="Meal plan" right={<div onClick={() => setStage('grocery')} style={{ fontFamily: H.body, fontSize: 14, fontWeight: 500, color: H.orange, cursor: 'pointer' }}>List</div>} />

      <div style={{ display: 'flex', gap: 8, marginBottom: 16, overflowX: 'auto', padding: '0 2px' }}>
        {days.map((d, i) => (
          <div key={i} onClick={() => setDay(i)} style={{
            padding: '10px 14px', borderRadius: 999, cursor: 'pointer',
            background: day === i ? H.black : '#fff', color: day === i ? '#fff' : H.fg1,
            fontFamily: H.body, fontWeight: 500, fontSize: 13,
            boxShadow: day === i ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
            flexShrink: 0,
          }}>{d}</div>
        ))}
      </div>

      <HCard style={{ padding: 16, borderRadius: 20, background: H.gradOrange, color: '#fff', marginBottom: 18 }}>
        <div style={{ fontFamily: H.body, fontSize: 12, letterSpacing: 1, textTransform: 'uppercase', opacity: 0.82 }}>{days[day]} · Apr {14 + day}</div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24, marginTop: 4 }}>{plan.reduce((a, m) => a + m.kcal, 0)} kcal</div>
        <div style={{ fontFamily: H.body, fontSize: 13, marginTop: 4, opacity: 0.92 }}>126g protein · 22g fiber · 12g sat fat</div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Meals</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {plan.map((m, i) => (
          <HCard key={i} onClick={() => setSwapIdx(i)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }}>
            <HIconTile color={['var(--brand-orange-vibey)','var(--focus-fitness)','var(--focus-heart)','var(--focus-sleep)'][i % 4]} alpha={0.14} size={48}>{HIcons.nutrition(['var(--brand-orange-vibey)','var(--focus-fitness)','var(--focus-heart)','var(--focus-sleep)'][i % 4])}</HIconTile>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>{m.meal}</div>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, marginTop: 1 }}>{m.dish}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 1 }}>{m.kcal} kcal · tap to swap</div>
            </div>
            <HChevron />
          </HCard>
        ))}
      </div>

      <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <HPrimaryButton onClick={() => setStage('grocery')}>View grocery list</HPrimaryButton>
        <HPrimaryButton type="outline" onClick={onSave}>Save plan to Nutrition</HPrimaryButton>
        <HPrimaryButton type="outline" onClick={() => onNavigate('chat', { topic: 'mealplan' })}>Ask Anna to adjust</HPrimaryButton>
      </div>

      {/* Swap sheet */}
      {swapIdx !== null && (
        <SwapSheet
          meal={plan[swapIdx]}
          onClose={() => setSwapIdx(null)}
          onSwap={(newDish) => {
            setPlan(p => p.map((m, i) => i === swapIdx ? { ...m, dish: newDish.dish, kcal: newDish.kcal, img: newDish.img } : m));
            setSwapIdx(null);
            setToast({ msg: `Swapped to ${newDish.dish}`, kind: 'success' });
          }}
        />
      )}

      {toast && <HToast msg={toast.msg} kind={toast.kind} onDone={() => setToast(null)} />}
    </div>
  );
}

function GroceryItem({ label }) {
  const [done, setDone] = useStateT1(false);
  return (
    <div onClick={() => setDone(v => !v)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', cursor: 'pointer', borderBottom: '0.5px solid ' + H.border }}>
      <div style={{ width: 22, height: 22, borderRadius: 999, background: done ? H.success : 'transparent', border: '2px solid ' + (done ? H.success : H.border), display: 'grid', placeItems: 'center', flexShrink: 0 }}>
        {done && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round"><path d="m5 12 5 5L20 7"/></svg>}
      </div>
      <div style={{ flex: 1, fontFamily: H.body, fontSize: 14, color: done ? H.fg3 : H.fg1, textDecoration: done ? 'line-through' : 'none' }}>{label}</div>
    </div>
  );
}

function SwapSheet({ meal, onClose, onSwap }) {
  const options = [
    { dish: 'Tofu stir-fry + brown rice', kcal: 510, img: '🥡' },
    { dish: 'Lentil soup + sourdough',    kcal: 480, img: '🍲' },
    { dish: 'Cod + sweet potato + greens', kcal: 540, img: '🐟' },
    { dish: 'Turkey chili + avocado',     kcal: 590, img: '🌶️' },
  ];
  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(3,4,13,0.4)', zIndex: 80, display: 'flex', alignItems: 'flex-end' }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background: H.bg, borderRadius: '24px 24px 0 0', width: '100%',
        padding: '14px 20px 28px', maxHeight: '80%', overflowY: 'auto',
        animation: 'hSheet 280ms ease-out',
      }}>
        <style>{`@keyframes hSheet { from { transform: translateY(100%); } }`}</style>
        <div style={{ width: 40, height: 4, background: H.border, borderRadius: 999, margin: '4px auto 14px' }}/>
        <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, marginBottom: 4 }}>Swap “{meal.dish}”</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginBottom: 14 }}>Tap to replace this meal.</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {options.map((o, i) => (
            <HCard key={i} onClick={() => onSwap(o)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
              <HIconTile color={H.orange} alpha={0.14} size={44}>{HIcons.nutrition(H.orange)}</HIconTile>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14 }}>{o.dish}</div>
                <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2 }}>{o.kcal} kcal</div>
              </div>
            </HCard>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  HToast, HSpinner, HToolLoading,
  BloodReportScreen, DNAScreen, MealPlanScreen,
  GroceryItem, SwapSheet,
});
