// Healify V2 — multi-step sub-flows.
// Each flow is a single screen that internally tracks step state.
// Wired into the router as: 'blood-flow', 'dna-flow', 'mealplan-flow',
// 'workout-flow', 'voice-flow'. The single-screen versions (blood, dna,
// mealplan, workout, voice) still work as the "primary view" — the *-flow
// variants kick off the multi-step intake.

// ==========================================================================
// BLOODWORK FLOW
// ==========================================================================
function BloodworkFlowScreen({ onNavigate, onBack }) {
  const [step, setStep] = React.useState('upload'); // upload | parsing | results | marker
  const [markerIndex, setMarkerIndex] = React.useState(null);

  const markers = [
    { name: 'HDL cholesterol', value: 64,  unit: 'mg/dL', range: '40–80',  status: 'normal',    delta: '+4',  why: 'Higher HDL is protective. Your aerobic activity is showing up here.' },
    { name: 'LDL cholesterol', value: 142, unit: 'mg/dL', range: '<100',   status: 'fair',      delta: '−6',  why: 'A bit high. Reducing saturated-fat sources (butter, cheese) and adding soluble fibre (oats, beans) will move this.' },
    { name: 'Vitamin D',       value: 28,  unit: 'ng/mL', range: '30–80',  status: 'fair',      delta: '+2',  why: 'Just below the optimal floor. 1,000 IU/day for 6 weeks should bring it into the 40s.' },
    { name: 'Iron · Ferritin', value: 24,  unit: 'ng/mL', range: '30–200', status: 'attention', delta: '0',   why: 'Iron stores are low. Iron-rich meals + a low-dose supplement bring this back over weeks.' },
    { name: 'HbA1c',           value: 5.3, unit: '%',     range: '<5.7',   status: 'normal',    delta: '−0.1',why: 'Healthy. Three-month blood-sugar average.' },
    { name: 'TSH',             value: 2.1, unit: 'mIU/L', range: '0.4–4',  status: 'normal',    delta: '−0.3',why: 'Thyroid signalling is in range.' },
  ];

  if (step === 'upload') {
    return (
      <HScreen label="Bloodwork · upload">
        <HTopBar title="" onBack={onBack}/>
        <div style={{ padding: '0 4px', marginBottom: 18 }}>
          <div className="h-label">AI tool</div>
          <div className="h-display" style={{ fontSize: 30, marginTop: 4 }}>Bloodwork</div>
          <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 6, lineHeight: 1.5 }}>Upload a PDF or photo. I decode it into plain English and flag what matters.</div>
        </div>
        <button onClick={() => setStep('parsing')} style={{ width: '100%' }}>
          <HCard pad="32px 16px" radius={22} elevate={false} style={{ background: 'transparent', border: '2px dashed var(--t-ink-12)' }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 56, height: 56, borderRadius: 18, background: 'var(--t-cream)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Glyph name="droplet" size={26}/>
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500 }}>Drop a report here</div>
              <div style={{ fontSize: 13, color: 'var(--t-fg-3)', textAlign: 'center' }}>PDF, photo, or import from Apple Health</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
                <HChip icon="plus" tone="cream">Browse files</HChip>
                <HChip icon="scan" tone="cream">Take photo</HChip>
              </div>
            </div>
          </HCard>
        </button>
        <div style={{ marginTop: 22 }}>
          <HSectionLabel>Past reports</HSectionLabel>
          <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
            {[
              { d: 'Apr 18, 2026', s: 'LabCorp · 14 markers · 2 flagged' },
              { d: 'Jan 04, 2026', s: 'Quest · 12 markers · all normal' },
              { d: 'Oct 22, 2025', s: 'LabCorp · 18 markers · 3 flagged' },
            ].map((r, i) => (
              <button key={i} onClick={() => setStep('results')} style={{ width: '100%', display: 'flex', alignItems: 'center', padding: '14px', textAlign: 'left', background: 'transparent', borderBottom: i < 2 ? '1px solid var(--t-border)' : 'none', color: 'var(--t-fg-1)', gap: 12 }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--t-ink-04)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Glyph name="droplet" size={16}/>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{r.d}</div>
                  <div style={{ fontSize: 12, color: 'var(--t-fg-3)', marginTop: 1 }}>{r.s}</div>
                </div>
                <Glyph name="chevR" size={14} style={{ color: 'var(--t-fg-3)' }}/>
              </button>
            ))}
          </HCard>
        </div>
      </HScreen>
    );
  }

  if (step === 'parsing') {
    return <LoaderScreen label="Reading your panel" steps={['Decoding markers', 'Matching reference ranges', 'Cross-checking your trends']} onDone={() => setStep('results')}/>;
  }

  if (step === 'marker' && markerIndex != null) {
    const m = markers[markerIndex];
    const statusColor = m.status === 'normal' ? 'var(--success)' : m.status === 'fair' ? 'var(--warning)' : 'var(--error)';
    const statusLabel = m.status === 'normal' ? 'Normal' : m.status === 'fair' ? 'Fair' : 'Needs attention';
    return (
      <HScreen label="Marker detail">
        <HTopBar title={m.name} onBack={() => setStep('results')}/>
        <HCard pad="20px" radius={22} style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div className="h-label">Current</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 4 }}>{m.value}<span style={{ fontSize: 16, color: 'var(--t-fg-3)' }}> {m.unit}</span></div>
              <div style={{ fontSize: 12, color: 'var(--t-fg-3)', marginTop: 4 }}>Reference {m.range}</div>
            </div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 999, background: `color-mix(in oklab, ${statusColor} 14%, transparent)`, color: statusColor, fontSize: 12, fontWeight: 600 }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: statusColor }}/>{statusLabel}
            </div>
          </div>
          <div style={{ marginTop: 16, padding: '10px 12px', background: 'var(--t-ink-04)', borderRadius: 12, fontSize: 13, color: 'var(--t-fg-2)' }}>
            {m.delta.startsWith('−') ? 'Down' : m.delta.startsWith('+') ? 'Up' : 'Flat'} {m.delta.replace('−','').replace('+','')} since last test.
          </div>
        </HCard>
        <HSectionLabel>Why this matters</HSectionLabel>
        <HCard pad="16px" radius={18} style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <HAnnaAvatar size={32}/>
            <div style={{ flex: 1, fontSize: 14, lineHeight: 1.55 }}>{m.why}</div>
          </div>
        </HCard>
        <HPrimaryButton variant="gradient" full size="lg" icon="voice" onClick={() => onNavigate('chat', { topic: m.name, reportId: 'bw-2026-04-18', focus: 'bloodwork', newThread: true })}>Discuss with Anna</HPrimaryButton>
      </HScreen>
    );
  }

  // results
  return (
    <HScreen label="Bloodwork · results">
      <HTopBar title="Bloodwork" onBack={() => setStep('upload')} right={<HIconButton icon="share" tone="soft"/>}/>
      <HCard pad="16px" radius={20} style={{ marginBottom: 16, background: 'var(--grad-cream, linear-gradient(180deg,#FFF6EE,#fff))' }} elevate={false}>
        <div className="h-label">Apr 18, 2026 · LabCorp</div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 6 }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500 }}>14 markers</div>
            <div style={{ fontSize: 13, color: 'var(--t-fg-2)', marginTop: 2 }}>2 flagged · 1 needs follow-up</div>
          </div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 10px', background: 'var(--t-cream)', borderRadius: 12 }}>
            <div style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--warning)' }}/>
            <div style={{ fontSize: 12, fontWeight: 500 }}>Fair</div>
          </div>
        </div>
      </HCard>
      <HCard pad="14px" radius={18} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 10 }}>
          <HAnnaAvatar size={32}/>
          <div style={{ flex: 1, fontSize: 14, lineHeight: 1.5 }}>
            <strong style={{ fontWeight: 600 }}>Ferritin is low</strong> at 24 ng/mL. Not urgent, but iron-rich meals plus a low-dose supplement should bring it up. Want a plan?
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 10, marginLeft: 42 }}>
          <HChip icon="check" tone="cream">Make a plan</HChip>
          <HChip tone="ghost">Why?</HChip>
        </div>
      </HCard>
      <HSectionLabel>All markers</HSectionLabel>
      <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
        {markers.map((m, i) => (
          <button key={i} onClick={() => { setMarkerIndex(i); setStep('marker'); }} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px', textAlign: 'left', background: 'transparent', borderBottom: i < markers.length - 1 ? '1px solid var(--t-border)' : 'none', color: 'var(--t-fg-1)' }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: m.status === 'normal' ? 'var(--success)' : m.status === 'fair' ? 'var(--warning)' : 'var(--error)' }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{m.name}</div>
              <div style={{ fontSize: 11, color: 'var(--t-fg-3)', marginTop: 1 }}>range {m.range}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 500 }}>{m.value}<span style={{ fontSize: 11, color: 'var(--t-fg-3)', fontFamily: 'var(--font-body)', fontWeight: 400 }}> {m.unit}</span></div>
              <div style={{ fontSize: 10, color: m.delta.startsWith('+') ? 'var(--success)' : m.delta.startsWith('−') ? 'var(--error)' : 'var(--t-fg-3)', fontWeight: 500 }}>{m.delta} since last</div>
            </div>
            <Glyph name="chevR" size={14} style={{ color: 'var(--t-fg-3)' }}/>
          </button>
        ))}
      </HCard>
    </HScreen>
  );
}

