// Healify Web — Tier A desktop page layouts. Multi-column dashboards that reuse
// the canonical kit primitives (H, HCard, HIconTile, HIcons, FOCUS_AREAS, …) and
// the SAME data as the mobile screens, arranged for the wide canvas.

const { useState: useStateDP, useRef: useRefDP, useEffect: useEffectDP } = React;

const DK_MAX = 1140;

// ── shared bits ──────────────────────────────────────────────────────────
function DkPageHead({ kicker, title, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 20, marginBottom: 22 }}>
      <div>
        {kicker && <div style={{ fontFamily: H.body, fontSize: 12, letterSpacing: 1.2, textTransform: 'uppercase', color: H.fg3, marginBottom: 7 }}>{kicker}</div>}
        <h1 style={{ fontFamily: H.display, fontWeight: 600, fontSize: 32, letterSpacing: -0.7, color: H.fg1, margin: 0, lineHeight: 1.05, whiteSpace: 'nowrap' }}>{title}</h1>
      </div>
      {right}
    </div>
  );
}
function DkLabel({ children, right, onPress }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', margin: '6px 2px 12px' }}>
      <span style={{ fontFamily: H.body, fontWeight: 500, fontSize: 12, letterSpacing: 1.3, textTransform: 'uppercase', color: H.fg3 }}>{children}</span>
      {right && <button onClick={onPress} style={{ border: 0, background: 'transparent', cursor: 'pointer', fontFamily: H.body, fontSize: 13, color: 'var(--brand-orange-vibey)', fontWeight: 500 }}>{right}</button>}
    </div>
  );
}
function DkRing({ value, size = 168, color = 'var(--brand-orange-vibey)', track = 'var(--bg-app)', thickness = 13, children }) {
  return (
    <div style={{ width: size, height: size, borderRadius: 999, background: `conic-gradient(${color} 0 ${value}%, ${track} ${value}% 100%)`, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
      <div style={{ width: size - thickness * 2, height: size - thickness * 2, borderRadius: 999, background: '#fff', display: 'grid', placeItems: 'center', lineHeight: 1 }}>{children}</div>
    </div>
  );
}
function useCountUp(target, dur = 950) {
  const [v, setV] = useStateDP(0);
  useEffectDP(() => {
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setV(target); return; }
    let raf, start; const ease = (t) => 1 - Math.pow(1 - t, 3);
    const tick = (ts) => { if (!start) start = ts; const p = Math.min(1, (ts - start) / dur); setV(target * ease(p)); if (p < 1) raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, dur]);
  return v;
}
function AnimatedRing({ value, size, color, thickness, renderCenter }) {
  const v = useCountUp(value);
  return <DkRing value={v} size={size} color={color} thickness={thickness}>{renderCenter(v)}</DkRing>;
}
function DkBtn({ children, onClick, kind = 'solid', icon }) {
  const base = { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, height: 44, padding: '0 20px', borderRadius: 999, cursor: 'pointer', fontFamily: H.body, fontWeight: 500, fontSize: 14.5, border: 0 };
  const kinds = {
    solid:   { ...base, background: H.black, color: '#fff' },
    primary: { ...base, background: 'var(--grad-vibey-cta)', color: '#fff' },
    outline: { ...base, background: '#fff', color: H.fg1, border: '1px solid var(--border-subtle)' },
  };
  return <button onClick={onClick} style={kinds[kind]}>{icon}{children}</button>;
}
function DkStat({ label, value, sub, subColor }) {
  return (
    <HCard style={{ padding: '16px 18px', borderRadius: 18 }}>
      <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.7, textTransform: 'uppercase', color: H.fg3 }}>{label}</div>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, color: H.fg1, marginTop: 6, letterSpacing: -0.4 }}>{value}</div>
      {sub && <div style={{ fontFamily: H.body, fontSize: 12.5, color: subColor || H.fg2, marginTop: 3 }}>{sub}</div>}
    </HCard>
  );
}
function DkFocusCard({ f, onClick }) {
  return (
    <HCard onClick={onClick} className="dk-hover" style={{ padding: '16px 18px', borderRadius: 18, minHeight: 96, boxSizing: 'border-box', display: 'flex', alignItems: 'center' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 13, width: '100%' }}>
        <HIconTile color={f.color} tint={f.tint} size={42} alpha={0.14}>{f.icon(f.color)}</HIconTile>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontFamily: H.body, fontWeight: 500, fontSize: 16, color: H.fg1 }}>{f.name}</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: H.body, fontSize: 13, color: H.fg2 }}>{f.val}<HStatusDot level={f.level} /></span>
          </div>
          <div style={{ height: 6, background: 'var(--bg-app)', borderRadius: 999, marginTop: 9, overflow: 'hidden' }}>
            <div style={{ width: f.val + '%', height: '100%', background: f.color, borderRadius: 999 }} />
          </div>
          <div style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg3, marginTop: 8 }}>{f.status}</div>
        </div>
      </div>
    </HCard>
  );
}

