// Healify — Primary tab screens (Home, Health, Chat, Nutrition, Fitness).
// Requires components.jsx loaded first (globals: H, HCard, ...).

const { useState: useStateP } = React;

// ══════════════════════════════════════════════════════════════════════════
// Home
// ══════════════════════════════════════════════════════════════════════════

function HomeScreen({ onNavigate }) {
  // Single source of truth for today's Health Score.
  // In production this would come from app state / API; for the prototype
  // we hold it locally so the greeting ring and the score-context card
  // below stay in sync.
  const score = 47;
  const scoreDelta = -2;
  const scoreLabel = score >= 80 ? 'On track' : score >= 60 ? 'Doing okay' : 'Needs attention';
  const peerAvg = 62;
  // 7-day trend (oldest → today). Today is the last value and matches `score`.
  const trend = [54, 58, 56, 52, 49, 51, 47];
  // What's pulling the score this morning — drivers ordered by impact magnitude.
  // delta is the points each one is contributing relative to a 7-day baseline.
  const drivers = [
    { k: 'sleep',  label: 'Sleep debt',     delta: -12, color: 'var(--focus-sleep-500)',   tint: 'var(--focus-sleep-100)' },
    { k: 'vitals', label: 'Resting HR up',  delta: -8,  color: 'var(--focus-heart-500)',   tint: 'var(--focus-heart-100)' },
    { k: 'mind',   label: 'Stress trend',   delta: -5,  color: 'var(--focus-mind-500)',    tint: 'var(--focus-mind-100)' },
  ];
  const accent = score < 60 ? 'var(--semantic-warn-500)' : score < 80 ? 'var(--brand-orange)' : 'var(--semantic-good-500)';
  const accentTint = score < 60 ? 'var(--semantic-warn-100)' : score < 80 ? 'rgba(255,105,66,0.10)' : 'var(--semantic-good-100)';

  return (
    <div className="screen-enter" style={{ padding: '0 20px 140px', display: 'flex', flexDirection: 'column', gap: 20, background: H.bg, minHeight: '100%' }}>
      <div style={{ paddingTop: 6 }}>
        <HGreetingHeader
          name="Kathryn"
          score={score}
          scoreDelta={scoreDelta}
          onScorePress={() => onNavigate('tab:health')}
          onMenu={() => onNavigate('menu')}
        />
      </div>

      <HAnnaPromptCard onClick={() => onNavigate('chat', { topic: 'sleep-checkin' })} />

      {/* Score context card — the WHY behind the number in the greeting.
          Greeting holds the glanceable 2-digit score; this card surfaces
          status label + peer comparison + tap target into Health detail. */}
      <HCard onClick={() => onNavigate('tab:health')} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14, borderRadius: 20 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', color: H.fg3 }}>Today's score · {score < 60 ? 'why' : 'breakdown'}</div>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 18, color: H.fg1, marginTop: 2 }}>{scoreLabel}</div>
          <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 1 }}>Women 30+ average is <b>{peerAvg}</b></div>
        </div>
        <HChevron />
      </HCard>

      <div>
        <div style={{
          fontFamily: H.body, fontSize: 13, color: H.fg3, marginBottom: 10, marginLeft: 2, letterSpacing: -0.1,
        }}>Focus Areas</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {FOCUS_AREAS.map(f => {
            const isExpandable = f.level !== 'normal';
            const metricsByArea = {
              vitals:  [{ title: '72 bpm RHR',  level: 'fair' }, { title: '130/85 BP', level: 'bad' }],
              mind:    [{ title: 'Stress 6/10', level: 'fair' }, { title: 'Mood steady', level: 'normal' }],
            };
            const recsByArea = {
              vitals:  ['Retest BP twice this week', '10-min daily zone-2 walk'],
              mind:    ['Try a 5-min breath reset at 2pm'],
            };
            return (
              <HFocusRow
                key={f.k}
                color={f.color} tint={f.tint}
                icon={f.icon(f.color)}
                title={f.name} level={f.level} status={f.status}
                expandable={isExpandable}
                metrics={metricsByArea[f.k]}
                recommendations={recsByArea[f.k]}
                ctaLabel="Start Chat with Anna"
                onCtaPress={() => onNavigate('chat', { topic: f.k })}
                onSeePlan={() => onNavigate('focus', { area: f.k })}
                secondary={{ title: `Open ${f.name.toLowerCase()} details`, onPress: () => onNavigate('focus', { area: f.k }) }}
                onClick={() => onNavigate('focus', { area: f.k })}
              />
            );
          })}
        </div>
      </div>

      {/* AI picks teaser */}
      <div>
        <HSectionLabel style={{ margin: '4px 4px 10px' }} onPress={() => onNavigate('picks')}>AI Tools</HSectionLabel>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {[
            { k: 'meal-plan', name: 'Meal plan', sub: 'Personal recipes', color: 'var(--quartz-150)' },
            { k: 'workout',   name: 'Workouts',  sub: '3 planned',         color: 'var(--focus-fitness-100)' },
            { k: 'meditate',  name: 'Meditation', sub: '5 new sessions',   color: 'var(--focus-sleep-100)' },
            { k: 'blood',     name: 'Blood report', sub: 'Upload & scan',  color: 'var(--focus-heart-100)' },
          ].map(t => (
            <HCard key={t.k} onClick={() => onNavigate(t.k === 'meal-plan' ? 'mealplan' : t.k === 'workout' ? 'workout' : t.k === 'blood' ? 'blood' : 'meditate')} style={{ padding: 14, borderRadius: 18 }}>
              <HIconTile color={t.color} alpha={0.16} size={40}>
                {t.k === 'meal-plan' && HIcons.nutrition(t.color)}
                {t.k === 'workout' && HIcons.fitness(t.color)}
                {t.k === 'meditate' && HIcons.mind(t.color)}
                {t.k === 'blood' && HIcons.vitals(t.color)}
              </HIconTile>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, marginTop: 10 }}>{t.name}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{t.sub}</div>
            </HCard>
          ))}
        </div>
      </div>

      <div style={{
        fontFamily: H.body, fontSize: 11, lineHeight: 1.45,
        color: H.fg3, textAlign: 'center', padding: '8px 20px 0',
      }}>
        For educational purposes only. Not medical advice. Sources include peer-reviewed medical literature and clinical guidelines.
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Health (Score) — primary tab
// ══════════════════════════════════════════════════════════════════════════

