// Healify — Secondary / stack screens. Requires components.jsx + screens-primary.jsx.
// Every screen here is reachable through navigation, not a tab.

const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

// ══════════════════════════════════════════════════════════════════════════
// Menu (opens from Home avatar/logo)
// ══════════════════════════════════════════════════════════════════════════

function MenuScreen({ onNavigate, onBack }) {
  const mi = (d) => (<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{typeof d === 'string' ? <path d={d} /> : d}</svg>);
  const ICON = {
    profile: mi('M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM4 21c0-4 4-6 8-6s8 2 8 6'),
    settings: mi(<React.Fragment><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-2.81 1.17V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 8 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15H4.5a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 6 9.4l-.13-.22a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 11 6.6V4.5a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 2.81 1.17l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 11h.1a2 2 0 1 1 0 4h-.1Z" /></React.Fragment>),
    notifications: mi('M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9M13.7 21a2 2 0 0 1-3.4 0'),
    blood: mi('M12 3s-6 6.5-6 11a6 6 0 0 0 12 0c0-4.5-6-11-6-11Z'),
    dna: mi('M4 3c0 5 16 5 16 13M20 3C20 8 4 8 4 16M5 7h14M5 17h14'),
    habits: mi('M9 11l3 3L22 4M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11'),
    history: mi('M3 12a9 9 0 1 0 3-6.7M3 4v4h4M12 7v5l3 2'),
    tools: mi('M14.7 6.3a4 4 0 0 1-5.4 5.4l-5.6 5.6a2 2 0 1 0 2.8 2.8l5.6-5.6a4 4 0 0 1 5.4-5.4l-2.7 2.7-1.4-1.4Z'),
    upgrade: mi('M3 8l5 4 4-7 4 7 5-4-2 11H5Z'),
    logout: mi('M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9'),
  };
  const item = (icon, title, dest, detail, destructive) => ({ icon, title, dest, detail, destructive });
  const sections = [
    {
      title: 'Account',
      rows: [
        item(ICON.profile, 'Profile',        'profile'),
        item(ICON.settings, 'Settings',       'settings'),
        item(ICON.notifications, 'Notifications',  'notifications'),
      ],
    },
    {
      title: 'Health data',
      rows: [
        item(ICON.blood, 'Blood report',   'blood',    'Upload & scan'),
        item(ICON.dna, 'DNA insights',   'dna'),
        item(ICON.habits, 'Habits',         'habits'),
      ],
    },
    {
      title: 'Anna',
      rows: [
        item(ICON.history, 'Chat history',   'history'),
        item(ICON.tools, 'AI Tools',       'picks'),
      ],
    },
    {
      title: 'Membership',
      rows: [
        item(ICON.upgrade, 'Upgrade to Life+', 'paywall'),
      ],
    },
    {
      title: '',
      rows: [
        item(ICON.logout, 'Log out', null, null, true),
      ],
    },
  ];

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

      {/* Identity card */}
      <HCard style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 16, borderRadius: 20, marginBottom: 18 }} onClick={() => onNavigate('profile')}>
        <div style={{ width: 52, height: 52, borderRadius: 999, background: H.gradOrange, display: 'grid', placeItems: 'center', color: '#fff', fontFamily: H.body, fontWeight: 600, fontSize: 20 }}>K</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 17 }}>Kathryn Murphy</div>
          <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2 }}>kathryn@healify.ai · Free plan</div>
        </div>
        <HChevron />
      </HCard>

      {sections.map((sec, i) => (
        <div key={i} style={{ marginBottom: 18 }}>
          {sec.title && <HSectionLabel style={{ margin: '0 4px 8px' }}>{sec.title}</HSectionLabel>}
          <div style={{ background: '#fff', borderRadius: 16, overflow: 'hidden', boxShadow: '0 1px 2px rgba(3,4,13,0.04)' }}>
            {sec.rows.map((r, j) => (
              <div
                key={j}
                onClick={() => r.dest && onNavigate(r.dest)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                  borderBottom: j === sec.rows.length - 1 ? 'none' : '0.5px solid ' + H.border,
                  cursor: r.dest ? 'pointer' : 'default',
                }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 10, background: H.bgSecondary,
                  display: 'grid', placeItems: 'center', flexShrink: 0,
                  color: r.destructive ? H.danger : H.fg1,
                }}>{r.icon}</div>
                <div style={{ flex: 1, fontFamily: H.body, fontSize: 15, color: r.destructive ? H.danger : H.fg1 }}>{r.title}</div>
                {r.detail && <span style={{ fontFamily: H.body, fontSize: 13, color: H.fg2 }}>{r.detail}</span>}
                {r.dest && <HChevron />}
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Profile
// ══════════════════════════════════════════════════════════════════════════

function ProfileScreen({ onNavigate, onBack }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Profile" />

      <HCard style={{ padding: 20, textAlign: 'center', borderRadius: 22 }}>
        <div style={{ width: 88, height: 88, borderRadius: 999, background: H.gradOrange, margin: '0 auto', display: 'grid', placeItems: 'center', color: '#fff', fontFamily: H.display, fontWeight: 600, fontSize: 34 }}>K</div>
        <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 22, marginTop: 12 }}>Kathryn Murphy</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2 }}>Member since Feb 2026</div>
      </HCard>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Personal</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Age" detail="46" />
        <HSettingsRow title="Sex" detail="Female" />
        <HSettingsRow title="Height" detail="5′ 6″" />
        <HSettingsRow title="Weight" detail="148 lb" />
        <HSettingsRow title="Goals" detail="Longevity · Energy" isLast />
      </HSettingsGroup>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Health</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Conditions" detail="None" />
        <HSettingsRow title="Medications" detail="None" />
        <HSettingsRow title="Allergies" detail="Peanuts" isLast />
      </HSettingsGroup>

      <div style={{ marginTop: 20 }}>
        <HPrimaryButton type="outline" onClick={onBack}>Done</HPrimaryButton>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Settings
// ══════════════════════════════════════════════════════════════════════════

function SettingsScreen({ onNavigate, onBack }) {
  const [haptics, setHaptics] = useStateS(true);
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Settings" />

      <HSectionLabel style={{ margin: '4px 4px 10px' }}>Personal</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Account" detail="Kathryn Murphy" onClick={() => onNavigate('account')} />
        <HSettingsRow title="Notifications" onClick={() => onNavigate('notification-prefs')} />
        <HSettingsRow title="Privacy" onClick={() => onNavigate('privacy')} />
        <HSettingsRow title="Subscription" detail="Plus \u00B7 Annual" onClick={() => onNavigate('subscription')} isLast />
      </HSettingsGroup>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Device</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Integrations" detail="Apple Health \u00B7 Oura" onClick={() => onNavigate('integrations')} />
        <HSettingsRow title="Units & locale" detail="Imperial \u00B7 \u00B0F" onClick={() => onNavigate('units')} />
        <HSettingsRow title="Appearance" detail="System" onClick={() => onNavigate('appearance')} />
        <HSettingsRow title="Haptic feedback" toggle toggleOn={haptics} onClick={() => setHaptics(v => !v)} isLast />
      </HSettingsGroup>

      <HSectionLabel style={{ margin: '20px 4px 10px' }}>Support</HSectionLabel>
      <HSettingsGroup>
        <HSettingsRow title="Help" onClick={() => onNavigate('help')} />
        <HSettingsRow title="System status" detail="All systems normal" onClick={() => onNavigate('status')} />
        <HSettingsRow title="About" onClick={() => onNavigate('legal-about')} />
        <HSettingsRow title="Version" detail="2.4.1 (build 208)" isLast />
      </HSettingsGroup>

      <div style={{ marginTop: 20 }}>
        <HPrimaryButton type="outline" onClick={() => onNavigate('auth-splash')}>Sign out</HPrimaryButton>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Notifications (inbox)
// ══════════════════════════════════════════════════════════════════════════

function NotificationsScreen({ onNavigate, onBack }) {
  const items = [
    { t: 'Anna', body: 'How did you sleep last night? Quick 2-question check-in.', when: '2h', unread: true,  dest: () => onNavigate('chat', { topic: 'sleep-checkin' }) },
    { t: 'Blood pressure', body: 'Your reading is above your target. Tap to log context.', when: '5h', unread: true, dest: () => onNavigate('focus', { area: 'vitals' }) },
    { t: 'Weekly recap', body: 'Your Apr 14 – 20 summary is ready.', when: '1d', dest: () => onNavigate('tab:health') },
    { t: 'New meditation', body: "Anna added a 10-min ‘body scan' to your picks.", when: '2d', dest: () => onNavigate('picks') },
    { t: 'Reminder', body: 'Zone-2 walk planned for 5:30pm today.', when: '3d', dest: () => onNavigate('tab:fitness') },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Notifications" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map((n, i) => (
          <HCard key={i} onClick={n.dest} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '14px 16px', borderRadius: 18 }}>
            {n.unread && <span style={{ width: 8, height: 8, borderRadius: 999, background: H.orange, marginTop: 8, flexShrink: 0 }}/>}
            <div style={{ flex: 1, minWidth: 0, marginLeft: n.unread ? 0 : 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{n.t}</div>
                <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3 }}>{n.when}</div>
              </div>
              <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 2, lineHeight: 1.4 }}>{n.body}</div>
            </div>
          </HCard>
        ))}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Habits
