// Healify V2 — Primary tab screens (Home, Health, Chat, Nutrition, Fitness)
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

// ============================================================================
// HOME — "Today" — the morning briefing
// ============================================================================
function HomeScreen({ onNavigate }) {
  const userName = (window.HEALIFY_USER && window.HEALIFY_USER.first) || 'Kathryn';
  const score = (window.HEALIFY_USER && window.HEALIFY_USER.score) || 73;
  const [briefingExpanded, setBriefingExpanded] = useStateP(false);

  // Live API integration — pulls real habits when the Tweaks "Live API" toggle is on.
  const [liveHabits, setLiveHabits] = useStateP(null);
  useEffectP(() => {
    if (!window.healifyApi) return;
    let cancelled = false;
    window.healifyApi.habits.list().then(d => {
      if (!cancelled && d && Array.isArray(d.habits) && d.habits.length > 0) setLiveHabits(d.habits);
    }).catch(() => {});
    return () => { cancelled = true; };
  }, []);

  const focusItems = [
    { domain: 'sleep',     title: 'Sleep',      value: '7h 12m', unit: 'last night',          status: 'normal',    trend: 4,  spark: [6,7,5,6,7.5,8,7.2] },
    { domain: 'fitness',   title: 'Movement',   value: '8,420',  unit: 'steps',               status: 'fair',      trend: -8, spark: [12,9,7,10,8,9,8] },
    { domain: 'nutrition', title: 'Nutrition',  value: '1,840',  unit: 'kcal · 38g protein left', status: 'fair',  trend: 0,  spark: [1.6,1.9,2.1,1.8,2.0,1.7,1.8] },
    { domain: 'mental',    title: 'Mind',       value: 'Calm',   unit: 'PHQ-9 ↓ 2 wk',        status: 'normal',    trend: 6,  spark: [3,4,5,4,5,6,7] },
    { domain: 'heart',     title: 'Heart',      value: '128/82', unit: 'mmHg · 3 reads',      status: 'attention', trend: -3, spark: [130,132,128,131,128,128,128] },
  ];

  const mockHabits = [
    { id: 'wat',     label: 'Water',         done: 5,  total: 8,   icon: 'droplet', color: 'var(--focus-mental)' },
    { id: 'med',     label: 'Meditation',    done: 0,  total: 1,   icon: 'brain',   color: 'var(--focus-sleep)' },
    { id: 'walk',    label: 'Walk 30 min',   done: 0,  total: 1,   icon: 'flame',   color: 'var(--focus-fitness)' },
    { id: 'protein', label: 'Protein 120g',  done: 82, total: 120, icon: 'plate',   color: 'var(--focus-nutrition)' },
  ];
  // Map live habits to the tile shape — show first 4.
  const habits = liveHabits ? liveHabits.slice(0, 4).map(h => ({
    id: h.id || h.habit_id || h.name,
    label: h.title || h.name || h.label || 'Habit',
    done: h.completed_today || h.completedCount || 0,
    total: h.target || h.target_per_day || 1,
    icon: h.icon || 'flame',
    color: h.color || 'var(--brand-orange-vibey)',
  })) : mockHabits;

  return (
    <HScreen label="01 Home">
      <div style={{ padding: '8px 4px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
          <HealifyHeart size={32}/>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 11, color: 'var(--t-fg-3)', letterSpacing: '-0.1px', fontWeight: 500 }}>Tuesday, May 26</div>
            <div className="h-display" style={{ fontSize: 26, marginTop: 0, letterSpacing: '-0.02em' }}>Hi, {userName}</div>
          </div>
        </div>
        <HIconButton icon="bell" tone="soft" onClick={() => onNavigate('notifications')} />
      </div>

      {/* Hero — Anna's morning briefing */}
      <div className="slide-up" style={{ marginBottom: 16, animationDelay: '60ms' }}>
        <HCard tone="ink" radius={28} pad="20px">
          {/* Identity row */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <HAnnaAvatar size={36} state="idle" />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', letterSpacing: '-0.1px' }}>Anna</div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 1 }}>Morning briefing · 7:24 am</div>
            </div>
            <button onClick={() => onNavigate('voice')} aria-label="Voice with Anna" style={{
              width: 40, height: 40, borderRadius: 999,
              background: 'var(--grad-warm-orange)', color: '#fff',
              boxShadow: 'var(--shadow-orange)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <Glyph name="mic" size={18}/>
            </button>
          </div>

          {/* Briefing copy */}
          <div style={{ marginTop: 16, fontSize: 17, lineHeight: 1.45, color: '#fff', letterSpacing: '-0.2px' }}>
            Sleep was solid — but BP is creeping up. Let's nudge sodium down today.
          </div>
          {briefingExpanded && (
            <div style={{ marginTop: 8, fontSize: 13, lineHeight: 1.55, color: 'rgba(255,255,255,0.7)' }}>
              HRV recovered to 48ms overnight. This morning's BP read 128/82 — +4 mmHg from yesterday. Likely culprit: yesterday's restaurant lunch (~1,800mg sodium). I queued a low-sodium meal swap.
            </div>
          )}

          {/* Inline actions */}
          <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
            <button onClick={() => setBriefingExpanded(!briefingExpanded)} style={{ color: 'var(--brand-gold-sand)', fontSize: 13, fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              {briefingExpanded ? 'Show less' : 'Read more'}
              <Glyph name={briefingExpanded ? 'chevU' : 'chevD'} size={12} stroke={2.2}/>
            </button>
            <span style={{ width: 3, height: 3, borderRadius: 999, background: 'rgba(255,255,255,0.3)' }}/>
            <button onClick={() => onNavigate('chat')} style={{ color: 'rgba(255,255,255,0.85)', fontSize: 13, fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              Chat with Anna
              <Glyph name="chevR" size={12} stroke={2.2}/>
            </button>
          </div>
        </HCard>
      </div>

      {/* Score orbital */}
      <div className="slide-up" style={{ marginBottom: 16, animationDelay: '160ms' }}>
        <HCard onClick={() => onNavigate('health')} pad="18px" radius={24} style={{ position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: -40, right: -40, width: 160, height: 160, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,179,107,0.25), transparent 70%)' }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, position: 'relative' }}>
            <div style={{ position: 'relative', width: 124, height: 124, flexShrink: 0 }}>
              <HFocusRing score={score} size={124} stroke={11}
                segments={[
                  { value: 0.8, color: 'var(--focus-sleep)' },
                  { value: 0.55, color: 'var(--focus-fitness)' },
                  { value: 0.6, color: 'var(--focus-nutrition)' },
                  { value: 0.7, color: 'var(--focus-mental)' },
                  { value: 0.45, color: 'var(--focus-heart)' },
                ]} />
              <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1 }}>
                  <CountUp to={score} duration={1100}/>
                </div>
                <div style={{ fontSize: 9, color: 'var(--t-fg-3)', textTransform: 'uppercase', letterSpacing: 1.2, marginTop: 2, fontWeight: 500 }}>Healify</div>
              </div>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="h-label">Health Score</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500 }}>+2</span>
                <span style={{ fontSize: 12, color: 'var(--success)', fontWeight: 500 }}>this week</span>
              </div>
              <div style={{ fontSize: 13, color: 'var(--t-fg-2)', marginTop: 6, lineHeight: 1.4 }}>
                Stronger than 68% of men your age. Drag is from heart & movement.
              </div>
              <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 6, color: 'var(--brand-orange-vibey)', fontSize: 12, fontWeight: 500 }}>
                See the why <Glyph name="chevR" size={12} />
              </div>
            </div>
          </div>
        </HCard>
      </div>

      <HSectionLabel action={{ label: 'All habits', onClick: () => onNavigate('habits') }}>Today's habits</HSectionLabel>
      <div className="stagger" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, marginBottom: 16 }}>
        {habits.map(h => <HabitTile key={h.id} habit={h} onClick={() => onNavigate('habits')} />)}
      </div>

      <HSectionLabel>Focus areas</HSectionLabel>
      <div className="stagger" style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 16 }}>
        {focusItems.map(f => (
          <HFocusRow key={f.domain} {...f} onClick={() => onNavigate('focus', { area: f.domain })} />
        ))}
      </div>

      <HSectionLabel action={{ label: 'All tools', onClick: () => onNavigate('picks') }}>For you today</HSectionLabel>
      <div style={{ display: 'flex', gap: 10, overflowX: 'auto', margin: '0 -16px', padding: '0 16px 4px', scrollbarWidth: 'none' }}>
        <ToolCard label="Meditation" sub="For your BP — 10 min" icon="brain" color="var(--focus-sleep)" onClick={() => onNavigate('meditation')} />
        <ToolCard label="Meal plan" sub="Low-sodium swaps" icon="plate" color="var(--focus-nutrition)" onClick={() => onNavigate('mealplan')} />
        <ToolCard label="Workout" sub="20-min walk" icon="dumbbell" color="var(--focus-fitness)" onClick={() => onNavigate('workout')} />
        <ToolCard label="Bloodwork" sub="Upload" icon="droplet" color="var(--focus-heart)" onClick={() => onNavigate('blood')} />
      </div>

      <div style={{ height: 24 }} />
      <button onClick={() => onNavigate('chat', { topic: 'evening' })} style={{ display: 'block', width: '100%', textAlign: 'left' }}>
        <HCard radius={20} pad="14px" elevate={false} style={{ border: '1px dashed var(--t-ink-12)', background: 'transparent' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Glyph name="sparkle" size={18} style={{ color: 'var(--brand-orange-vibey)' }} />
            <div style={{ flex: 1, fontSize: 13, color: 'var(--t-fg-2)', lineHeight: 1.4 }}>
              <em style={{ fontStyle: 'normal', fontFamily: 'var(--font-display)', color: 'var(--t-fg-1)' }}>Tonight at 9pm</em> — Anna will ping you about a wind-down.
            </div>
            <Glyph name="chevR" size={14} style={{ color: 'var(--t-fg-3)' }} />
          </div>
        </HCard>
      </button>
    </HScreen>
  );
}