function HealthScreen({ onNavigate }) {
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <div style={{
        fontFamily: H.body, fontSize: 11, letterSpacing: 1.2,
        color: H.fg3, textTransform: 'uppercase', marginBottom: 6,
      }}>Week of Apr 14 · Apr 20</div>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, marginBottom: 16, letterSpacing: -0.4 }}>Your Health</div>

      <HCard style={{ padding: 20, textAlign: 'center', borderRadius: 24 }}>
        <div style={{ width: 160, height: 160, borderRadius: 999, margin: '0 auto', background: `conic-gradient(${H.orange} 0 47%, var(--bg-app) 47% 100%)`, display: 'grid', placeItems: 'center' }}>
          <div style={{ width: 134, height: 134, borderRadius: 999, background: '#fff', display: 'grid', placeItems: 'center', lineHeight: 1 }}>
            <div>
              <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 44 }}>47</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 4 }}>of 100</div>
            </div>
          </div>
        </div>
        <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 14 }}>
          Down <b style={{ color: H.danger }}>15%</b> vs last month · Men 45+ average is <b style={{ color: H.fg1 }}>62</b>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 16, justifyContent: 'center' }}>
          <HPrimaryButton type="outline" style={{ width: 'auto', padding: '10px 16px', fontSize: 14 }} onClick={() => onNavigate('chat', { topic: 'why-score-low' })}>
            Why is it low?
          </HPrimaryButton>
          <HPrimaryButton style={{ width: 'auto', padding: '10px 18px', fontSize: 14 }} onClick={() => onNavigate('chat', { topic: 'improve-score' })}>
            Improve score
          </HPrimaryButton>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>Breakdown</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {FOCUS_AREAS.map(r => (
          <HCard key={r.k} onClick={() => onNavigate('focus', { area: r.k })} style={{ padding: '14px 16px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <HIconTile color={r.color} tint={r.tint} size={36} alpha={0.14}>{r.icon(r.color)}</HIconTile>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{r.name}</div>
                <div style={{ height: 6, background: 'var(--bg-app)', borderRadius: 999, marginTop: 6, overflow: 'hidden' }}>
                  <div style={{ width: `${r.val}%`, height: '100%', background: r.color, borderRadius: 999 }}/>
                </div>
              </div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: H.body, fontSize: 13, color: H.fg2 }}>
                {r.val}
                <HStatusDot level={r.level}/>
                <HChevron />
              </div>
            </div>
          </HCard>
        ))}
      </div>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>Data Points</HSectionLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {[
          { label: 'Resting HR', value: '72 bpm', trend: '↑ 6' },
          { label: 'Blood pressure', value: '130/85', trend: 'High' },
          { label: 'Sleep (avg)', value: '6h 42m', trend: '↓ 18m' },
          { label: 'Steps (avg)', value: '9,200', trend: '↑ 400' },
        ].map(d => (
          <HCard key={d.label} style={{ padding: 12 }}>
            <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>{d.label}</div>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 20, marginTop: 4 }}>{d.value}</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{d.trend}</div>
          </HCard>
        ))}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Chat (Anna)