// ══════════════════════════════════════════════════════════════════════════

function HabitsScreen({ onNavigate, onBack }) {
  const [habits, setHabits] = useStateS([
    { k: 'water',   name: 'Drink 2L water',     streak: 12, done: true,  color: 'var(--focus-mental-100)', freq: 'Daily',    time: '08:00' },
    { k: 'walk',    name: '30-min zone-2 walk', streak: 6,  done: true,  color: 'var(--focus-fitness-100)', freq: 'Daily',   time: '17:30' },
    { k: 'stretch', name: '5-min stretch',      streak: 3,  done: false, color: 'var(--focus-sleep-100)',   freq: 'Daily',   time: '22:00' },
    { k: 'screen',  name: 'No screens 9pm',     streak: 1,  done: false, color: 'var(--quartz-150)',        freq: 'Daily',   time: '21:00' },
    { k: 'journal', name: 'Journal 3 lines',    streak: 0,  done: false, color: 'var(--focus-heart-100)',   freq: 'Weekdays',time: '21:30' },
  ]);
  const [sheet, setSheet] = useStateS(null); // null | { mode: 'add' } | { mode: 'edit', k }
  const toggle = (k) => setHabits(hs => hs.map(h => h.k === k ? { ...h, done: !h.done } : h));
  const onSave = (data) => {
    if (sheet?.mode === 'add') {
      const k = 'h' + Date.now();
      setHabits(hs => [...hs, { k, name: data.name, freq: data.freq, time: data.time, color: data.color, streak: 0, done: false }]);
    } else if (sheet?.mode === 'edit') {
      setHabits(hs => hs.map(h => h.k === sheet.k ? { ...h, ...data } : h));
    }
    setSheet(null);
  };
  const onDelete = (k) => { setHabits(hs => hs.filter(h => h.k !== k)); setSheet(null); };
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Habits" />

      <HCard style={{ padding: 18, display: 'flex', alignItems: 'center', gap: 14, borderRadius: 20, marginBottom: 18 }}>
        <div style={{ width: 70, height: 70, borderRadius: 999, background: `conic-gradient(${H.orange} 0 40%, var(--bg-app) 40% 100%)`, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          <div style={{ width: 56, height: 56, borderRadius: 999, background: '#fff', display: 'grid', placeItems: 'center' }}>
            <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 18 }}>2/5</div>
          </div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 17 }}>Today's habits</div>
          <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 3 }}>Keep your 12-day water streak alive</div>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '0 4px 10px' }}>Routines</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {habits.map(h => (
          <HCard key={h.k} onClick={() => setSheet({ mode: 'edit', k: h.k })} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }}>
            <div onClick={e => { e.stopPropagation(); toggle(h.k); }} style={{
              width: 28, height: 28, borderRadius: 999,
              background: h.done ? H.success : 'transparent',
              border: '2px solid ' + (h.done ? H.success : H.border),
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              {h.done && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, color: H.fg1, textDecoration: h.done ? 'line-through' : 'none', opacity: h.done ? 0.55 : 1 }}>{h.name}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 1 }}>{h.streak}-day streak · {h.freq || 'Daily'} · {h.time || '08:00'}</div>
            </div>
            <HIconTile color={h.color} alpha={0.14} size={36}>{HIcons.fitness(h.color)}</HIconTile>
          </HCard>
        ))}
      </div>

      <div style={{ marginTop: 20 }}>
        <HPrimaryButton type="outline" onClick={() => setSheet({ mode: 'add' })}>+ Add habit</HPrimaryButton>
      </div>

      {sheet && (
        <AddHabitSheet
          mode={sheet.mode}
          habit={sheet.mode === 'edit' ? habits.find(h => h.k === sheet.k) : null}
          onClose={() => setSheet(null)}
          onSave={onSave}
          onDelete={sheet.mode === 'edit' ? () => onDelete(sheet.k) : null}
        />
      )}
    </div>
  );
}