// ==========================================================================
// DNA FLOW
// ==========================================================================
function DNAFlowScreen({ onNavigate, onBack }) {
  const [step, setStep] = React.useState('connect'); // connect | importing | traits | trait
  const [traitIndex, setTraitIndex] = React.useState(null);

  const traits = [
    { tag: 'Metabolism', color: 'var(--focus-nutrition)', t: 'Slow caffeine metabolizer', s: 'Cut off coffee by 11am — sleep on you depends on it.', detail: 'Your CYP1A2 variant means caffeine sticks around twice as long. Late coffee correlates strongly with your worst sleep nights.' },
    { tag: 'Heart',      color: 'var(--focus-heart)',     t: 'Higher sensitivity to sodium', s: 'Aim for <1,500 mg/day to manage BP.', detail: 'Salt-sensitive hypertension variants are present. Sodium reduction will move your BP more than most people.' },
    { tag: 'Fitness',    color: 'var(--focus-fitness)',   t: 'Endurance > Power', s: 'Your fast-twitch muscle ratio is lower — favor Zone 2.', detail: 'ACTN3 variant. Zone 2 cardio and long-duration efforts will produce more gains than max-power lifting.' },
    { tag: 'Sleep',      color: 'var(--focus-sleep)',     t: 'Natural early bird', s: 'Your chronotype peaks 6-8am. Schedule deep work then.', detail: 'PER3 and CLOCK variants suggest morning chronotype. Pushing bedtime past 11pm costs you disproportionately.' },
  ];

  if (step === 'connect') {
    return (
      <HScreen label="DNA · connect">
        <HTopBar title="" onBack={onBack}/>
        <div style={{ padding: '0 4px', marginBottom: 18 }}>
          <div className="h-label">AI tool</div>
          <div className="h-display" style={{ fontSize: 30, marginTop: 4 }}>DNA insights</div>
          <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 6, lineHeight: 1.5 }}>Connect your raw DNA file (23andMe / AncestryDNA) so Anna can tune everything to your genome.</div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 16 }}>
          {[
            { i: 'scan',    t: '23andMe',     s: 'Sign in to import raw data.' },
            { i: 'scan',    t: 'AncestryDNA', s: 'Sign in to import raw data.' },
            { i: 'plus',    t: 'Upload raw file', s: '.txt or .vcf from any provider.' },
          ].map(o => (
            <HCard key={o.t} pad="14px" radius={16} onClick={() => setStep('importing')}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 38, height: 38, borderRadius: 12, background: 'var(--t-cream)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Glyph name={o.i} size={18}/>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{o.t}</div>
                  <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>{o.s}</div>
                </div>
                <Glyph name="chevR" size={14} style={{ color: 'var(--t-fg-3)' }}/>
              </div>
            </HCard>
          ))}
        </div>
        <HCard pad="14px" radius={16} tone="cream" elevate={false}>
          <div style={{ display: 'flex', gap: 10 }}>
            <Glyph name="shield" size={20} style={{ color: 'var(--brand-orange-vibey)' }}/>
            <div style={{ flex: 1, fontSize: 12, color: 'var(--t-fg-2)', lineHeight: 1.5 }}>Your raw file stays encrypted on your device. Anna only sees the trait read-outs, never your full genome.</div>
          </div>
        </HCard>
      </HScreen>
    );
  }

  if (step === 'importing') {
    return <LoaderScreen label="Importing your DNA" steps={['Reading the raw file', 'Mapping 142 actionable traits', 'Building your recommendations']} onDone={() => setStep('traits')} dur={2400}/>;
  }

  if (step === 'trait' && traitIndex != null) {
    const t = traits[traitIndex];
    return (
      <HScreen label="Trait detail">
        <HTopBar title={t.t} onBack={() => setStep('traits')}/>
        <HCard pad="18px" radius={22} style={{ marginBottom: 16 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 8px', background: `color-mix(in oklab, ${t.color} 14%, transparent)`, color: t.color, borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
            <span style={{ width: 5, height: 5, borderRadius: 999, background: t.color }}/>{t.tag}
          </div>
          <div style={{ marginTop: 10, fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>{t.t}</div>
          <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 8, lineHeight: 1.55 }}>{t.detail}</div>
        </HCard>
        <HSectionLabel>What to do</HSectionLabel>
        <HCard pad="14px" radius={18}>
          <div style={{ display: 'flex', gap: 10 }}>
            <HAnnaAvatar size={32}/>
            <div style={{ flex: 1, fontSize: 14, lineHeight: 1.55 }}>{t.s}</div>
          </div>
        </HCard>
        <div style={{ height: 16 }}/>
        <HPrimaryButton variant="gradient" full size="lg" icon="voice" onClick={() => onNavigate('chat', { topic: t.t, focus: 'dna', newThread: true })}>Ask Anna more</HPrimaryButton>
      </HScreen>
    );
  }

  // traits
  return (
    <HScreen label="DNA · traits">
      <HTopBar title="DNA insights" onBack={() => setStep('connect')}/>
      <div style={{ padding: '0 4px', marginBottom: 18 }}>
        <div style={{ fontSize: 14, color: 'var(--t-fg-2)', lineHeight: 1.5 }}>23andMe synced · 142 traits decoded. The 4 most actionable for you:</div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 16 }}>
        {traits.map((t, i) => (
          <HCard key={i} pad="16px" radius={20} onClick={() => { setTraitIndex(i); setStep('trait'); }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 8px', background: `color-mix(in oklab, ${t.color} 14%, transparent)`, color: t.color, borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
              <span style={{ width: 5, height: 5, borderRadius: 999, background: t.color }}/>{t.tag}
            </div>
            <div style={{ marginTop: 8, fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500, letterSpacing: '-0.02em' }}>{t.t}</div>
            <div style={{ fontSize: 13, color: 'var(--t-fg-2)', marginTop: 6, lineHeight: 1.5 }}>{t.s}</div>
          </HCard>
        ))}
      </div>
      <HPrimaryButton variant="ghost" full icon="plus" size="md">View all 142 traits</HPrimaryButton>
    </HScreen>
  );
}