// ══════════════════════════════════════════════════════════════════════════

const TOPIC_LABELS = {
  'sleep-checkin':  'Sleep check-in',
  'why-score-low':  'Why is my score low?',
  'improve-score':  'Improve my score',
  sleep:   'Sleep plan',
  fitness: 'Fitness plan',
  vitals:  'Blood pressure check-in',
  mind:    'Mind & stress',
  blood:   'Blood report review',
  dna:     'DNA insights',
  mealplan:'Meal plan chat',
  workout: 'Workout plan chat',
};

function ChatScreen({ onNavigate, onBack, topic = 'vitals' }) {
  const label = TOPIC_LABELS[topic] || 'Chat with Anna';
  const seed = (() => {
    if (topic === 'vitals') return [
      { who: 'user', text: "Hey, I just checked my blood pressure and it's on the high edge. What should I do?", time: '9:41 AM' },
      { who: 'ai', text: "Hi Kathryn, you are correct. Your latest numbers (130/85 mmHg) are a bit high, which means it's important to take steps to keep them from rising further.", time: '9:41 AM' },
    ];
    if (topic === 'sleep-checkin' || topic === 'sleep') return [
      { who: 'ai', text: "Hi Kathryn — quick check-in on sleep. How would you rate your sleep quality this week?", time: '9:41 AM' },
    ];
    if (topic === 'why-score-low') return [
      { who: 'user', text: "Why is my health score low?", time: '9:40 AM' },
      { who: 'ai', text: "Your score is 47 this week, down 15% from last month. The two biggest drivers: your resting HR trended up, and your blood pressure was borderline twice. Want me to break it down by focus area?", time: '9:41 AM' },
    ];
    return [
      { who: 'ai', text: `Hi Kathryn — I'm here to talk about ${label.toLowerCase()}. What's on your mind?`, time: '9:41 AM' },
    ];
  })();

  const [messages, setMessages] = useStateP(seed);
  const [draft, setDraft] = useStateP('');
  const [typing, setTyping] = useStateP(false);
  const [threadId, setThreadId] = useStateP(null);
  const prompts = topic === 'vitals'
    ? ['How do I lower my BP?', 'Plan a zone-2 walk', 'What foods help?']
    : topic.startsWith('sleep')
    ? ['I slept 5 hours', 'Help me unwind', 'Why do I wake up at 3am?']
    : ['Tell me more', 'Plan my week', 'What should I track?'];

  const nowStamp = () => {
    const d = new Date();
    let h = d.getHours(); const m = d.getMinutes();
    const ampm = h >= 12 ? 'PM' : 'AM';
    h = h % 12 || 12;
    return `${h}:${String(m).padStart(2, '0')} ${ampm}`;
  };

  const send = async (t) => {
    if (!t.trim()) return;
    setMessages(m => [...m, { who: 'user', text: t, time: nowStamp() }]);
    setDraft('');
    setTyping(true);
    try {
      const { answer, threadId: newThread } = await askAnna(t, threadId);
      if (newThread) setThreadId(newThread);
      setTyping(false);
      setMessages(m => [...m, { who: 'ai', text: answer || "I'm here — could you say a bit more?", time: nowStamp() }]);
    } catch {
      setTyping(false);
      setMessages(m => [...m, { who: 'ai', text: "I'm having trouble reaching my brain right now — give me a moment and try again.", time: nowStamp() }]);
    }
  };

  const sendFile = (file) => {
    setMessages(m => [...m, { who: 'user', type: 'file', file, time: nowStamp() }]);
    setTyping(true);
    setTimeout(() => { setTyping(false); setMessages(m => [...m, { who: 'ai', text: `Got your ${file.isImage ? 'image' : 'file'} — I'm reviewing it now and will flag anything that stands out.`, time: nowStamp() }]); }, 1300);
  };
  const sendVoice = (seconds) => {
    setMessages(m => [...m, { who: 'user', type: 'voice', seconds, time: nowStamp() }]);
    setTyping(true);
    setTimeout(() => { setTyping(false); setMessages(m => [...m, { who: 'ai', text: "Thanks for the voice note — I listened. Let's talk it through.", time: nowStamp() }]); }, 1300);
  };

  const setFeedback = (idx, v) => setMessages(ms => ms.map((m, i) => i === idx ? { ...m, feedback: m.feedback === v ? null : v } : m));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: H.bg }}>
      {/* Chat header */}
      <div style={{
        position: 'relative',
        background: 'linear-gradient(180deg,var(--quartz-deep-warm) 0%, #FFFFFF 100%)',
        borderBottomLeftRadius: 24, borderBottomRightRadius: 24,
        borderBottom: '0.5px solid ' + H.border,
        padding: '14px 12px 12px',
        display: 'flex', alignItems: 'center', gap: 8,
        boxShadow: '0 2px 10px rgba(3,4,13,0.04)',
      }}>
        <div onClick={onBack} role="button" aria-label="Close chat" style={{
          width: 40, height: 40, borderRadius: 999, background: '#fff',
          display: 'grid', placeItems: 'center', cursor: 'pointer', flexShrink: 0,
          boxShadow: '0 1px 2px rgba(3,4,13,0.05)',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="2.2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
        </div>

        <div style={{ flex: 1, minWidth: 0, textAlign: 'center', padding: '0 4px' }}>
          <div style={{
            fontFamily: H.body, fontWeight: 500, fontSize: 17, lineHeight: 1.2,
            color: H.fg1, letterSpacing: -0.3,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{label}</div>
          <div style={{ fontFamily: H.body, fontSize: 11, color: H.success, marginTop: 2, letterSpacing: 0.2 }}>
            <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: 999, background: H.success, marginRight: 4, verticalAlign: 1 }}/>
            Anna is online
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
          {[
            { k: 'call',    label: 'Voice call',  onClick: () => onNavigate('voice'), icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 4h3l2 5-2 2a12 12 0 0 0 5 5l2-2 5 2v3a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2Z"/></svg> },
            { k: 'history', label: 'Chat history', onClick: () => onNavigate('history'), icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7M3 4v4h4"/><path d="M12 7v5l3 2"/></svg> },
            { k: 'new',     label: 'New chat',     onClick: () => { setMessages([{ who: 'ai', text: "What would you like to talk about, Kathryn?" }]); }, icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M20 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4"/><path d="m15 5 4 4-8 8H7v-4l8-8Z"/></svg> },
          ].map(b => (
            <div key={b.k} role="button" aria-label={b.label} onClick={b.onClick} style={{
              width: 36, height: 36, borderRadius: 999,
              display: 'grid', placeItems: 'center', cursor: 'pointer',
            }}>{b.icon}</div>
          ))}
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 16px 110px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {messages.map((m, i) => renderRichMessage(m, i) || (m.who === 'user' ? (
          <div key={i} style={{ alignSelf: 'flex-end', maxWidth: '78%', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
            <div style={{ background: H.gradBubble, color: '#fff', borderRadius: '22px 22px 4px 22px', padding: '12px 14px', fontFamily: H.body, fontSize: 14.5, lineHeight: 1.45 }}>{m.text}</div>
            <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, paddingRight: 6, letterSpacing: 0.1 }}>{m.time}</div>
          </div>
        ) : (
          <div key={i} style={{ alignSelf: 'flex-start', maxWidth: '84%', display: 'flex', flexDirection: 'column', gap: 4 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 4 }}>
              <HAnnaAvatar size={24} />
              <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg3 }}>Anna</div>
            </div>
            <div style={{ background: '#fff', borderRadius: '22px 22px 22px 4px', padding: '12px 14px', boxShadow: '0 2px 8px rgba(3,4,13,0.05), 0 0 0 0.5px rgba(3,4,13,0.03)', fontFamily: H.body, fontSize: 14.5, lineHeight: 1.5 }}>{m.text}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 4, paddingLeft: 6, marginTop: 2 }}>
              <span style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, letterSpacing: 0.1 }}>{m.time}</span>
              <span style={{ width: 1, height: 10, background: H.border, margin: '0 6px' }}/>
              {[
                { v: 'up',   d: 'M7 22V11M2 13v7a2 2 0 0 0 2 2h11.5a2 2 0 0 0 2-1.7l1.4-7A2 2 0 0 0 17 11h-4l1-4a2 2 0 0 0-2-2L7 11' },
                { v: 'down', d: 'M17 2v11M22 11V4a2 2 0 0 0-2-2H8.5a2 2 0 0 0-2 1.7L5.1 10.7A2 2 0 0 0 7 13h4l-1 4a2 2 0 0 0 2 2l5-6' },
              ].map(b => {
                const active = m.feedback === b.v;
                return (
                  <div key={b.v} role="button" aria-label={b.v === 'up' ? 'Helpful' : 'Not helpful'}
                    onClick={() => setFeedback(i, b.v)}
                    style={{
                      width: 26, height: 26, borderRadius: 999, display: 'grid', placeItems: 'center', cursor: 'pointer',
                      background: active ? 'var(--quartz-soft-bg)' : 'transparent', transition: 'background 140ms',
                    }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
                      stroke={active ? H.orange : H.fg3} strokeWidth={active ? 2.1 : 1.7}
                      strokeLinecap="round" strokeLinejoin="round">
                      <path d={b.d} />
                    </svg>
                  </div>
                );
              })}
            </div>
          </div>
        )))}
        {typing && (
          <div style={{ alignSelf: 'flex-start', display: 'flex', flexDirection: 'column', gap: 4 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 4 }}>
              <HAnnaAvatar size={24} />
              <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg3 }}>Anna</div>
            </div>
            <HTypingIndicator />
          </div>
        )}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 4 }}>
          {prompts.map(p => (
            <div key={p} onClick={() => send(p)} style={{
              fontFamily: H.body, fontSize: 13, color: H.fg2, cursor: 'pointer',
              background: '#fff', border: '1px solid ' + H.border, borderRadius: 999,
              padding: '6px 12px',
            }}>{p}</div>
          ))}
        </div>
      </div>

      <div style={{ position: 'absolute', left: 16, right: 16, bottom: 24, zIndex: 40 }}>
        <ChatComposer variant="mobile" onSendText={send} onSendFile={sendFile} onSendVoice={sendVoice} />
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Nutrition
// ══════════════════════════════════════════════════════════════════════════