// Add / edit habit sheet --------------------------------------------------
function AddHabitSheet({ mode, habit, onClose, onSave, onDelete }) {
  const [name, setName] = useStateS(habit?.name || '');
  const [freq, setFreq] = useStateS(habit?.freq || 'Daily');
  const [time, setTime] = useStateS(habit?.time || '08:00');
  const COLORS = [
    'var(--focus-mental-100)',
    'var(--focus-fitness-100)',
    'var(--focus-sleep-100)',
    'var(--quartz-150)',
    'var(--focus-heart-100)',
    'var(--brand-orange)',
  ];
  const [color, setColor] = useStateS(habit?.color || COLORS[0]);
  const FREQS = ['Daily', 'Weekdays', 'Weekly'];
  const canSave = name.trim().length > 0;

  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: '88%', 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 16px' }}/>
        <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, marginBottom: 14 }}>{mode === 'add' ? 'New habit' : 'Edit habit'}</div>

        <HSectionLabel style={{ margin: '0 0 8px' }}>Name</HSectionLabel>
        <HCard style={{ padding: 0, marginBottom: 16 }}>
          <input
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="e.g. Morning meditation"
            style={{
              width: '100%', border: 0, outline: 'none', background: 'transparent',
              padding: '14px 16px', borderRadius: 16, boxSizing: 'border-box',
              fontFamily: H.body, fontSize: 15, color: H.fg1,
            }}
          />
        </HCard>

        <HSectionLabel style={{ margin: '0 0 8px' }}>Frequency</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
          {FREQS.map(f => (
            <div key={f} onClick={() => setFreq(f)} style={{
              flex: 1, textAlign: 'center', padding: '10px 12px', borderRadius: 999, cursor: 'pointer',
              background: freq === f ? H.black : '#fff', color: freq === f ? '#fff' : H.fg1,
              fontFamily: H.body, fontWeight: 500, fontSize: 13,
              boxShadow: freq === f ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
            }}>{f}</div>
          ))}
        </div>

        <HSectionLabel style={{ margin: '0 0 8px' }}>Reminder</HSectionLabel>
        <HCard style={{ padding: 0, marginBottom: 16 }}>
          <input
            type="time"
            value={time}
            onChange={e => setTime(e.target.value)}
            style={{
              width: '100%', border: 0, outline: 'none', background: 'transparent',
              padding: '14px 16px', borderRadius: 16, boxSizing: 'border-box',
              fontFamily: H.body, fontSize: 15, color: H.fg1,
            }}
          />
        </HCard>

        <HSectionLabel style={{ margin: '0 0 8px' }}>Color</HSectionLabel>
        <div style={{ display: 'flex', gap: 10, marginBottom: 22, flexWrap: 'wrap' }}>
          {COLORS.map(c => (
            <div key={c} onClick={() => setColor(c)} style={{
              width: 36, height: 36, borderRadius: 999, cursor: 'pointer',
              background: c, border: color === c ? `2.5px solid ${H.orange}` : '2.5px solid transparent',
              boxShadow: '0 1px 2px rgba(3,4,13,0.08)',
            }}/>
          ))}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <HPrimaryButton onClick={() => canSave && onSave({ name: name.trim(), freq, time, color })}>{mode === 'add' ? 'Add habit' : 'Save changes'}</HPrimaryButton>
          {onDelete && (
            <div onClick={onDelete} style={{
              textAlign: 'center', padding: '12px 0', cursor: 'pointer',
              fontFamily: H.body, fontWeight: 500, fontSize: 14, color: H.danger,
            }}>Delete habit</div>
          )}
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Blood report upload / insights
// ══════════════════════════════════════════════════════════════════════════