// ==========================================================================
// MEAL PLANNER FLOW
// ==========================================================================
function MealPlannerFlowScreen({ onNavigate, onBack }) {
  const [step, setStep] = React.useState('prefs'); // prefs | generating | plan | grocery
  const [diet, setDiet] = React.useState('omnivore');
  const [protein, setProtein] = React.useState(120);
  const [days, setDays] = React.useState(3);
  const [allergies, setAllergies] = React.useState({});

  const toggleAllergy = (k) => setAllergies(a => ({ ...a, [k]: !a[k] }));

  if (step === 'prefs') {
    return (
      <HScreen label="Meal plan · preferences">
        <HTopBar title="" onBack={onBack}/>
        <div style={{ padding: '0 4px', marginBottom: 16 }}>
          <div className="h-label">Step 1 of 3</div>
          <div className="h-display" style={{ fontSize: 26, marginTop: 4 }}>How do you eat?</div>
        </div>

        <HSectionLabel>Diet</HSectionLabel>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, marginBottom: 16 }}>
          {['omnivore','pescatarian','vegetarian','vegan'].map(d => {
            const a = diet === d;
            return (
              <button key={d} onClick={() => setDiet(d)} style={{ padding: '14px', borderRadius: 16, background: a ? 'var(--t-cream)' : 'var(--t-surface)', border: a ? '2px solid var(--brand-orange-vibey)' : '2px solid transparent', boxShadow: 'var(--shadow-md)', color: 'var(--t-fg-1)', fontSize: 14, fontWeight: 500, textTransform: 'capitalize' }}>{d}</button>
            );
          })}
        </div>

        <HSectionLabel>Allergies / avoid</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
          {['Gluten','Dairy','Eggs','Nuts','Shellfish','Soy'].map(a => (
            <HChip key={a} tone={allergies[a] ? 'cream' : 'ghost'} onClick={() => toggleAllergy(a)} icon={allergies[a] ? 'check' : null}>{a}</HChip>
          ))}
        </div>

        <HSectionLabel>Protein target</HSectionLabel>
        <HCard pad="16px" radius={18} style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
            <span style={{ fontSize: 13, color: 'var(--t-fg-2)' }}>Daily target</span>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600 }}>{protein}<span style={{ fontSize: 12, color: 'var(--t-fg-3)' }}> g</span></span>
          </div>
          <input type="range" min={60} max={200} step={5} value={protein} onChange={(e) => setProtein(+e.target.value)} style={{ width: '100%', accentColor: 'var(--brand-orange-vibey)' }}/>
        </HCard>

        <HSectionLabel>How many days?</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
          {[1, 3, 7].map(n => (
            <button key={n} onClick={() => setDays(n)} style={{ flex: 1, height: 44, borderRadius: 12, background: days === n ? 'var(--t-pill)' : 'var(--t-ink-04)', color: days === n ? 'var(--t-pill-fg)' : 'var(--t-fg-2)', fontSize: 13, fontWeight: 500 }}>{n} day{n>1?'s':''}</button>
          ))}
        </div>

        <HPrimaryButton variant="gradient" full size="lg" icon="sparkle" onClick={() => setStep('generating')}>Generate plan</HPrimaryButton>
      </HScreen>
    );
  }

  if (step === 'generating') {
    return <LoaderScreen label="Building your meal plan" steps={['Reading your last 14 days', `Honouring ${diet} + allergies`, `Hitting ${protein}g protein × ${days} days`]} onDone={() => setStep('plan')} dur={2400}/>;
  }

  if (step === 'grocery') {
    const groceries = [
      { c: 'Produce',  i: ['Spinach', 'Berries', 'Sweet potatoes', 'Lemons', 'Asparagus'] },
      { c: 'Protein',  i: ['Salmon × 2', 'Chicken breast × 3', 'Greek yogurt 32oz', 'Eggs × 12'] },
      { c: 'Pantry',   i: ['Steel-cut oats', 'Quinoa', 'Olive oil', 'Walnuts'] },
      { c: 'Dairy',    i: ['Cottage cheese', 'Almond milk'] },
    ];
    return (
      <HScreen label="Grocery list">
        <HTopBar title="Grocery list" onBack={() => setStep('plan')} right={<HIconButton icon="share" tone="soft"/>}/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {groceries.map((g, k) => (
            <div key={k}>
              <HSectionLabel>{g.c}</HSectionLabel>
              <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
                {g.i.map((item, i) => <CheckRow key={i} label={item} last={i === g.i.length - 1}/>)}
              </HCard>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 16 }}>
          <HPrimaryButton variant="gradient" full size="lg" icon="share">Send to grocery app</HPrimaryButton>
        </div>
      </HScreen>
    );
  }

  // plan
  return (
    <HScreen label="Meal plan">
      <HTopBar title="" onBack={() => setStep('prefs')} right={<HIconButton icon="refresh" tone="soft"/>}/>
      <div style={{ padding: '0 4px', marginBottom: 16 }}>
        <div className="h-label">AI tool · ready</div>
        <div className="h-display" style={{ fontSize: 26, marginTop: 4 }}>Your {days}-day plan</div>
        <div style={{ fontSize: 13, color: 'var(--t-fg-2)', marginTop: 4 }}>{diet} · {protein}g protein · low sodium</div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[
          { t: 'Breakfast', n: 'Steel-cut oats + berries + walnuts', kcal: 410, p: 14 },
          { t: 'Lunch',     n: 'Grilled chicken + quinoa + greens',  kcal: 540, p: 38 },
          { t: 'Snack',     n: 'Greek yogurt + honey',               kcal: 180, p: 18 },
          { t: 'Dinner',    n: 'Salmon · sweet potato · asparagus',  kcal: 620, p: 42 },
        ].map((m, i) => (
          <HCard key={i} pad="14px" radius={18}>
            <div style={{ display: 'flex', gap: 12 }}>
              <div style={{ width: 60, height: 60, borderRadius: 14, background: 'color-mix(in oklab, var(--brand-orange-vibey) 10%, transparent)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Glyph name="plate" size={26}/>
              </div>
              <div style={{ flex: 1 }}>
                <div className="h-label">{m.t}</div>
                <div style={{ fontSize: 14, fontWeight: 500, marginTop: 2, letterSpacing: '-0.2px' }}>{m.n}</div>
                <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
                  <span style={{ fontSize: 11, color: 'var(--t-fg-3)' }}>{m.kcal} kcal</span>
                  <span style={{ fontSize: 11, color: 'var(--brand-orange-vibey)', fontWeight: 500 }}>{m.p}g protein</span>
                </div>
              </div>
              <button style={{ alignSelf: 'flex-start', width: 30, height: 30, borderRadius: 999, background: 'var(--t-ink-04)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--t-fg-1)' }} aria-label="Swap">
                <Glyph name="refresh" size={14}/>
              </button>
            </div>
          </HCard>
        ))}
      </div>
      <div style={{ marginTop: 16, display: 'flex', gap: 10 }}>
        <HPrimaryButton variant="ghost" full size="md" icon="copy" onClick={() => setStep('grocery')}>Grocery list</HPrimaryButton>
        <HPrimaryButton variant="gradient" full size="md" icon="check">Save plan</HPrimaryButton>
      </div>
    </HScreen>
  );
}

function CheckRow({ label, last }) {
  const [done, setDone] = React.useState(false);
  return (
    <button onClick={() => setDone(!done)} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '12px 14px', borderBottom: last ? 'none' : '1px solid var(--t-border)', background: 'transparent', color: 'var(--t-fg-1)', textAlign: 'left' }}>
      <HHabitCheck done={done} onClick={() => setDone(!done)}/>
      <span style={{ fontSize: 14, fontWeight: 500, textDecoration: done ? 'line-through' : 'none', color: done ? 'var(--t-fg-3)' : 'var(--t-fg-1)' }}>{label}</span>
    </button>
  );
}