function NutritionScreen({ onNavigate }) {
  const meals = [
    { k: 'breakfast', name: 'Breakfast', dish: 'Greek yogurt parfait', kcal: 410, macros: '32P / 48C / 12F', color: 'var(--brand-orange-vibey)' },
    { k: 'lunch',     name: 'Lunch',     dish: 'Salmon + farro bowl',  kcal: 620, macros: '42P / 58C / 22F', color: 'var(--focus-fitness)' },
    { k: 'snack',     name: 'Snack',     dish: 'Almond + apple',        kcal: 240, macros: '8P / 28C / 12F',  color: 'var(--focus-heart)' },
    { k: 'dinner',    name: 'Dinner',    dish: 'Chicken stir-fry',      kcal: 560, macros: '44P / 52C / 18F', color: 'var(--focus-sleep)' },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1.2, color: H.fg3, textTransform: 'uppercase', marginBottom: 6 }}>Today · Thu Apr 17</div>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, marginBottom: 14, letterSpacing: -0.4 }}>Nutrition</div>

      {/* Daily summary */}
      <HCard style={{ padding: 18, borderRadius: 22 }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16 }}>
          <div>
            <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 34, lineHeight: 1, letterSpacing: -0.5 }}>1,830</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 3 }}>of 2,100 kcal</div>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ height: 8, background: 'var(--bg-app)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: '87%', height: '100%', background: H.gradOrange }}/>
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 10, flexWrap: 'wrap' }}>
              <HBadge title="Protein 126g / 140" level="fair" />
              <HBadge title="Fiber 22g / 30" level="fair" />
              <HBadge title="Sat fat 12g" level="normal" />
            </div>
          </div>
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '22px 4px 10px' }} right="See plan" onPress={() => onNavigate('mealplan')}>Today's Meals</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {meals.map(m => (
          <HCard key={m.k} onClick={() => onNavigate('mealplan')} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
            <HIconTile color={m.color} alpha={0.14} size={44}>{HIcons.nutrition(m.color)}</HIconTile>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>{m.name}</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 · {m.macros}</div>
            </div>
            <HChevron />
          </HCard>
        ))}
      </div>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>Quick Actions</HSectionLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <HCard onClick={() => onNavigate('chat', { topic: 'mealplan' })} style={{ padding: 14 }}>
          <HIconTile color={H.orange} alpha={0.14} size={40}>{HIcons.nutrition(H.orange)}</HIconTile>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14, marginTop: 10 }}>Ask Anna</div>
          <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2 }}>Meal ideas & swaps</div>
        </HCard>
        <HCard onClick={() => onNavigate('mealplan')} style={{ padding: 14 }}>
          <HIconTile color="var(--focus-fitness-100)" alpha={0.14} size={40}>{HIcons.fitness('var(--focus-fitness-100)')}</HIconTile>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14, marginTop: 10 }}>Weekly plan</div>
          <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2 }}>7-day recipes</div>
        </HCard>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// Fitness