function _BloodReportScreen_LEGACY_UNUSED({ onNavigate, onBack }) {
  const [stage, setStage] = useStateS('upload'); // upload | scanning | results
  useEffectS(() => {
    if (stage === 'scanning') {
      const t = setTimeout(() => setStage('results'), 1800);
      return () => clearTimeout(t);
    }
  }, [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' },
  ];

  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: '#FFEEE8', 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')} icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" 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"/></svg>}>Upload PDF</HPrimaryButton>
              <HPrimaryButton type="outline" onClick={() => setStage('scanning')} icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>}>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>
        </>
      )}

      {stage === 'scanning' && (
        <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)' }}>
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ animation: 'hSpin 1.3s linear infinite' }}>
              <circle cx="12" cy="12" r="9" opacity="0.3"/>
              <path d="M12 3a9 9 0 0 1 9 9"/>
            </svg>
            <style>{`@keyframes hSpin { to { transform: rotate(360deg); } }`}</style>
          </div>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, marginTop: 16 }}>Scanning your report…</div>
          <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 4 }}>Extracting markers and comparing ranges</div>
        </HCard>
      )}

      {stage === 'results' && (
        <>
          <HCard style={{ padding: 18, borderRadius: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: 14, background: '#FFEEE8', 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 }}>
            <HPrimaryButton onClick={() => onNavigate('chat', { topic: 'blood' })}>Chat with Anna about your results</HPrimaryButton>
          </div>
        </>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// DNA insights
// ══════════════════════════════════════════════════════════════════════════

function _DNAScreen_LEGACY_UNUSED({ onNavigate, onBack }) {
  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)' },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="DNA insights" />

      <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 Mar 12</div>
          </div>
        </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 }}>
        <HPrimaryButton onClick={() => onNavigate('chat', { topic: 'dna' })}>Ask Anna about your DNA</HPrimaryButton>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// AI Tools / Picks
// ══════════════════════════════════════════════════════════════════════════

function PicksScreen({ onNavigate, onBack }) {
  const picks = [
    { k: 'mealplan',  name: 'Meal plan',       sub: '7-day personalized recipes', color: 'var(--brand-orange-vibey)', dest: 'mealplan' },
    { k: 'workout',   name: 'Workout plan',    sub: 'Strength + cardio weekly',   color: 'var(--focus-fitness-100)', dest: 'workout' },
    { k: 'meditate',  name: 'Meditation',      sub: 'Guided sessions 5–20 min',   color: 'var(--focus-sleep-100)', dest: 'meditation' },
    { k: 'voice',     name: 'Voice with Anna', sub: 'Hands-free coaching call',   color: 'var(--brand-ink)', dest: 'voice' },
    { k: 'habits',    name: 'Habit tracking',  sub: 'Build routines with Anna',   color: 'var(--quartz-150)', dest: 'habits' },
    { k: 'blood',     name: 'Blood report',    sub: 'Upload & insights',          color: 'var(--focus-heart-100)', dest: 'blood' },
    { k: 'dna',       name: 'DNA insights',    sub: 'Genetic trait analysis',     color: 'var(--focus-mental-100)', dest: 'dna' },
    { k: 'bp',        name: 'BP tracker',      sub: 'Log + trend line',           color: 'var(--focus-sleep-100)', dest: () => onNavigate('focus', { area: 'vitals' }) },
    { k: 'sleep',     name: 'Sleep coach',     sub: 'Unwind & wind-down',         color: 'var(--focus-sleep)', dest: () => onNavigate('focus', { area: 'sleep' }) },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="AI Tools" />

      <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 20, marginBottom: 4, letterSpacing: -0.3 }}>
        What would you like Anna to help with?
      </div>
      <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginBottom: 18 }}>
        Tap any tool to get started.
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {picks.map(p => (
          <HCard key={p.k} onClick={() => typeof p.dest === 'function' ? p.dest() : onNavigate(p.dest)} style={{ padding: 16, borderRadius: 18 }}>
            <HIconTile color={p.color} alpha={0.18} size={44}>
              {p.k === 'mealplan' && HIcons.nutrition(p.color)}
              {p.k === 'workout'  && HIcons.fitness(p.color)}
              {p.k === 'meditate' && HIcons.mind(p.color)}
              {p.k === 'habits'   && HIcons.fitness(p.color)}
              {p.k === 'blood'    && HIcons.vitals(p.color)}
              {p.k === 'dna'      && HIcons.vitals(p.color)}
              {p.k === 'bp'       && HIcons.vitals(p.color)}
              {p.k === 'sleep'    && HIcons.sleep(p.color)}
              {p.k === 'voice'    && HIcons.mind(p.color)}
            </HIconTile>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, marginTop: 12 }}>{p.name}</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2, lineHeight: 1.35 }}>{p.sub}</div>
          </HCard>
        ))}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Meal plan detail (weekly recipes)
