// Healify V2 — Health screen

function HealthScreen({ onNavigate }) {
  const score = (window.HEALIFY_USER && window.HEALIFY_USER.score) || 73;
  const [timeframe, setTimeframe] = React.useState('week');

  const domains = [
  { domain: 'sleep', title: 'Sleep', pct: 80, val: '7h 12m', delta: '+4%', color: 'var(--focus-sleep)', icon: 'moon' },
  { domain: 'fitness', title: 'Movement', pct: 55, val: '8.4k steps', delta: '-8%', color: 'var(--focus-fitness)', icon: 'dumbbell' },
  { domain: 'nutrition', title: 'Nutrition', pct: 60, val: '1840 kcal', delta: '—', color: 'var(--focus-nutrition)', icon: 'plate' },
  { domain: 'mental', title: 'Mind', pct: 70, val: 'Calm', delta: '+6%', color: 'var(--focus-mental)', icon: 'brain' },
  { domain: 'heart', title: 'Heart', pct: 45, val: '128/82', delta: '-3%', color: 'var(--focus-heart)', icon: 'heart' }];


  const insights = [
  { tag: 'Heart', color: 'var(--focus-heart)', title: 'Blood pressure is creeping up', body: 'Average BP this week: 128/82 mmHg — Stage 1 hypertension territory. Last week was 124/79.', cta: 'Talk to Anna', topic: 'bp' },
  { tag: 'Movement', color: 'var(--focus-fitness)', title: 'Steps dropped 8% since last week', body: 'You\'ve averaged 8,420/day vs your 9,200 baseline. Three days under 7k.', cta: 'See plan', topic: 'movement' },
  { tag: 'Sleep', color: 'var(--focus-sleep)', title: 'Sleep is your strongest signal', body: 'Deep-sleep ratio is 22% — top quartile for your age. Keep your 10:45pm wind-down.', cta: null }];


  return (
    <HScreen label="02 Health" pad="0 0 140px">
      <div style={{ padding: '8px 12px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div className="h-display" style={{ fontSize: 24, padding: '0 4px' }}>Health</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <HIconButton icon="calendar" tone="soft" onClick={() => onNavigate('habits')} />
          <HIconButton icon="share" tone="soft" onClick={() => { if (navigator.share) navigator.share({ title: 'Healify Score', text: `My Healify score this week: ${score} (+2)` }).catch(()=>{}); }} />
        </div>
      </div>

      <div style={{ padding: '0 16px', marginTop: 16 }}>
        <HCard pad="22px 18px" radius={26} style={{ position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: -60, left: -60, width: 240, height: 240, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,179,107,0.18), transparent 70%)' }} />
          <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <div style={{ position: 'relative', width: 240, height: 240 }}>
              <HFocusRing score={score} size={240} stroke={16}
              segments={domains.map((d) => ({ value: d.pct / 100, color: d.color }))} />
              <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
                <div style={{ fontSize: 11, letterSpacing: 1.4, textTransform: 'uppercase', color: 'var(--t-fg-3)', fontWeight: 500 }}>Healify Score</div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 64, fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1, marginTop: 4 }}>
                  <CountUp to={score} duration={1300} />
                </div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginTop: 6, fontSize: 12, color: 'var(--success)', fontWeight: 500 }}>
                  <Glyph name="arrowU" size={12} stroke={2} /> +2 this week
                </div>
              </div>
            </div>
            <div style={{ marginTop: 12, padding: '6px 12px', borderRadius: 999, background: 'var(--t-cream)', fontSize: 12, color: 'var(--t-fg-2)' }}>
              Stronger than <strong style={{ color: 'var(--t-fg-1)', fontWeight: 600 }}>68%</strong> of men 45+
            </div>
          </div>
        </HCard>
      </div>

      <div style={{ padding: '20px 16px 12px', display: 'flex', gap: 6 }}>
        {[['day', 'Day'], ['week', 'Week'], ['month', 'Month'], ['year', 'Year']].map(([k, l]) =>
        <button key={k} onClick={() => setTimeframe(k)} style={{
          flex: 1, height: 36, borderRadius: 999,
          background: timeframe === k ? 'var(--t-pill)' : 'var(--t-ink-04)',
          color: timeframe === k ? 'var(--t-pill-fg)' : 'var(--t-fg-2)',
          fontSize: 13, fontWeight: 500
        }}>{l}</button>
        )}
      </div>

      <div style={{ padding: '0 16px', marginBottom: 16 }}>
        <HCard pad="16px" radius={20}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
            <div>
              <div className="h-label">Trend · {timeframe}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em' }}>71</span>
                <span style={{ fontSize: 13, color: 'var(--t-fg-3)' }}>avg</span>
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 11, color: 'var(--t-fg-3)', fontWeight: 500 }}>RANGE</div>
              <div style={{ fontSize: 13, color: 'var(--t-fg-1)', fontWeight: 500, marginTop: 2 }}>68 – 75</div>
            </div>
          </div>
          <TrendChart data={[score-5, score-3, score-1, score-2, score, score+2, score]} labels={['M', 'T', 'W', 'T', 'F', 'S', 'S']} />
        </HCard>
      </div>

      <div style={{ padding: '0 16px' }}>
        <HSectionLabel>Breakdown</HSectionLabel>
        <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
          <div className="stagger">
          {domains.map((d, i) =>
            <button key={d.domain} onClick={() => onNavigate('focus', { area: d.domain })} style={{
              display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '14px 16px', textAlign: 'left',
              borderBottom: i < domains.length - 1 ? '1px solid var(--t-border)' : 'none',
              background: 'transparent', color: 'var(--t-fg-1)'
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 12, background: `color-mix(in oklab, ${d.color} 14%, transparent)`, color: d.color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Glyph name={d.icon} size={18} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{d.title}</div>
                <div style={{ fontSize: 12, color: 'var(--t-fg-3)', marginTop: 1 }}>{d.val}</div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600 }}>{d.pct}</div>
                <div style={{ width: 60, height: 4, borderRadius: 999, background: 'var(--t-ink-04)', overflow: 'hidden' }}>
                  <div style={{ width: `${d.pct}%`, height: '100%', background: d.color, borderRadius: 999, transition: 'width 1200ms cubic-bezier(.2,.7,.3,1) 200ms' }} />
                </div>
              </div>
            </button>
            )}
          </div>
        </HCard>
      </div>

      <div style={{ padding: '24px 16px 0' }}>
        <HSectionLabel action={{ label: 'All insights', onClick: () => onNavigate('focus', { area: 'heart' }) }}>Why your score</HSectionLabel>
        <div className="stagger" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {insights.map((ins, i) =>
          <HCard key={i} pad="14px" radius={18}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 8px', background: `color-mix(in oklab, ${ins.color} 14%, transparent)`, color: ins.color, borderRadius: 999, fontSize: 11, fontWeight: 500 }}>
                    <span style={{ width: 5, height: 5, borderRadius: 999, background: ins.color }} />{ins.tag}
                  </div>
                  <div style={{ marginTop: 8, fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500, color: 'var(--t-fg-1)', letterSpacing: '-0.02em' }}>{ins.title}</div>
                  <div style={{ fontSize: 13, color: 'var(--t-fg-2)', marginTop: 6, lineHeight: 1.5 }}>{ins.body}</div>
                  {ins.cta &&
                <button onClick={() => onNavigate('chat', { topic: ins.topic })} style={{ marginTop: 10, display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 13, fontWeight: 500, color: 'var(--brand-orange-vibey)' }}>
                      {ins.cta} <Glyph name="chevR" size={12} />
                    </button>
                }
                </div>
              </div>
            </HCard>
          )}
        </div>
      </div>

      <div style={{ padding: '24px 16px 0' }}>
        <HSectionLabel>Data sources</HSectionLabel>
        <HCard pad="0" radius={20} style={{ overflow: 'hidden' }}>
          <SourceRow icon="heart" name="Apple Health" sub="Synced 2 min ago" status="ok" />
          <SourceRow icon="droplet" name="Bloodwork" sub="Apr 18 · 14 markers" status="ok" />
          <SourceRow icon="scan" name="DNA" sub="23andMe · 142 traits" status="ok" />
          <SourceRow icon="brain" name="Mood check-ins" sub="3 of 7 days this week" status="warn" last />
        </HCard>
      </div>
    </HScreen>);

}