// ══════════════════════════════════════════════════════════════════════════

function FitnessScreen({ onNavigate }) {
  const workouts = [
    { k: 'zone2',    name: 'Zone-2 walk',      length: '35 min', type: 'Cardio',      color: 'var(--focus-fitness-100)' },
    { k: 'strength', name: 'Full-body strength', length: '45 min', type: 'Strength', color: 'var(--quartz-150)' },
    { k: 'mobility', name: 'Hips & spine mobility', length: '15 min', type: 'Mobility', color: 'var(--focus-sleep-100)' },
    { k: 'run',      name: 'Easy run (5k)',    length: '28 min', type: 'Cardio',      color: 'var(--focus-mental-100)' },
  ];
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
      <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 1.2, color: H.fg3, textTransform: 'uppercase', marginBottom: 6 }}>This week</div>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, marginBottom: 14, letterSpacing: -0.4 }}>Fitness</div>

      {/* Activity ring + stats */}
      <HCard style={{ padding: 18, display: 'flex', alignItems: 'center', gap: 18, borderRadius: 22 }}>
        <div style={{ width: 110, height: 110, borderRadius: 999, background: `conic-gradient(${H.saladGreen} 0 68%, var(--bg-app) 68% 100%)`, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          <div style={{ width: 92, height: 92, borderRadius: 999, background: '#fff', display: 'grid', placeItems: 'center', lineHeight: 1 }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24 }}>68%</div>
              <div style={{ fontFamily: H.body, fontSize: 10, color: H.fg3, letterSpacing: 0.4 }}>OF WEEK</div>
            </div>
          </div>
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            { label: 'Steps', value: '64,200', of: '56,000 goal' },
            { label: 'Active min', value: '182', of: '150 goal' },
            { label: 'Workouts', value: '3', of: '4 planned' },
          ].map(s => (
            <div key={s.label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3 }}>{s.label}</div>
              <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg2 }}>
                <b style={{ fontFamily: H.body, fontWeight: 500, color: H.fg1, fontSize: 15 }}>{s.value}</b>{' · '}{s.of}
              </div>
            </div>
          ))}
        </div>
      </HCard>

      <HSectionLabel style={{ margin: '22px 4px 10px' }} right="Weekly plan" onPress={() => onNavigate('chat', { topic: 'workout' })}>Planned Workouts</HSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {workouts.map(w => (
          <HCard key={w.k} onClick={() => onNavigate('workout', { id: w.k })} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }}>
            <HIconTile color={w.color} alpha={0.16} size={42}>{HIcons.fitness(w.color)}</HIconTile>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 16 }}>{w.name}</div>
              <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 1 }}>{w.type} · {w.length}</div>
            </div>
            <div style={{
              fontFamily: H.body, fontWeight: 500, fontSize: 12,
              background: H.bgSecondary, padding: '6px 10px', borderRadius: 999,
              color: H.fg2,
            }}>Start</div>
          </HCard>
        ))}
      </div>

      <HSectionLabel style={{ margin: '22px 4px 10px' }}>This Week</HSectionLabel>
      <HCard style={{ padding: 14 }}>
        <div style={{ display: 'flex', gap: 6, alignItems: 'flex-end', height: 120, justifyContent: 'space-between' }}>
          {[{ d: 'M', h: 62 }, { d: 'T', h: 48 }, { d: 'W', h: 86 }, { d: 'T', h: 40 }, { d: 'F', h: 72 }, { d: 'S', h: 94 }, { d: 'S', h: 30 }].map((b, i) => (
            <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              <div style={{ width: '100%', height: b.h, background: H.gradOrange, borderRadius: '10px 10px 2px 2px' }}/>
              <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg3 }}>{b.d}</div>
            </div>
          ))}
        </div>
      </HCard>
    </div>
  );
}

Object.assign(window, { HomeScreen, HealthScreen, ChatScreen, NutritionScreen, FitnessScreen, TOPIC_LABELS });