// ══════════════════════════════════════════════════════════════════════════

function _MealPlanScreen_LEGACY_UNUSED({ onNavigate, onBack }) {
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const [day, setDay] = useStateS(3);
  const planByDay = {
    3: [
      { 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: '🍜' },
    ],
  };
  const plan = planByDay[day] || planByDay[3];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Meal plan" />

      <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 }}>Thu · Apr 17</div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24, marginTop: 4 }}>1,830 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={() => onNavigate('chat', { topic: 'mealplan' })} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }}>
            <div style={{ width: 48, height: 48, borderRadius: 14, background: 'var(--quartz-cream-bg)', display: 'grid', placeItems: 'center', fontSize: 24, flexShrink: 0 }}>{m.img}</div>
            <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</div>
            </div>
            <HChevron />
          </HCard>
        ))}
      </div>

      <div style={{ marginTop: 20 }}>
        <HPrimaryButton onClick={() => onNavigate('chat', { topic: 'mealplan' })}>Swap a meal with Anna</HPrimaryButton>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Workout detail — moved to screens-tools-2.jsx (deep flow with session timer)
// ══════════════════════════════════════════════════════════════════════════

function _WorkoutScreen_LEGACY_UNUSED({ onNavigate, onBack, id = 'strength' }) {
  const workouts = {
    strength: {
      name: 'Full-body strength',
      length: '45 min',
      type: 'Strength · 3 rounds',
      color: 'var(--quartz-150)',
      steps: [
        { name: 'Goblet squat', reps: '4 × 10', rest: '60s' },
        { name: 'Incline dumbbell press', reps: '4 × 10', rest: '60s' },
        { name: 'Romanian deadlift', reps: '4 × 10', rest: '75s' },
        { name: 'Single-arm row', reps: '4 × 10/side', rest: '45s' },
        { name: 'Plank', reps: '3 × 45s', rest: '30s' },
      ],
    },
    zone2: {
      name: 'Zone-2 walk',
      length: '35 min',
      type: 'Cardio · HR 105–135',
      color: 'var(--focus-fitness-100)',
      steps: [
        { name: 'Warm-up walk', reps: '5 min', rest: '' },
        { name: 'Zone-2 sustained', reps: '25 min · 3.2 mph', rest: '' },
        { name: 'Cool down', reps: '5 min', rest: '' },
      ],
    },
    mobility: {
      name: 'Hips & spine mobility',
      length: '15 min',
      type: 'Mobility · 1 round',
      color: 'var(--focus-sleep-100)',
      steps: [
        { name: '90/90 hip rotations', reps: '8/side', rest: '' },
        { name: 'Cat-cow', reps: '10 reps', rest: '' },
        { name: "World's greatest stretch", reps: '5/side', rest: '' },
        { name: 'Thread the needle', reps: '8/side', rest: '' },
      ],
    },
    run: {
      name: 'Easy run (5k)',
      length: '28 min',
      type: 'Cardio · easy pace',
      color: 'var(--focus-mental-100)',
      steps: [
        { name: 'Dynamic warm-up', reps: '5 min', rest: '' },
        { name: 'Easy run', reps: '5k · conversational', rest: '' },
        { name: 'Cool down', reps: '3 min walk', rest: '' },
      ],
    },
  };
  const w = workouts[id] || workouts.strength;
  const [started, setStarted] = useStateS(false);
  const [done, setDone] = useStateS({});

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

      <HCard style={{ padding: 20, borderRadius: 22, background: `linear-gradient(135deg, ${w.color}22 0%, ${w.color}08 100%)` }}>
        <HIconTile color={w.color} alpha={0.22} size={52}>{HIcons.fitness(w.color)}</HIconTile>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24, marginTop: 14, letterSpacing: -0.3 }}>{w.name}</div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 3 }}>{w.type} · {w.length}</div>
      </HCard>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>Plan</HSectionLabel>
      <div style={{ background: '#fff', borderRadius: 16, overflow: 'hidden', boxShadow: '0 1px 2px rgba(3,4,13,0.04)' }}>
        {w.steps.map((s, i) => (
          <div key={i} onClick={() => setDone(d => ({ ...d, [i]: !d[i] }))} style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
            borderBottom: i === w.steps.length - 1 ? 'none' : '0.5px solid ' + H.border,
            cursor: 'pointer',
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: 999,
              background: done[i] ? H.success : 'transparent',
              border: '2px solid ' + (done[i] ? H.success : H.border),
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              {done[i]
                ? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round"><path d="m5 12 5 5L20 7"/></svg>
                : <span style={{ fontFamily: H.body, fontWeight: 500, fontSize: 12, color: H.fg3 }}>{i + 1}</span>}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, textDecoration: done[i] ? 'line-through' : 'none', opacity: done[i] ? 0.55 : 1 }}>{s.name}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 1 }}>{s.reps}{s.rest ? ' · rest ' + s.rest : ''}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {!started
          ? <HPrimaryButton onClick={() => setStarted(true)}>Start workout</HPrimaryButton>
          : <HPrimaryButton type="dark" onClick={() => setStarted(false)}>Pause workout</HPrimaryButton>}
        <HPrimaryButton type="outline" onClick={() => onNavigate('chat', { topic: 'workout' })}>Ask Anna to swap</HPrimaryButton>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Chat history