function HabitTile({ habit, onClick }) {
  const pct = habit.done / habit.total;
  const r = 14;
  const c = 2 * Math.PI * r;
  const [drawn, setDrawn] = React.useState(false);
  React.useEffect(() => { const id = requestAnimationFrame(() => setDrawn(true)); return () => cancelAnimationFrame(id); }, []);
  return (
    <HCard pad="12px" radius={16} onClick={onClick}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ position: 'relative', width: 36, height: 36, flexShrink: 0 }}>
          <svg width={36} height={36} viewBox="0 0 36 36">
            <circle cx={18} cy={18} r={r} fill="none" stroke="var(--t-ink-04)" strokeWidth={4} />
            <circle cx={18} cy={18} r={r} fill="none" stroke={habit.color} strokeWidth={4} strokeLinecap="round"
                    strokeDasharray={`${(drawn ? c * pct : 0)} ${c}`} transform="rotate(-90 18 18)"
                    style={{ transition: 'stroke-dasharray 1100ms cubic-bezier(.2,.7,.3,1) 120ms' }}/>
          </svg>
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: habit.color }}>
            <Glyph name={habit.icon} size={14} />
          </div>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, color: 'var(--t-fg-3)', fontWeight: 500, letterSpacing: 0.2 }}>{habit.done}/{habit.total}</div>
          <div style={{ fontSize: 12.5, fontWeight: 500, letterSpacing: '-0.1px', lineHeight: 1.25, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', color: 'var(--t-fg-1)' }}>{habit.label}</div>
        </div>
      </div>
    </HCard>
  );
}

function ToolCard({ label, sub, icon, color, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 170, flexShrink: 0, padding: 14, borderRadius: 18,
      background: 'var(--t-surface)', boxShadow: 'var(--shadow-md)',
      display: 'flex', flexDirection: 'column', gap: 10, textAlign: 'left',
    }}>
      <div style={{ width: 36, height: 36, borderRadius: 12, background: `color-mix(in oklab, ${color} 14%, transparent)`, color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Glyph name={icon} size={20} />
      </div>
      <div>
        <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{label}</div>
        <div style={{ fontSize: 12, color: 'var(--t-fg-3)', marginTop: 2 }}>{sub}</div>
      </div>
    </button>
  );
}

Object.assign(window, { HomeScreen, HabitTile, ToolCard });