// ════════════════════════════════════════ HOME ════════════════════════════
function DeskHome({ nav, wallStore }) {
  const score = 47, peer = 62;
  const drivers = [
    { label: 'Sleep debt', delta: -12, color: 'var(--focus-sleep)' },
    { label: 'Resting HR up', delta: -8, color: 'var(--error-500)' },
    { label: 'Stress trend', delta: -5, color: 'var(--focus-mental)' },
  ];
  const tools = [
    { k: 'mealplan', name: 'Meal plan', sub: 'Personal recipes', icon: HIcons.nutrition, color: 'var(--brand-orange-vibey)' },
    { k: 'workout', name: 'Workouts', sub: '3 planned', icon: HIcons.fitness, color: 'var(--focus-fitness)' },
    { k: 'meditation', name: 'Meditation', sub: '5 new sessions', icon: HIcons.mind, color: 'var(--focus-sleep)' },
    { k: 'blood', name: 'Blood report', sub: 'Upload & scan', icon: HIcons.vitals, color: 'var(--error-500)' },
  ];
  const wallUnread = wallStore ? wallStore.posts.filter(p => p.readAt === null).length : 0;
  return (
    <div style={{ maxWidth: DK_MAX, margin: '0 auto' }}>
      <DkPageHead kicker="Thursday · Apr 17" title="Good morning, Kathryn" />

      {/* Row 1 — score (left) | Anna prompt + Wall teaser (right) */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.65fr 1fr', gap: 18, alignItems: 'start' }}>
        <HCard style={{ padding: 24, borderRadius: 24 }}>
          <div style={{ display: 'flex', gap: 26, alignItems: 'center' }}>
            <AnimatedRing value={score} size={150} renderCenter={(v) => (
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 42, color: H.fg1 }}>{Math.round(v)}</div>
                <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg3 }}>of 100</div>
              </div>
            )} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: H.body, fontSize: 12, letterSpacing: 1, textTransform: 'uppercase', color: H.fg3 }}>Today's Health Score</div>
              <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24, color: H.fg1, marginTop: 4, letterSpacing: -0.4 }}>Needs attention</div>
              <div style={{ fontFamily: H.body, fontSize: 13.5, color: H.fg2, marginTop: 4 }}>Down <b style={{ color: H.danger }}>15%</b> vs last month · Women 30+ average is <b style={{ color: H.fg1 }}>{peer}</b></div>
              <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
                <DkBtn kind="outline" onClick={() => nav('chat', { topic: 'why-score-low' })}>Why is it low?</DkBtn>
                <DkBtn kind="primary" onClick={() => nav('chat', { topic: 'improve-score' })}>Improve score</DkBtn>
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 20, paddingTop: 18, borderTop: '0.5px solid var(--border-subtle)' }}>
            {drivers.map(d => (
              <div key={d.label} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 9, padding: '10px 12px', borderRadius: 14, background: 'var(--bg-app)' }}>
                <span style={{ width: 9, height: 9, borderRadius: 999, background: d.color, flexShrink: 0 }} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.label}</div>
                  <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 13, color: H.danger }}>{d.delta} pts</div>
                </div>
              </div>
            ))}
          </div>
        </HCard>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <HAnnaPromptCard onClick={() => nav('chat', { topic: 'sleep-checkin' })} />
          <HCard onClick={() => nav('wall')} className="dk-hover" style={{ padding: 18, borderRadius: 20, background: 'linear-gradient(180deg, rgba(255,244,240,0.7), #fff 70%)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
              <img src="anna.png" alt="" width="40" height="40" style={{ width: 40, height: 40, borderRadius: 999, objectFit: 'cover' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 15, color: H.fg1 }}>Your Wall</div>
                <div style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg2 }}>{wallUnread > 0 ? `${wallUnread} new insight${wallUnread > 1 ? 's' : ''} from Anna` : 'Anna’s latest insights'}</div>
              </div>
              {wallUnread > 0 && <span style={{ fontFamily: H.body, fontWeight: 600, fontSize: 11.5, color: 'var(--brand-orange-vibey)', background: 'rgba(255,105,66,0.12)', padding: '4px 9px', borderRadius: 999 }}>{wallUnread} new</span>}
            </div>
          </HCard>
        </div>
      </div>

      {/* Row 2 — Focus areas (left) | AI tools (right), labels + grids aligned */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.65fr 1fr', gap: 18, alignItems: 'start', marginTop: 8 }}>
        <div>
          <DkLabel right="Open Health" onPress={() => nav('tab:health')}>Focus areas</DkLabel>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {FOCUS_AREAS.map(f => <DkFocusCard key={f.k} f={f} onClick={() => nav('focus', { area: f.k })} />)}
          </div>
        </div>
        <div>
          <DkLabel right="All tools" onPress={() => nav('picks')}>AI tools</DkLabel>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {tools.map(t => (
              <HCard key={t.k} onClick={() => nav(t.k)} className="dk-hover" style={{ padding: '16px 18px', borderRadius: 18, minHeight: 96, boxSizing: 'border-box', display: 'flex', alignItems: 'center', gap: 13 }}>
                <HIconTile color={t.color} alpha={0.16} size={42}>{t.icon(t.color)}</HIconTile>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14.5, color: H.fg1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}</div>
                  <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 3 }}>{t.sub}</div>
                </div>
              </HCard>
            ))}
          </div>
        </div>
      </div>
      <DkDisclaimer />
    </div>
  );
}