function TrendChart({ data = [], labels = [] }) {
  const w = 300,h = 90;
  const min = Math.min(...data) - 2,max = Math.max(...data) + 2;
  const range = max - min;
  const pts = data.map((v, i) => [i / (data.length - 1) * w, h - 8 - (v - min) / range * (h - 20)]);
  const path = pts.map(([x, y], i) => i === 0 ? `M${x} ${y}` : `L${x} ${y}`).join(' ');
  const area = path + ` L${w} ${h} L0 ${h} Z`;
  return (
    <div>
      <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
        <defs>
          <linearGradient id="trend-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#FF6942" stopOpacity="0.22" />
            <stop offset="100%" stopColor="#FF6942" stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d={area} fill="url(#trend-grad)" />
        <path d={path} stroke="#FF6942" strokeWidth={2.2} fill="none" strokeLinecap="round" />
        {pts.map(([x, y], i) => i === data.length - 1 ? <circle key={i} cx={x} cy={y} r={4} fill="#fff" stroke="#FF6942" strokeWidth={2} /> : null)}
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4, padding: '0 4px' }}>
        {labels.map((l, i) => <span key={i} style={{ fontSize: 10, color: 'var(--t-fg-3)', fontWeight: 500 }}>{l}</span>)}
      </div>
    </div>);

}

function SourceRow({ icon, name, sub, status, last }) {
  const colors = { ok: 'var(--success)', warn: 'var(--warning)', err: 'var(--error)' };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderBottom: last ? 'none' : '1px solid var(--t-border)' }}>
      <div style={{ width: 32, height: 32, borderRadius: 10, background: 'var(--t-ink-04)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Glyph name={icon} size={16} />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{name}</div>
        <div style={{ fontSize: 12, color: 'var(--t-fg-3)' }}>{sub}</div>
      </div>
      <span style={{ width: 8, height: 8, borderRadius: 999, background: colors[status] }} />
    </div>);

}

Object.assign(window, { HealthScreen, TrendChart, SourceRow });