// ══════════════════════════════════════════════════════════════════════════

function ChatHistoryScreen({ onNavigate, onBack }) {
  const threads = [
    { t: 'Blood pressure check-in',       last: 'Try 10 min zone-2 walking daily…', when: '2h',  topic: 'vitals',         unread: true },
    { t: 'Why is my score low?',          last: 'Two biggest drivers: resting HR…', when: '1d',  topic: 'why-score-low' },
    { t: 'Sleep check-in',                last: 'Thanks for sharing — let me…',     when: '3d',  topic: 'sleep-checkin' },
    { t: 'Meal plan swap: dinner',        last: 'Subbed chicken for tofu stir-fry', when: '5d',  topic: 'mealplan' },
    { t: 'Blood report review',           last: 'Vitamin D at 22 ng/mL — low',      when: '1w',  topic: 'blood' },
    { t: 'Workout: zone-2 schedule',      last: 'Mon/Wed/Fri 35-min blocks',         when: '2w',  topic: 'workout' },
    { t: 'DNA: caffeine metabolism',      last: 'You are a slow metabolizer…',      when: '3w',  topic: 'dna' },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 120px', background: H.bg, minHeight: '100%' }}>
      <HTopBar onBack={onBack} title="Chat history" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {threads.map((t, i) => (
          <HCard key={i} onClick={() => onNavigate('chat', { topic: t.topic })} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }}>
            <HAnnaAvatar size={36} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.t}</div>
                <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, flexShrink: 0, marginLeft: 6 }}>{t.when}</div>
              </div>
              <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.last}</div>
            </div>
            {t.unread && <span style={{ width: 8, height: 8, borderRadius: 999, background: H.orange, flexShrink: 0 }}/>}
          </HCard>
        ))}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Voice call sheet (animated)
// ══════════════════════════════════════════════════════════════════════════