function DkDisclaimer() {
  return <div style={{ fontFamily: H.body, fontSize: 11, lineHeight: 1.5, color: H.fg3, textAlign: 'center', padding: '30px 30px 0', maxWidth: 640, margin: '0 auto' }}>For educational purposes only. Not medical advice. Sources include peer-reviewed medical literature and clinical guidelines.</div>;
}

// ════════════════════════════════════════ HEALTH ══════════════════════════
function DeskHealth({ nav }) {
  const data = [
    { label: 'Resting HR', value: '72 bpm', trend: '↑ 6', tc: H.danger },
    { label: 'Blood pressure', value: '130/85', trend: 'High', tc: H.danger },
    { label: 'Sleep (avg)', value: '6h 42m', trend: '↓ 18m', tc: H.fg2 },
    { label: 'Steps (avg)', value: '9,200', trend: '↑ 400', tc: H.success },
  ];
  return (
    <div style={{ maxWidth: DK_MAX, margin: '0 auto' }}>
      <DkPageHead kicker="Week of Apr 14 · Apr 20" title="Your Health" />
      <div style={{ display: 'grid', gridTemplateColumns: '1.65fr 1fr', gap: 18, alignItems: 'start' }}>
        <div>
          <DkLabel>Health score</DkLabel>
          <HCard style={{ padding: 24, borderRadius: 24, minHeight: 214, boxSizing: 'border-box', display: 'flex', alignItems: 'center', gap: 26 }}>
            <AnimatedRing value={47} size={158} thickness={14} renderCenter={(v) => (
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 46, color: H.fg1 }}>{Math.round(v)}</div>
                <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginTop: 2 }}>of 100</div>
              </div>
            )} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24, color: H.fg1, letterSpacing: -0.4 }}>Needs attention</div>
              <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6, lineHeight: 1.5 }}>Down <b style={{ color: H.danger }}>15%</b> vs last month. Women 30+ average is <b style={{ color: H.fg1 }}>62</b>.</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
                <DkBtn kind="outline" onClick={() => nav('chat', { topic: 'why-score-low' })}>Why is it low?</DkBtn>
                <DkBtn kind="primary" onClick={() => nav('chat', { topic: 'improve-score' })}>Improve score</DkBtn>
              </div>
            </div>
          </HCard>
        </div>
        <div>
          <DkLabel>Data points</DkLabel>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {data.map(d => <DkStat key={d.label} label={d.label} value={d.value} sub={d.trend} subColor={d.tc} />)}
          </div>
        </div>
      </div>
      <div style={{ marginTop: 26 }}>
        <DkLabel>Breakdown</DkLabel>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {FOCUS_AREAS.map(f => <DkFocusCard key={f.k} f={f} onClick={() => nav('focus', { area: f.k })} />)}
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════ NUTRITION ═══════════════════════
function DeskNutrition({ nav }) {
  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)' },
  ];
  const macros = [
    { label: 'Protein', val: 126, goal: 140, unit: 'g', color: 'var(--brand-orange-vibey)' },
    { label: 'Carbs', val: 186, goal: 230, unit: 'g', color: 'var(--focus-fitness)' },
    { label: 'Fat', val: 64, goal: 70, unit: 'g', color: 'var(--focus-sleep)' },
    { label: 'Fiber', val: 22, goal: 30, unit: 'g', color: 'var(--focus-mental)' },
  ];
  return (
    <div style={{ maxWidth: DK_MAX, margin: '0 auto' }}>
      <DkPageHead kicker="Today · Thu Apr 17" title="Nutrition" />
      <div style={{ display: 'grid', gridTemplateColumns: '1.65fr 1fr', gap: 18, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div>
            <DkLabel>Today's intake</DkLabel>
            <HCard style={{ padding: 24, borderRadius: 24 }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 22 }}>
              <div>
                <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 44, lineHeight: 1, letterSpacing: -0.6 }}>1,830</div>
                <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg3, marginTop: 4 }}>of 2,100 kcal</div>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ height: 10, background: 'var(--bg-app)', borderRadius: 999, overflow: 'hidden' }}><div style={{ width: '87%', height: '100%', background: 'var(--grad-vibey-cta)' }} /></div>
                <div style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg2, marginTop: 8 }}>270 kcal remaining today</div>
              </div>
            </div>
            </HCard>
          </div>
          <div>
            <DkLabel right="See weekly plan" onPress={() => nav('mealplan')}>Today's meals</DkLabel>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {meals.map(m => (
                <HCard key={m.k} onClick={() => nav('mealplan')} className="dk-hover" style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px', borderRadius: 18 }}>
                  <HIconTile color={m.color} alpha={0.14} size={48}>{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.5, marginTop: 1 }}>{m.dish}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15, color: H.fg1 }}>{m.kcal}</div>
                    <div style={{ fontFamily: H.body, fontSize: 11.5, color: H.fg3 }}>{m.macros}</div>
                  </div>
                </HCard>
              ))}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <DkLabel>Macros</DkLabel>
          <HCard style={{ padding: 20, borderRadius: 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
            {macros.map(m => (
              <div key={m.label}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontFamily: H.body, fontSize: 13.5, color: H.fg1 }}>{m.label}</span>
                  <span style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg2 }}>{m.val} / {m.goal}{m.unit}</span>
                </div>
                <div style={{ height: 7, background: 'var(--bg-app)', borderRadius: 999, overflow: 'hidden' }}><div style={{ width: Math.min(100, m.val / m.goal * 100) + '%', height: '100%', background: m.color, borderRadius: 999 }} /></div>
              </div>
            ))}
          </HCard>
          <HCard onClick={() => nav('chat', { topic: 'mealplan' })} className="dk-hover" style={{ padding: 18, borderRadius: 18, display: 'flex', alignItems: 'center', gap: 12 }}>
            <HIconTile color={H.orange} alpha={0.14} size={42}>{HIcons.nutrition(H.orange)}</HIconTile>
            <div><div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>Ask Anna</div><div style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg2 }}>Meal ideas & swaps</div></div>
          </HCard>
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════ FITNESS ═════════════════════════
function DeskFitness({ nav }) {
  const workouts = [
    { k: 'zone2', name: 'Zone-2 walk', length: '35 min', type: 'Cardio', color: 'var(--focus-fitness)' },
    { k: 'strength', name: 'Full-body strength', length: '45 min', type: 'Strength', color: 'var(--quartz-400)' },
    { k: 'mobility', name: 'Hips & spine mobility', length: '15 min', type: 'Mobility', color: 'var(--focus-sleep)' },
    { k: 'run', name: 'Easy run (5k)', length: '28 min', type: 'Cardio', color: 'var(--focus-mental)' },
  ];
  const bars = [{ 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 }];
  const stats = [{ label: 'Steps', value: '64,200', of: '56,000 goal' }, { label: 'Active min', value: '182', of: '150 goal' }, { label: 'Workouts', value: '3', of: '4 planned' }];
  return (
    <div style={{ maxWidth: DK_MAX, margin: '0 auto' }}>
      <DkPageHead kicker="This week" title="Fitness" />
      <div style={{ display: 'grid', gridTemplateColumns: '1.65fr 1fr', gap: 18, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div>
            <DkLabel>This week's activity</DkLabel>
            <HCard style={{ padding: 24, borderRadius: 24, display: 'flex', alignItems: 'center', gap: 26 }}>
              <AnimatedRing value={68} size={140} color="var(--focus-fitness)" renderCenter={(v) => (
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 30, color: H.fg1 }}>{Math.round(v)}%</div>
                  <div style={{ fontFamily: H.body, fontSize: 10, color: H.fg3, letterSpacing: 0.4 }}>OF WEEK</div>
                </div>
              )} />
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 14 }}>
                {stats.map(s => (
                  <div key={s.label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', paddingBottom: 12, borderBottom: '0.5px solid var(--border-subtle)' }}>
                    <span style={{ fontFamily: H.body, fontSize: 13.5, color: H.fg3 }}>{s.label}</span>
                    <span style={{ fontFamily: H.body, fontSize: 13.5, color: H.fg2 }}><b style={{ fontWeight: 600, color: H.fg1, fontSize: 17 }}>{s.value}</b> · {s.of}</span>
                  </div>
                ))}
              </div>
            </HCard>
          </div>
          <div>
            <DkLabel>Daily minutes</DkLabel>
            <HCard style={{ padding: 20, borderRadius: 20 }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end', height: 150, justifyContent: 'space-between' }}>
                {bars.map((b, i) => (
                  <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: '100%', maxWidth: 46, height: b.h, background: 'var(--grad-vibey-cta)', borderRadius: '10px 10px 3px 3px' }} />
                    <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3 }}>{b.d}</div>
                  </div>
                ))}
              </div>
            </HCard>
          </div>
        </div>
        <div>
          <DkLabel right="Weekly plan" onPress={() => nav('chat', { topic: 'workout' })}>Planned workouts</DkLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {workouts.map(w => (
              <HCard key={w.k} onClick={() => nav('workout', { id: w.k })} className="dk-hover" style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 16px', borderRadius: 18 }}>
                <HIconTile color={w.color} alpha={0.16} size={44}>{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.5, color: H.fg2, marginTop: 1 }}>{w.type} · {w.length}</div>
                </div>
                <span style={{ fontFamily: H.body, fontWeight: 500, fontSize: 12.5, background: H.bgSecondary, padding: '7px 12px', borderRadius: 999, color: H.fg2 }}>Start</span>
              </HCard>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════ CHAT ════════════════════════════
function DeskChat({ nav, pop, resetTo, stackLen = 1, topic = 'vitals' }) {
  const label = (window.TOPIC_LABELS && window.TOPIC_LABELS[topic]) || 'Chat with Anna';
  const seedFor = (tp) => {
    if (tp === '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 (tp === 'sleep-checkin' || tp === '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 (tp === '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] = useStateDP(seedFor(topic));
  const [draft, setDraft] = useStateDP('');
  const [typing, setTyping] = useStateDP(false);
  const [threadId, setThreadId] = useStateDP(null);
  const scrollRef = useRefDP(null);
  const replyTimers = useRefDP([]);
  const onBack = stackLen > 1 ? pop : () => resetTo('home');
  useRevokeMessageBlobUrlsOnUnmount(messages);
  useEffectDP(() => { setMessages(seedFor(topic)); setThreadId(null); }, [topic]);
  useEffectDP(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [messages, typing]);
  useEffectDP(() => () => { replyTimers.current.forEach(clearTimeout); replyTimers.current = []; }, []);
  const afterReply = (ms, fn) => { const id = setTimeout(fn, ms); replyTimers.current.push(id); };

  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 a = h >= 12 ? 'PM' : 'AM'; h = h % 12 || 12; return `${h}:${String(m).padStart(2, '0')} ${a}`; };
  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); afterReply(1300, () => { 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() }]); }); };
  const sendVoice = (seconds) => { setMessages(m => [...m, { who: 'user', type: 'voice', seconds, time: nowStamp() }]); setTyping(true); afterReply(1300, () => { setTyping(false); setMessages(m => [...m, { who: 'ai', text: "Thanks for the voice note — I listened. Let's talk it through.", time: nowStamp() }]); }); };
  const setFeedback = (idx, v) => setMessages(ms => ms.map((mm, ii) => ii === idx ? { ...mm, feedback: mm.feedback === v ? null : v } : mm));

  return (
    <div style={{ maxWidth: 1080, margin: '0 auto', height: '100%', display: 'grid', gridTemplateColumns: '1fr 300px', gap: 20 }}>
      {/* conversation */}
      <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0, background: '#fff', borderRadius: 24, boxShadow: '0 1px 2px rgba(3,4,13,0.05)', overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '16px 22px', borderBottom: '0.5px solid var(--border-subtle)' }}>
          <HBackButton onClick={onBack} variant="close" label="Back" />
          <HAnnaAvatar size={36} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 16, color: H.fg1 }}>{label}</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.success }}><span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: 999, background: H.success, marginRight: 5, verticalAlign: 1 }} />Anna is online</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            {[
              { k: 'call', label: 'Voice call', onClick: () => nav('voice'), 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' },
              { k: 'history', label: 'Chat history', onClick: () => nav('history'), d: 'M3 12a9 9 0 1 0 3-6.7M3 4v4h4M12 7v5l3 2' },
              { k: 'new', label: 'New chat', onClick: () => { revokeMessageBlobUrls(messages); setMessages([{ who: 'ai', text: 'What would you like to talk about, Kathryn?', time: nowStamp() }]); }, d: 'M20 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4M15 5l4 4-8 8H7v-4l8-8Z' },
            ].map(b => (
              <button key={b.k} onClick={b.onClick} aria-label={b.label} style={{ width: 40, height: 40, borderRadius: 999, border: '1px solid var(--border-subtle)', background: '#fff', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d={b.d} /></svg>
              </button>
            ))}
          </div>
        </div>
        <div ref={scrollRef} className="no-scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {messages.map((m, i) => renderRichMessage(m, i) || (m.who === 'user' ? (
            <div key={i} style={{ alignSelf: 'flex-end', maxWidth: '74%', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
              <div style={{ background: H.gradBubble, color: '#fff', borderRadius: '22px 22px 4px 22px', padding: '12px 15px', fontFamily: H.body, fontSize: 15, lineHeight: 1.45 }}>{m.text}</div>
              <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, paddingRight: 6 }}>{m.time}</div>
            </div>
          ) : (
            <div key={i} style={{ alignSelf: 'flex-start', maxWidth: '82%', display: 'flex', flexDirection: 'column', gap: 4 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 4 }}><HAnnaAvatar size={22} /><span style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg3 }}>Anna</span></div>
              <div style={{ background: H.bg, borderRadius: '22px 22px 22px 4px', padding: '12px 15px', fontFamily: H.body, fontSize: 15, lineHeight: 1.5, color: H.fg1 }}>{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 }}>{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 (<button key={b.v} onClick={() => setFeedback(i, b.v)} aria-label={b.v === 'up' ? 'Helpful' : 'Not helpful'} style={{ width: 26, height: 26, borderRadius: 999, border: 0, display: 'grid', placeItems: 'center', cursor: 'pointer', background: active ? 'var(--quartz-soft-bg)' : 'transparent' }}><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></button>); })}
              </div>
            </div>
          )))}
          {typing && <div style={{ alignSelf: 'flex-start', marginLeft: 4 }}><HTypingIndicator /></div>}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 4 }}>
            {prompts.map(pr => <button key={pr} onClick={() => send(pr)} style={{ fontFamily: H.body, fontSize: 13, color: H.fg2, cursor: 'pointer', background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 999, padding: '7px 13px' }}>{pr}</button>)}
          </div>
        </div>
        <div style={{ padding: 14, borderTop: '0.5px solid var(--border-subtle)' }}>
          <ChatComposer variant="desktop" onSendText={send} onSendFile={sendFile} onSendVoice={sendVoice} />
        </div>
      </div>

      {/* context rail */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, paddingTop: 2 }}>
        <HCard style={{ padding: 20, borderRadius: 20, textAlign: 'center' }}>
          <img src="anna.png" alt="Anna" width="64" height="64" style={{ width: 64, height: 64, borderRadius: 999, objectFit: 'cover', margin: '0 auto' }} />
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 18, color: H.fg1, marginTop: 10 }}>Anna</div>
          <div style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg2, marginTop: 2 }}>Your AI health coach</div>
        </HCard>
        <DkLabel>Jump to</DkLabel>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[{ l: 'Chat history', r: 'history' }, { l: 'Your Wall', r: 'wall' }, { l: 'Voice call', r: 'voice' }].map(it => (
            <HCard key={it.r} onClick={() => nav(it.r)} className="dk-hover" style={{ padding: '13px 16px', borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontFamily: H.body, fontSize: 14, color: H.fg1 }}>{it.l}</span><HChevron />
            </HCard>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DeskHome, DeskHealth, DeskNutrition, DeskFitness, DeskChat, DkPageHead, DkLabel, DkRing, DkBtn, DkStat, DkFocusCard, DK_MAX });
