// Healify — AI tool deep flows: Workout, Meditation, Voice.
// Requires components.jsx + screens-tools-1.jsx (HToast, HToolLoading).

const { useState: useStateT2, useEffect: useEffectT2, useRef: useRefT2 } = React;

// ══════════════════════════════════════════════════════════════════════════
// 4. WORKOUT — goal/equipment → generating → plan → session → finish
// ══════════════════════════════════════════════════════════════════════════

function WorkoutScreen({ onNavigate, onBack, id }) {
  // Stages: prefs (only when no id) | generating | plan | session | finished
  const [stage, setStage] = useStateT2(id ? 'plan' : 'prefs');
  const [prefs, setPrefs] = useStateT2({
    goal: 'strength', equipment: ['dumbbells'], minutes: 45, days: 4,
  });
  const [toast, setToast] = useStateT2(null);
  const [done, setDone] = useStateT2({});
  const [activeStep, setActiveStep] = useStateT2(0);
  const [seconds, setSeconds] = useStateT2(0);
  const [running, setRunning] = useStateT2(false);

  useEffectT2(() => {
    if (stage === 'generating') {
      const t = setTimeout(() => setStage('plan'), 1900);
      return () => clearTimeout(t);
    }
  }, [stage]);

  useEffectT2(() => {
    if (!running) return;
    const iv = setInterval(() => setSeconds(s => s + 1), 1000);
    return () => clearInterval(iv);
  }, [running]);

  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 DB 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 idMap = { strength: 'strength', muscle: 'strength', cardio: 'zone2', endurance: 'run', mobility: 'mobility' };
  const workoutKey = id ? idMap[id] || id : idMap[prefs.goal] || 'strength';
  const w = workouts[workoutKey] || workouts.strength;

  const toggleEquipment = (k) => setPrefs(p => ({
    ...p, equipment: p.equipment.includes(k) ? p.equipment.filter(x => x !== k) : [...p.equipment, k],
  }));

  const onSave = () => {
    setStage('finished');
    setToast({ msg: 'Workout logged to Fitness', kind: 'success' });
    setTimeout(() => onNavigate('tab:fitness'), 1200);
  };

  // ── Preferences
  if (stage === 'prefs') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={onBack} title="Workout" />

        <HToolHero kicker="Workout · Generator" title="Build your weekly plan" subtitle="Anna picks moves that match your goal and gear." />

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Goal</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
          {[
            { k: 'strength',  label: 'Build strength' },
            { k: 'cardio',    label: 'Cardio base' },
            { k: 'endurance', label: 'Run further' },
            { k: 'mobility',  label: 'Mobility' },
          ].map(o => (
            <div key={o.k} onClick={() => setPrefs(p => ({ ...p, goal: o.k }))} style={{
              padding: '10px 14px', borderRadius: 999, cursor: 'pointer',
              background: prefs.goal === o.k ? H.black : '#fff', color: prefs.goal === o.k ? '#fff' : H.fg1,
              fontFamily: H.body, fontWeight: 500, fontSize: 13,
              boxShadow: prefs.goal === o.k ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
            }}>{o.label}</div>
          ))}
        </div>

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Equipment</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
          {[
            { k: 'bodyweight', label: 'Bodyweight only' },
            { k: 'dumbbells',  label: 'Dumbbells' },
            { k: 'barbell',    label: 'Barbell' },
            { k: 'bands',      label: 'Bands' },
            { k: 'gym',        label: 'Full gym' },
          ].map(o => {
            const on = prefs.equipment.includes(o.k);
            return (
              <div key={o.k} onClick={() => toggleEquipment(o.k)} style={{
                padding: '10px 14px', borderRadius: 999, cursor: 'pointer',
                background: on ? H.orange : '#fff', color: on ? '#fff' : H.fg1,
                fontFamily: H.body, fontWeight: 500, fontSize: 13,
                boxShadow: on ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
              }}>{on ? '✓ ' : ''}{o.label}</div>
            );
          })}
        </div>

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Session length</HSectionLabel>
        <HCard style={{ padding: 16, marginBottom: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontFamily: H.body, fontSize: 14 }}>Minutes per session</div>
            <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22 }}>{prefs.minutes}</div>
          </div>
          <input type="range" min="15" max="90" step="5" value={prefs.minutes} onChange={e => setPrefs(p => ({ ...p, minutes: +e.target.value }))} style={{ width: '100%', marginTop: 10, accentColor: H.orange }}/>
        </HCard>
        <HCard style={{ padding: 16, marginBottom: 22 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontFamily: H.body, fontSize: 14 }}>Days per week</div>
            <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22 }}>{prefs.days}</div>
          </div>
          <input type="range" min="2" max="6" step="1" value={prefs.days} onChange={e => setPrefs(p => ({ ...p, days: +e.target.value }))} style={{ width: '100%', marginTop: 10, accentColor: H.orange }}/>
        </HCard>

        <HPrimaryButton onClick={() => setStage('generating')}>Generate workout</HPrimaryButton>
      </div>
    );
  }

  if (stage === 'generating') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={onBack} title="Workout" />
        <HToolLoading title="Designing your session…" sub={`${prefs.minutes} min · ${prefs.goal}`} hint="Sequencing exercises and recovery" />
      </div>
    );
  }

  // ── Active session
  if (stage === 'session') {
    const mm = String(Math.floor(seconds / 60)).padStart(2, '0');
    const ss = String(seconds % 60).padStart(2, '0');
    const step = w.steps[activeStep];
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => setStage('plan')} title={w.name} />

        <HCard style={{ padding: 24, borderRadius: 22, background: `linear-gradient(135deg, ${w.color}33 0%, ${w.color}11 100%)`, textAlign: 'center' }}>
          <div style={{ fontFamily: H.body, fontSize: 12, letterSpacing: 1, textTransform: 'uppercase', color: H.fg2 }}>Step {activeStep + 1} of {w.steps.length}</div>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 28, marginTop: 8, letterSpacing: -0.4 }}>{step.name}</div>
          <div style={{ fontFamily: H.body, fontSize: 15, color: H.fg2, marginTop: 4 }}>{step.reps}{step.rest ? ` · rest ${step.rest}` : ''}</div>

          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 64, marginTop: 24, letterSpacing: -1, color: H.fg1 }}>{mm}:{ss}</div>

          <div style={{ display: 'flex', gap: 10, justifyContent: 'center', marginTop: 22 }}>
            <div onClick={() => setRunning(r => !r)} style={{
              width: 64, height: 64, borderRadius: 999, background: H.gradOrange,
              display: 'grid', placeItems: 'center', cursor: 'pointer',
              boxShadow: '0 10px 24px rgba(255,104,65,0.4)',
            }}>
              {running
                ? <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
                : <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><path d="M7 4v16l13-8z"/></svg>}
            </div>
          </div>
        </HCard>

        <HSectionLabel style={{ margin: '22px 4px 10px' }}>Up next</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={() => setActiveStep(i)} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
              borderBottom: i === w.steps.length - 1 ? 'none' : '0.5px solid ' + H.border,
              cursor: 'pointer',
              background: i === activeStep ? 'var(--bg-app)' : 'transparent',
            }}>
              <div style={{ width: 28, height: 28, borderRadius: 999,
                background: done[i] ? H.success : i === activeStep ? H.orange : 'transparent',
                border: '2px solid ' + (done[i] ? H.success : i === activeStep ? H.orange : 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: i === activeStep ? '#fff' : H.fg3 }}>{i + 1}</span>}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14, opacity: done[i] ? 0.55 : 1 }}>{s.name}</div>
                <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2 }}>{s.reps}</div>
              </div>
              {i === activeStep && (
                <div onClick={(e) => { e.stopPropagation(); setDone(d => ({ ...d, [i]: true })); if (i < w.steps.length - 1) setActiveStep(i + 1); }} style={{ padding: '6px 12px', borderRadius: 999, background: H.black, color: '#fff', fontFamily: H.body, fontWeight: 500, fontSize: 12 }}>Done</div>
              )}
            </div>
          ))}
        </div>

        <div style={{ marginTop: 20 }}>
          <HPrimaryButton type="dark" onClick={onSave}>Finish session</HPrimaryButton>
        </div>

        {toast && <HToast msg={toast.msg} kind={toast.kind} onDone={() => setToast(null)} />}
      </div>
    );
  }

  // ── Finished
  if (stage === 'finished') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => onNavigate('tab:fitness')} title="Logged" />
        <HCard style={{ padding: 28, textAlign: 'center', borderRadius: 22 }}>
          <div style={{ width: 88, height: 88, borderRadius: 999, margin: '0 auto', background: H.success, display: 'grid', placeItems: 'center' }}>
            <svg width="40" height="40" 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={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, marginTop: 16 }}>Nice work, Kathryn</div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6 }}>{w.name} · {seconds > 60 ? `${Math.round(seconds/60)} min` : `${seconds}s`} logged</div>
        </HCard>
        <div style={{ marginTop: 20 }}>
          <HPrimaryButton onClick={() => onNavigate('tab:fitness')}>Back to fitness</HPrimaryButton>
        </div>
      </div>
    );
  }

  // ── Plan view (default)
  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}33 0%, ${w.color}08 100%)` }}>
        <HIconTile color={w.color} alpha={0.3} 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 }}>
        <HPrimaryButton onClick={() => { setStage('session'); setRunning(true); }}>Start session</HPrimaryButton>
        <HPrimaryButton type="outline" onClick={() => onNavigate('chat', { topic: 'workout' })}>Ask Anna to swap</HPrimaryButton>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// 5. MEDITATION — picker → player → finished/save
// ══════════════════════════════════════════════════════════════════════════

function MeditationScreen({ onNavigate, onBack }) {
  const [stage, setStage] = useStateT2('picker'); // picker | player | finished
  const [active, setActive] = useStateT2(null);
  const [t, setT] = useStateT2(0);
  const [playing, setPlaying] = useStateT2(false);
  const [toast, setToast] = useStateT2(null);

  // No library — every meditation is generated on the fly. The user picks a
  // TYPE + LENGTH, optionally adds a free-text intention, and Anna generates
  // the script + voice + music against their health profile.
  const TYPES = [
    { k: 'sleep',    label: 'Wind down',    sub: 'Body scan, slow breath',     color: 'var(--focus-sleep-500)',  tint: 'var(--focus-sleep-100)' },
    { k: 'breath',   label: 'Reset',        sub: 'Box / 4-7-8 / coherent',     color: 'var(--focus-mind-500)',   tint: 'var(--focus-mind-100)' },
    { k: 'focus',    label: 'Focus',        sub: 'Attention, intention set',   color: 'var(--focus-fitness-500)',tint: 'var(--focus-fitness-100)' },
    { k: 'anxiety',  label: 'Soothe anxiety',sub:'Grounding, body release',    color: 'var(--quartz-500)',       tint: 'var(--quartz-150)' },
    { k: 'gratitude',label: 'Gratitude',    sub: 'Reflective, heart-led',      color: 'var(--focus-heart-500)',  tint: 'var(--focus-heart-100)' },
    { k: 'morning',  label: 'Morning lift', sub: 'Energizing intention set',   color: 'var(--brand-orange)',     tint: 'rgba(255,105,66,0.10)' },
  ];
  const LENGTHS = [5, 10, 15, 20]; // minutes
  const VOICES  = ['Anna', 'Soft male', 'Soft female']; // narrator voice (defaults to Anna)
  const MUSIC   = ['Ambient', 'Nature', 'Drone', 'Silence'];

  const [typ, setTyp]       = useStateT2('breath');
  const [mins, setMins]     = useStateT2(10);
  const [intent, setIntent] = useStateT2('');
  const [voice, setVoice]   = useStateT2('Anna');
  const [music, setMusic]   = useStateT2('Ambient');
  const [genProgress, setGenProgress] = useStateT2(0);

  const chosen = TYPES.find(t => t.k === typ) || TYPES[0];
  const dur = mins * 60;
  // Temporary bridge until full personalized-flow JSX lands (see audit plan).
  const sessions = TYPES.map(t => ({ k: t.k, title: t.label, sub: t.sub, dur: 600, color: t.tint, icon: HIcons.mind }));

  useEffectT2(() => {
    if (stage !== 'generating') return;
    setGenProgress(0);
    const iv = setInterval(() => {
      setGenProgress(p => {
        if (p >= 100) {
          clearInterval(iv);
          setActive({
            title: chosen.label,
            sub: `${mins} min · ${voice} · ${music}`,
            dur,
            color: chosen.tint,
          });
          setT(0);
          setPlaying(true);
          setStage('player');
          return 100;
        }
        return p + 3;
      });
    }, 80);
    return () => clearInterval(iv);
  }, [stage]);

  useEffectT2(() => {
    if (!playing || !active) return;
    const iv = setInterval(() => {
      setT(prev => {
        if (prev >= active.dur) { clearInterval(iv); setPlaying(false); setStage('finished'); return active.dur; }
        return prev + 1;
      });
    }, 1000);
    return () => clearInterval(iv);
  }, [playing, active]);

  const fmt = (n) => `${String(Math.floor(n / 60)).padStart(2, '0')}:${String(n % 60).padStart(2, '0')}`;

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

        <HToolHero subtitle="Anna generates a personalized session — script, voice, and music — for your profile." />

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Type</HSectionLabel>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 18 }}>
          {TYPES.map(o => {
            const on = typ === o.k;
            return (
              <HCard key={o.k} onClick={() => setTyp(o.k)} style={{
                padding: 14, borderRadius: 16,
                background: on ? '#fff' : '#fff',
                border: on ? `1.5px solid ${H.orange}` : '1px solid ' + H.border,
                boxShadow: on ? '0 6px 18px rgba(255,104,65,0.14)' : '0 1px 2px rgba(3,4,13,0.04)',
              }}>
                <HIconTile color={o.color} alpha={0.18} size={36}>{HIcons.mind(o.color)}</HIconTile>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 14, marginTop: 10 }}>{o.label}</div>
                <div style={{ fontFamily: H.body, fontSize: 11, color: H.fg2, marginTop: 2, lineHeight: 1.35 }}>{o.sub}</div>
              </HCard>
            );
          })}
        </div>

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Length</HSectionLabel>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
          {LENGTHS.map(n => {
            const on = mins === n;
            return (
              <div key={n} onClick={() => setMins(n)} style={{
                padding: '10px 16px', borderRadius: 999, cursor: 'pointer',
                background: on ? H.black : '#fff', color: on ? '#fff' : H.fg1,
                fontFamily: H.body, fontWeight: 500, fontSize: 13,
                boxShadow: on ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
                minWidth: 64, textAlign: 'center',
              }}>{n} min</div>
            );
          })}
        </div>

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Anything you'd like to add? <span style={{ color: H.fg3, fontWeight: 400 }}>(optional)</span></HSectionLabel>
        <HCard style={{ padding: 0, marginBottom: 18 }}>
          <textarea
            value={intent}
            onChange={e => setIntent(e.target.value)}
            placeholder="e.g. I'm anxious about a 9am presentation, help me ground before bed…"
            rows={3}
            style={{
              width: '100%', border: 0, outline: 'none', resize: 'none',
              padding: '14px 16px', borderRadius: 16, background: 'transparent',
              fontFamily: H.body, fontSize: 14, color: H.fg1, lineHeight: 1.45,
              boxSizing: 'border-box',
            }}
          />
        </HCard>

        <HSectionLabel style={{ margin: '0 4px 10px' }}>Voice & music</HSectionLabel>
        <HCard style={{ padding: 0, marginBottom: 24 }}>
          <div style={{ padding: '12px 16px', borderBottom: '0.5px solid ' + H.border }}>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginBottom: 6 }}>Voice</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {VOICES.map(v => (
                <div key={v} onClick={() => setVoice(v)} style={{
                  padding: '6px 12px', borderRadius: 999, cursor: 'pointer',
                  background: voice === v ? H.orange : 'var(--bg-app)', color: voice === v ? '#fff' : H.fg1,
                  fontFamily: H.body, fontWeight: 500, fontSize: 12,
                }}>{v}</div>
              ))}
            </div>
          </div>
          <div style={{ padding: '12px 16px' }}>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginBottom: 6 }}>Music</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {MUSIC.map(m => (
                <div key={m} onClick={() => setMusic(m)} style={{
                  padding: '6px 12px', borderRadius: 999, cursor: 'pointer',
                  background: music === m ? H.orange : 'var(--bg-app)', color: music === m ? '#fff' : H.fg1,
                  fontFamily: H.body, fontWeight: 500, fontSize: 12,
                }}>{m}</div>
              ))}
            </div>
          </div>
        </HCard>

        <HPrimaryButton onClick={() => setStage('generating')}>Generate meditation</HPrimaryButton>
      </div>
    );
  }

  if (stage === 'generating') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => setStage('picker')} title="Meditation" />
        <HToolLoading
          title="Anna is writing your session…"
          sub={`${chosen.label} · ${mins} min · ${voice} voice · ${music}`}
          hint={genProgress < 33 ? 'Drafting your script…' : genProgress < 66 ? 'Synthesizing voice…' : 'Mixing background music…'}
        />
        <div style={{ height: 6, borderRadius: 999, background: 'var(--bg-app)', overflow: 'hidden', marginTop: 16 }}>
          <div style={{ width: genProgress + '%', height: '100%', background: H.gradOrange, transition: 'width 80ms linear' }}/>
        </div>
        {intent && (
          <HCard style={{ padding: 14, marginTop: 16, background: 'var(--bg-app)' }}>
            <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>Your intention</div>
            <div style={{ fontFamily: H.body, fontSize: 13, color: H.fg1, marginTop: 4, lineHeight: 1.4 }}>{intent}</div>
          </HCard>
        )}
      </div>
    );
  }

  if (stage === 'finished') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => setStage('picker')} title="Complete" />
        <HCard style={{ padding: 28, textAlign: 'center', borderRadius: 22 }}>
          <div style={{ width: 88, height: 88, borderRadius: 999, margin: '0 auto', background: 'var(--focus-sleep-100)', display: 'grid', placeItems: 'center' }}>
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><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>
          </div>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 22, marginTop: 16 }}>Beautiful.</div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg2, marginTop: 6, lineHeight: 1.5 }}>You completed {active?.title} · {Math.round((active?.dur || 0)/60)} min</div>
        </HCard>
        <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <HPrimaryButton onClick={() => { setToast({ msg: 'Session saved to Mind', kind: 'success' }); setTimeout(() => onNavigate('tab:home'), 1200); }}>Save to Mind</HPrimaryButton>
          <HPrimaryButton type="outline" onClick={() => setStage('picker')}>Pick another</HPrimaryButton>
        </div>
        {toast && <HToast msg={toast.msg} kind={toast.kind} onDone={() => setToast(null)} />}
      </div>
    );
  }

  // ── Player
  const pct = (t / (active?.dur || 1)) * 100;
  return (
    <div className="screen-enter" style={{ padding: '14px 20px 40px', background: 'linear-gradient(180deg, var(--focus-sleep-100) 0%, var(--focus-sleep) 70%, var(--brand-ink) 100%)', color: '#fff', minHeight: '100%' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <HBackButton onClick={() => setStage('picker')} dark variant="close" label="" />
        <div style={{ fontFamily: H.body, fontSize: 13, color: 'rgba(255,255,255,0.75)' }}>Meditation</div>
        <div style={{ width: 36 }}/>
      </div>

      <div style={{ textAlign: 'center', marginTop: 30 }}>
        <div style={{ width: 200, height: 200, borderRadius: 999, margin: '0 auto', background: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(20px)', display: 'grid', placeItems: 'center', position: 'relative' }}>
          <div style={{ position: 'absolute', inset: 0, borderRadius: 999, border: '2px solid rgba(255,255,255,0.3)', animation: 'hPulse 4s ease-in-out infinite' }}/>
          <div style={{ position: 'absolute', inset: 16, borderRadius: 999, border: '1px solid rgba(255,255,255,0.2)', animation: 'hPulse 4s ease-in-out infinite', animationDelay: '0.5s' }}/>
          <style>{`@keyframes hPulse { 0%,100% { transform: scale(1); opacity: 0.8; } 50% { transform: scale(1.08); opacity: 0.3; } }`}</style>
          <div style={{ width: 90, height: 90, borderRadius: 999, background: 'rgba(255,255,255,0.18)', display: 'grid', placeItems: 'center' }}>
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><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>
          </div>
        </div>
        <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 26, marginTop: 28, letterSpacing: -0.3 }}>{active?.title}</div>
        <div style={{ fontFamily: H.body, fontSize: 14, color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>{active?.sub}</div>
      </div>

      {/* Scrubber */}
      <div style={{ marginTop: 50, padding: '0 6px' }}>
        <div style={{ height: 4, background: 'rgba(255,255,255,0.18)', borderRadius: 999, position: 'relative', overflow: 'hidden' }}>
          <div style={{ width: pct + '%', height: '100%', background: '#fff', borderRadius: 999, transition: 'width 240ms linear' }}/>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontFamily: H.body, fontSize: 12, color: 'rgba(255,255,255,0.7)' }}>
          <span>{fmt(t)}</span>
          <span>-{fmt(Math.max(0, (active?.dur || 0) - t))}</span>
        </div>
      </div>

      {/* Transport */}
      <div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 36, alignItems: 'center' }}>
        <div onClick={() => setT(s => Math.max(0, s - 15))} style={{ width: 52, height: 52, borderRadius: 999, background: 'rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 9"/><path d="M3 4v5h5"/><text x="12" y="16" fontSize="6" fill="#fff" textAnchor="middle" fontFamily="sans-serif">15</text></svg>
        </div>
        <div onClick={() => setPlaying(p => !p)} style={{ width: 76, height: 76, borderRadius: 999, background: '#fff', display: 'grid', placeItems: 'center', cursor: 'pointer', boxShadow: '0 14px 36px rgba(0,0,0,0.3)' }}>
          {playing
            ? <svg width="28" height="28" viewBox="0 0 24 24" fill={H.fg1}><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
            : <svg width="28" height="28" viewBox="0 0 24 24" fill={H.fg1}><path d="M7 4v16l13-8z"/></svg>}
        </div>
        <div onClick={() => setT(s => Math.min((active?.dur || 0), s + 15))} style={{ width: 52, height: 52, borderRadius: 999, background: 'rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a9 9 0 1 1-3-6.7L21 9"/><path d="M21 4v5h-5"/></svg>
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════════
// 6. VOICE — pre-flight → live → transcript → summary
// ══════════════════════════════════════════════════════════════════════════

function VoiceCallScreen({ onBack, onNavigate }) {
  const [stage, setStage] = useStateT2('preflight'); // preflight | live | transcript | summary
  const [t, setT] = useStateT2(0);
  const [muted, setMuted] = useStateT2(false);
  const [toast, setToast] = useStateT2(null);

  useEffectT2(() => {
    if (stage !== 'live') return;
    const iv = setInterval(() => setT(x => x + 1), 1000);
    return () => clearInterval(iv);
  }, [stage]);

  const mm = String(Math.floor(t / 60)).padStart(2, '0');
  const ss = String(t % 60).padStart(2, '0');

  const transcript = [
    { who: 'anna', text: "Hey Kathryn, what's on your mind tonight?" },
    { who: 'me',   text: "I've been waking up at 3am for the last three nights. Can't fall back asleep." },
    { who: 'anna', text: "That's frustrating. A few quick checks: any caffeine after lunch, and how was your stress on those days?" },
    { who: 'me',   text: 'Tuesday I had a 4pm latte. And work has been heavy all week.' },
    { who: 'anna', text: "Got it. The late caffeine likely shortened your deep sleep. Let's cap caffeine at 2pm and try a 5-min wind-down at 10:30 tonight." },
    { who: 'me',   text: 'Sounds good.' },
    { who: 'anna', text: "I'll send a reminder. If you wake again, try the body-scan meditation in your library — most people fall back asleep within 8 minutes." },
  ];

  const summary = [
    { k: 'Issue',   v: '3 nights of 3am waking' },
    { k: 'Drivers', v: 'Late caffeine + work stress' },
    { k: 'Plan',    v: 'Cap caffeine at 2pm · Wind-down 10:30 · Body-scan if waking' },
    { k: 'Follow-up', v: 'Anna will check in tomorrow morning' },
  ];

  // ── Pre-flight
  if (stage === 'preflight') {
    return (
      <div className="screen-enter" style={{ background: 'linear-gradient(135deg, var(--brand-ink) 0%, #1A1018 55%, #2A0E1A 100%)', color: '#fff', minHeight: '100%', 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: 24 }}>
          <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 }}>Talk to Anna</div>
          <div style={{ fontFamily: H.body, fontSize: 14, color: 'rgba(255,255,255,0.7)', marginTop: 6, lineHeight: 1.5 }}>Hands-free chat. Anna will speak back.</div>
        </div>
        <div style={{ marginTop: 36, padding: '0 12px' }}>
          {[
            { ic: '🎙', t: 'Mic access', s: 'Required for the call' },
            { ic: '📝', t: 'Transcribed locally', s: 'You can review or delete after' },
            { ic: '🔇', t: 'Mute anytime',  s: 'Toggle without ending the call' },
          ].map((r, i) => (
            <div key={i} style={{ display: 'flex', gap: 12, padding: '12px 0', borderBottom: i < 2 ? '0.5px solid rgba(255,255,255,0.1)' : 'none' }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(255,255,255,0.1)', display: 'grid', placeItems: 'center', fontSize: 18 }}>{r.ic}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 15 }}>{r.t}</div>
                <div style={{ fontFamily: H.body, fontSize: 12, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>{r.s}</div>
              </div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 30 }}>
          <button onClick={() => setStage('live')} style={{ width: '100%', border: 0, padding: '16px 20px', borderRadius: 999, background: 'var(--grad-vibey)', color: '#fff', fontFamily: H.body, fontWeight: 500, fontSize: 16, boxShadow: '0 10px 28px rgba(255,104,65,0.4)', cursor: 'pointer' }}>Start call</button>
        </div>
      </div>
    );
  }

  // ── Transcript
  if (stage === 'transcript') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => setStage('summary')} title="Transcript" />
        <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg3, marginBottom: 14 }}>{mm}:{ss} · just now</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {transcript.map((m, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', flexDirection: m.who === 'me' ? 'row-reverse' : 'row' }}>
              {m.who === 'anna' && <HAnnaAvatar size={28} />}
              <div style={{
                maxWidth: '78%',
                background: m.who === 'me' ? H.black : '#fff',
                color: m.who === 'me' ? '#fff' : H.fg1,
                padding: '10px 14px', borderRadius: 16,
                fontFamily: H.body, fontSize: 14, lineHeight: 1.45,
                boxShadow: m.who === 'me' ? 'none' : '0 1px 2px rgba(3,4,13,0.04)',
              }}>{m.text}</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 22 }}>
          <HPrimaryButton type="outline" onClick={() => setStage('summary')}>Back to summary</HPrimaryButton>
        </div>
      </div>
    );
  }

  // ── Summary
  if (stage === 'summary') {
    return (
      <div className="screen-enter" style={{ padding: '14px 20px 140px', background: H.bg, minHeight: '100%' }}>
        <HTopBar onBack={() => onNavigate ? onNavigate('tab:home') : onBack()} title="Call summary" />
        <HCard style={{ padding: 18, borderRadius: 22, display: 'flex', alignItems: 'center', gap: 12 }}>
          <HAnnaAvatar size={44} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 16 }}>Anna · sleep check-in</div>
            <div style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, marginTop: 2 }}>{mm}:{ss} · just now</div>
          </div>
        </HCard>

        <HSectionLabel style={{ margin: '22px 4px 10px' }}>Summary</HSectionLabel>
        <HCard style={{ padding: 0 }}>
          {summary.map((s, i, arr) => (
            <div key={s.k} style={{ padding: '14px 16px', borderBottom: i === arr.length - 1 ? 'none' : '0.5px solid ' + H.border }}>
              <div style={{ fontFamily: H.body, fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', color: H.fg3 }}>{s.k}</div>
              <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg1, marginTop: 4, lineHeight: 1.45 }}>{s.v}</div>
            </div>
          ))}
        </HCard>

        <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <HPrimaryButton onClick={() => setStage('transcript')}>View full transcript</HPrimaryButton>
          <HPrimaryButton type="outline" onClick={() => onNavigate ? onNavigate('tab:home') : onBack()}>Done</HPrimaryButton>
        </div>
      </div>
    );
  }

  // ── Live
  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={() => setStage('preflight')} 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>

      <div style={{ display: 'flex', gap: 4, alignItems: 'center', justifyContent: 'center', height: 80, marginTop: 40 }}>
        {Array.from({ length: 28 }).map((_, i) => (
          <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: `${i * 80}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={() => setStage('summary')} 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={() => setToast({ msg: 'Speaker toggled', kind: 'success' })} 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>
      {toast && <HToast msg={toast.msg} kind={toast.kind} onDone={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, {
  WorkoutScreen, MeditationScreen, VoiceCallScreen,
});