function _VoiceCallScreen_LEGACY_UNUSED({ onBack }) {
  const [t, setT] = useStateS(0);
  const [muted, setMuted] = useStateS(false);
  useEffectS(() => {
    const iv = setInterval(() => setT(x => x + 1), 1000);
    return () => clearInterval(iv);
  }, []);
  const mm = String(Math.floor(t / 60)).padStart(2, '0');
  const ss = String(t % 60).padStart(2, '0');

  return (
    <div className="screen-enter" style={{ background: 'linear-gradient(135deg, var(--brand-ink) 0%, #1A1018 55%, #2A0E1A 100%)', color: '#fff', minHeight: '100%', position: 'relative', overflow: 'hidden', padding: '14px 20px 40px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 30 }}>
        <HBackButton onClick={onBack} dark variant="close" label="" />
        <div style={{ fontFamily: H.body, fontSize: 13, color: 'rgba(255,255,255,0.7)' }}>Voice call</div>
        <div style={{ width: 36 }}/>
      </div>

      <div style={{ textAlign: 'center', marginTop: 30 }}>
        <div style={{ width: 140, height: 140, borderRadius: 999, margin: '0 auto', background: H.gradOrange, display: 'grid', placeItems: 'center', boxShadow: '0 20px 50px rgba(255,104,65,0.45)' }}>
          <HealifyMark size={100} />
        </div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, marginTop: 22, letterSpacing: -0.3 }}>Anna</div>
        <div style={{ fontFamily: H.body, fontSize: 14, color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>{muted ? 'Muted · ' : ''}{mm}:{ss}</div>
      </div>

      {/* Waveform */}
      <div style={{ display: 'flex', gap: 4, alignItems: 'center', justifyContent: 'center', height: 80, marginTop: 40 }}>
        {Array.from({ length: 28 }).map((_, i) => {
          const delay = i * 80;
          return (
            <div key={i} style={{
              width: 4, borderRadius: 4,
              background: H.gold, opacity: muted ? 0.25 : 0.9,
              animation: muted ? 'none' : 'hWave 1.2s ease-in-out infinite',
              animationDelay: `${delay}ms`,
              height: 16,
            }}/>
          );
        })}
        <style>{`@keyframes hWave { 0%,100% { height: 10px; } 50% { height: 56px; } }`}</style>
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', gap: 24, marginTop: 60 }}>
        <div onClick={() => setMuted(v => !v)} style={{
          width: 64, height: 64, borderRadius: 999,
          background: muted ? '#fff' : 'rgba(255,255,255,0.14)',
          color: muted ? H.black : '#fff',
          display: 'grid', placeItems: 'center', cursor: 'pointer',
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 1 0 6 0V5a3 3 0 0 0-3-3zM19 10v2a7 7 0 0 1-14 0v-2M12 19v3"/>
            {muted && <line x1="4" y1="4" x2="20" y2="20" stroke="currentColor" strokeWidth="2.5"/>}
          </svg>
        </div>
        <div onClick={onBack} style={{
          width: 64, height: 64, borderRadius: 999,
          background: H.danger,
          display: 'grid', placeItems: 'center', cursor: 'pointer',
          boxShadow: '0 10px 24px rgba(255,66,66,0.45)',
        }}>
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M4 14a14 14 0 0 1 16 0M7 17l1-2a2 2 0 0 1 1.4-1h5.2A2 2 0 0 1 16 15l1 2M20 8a14 14 0 0 0-16 0" transform="rotate(135 12 12)"/>
          </svg>
        </div>
        <div onClick={() => {}} style={{
          width: 64, height: 64, borderRadius: 999,
          background: 'rgba(255,255,255,0.14)', color: '#fff',
          display: 'grid', placeItems: 'center', cursor: 'pointer',
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 5 6 9H2v6h4l5 4zM15.5 8.5a5 5 0 0 1 0 7M19 5a9 9 0 0 1 0 14"/></svg>
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Focus detail
// ══════════════════════════════════════════════════════════════════════════

function FocusDetailScreen({ area = 'sleep', onNavigate, onBack }) {
  const f = FOCUS_AREAS.find(x => x.k === area) || FOCUS_AREAS[0];
  const recsByArea = {
    sleep: [
      { sev: 'bad',  title: 'Consistent wake time', body: 'Bedtime varied by 2h last week. Anchor wake-up to within 30 min.' },
      { sev: 'meh',  title: 'Reduce late caffeine', body: 'Last coffee after 4pm on 5 days. Try to cap at 2pm.' },
      { sev: 'good', title: 'Room temp is ideal',   body: 'Average 18.5°C — in the sweet spot.' },
    ],
    fitness: [
      { sev: 'good', title: 'Steps on target',      body: '9,200/day avg — above your 8,000 goal.' },
      { sev: 'meh',  title: 'Strength days low',    body: '1 session this week; aim for 2–3.' },
      { sev: 'bad',  title: 'Sedentary stretches',  body: '4 blocks of 2h+ sitting — set a movement reminder.' },
    ],
    vitals: [
      { sev: 'meh',  title: 'Resting HR trending up', body: 'Up 6 bpm vs last month.' },
      { sev: 'good', title: 'HRV stable',             body: 'Within expected range.' },
      { sev: 'bad',  title: 'Recheck blood pressure', body: 'Last reading 130/85. Worth retesting this week.' },
    ],
    mind: [
      { sev: 'good', title: 'Mood check-ins strong', body: 'Logged 6/7 days.' },
      { sev: 'meh',  title: 'Stress peaks midweek',  body: 'Pattern suggests Tue/Wed workload.' },
      { sev: 'bad',  title: 'Try a 5-min reset',     body: 'Anna can guide you through a breath session now.' },
    ],
  };
  const recs = recsByArea[f.k] || [];

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

      <HCard style={{ padding: 18, borderRadius: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <HIconTile color={f.color} tint={f.tint} alpha={0.14} size={54}>{f.icon(f.color)}</HIconTile>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 22 }}>{f.name}</div>
            <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2 }}>{f.status} · score {f.val}</div>
          </div>
          <HStatusDot level={f.level} />
        </div>
        <div style={{ height: 8, background: 'var(--bg-app)', borderRadius: 999, marginTop: 16, overflow: 'hidden' }}>
          <div style={{ width: f.val + '%', height: '100%', background: f.color, borderRadius: 999 }}/>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>Recommendations</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {recs.map((r, i) => (
          <HRecommendationCard key={i} severity={r.sev} title={r.title} body={r.body} onClick={() => onNavigate('chat', { topic: f.k })} />
        ))}
      </div>

      <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <HPrimaryButton
          onClick={() => onNavigate('chat', { topic: f.k })}
          icon={<svg width="18" height="18" viewBox="0 0 20 20" fill="none"><path d="M4 6a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H9l-3 3v-3H6a2 2 0 0 1-2-2V6z" stroke="#fff" strokeWidth="1.8" strokeLinejoin="round"/></svg>}
        >Start Chat with Anna</HPrimaryButton>
        <HPrimaryButton type="outline" onClick={onBack}>Close</HPrimaryButton>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Paywall (condensed — logo prominent)
// ══════════════════════════════════════════════════════════════════════════

function PaywallScreen({ onBack }) {
  const bokeh = [
    { top: 30,  left: 20,  s: 130, icon: 'glass' },
    { top: 70,  left: 175, s: 120, icon: 'bed' },
    { top: 50,  left: 300, s: 110, icon: 'mug'  },
    { top: 160, left: -40, s: 105, icon: 'mask' },
    { top: 170, left: 105, s: 85,  icon: 'flame'},
    { top: 190, left: 300, s: 130, icon: 'hearteye' },
  ];
  const Ic = ({ name, s = 28 }) => {
    const p = { width: s, height: s, viewBox: '0 0 24 24', fill: 'none', stroke: 'rgba(255,130,80,0.55)', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round' };
    if (name === 'bed')      return <svg {...p}><path d="M3 16h18M3 16V8M3 16v3M21 16V12a3 3 0 0 0-3-3h-6v7M21 16v3"/></svg>;
    if (name === 'mug')      return <svg {...p}><path d="M5 9h12v7a4 4 0 0 1-4 4H9a4 4 0 0 1-4-4ZM17 11h2a2 2 0 0 1 0 4h-2"/></svg>;
    if (name === 'glass')    return <svg {...p}><path d="M7 3h10l-1.5 18H8.5ZM7.5 9h9"/></svg>;
    if (name === 'flame')    return <svg {...p}><path d="M12 3c0 3-2 4-2 7a2 2 0 0 0 4 0c0-1-1-1-1-2 2 1 4 4 4 7a5 5 0 0 1-10 0c0-3 2-5 3-7s2-3 2-5Z"/></svg>;
    if (name === 'mask')     return <svg {...p}><path d="M4 8c0-2 2-3 4-3s3 1 4 1 2-1 4-1 4 1 4 3v5a6 6 0 0 1-6 6h-4a6 6 0 0 1-6-6Z"/></svg>;
    if (name === 'hearteye') return <svg {...p}><path d="M12 21s-8-5-8-11a4 4 0 0 1 8-1 4 4 0 0 1 8 1c0 6-8 11-8 11Z"/></svg>;
    return null;
  };
  const Check = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>
  );
  return (
    <div className="screen-enter" style={{ background: '#000', color: '#fff', minHeight: '100%', position: 'relative', overflow: 'hidden', paddingBottom: 40 }}>
      <div style={{ position: 'absolute', inset: 0 }}>
        {bokeh.map((b, i) => (
          <div key={i} style={{ position: 'absolute', top: b.top, left: b.left, width: b.s, height: b.s, borderRadius: 999, background: 'radial-gradient(circle at 38% 32%, rgba(255,104,65,0.22) 0%, rgba(50,22,14,0.55) 55%, rgba(0,0,0,0) 100%)', display: 'grid', placeItems: 'center' }}>
            <Ic name={b.icon} s={b.s * 0.36} />
          </div>
        ))}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.5) 42%, rgba(0,0,0,0.92) 70%, #000 100%)' }}/>
      </div>

      <div onClick={onBack} style={{ position: 'absolute', top: 18, right: 20, width: 34, height: 34, borderRadius: 999, zIndex: 2, background: 'rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
      </div>

      <div style={{ position: 'relative', zIndex: 1, display: 'grid', placeItems: 'center', paddingTop: 56 }}>
        <div style={{ width: 200, height: 200, borderRadius: 48, background: 'linear-gradient(160deg, var(--brand-gold-sand) 0%, var(--brand-orange-vibey) 55%, #9A2F1C 100%)', boxShadow: '0 20px 50px rgba(255,104,65,0.35), inset 0 1px 0 rgba(255,255,255,0.25)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6, position: 'relative' }}>
          <HealifyMark size={160} />
          <div style={{ position: 'absolute', bottom: 16, fontFamily: H.body, fontWeight: 400, fontSize: 14, color: 'rgba(255,255,255,0.94)' }}>Healify Life+</div>
        </div>
      </div>

      <div style={{ position: 'relative', zIndex: 1, padding: '30px 28px 0', textAlign: 'center' }}>
        <div style={{ fontFamily: H.body, fontWeight: 400, fontSize: 22, lineHeight: 1.22 }}>
          Trade 1 latte a week for 10+ years with your loved ones.
        </div>
        <div style={{ fontFamily: H.body, fontSize: 13, color: 'rgba(255,255,255,0.6)', marginTop: 12, lineHeight: 1.45 }}>
          People with access to preventative health coaching add avg. 11.9 years to their lives.
        </div>
      </div>

      <div style={{ position: 'relative', zIndex: 1, padding: '22px 36px 0', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {['Unlimited 24/7 chat with Anna', 'Bloodwork & DNA insights', 'All AI tools + personal meal plans'].map((t, i) => (
          <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <Check />
            <div style={{ fontFamily: H.body, fontSize: 14, color: 'rgba(255,255,255,0.92)' }}>{t}</div>
          </div>
        ))}
      </div>

      <div style={{ position: 'relative', zIndex: 1, padding: '28px 24px 0', textAlign: 'center' }}>
        <div style={{ fontFamily: H.body, fontSize: 13, color: 'rgba(255,255,255,0.72)' }}>
          Optimize your health for <b style={{ color: '#fff' }}>$0.27 per day</b>
        </div>
        <button onClick={onBack} style={{ marginTop: 14, width: '100%', border: 0, cursor: 'pointer', padding: '16px 22px', borderRadius: 999, color: '#fff', fontFamily: H.body, fontWeight: 500, fontSize: 16, background: 'var(--grad-vibey)', boxShadow: '0 10px 28px rgba(255,104,65,0.45)' }}>Unlock Life+</button>
        <div style={{ fontFamily: H.body, fontSize: 12, color: 'rgba(255,255,255,0.55)', marginTop: 12 }}>
          Already a member? <span style={{ color: 'rgba(255,255,255,0.82)' }}>Restore purchase</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  MenuScreen, ProfileScreen, SettingsScreen, NotificationsScreen,
  HabitsScreen, PicksScreen,
  ChatHistoryScreen,
  FocusDetailScreen, PaywallScreen,
});