// ==========================================================================
// FITNESS / WORKOUT FLOW
// ==========================================================================
function WorkoutFlowScreen({ onNavigate, onBack }) {
  const [step, setStep] = React.useState('setup'); // setup | generating | plan | session | summary
  const [goal, setGoal] = React.useState('recovery');
  const [equip, setEquip] = React.useState('none');

  if (step === 'setup') {
    return (
      <HScreen label="Workout · setup">
        <HTopBar title="" onBack={onBack}/>
        <div style={{ padding: '0 4px', marginBottom: 16 }}>
          <div className="h-label">Step 1 of 2</div>
          <div className="h-display" style={{ fontSize: 26, marginTop: 4 }}>What's the goal?</div>
        </div>
        <HSectionLabel>Today</HSectionLabel>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, marginBottom: 16 }}>
          {[
            { k: 'recovery', t: 'Recovery',  s: 'Low-intensity reset', icon: 'heart' },
            { k: 'cardio',   t: 'Cardio',    s: 'Zone 2 stamina',      icon: 'flame' },
            { k: 'strength', t: 'Strength',  s: 'Build muscle',         icon: 'dumbbell' },
            { k: 'mobility', t: 'Mobility',  s: 'Long stretch',         icon: 'brain' },
          ].map(o => {
            const a = goal === o.k;
            return (
              <button key={o.k} onClick={() => setGoal(o.k)} style={{ padding: 14, borderRadius: 18, textAlign: 'left', background: a ? 'var(--t-cream)' : 'var(--t-surface)', border: a ? '2px solid var(--brand-orange-vibey)' : '2px solid transparent', boxShadow: 'var(--shadow-md)', color: 'var(--t-fg-1)' }}>
                <div style={{ width: 36, height: 36, borderRadius: 12, background: 'color-mix(in oklab, var(--brand-orange-vibey) 12%, transparent)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10 }}>
                  <Glyph name={o.icon} size={18}/>
                </div>
                <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{o.t}</div>
                <div style={{ fontSize: 11, color: 'var(--t-fg-3)', marginTop: 2 }}>{o.s}</div>
              </button>
            );
          })}
        </div>

        <HSectionLabel>Equipment</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 24 }}>
          {[
            { k: 'none',  t: 'Bodyweight only' },
            { k: 'mat',   t: 'Yoga mat' },
            { k: 'bands', t: 'Resistance bands' },
            { k: 'full',  t: 'Full gym' },
          ].map(e => (
            <HChip key={e.k} tone={equip === e.k ? 'cream' : 'ghost'} icon={equip === e.k ? 'check' : null} onClick={() => setEquip(e.k)}>{e.t}</HChip>
          ))}
        </div>

        <HPrimaryButton variant="gradient" full size="lg" icon="sparkle" onClick={() => setStep('generating')}>Build today's workout</HPrimaryButton>
      </HScreen>
    );
  }

  if (step === 'generating') {
    return <LoaderScreen label="Building your workout" steps={['Reading your recovery (HRV 48ms)', 'Honouring your BP context', `Sequencing the ${goal} session`]} onDone={() => setStep('plan')} dur={2200}/>;
  }

  if (step === 'session') {
    return <WorkoutSessionView goal={goal} onFinish={() => setStep('summary')} onBack={() => setStep('plan')}/>;
  }

  if (step === 'summary') {
    return (
      <HScreen label="Workout · summary">
        <HTopBar title="Nice work" onBack={() => setStep('plan')}/>
        <HCard pad="22px" radius={26} style={{ marginBottom: 16, background: 'linear-gradient(135deg, #2A2126, #3B2F2E)', color: '#fff' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <div className="h-label" style={{ color: 'rgba(255,255,255,0.55)' }}>Session complete</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 600, marginTop: 6 }}>20<span style={{ fontSize: 18, color: 'rgba(255,255,255,0.6)' }}> min</span></div>
              <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)', marginTop: 4 }}>Zone 2 · {goal}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-end' }}>
              <SummaryStat label="Calories" value="~118"/>
              <SummaryStat label="Avg HR" value="118 bpm"/>
              <SummaryStat label="Effort" value="Z2"/>
            </div>
          </div>
        </HCard>
        <HCard pad="14px" radius={18} style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <HAnnaAvatar size={32}/>
            <div style={{ flex: 1, fontSize: 14, lineHeight: 1.55 }}>Solid recovery session. Your BP usually drops 5–8 mmHg in the next 60 minutes — check it in.</div>
          </div>
        </HCard>
        <div style={{ display: 'flex', gap: 10 }}>
          <HPrimaryButton variant="ghost" full size="md" onClick={() => onNavigate('home')}>Done</HPrimaryButton>
          <HPrimaryButton variant="gradient" full size="md" icon="check" onClick={() => onNavigate('home')}>Save to Health</HPrimaryButton>
        </div>
      </HScreen>
    );
  }

  // plan
  return (
    <HScreen label="Workout · plan">
      <HTopBar title="" onBack={() => setStep('setup')}/>
      <HCard pad="0" radius={26} style={{ marginBottom: 16, overflow: 'hidden', background: 'linear-gradient(135deg, #2A2126, #3B2F2E)' }}>
        <div style={{ padding: '22px 18px', color: '#fff' }}>
          <div className="h-label" style={{ color: 'rgba(255,255,255,0.5)' }}>Today's workout</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 500, marginTop: 6 }}>{goal === 'recovery' ? 'Recovery walk + mobility' : goal === 'cardio' ? 'Zone 2 cardio' : goal === 'strength' ? 'Strength · push' : 'Long mobility'}</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.6)', marginTop: 4 }}>20 min · low intensity · for your BP</div>
          <div style={{ display: 'flex', gap: 18, marginTop: 16 }}>
            <SummaryStat label="Time" value="20 min" dark/>
            <SummaryStat label="Effort" value="Z2" dark/>
            <SummaryStat label="Kcal" value="~120" dark/>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
            <button onClick={() => setStep('session')} style={{ flex: 1, height: 44, borderRadius: 999, background: '#fff', color: 'var(--brand-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, fontWeight: 500, fontSize: 14 }}>
              <Glyph name="arrowR" size={16}/> Start session
            </button>
            <button onClick={() => setStep('setup')} style={{ width: 44, height: 44, borderRadius: 999, background: 'rgba(255,255,255,0.12)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }} aria-label="Rebuild">
              <Glyph name="refresh" size={16}/>
            </button>
          </div>
        </div>
      </HCard>
      <HSectionLabel>Exercises</HSectionLabel>
      <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
        {['Easy walk · 10 min Z2','Cat-cow · 8 slow','Hip circles · 5 each side','Forward fold · 60s hold','Walk-out + push · 6 reps','Cool down · 3 min'].map((line, i, arr) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px', borderBottom: i < arr.length - 1 ? '1px solid var(--t-border)' : 'none' }}>
            <div style={{ width: 26, height: 26, borderRadius: 999, background: 'var(--t-ink-04)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontSize: 12, fontWeight: 600, color: 'var(--t-fg-2)' }}>{i+1}</div>
            <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{line}</span>
          </div>
        ))}
      </HCard>
    </HScreen>
  );
}

function WorkoutSessionView({ goal, onFinish, onBack }) {
  const [exercises, setExercises] = React.useState([
    { n: 'Easy walk',  sub: '10 min Z2',     done: false },
    { n: 'Cat-cow',    sub: '8 reps slow',   done: false },
    { n: 'Hip circles',sub: '5 each side',   done: false },
    { n: 'Forward fold', sub: '60s hold',    done: false },
    { n: 'Walk-out',   sub: '6 reps',        done: false },
    { n: 'Cool down',  sub: '3 min stretch', done: false },
  ]);
  const [elapsed, setElapsed] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setElapsed(e => e + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const done = exercises.filter(e => e.done).length;
  const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
  const ss = String(elapsed % 60).padStart(2, '0');
  const toggle = (i) => setExercises(es => es.map((e, j) => j === i ? { ...e, done: !e.done } : e));
  return (
    <HScreen label="Workout · session">
      <HTopBar title="" onBack={onBack}/>
      <HCard pad="20px" radius={26} style={{ marginBottom: 16, background: 'linear-gradient(135deg, #2A2126, #3B2F2E)', color: '#fff' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <div>
            <div className="h-label" style={{ color: 'rgba(255,255,255,0.5)' }}>{goal} · live</div>
            <div style={{ fontFamily: 'var(--font-mono, ui-monospace)', fontSize: 36, fontWeight: 500, letterSpacing: '0.02em', marginTop: 6 }}>{mm}:{ss}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="h-label" style={{ color: 'rgba(255,255,255,0.5)' }}>Done</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 600 }}>{done}<span style={{ color: 'rgba(255,255,255,0.6)' }}> / {exercises.length}</span></div>
          </div>
        </div>
      </HCard>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
        {exercises.map((ex, i) => (
          <HCard key={i} pad="14px" radius={14}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <HHabitCheck done={ex.done} onClick={() => toggle(i)}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px', textDecoration: ex.done ? 'line-through' : 'none', color: ex.done ? 'var(--t-fg-3)' : 'var(--t-fg-1)' }}>{ex.n}</div>
                <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>{ex.sub}</div>
              </div>
            </div>
          </HCard>
        ))}
      </div>
      <HPrimaryButton variant="gradient" full size="lg" icon="check" onClick={onFinish}>Finish session</HPrimaryButton>
    </HScreen>
  );
}

function SummaryStat({ label, value, dark }) {
  return (
    <div style={{ textAlign: dark ? 'left' : 'right' }}>
      <div style={{ fontSize: 10, color: dark ? 'rgba(255,255,255,0.5)' : 'var(--t-fg-3)', textTransform: 'uppercase', letterSpacing: 0.8, fontWeight: 600 }}>{label}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 500, color: dark ? '#fff' : 'var(--t-fg-1)' }}>{value}</div>
    </div>
  );
}

// ==========================================================================
// VOICE FLOW
// ==========================================================================
function VoiceFlowScreen({ onNavigate, onBack }) {
  const [step, setStep] = React.useState('preflight'); // preflight | live | transcript | summary

  if (step === 'preflight') {
    return (
      <HScreen label="Voice · preflight">
        <HTopBar title="" onBack={onBack}/>
        <div style={{ padding: '0 4px', marginBottom: 18 }}>
          <div className="h-label">Before we start</div>
          <div className="h-display" style={{ fontSize: 28, marginTop: 4 }}>Voice with Anna</div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 16 }}>
          {[
            { i: 'mic',     t: 'Microphone',           s: 'Allow when prompted.' },
            { i: 'voice',   t: 'Quiet room helps',     s: 'Anna interrupts less.' },
            { i: 'shield',  t: 'Voice is private',     s: 'Transcript stays on your device.' },
          ].map(o => (
            <HCard key={o.t} pad="14px" radius={16}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 38, height: 38, borderRadius: 12, background: 'var(--t-cream)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Glyph name={o.i} size={18}/>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{o.t}</div>
                  <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>{o.s}</div>
                </div>
              </div>
            </HCard>
          ))}
        </div>
        <HPrimaryButton variant="gradient" full size="lg" icon="mic" onClick={() => setStep('live')}>Start session</HPrimaryButton>
      </HScreen>
    );
  }

  if (step === 'transcript') {
    return (
      <HScreen label="Voice · transcript">
        <HTopBar title="Transcript" onBack={() => setStep('live')}/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { from: 'user', text: 'My BP read 132/86 this morning.' },
            { from: 'anna', text: `Hi ${(window.HEALIFY_USER && window.HEALIFY_USER.first) || 'Kathryn'} — you're right to flag that. 132/86 is in Stage 1 territory. Two days in a row?` },
            { from: 'user', text: 'Yeah, second day. Should I be worried?' },
            { from: 'anna', text: 'Not alarming, but worth steering down. Three things would help most: cut sodium under 1,500mg today, walk 20 minutes after lunch, and skip the evening wine for the next two weeks. I can set you up.' },
            { from: 'user', text: 'Yes please.' },
            { from: 'anna', text: 'Done. I queued a low-sodium meal swap and dropped a 6:30pm walking reminder on your calendar. We\'ll re-check Friday morning.' },
          ].map((m, i) => (
            <HChatBubble key={i} from={m.from} delay={i * 80}>{m.text}</HChatBubble>
          ))}
        </div>
        <div style={{ marginTop: 16 }}>
          <HPrimaryButton variant="gradient" full size="lg" icon="check" onClick={() => setStep('summary')}>End & summarize</HPrimaryButton>
        </div>
      </HScreen>
    );
  }

  if (step === 'summary') {
    return (
      <HScreen label="Voice · summary">
        <HTopBar title="Session summary" onBack={() => setStep('transcript')}/>
        <HCard pad="20px" radius={22} style={{ marginBottom: 16 }}>
          <div className="h-label">3 min · BP check-in</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, marginTop: 6 }}>Steering BP down</div>
          <div style={{ fontSize: 14, color: 'var(--t-fg-2)', marginTop: 8, lineHeight: 1.55 }}>You flagged 132/86. I queued sodium ≤ 1,500mg today, a 6:30pm walk, and two weeks no evening wine. Re-check Friday morning.</div>
        </HCard>
        <HSectionLabel>What I'll do</HSectionLabel>
        <HCard pad="14px" radius={18} style={{ marginBottom: 16 }}>
          <HNumberedActions items={[
            { title: 'Swap your lunch to low-sodium', body: 'I queued grilled chicken bowl instead of deli.' },
            { title: 'Set a 6:30pm walking reminder', body: 'On your calendar.' },
            { title: 'Re-check BP Friday 7am', body: 'I\'ll ping you.' },
          ]}/>
        </HCard>
        <div style={{ display: 'flex', gap: 10 }}>
          <HPrimaryButton variant="ghost" full size="md" onClick={() => onNavigate('home')}>Discard</HPrimaryButton>
          <HPrimaryButton variant="gradient" full size="md" icon="check" onClick={() => onNavigate('home')}>Save to Health</HPrimaryButton>
        </div>
      </HScreen>
    );
  }

  // live — reuse the VoiceCallScreen orb
  return <VoiceCallScreen onBack={() => setStep('transcript')}/>;
}

// ==========================================================================
// LOADER — shared loading screen used by every multi-step flow
// ==========================================================================
function LoaderScreen({ label, steps = [], onDone, dur = 2200 }) {
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    if (i >= steps.length - 1) {
      const t = setTimeout(() => onDone && onDone(), dur / 2);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setI(i + 1), dur / steps.length);
    return () => clearTimeout(t);
  }, [i, steps.length]);

  return (
    <HScreen label={label}>
      <div style={{ height: 80 }}/>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '0 24px' }}>
        <div style={{ width: 84, height: 84, borderRadius: 999, background: 'var(--grad-warm-orange)', boxShadow: 'var(--shadow-orange)', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'breathe 2.4s ease-in-out infinite' }}>
          <Glyph name="sparkle" size={36} style={{ color: '#fff' }}/>
        </div>
        <div className="h-display" style={{ fontSize: 22, marginTop: 20 }}>{label}</div>
        <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start' }}>
          {steps.map((s, k) => {
            const active = k <= i;
            return (
              <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 10, opacity: active ? 1 : 0.4, transition: 'opacity 400ms ease' }}>
                <div style={{ width: 18, height: 18, borderRadius: 999, background: active && k < i ? 'var(--success)' : active ? 'var(--brand-orange-vibey)' : 'var(--t-ink-12)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  {active && k < i ? <Glyph name="check" size={11} stroke={3}/> : null}
                </div>
                <span style={{ fontSize: 13, color: 'var(--t-fg-2)', fontWeight: 500 }}>{s}</span>
              </div>
            );
          })}
        </div>
      </div>
    </HScreen>
  );
}

Object.assign(window, {
  BloodworkFlowScreen, DNAFlowScreen, MealPlannerFlowScreen,
  WorkoutFlowScreen, VoiceFlowScreen, LoaderScreen,
});
