/* global React */
// =========================================================================
// EDUCATION — Cycles & Rhythm / Disorders / Quality / Myths
// =========================================================================

const { useState: useEdState, useEffect: useEdEffect } = React;

// ── 1. SLEEP CYCLE & CIRCADIAN RHYTHM ────────────────────────────────────
function CyclesWindow() {
  const [view, setView] = useEdState('cycle');
  return (
    <div className="window-inner">
      <h1>SLEEP CYCLE & RHYTHM</h1>
      <p className="muted" style={{margin: '8px 0 16px'}}>
        Two clocks rule sleep: <span className="accent-moon">Process S</span> (homeostatic pressure that builds while awake) and <span className="accent-cyan">Process C</span> (circadian rhythm — a ~24h oscillation). Together they decide when you're sleepy.
      </p>

      <div className="tabs">
        <button className={`tab ${view==='cycle'?'active':''}`} onClick={()=>setView('cycle')}>STAGES (90 MIN)</button>
        <button className={`tab ${view==='night'?'active':''}`} onClick={()=>setView('night')}>WHOLE NIGHT</button>
        <button className={`tab ${view==='circadian'?'active':''}`} onClick={()=>setView('circadian')}>24-HOUR CLOCK</button>
      </div>

      {view === 'cycle' && <CycleStages />}
      {view === 'night' && <WholeNight />}
      {view === 'circadian' && <CircadianClock />}

      <div className="pixel-divider" />
      <div className="pixel-card">
        <h4 style={{marginBottom: 8}}>WHY IT MATTERS</h4>
        <p style={{fontSize: 18}}>
          Cutting sleep short doesn't just remove "the end" — REM is back-loaded, so the last hour you skip is mostly the dreaming hour. Skipping bedtime by 90 minutes can wipe out an entire REM episode and most of the memory consolidation that comes with it.
        </p>
      </div>
    </div>
  );
}

const STAGES = [
  { id: 'n1', label: 'NREM-1', color: '#c490e4', pct: 5,  desc: 'Drifting off. Muscles relax, you may twitch (hypnic jerk). Easy to wake.', brain: 'mixed alpha→theta' },
  { id: 'n2', label: 'NREM-2', color: '#8475d4', pct: 45, desc: 'Light sleep. Body temp drops, heart rate slows. Sleep spindles + K-complexes appear.', brain: 'spindles 12-14Hz' },
  { id: 'n3', label: 'NREM-3', color: '#7de2d1', pct: 25, desc: 'Deep slow-wave sleep. Hardest to wake. Memory consolidation, growth hormone release, glymphatic clearance.', brain: 'delta <4Hz' },
  { id: 'rem', label: 'REM',    color: '#ff8fb8', pct: 25, desc: 'Vivid dreams. Eyes dart, brain is highly active, body is paralyzed (atonia). Procedural + emotional memory.', brain: 'mixed, awake-like' },
];

function CycleStages() {
  const [hover, setHover] = useEdState('n3');
  const current = STAGES.find(s => s.id === hover);
  return (
    <div>
      <div style={{display: 'flex', height: 32, marginBottom: 14, boxShadow: 'inset 0 0 0 2px var(--chrome)'}}>
        {STAGES.map(s => (
          <div key={s.id}
            onMouseEnter={() => setHover(s.id)}
            onClick={() => setHover(s.id)}
            style={{
              flex: s.pct,
              background: s.color,
              borderRight: '2px solid var(--bg-0)',
              cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-pixel)', fontSize: 9, color: 'var(--bg-0)',
              opacity: hover === s.id ? 1 : 0.7
            }}>
            {s.label}
          </div>
        ))}
      </div>
      <div className="chart-axis" style={{justifyContent: 'space-between', padding: '0 4px'}}>
        <span>0 min</span><span>~22</span><span>~67</span><span>~80</span><span>90 min</span>
      </div>

      <div className="stage-grid" style={{display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10, marginTop: 18}}>
        {STAGES.map(s => (
          <div key={s.id}
            onClick={() => setHover(s.id)}
            className="pixel-card"
            style={{cursor: 'pointer', margin: 0, boxShadow: hover === s.id ? `inset 0 0 0 2px ${s.color}` : 'inset 0 0 0 2px var(--chrome-hi)'}}>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6}}>
              <span style={{fontFamily: 'var(--font-pixel)', fontSize: 11, color: s.color}}>{s.label}</span>
              <span className="muted" style={{fontSize: 14}}>{s.pct}%</span>
            </div>
            <div style={{fontFamily: 'var(--font-mono)', fontSize: 17, color: 'var(--ink)'}}>{s.desc}</div>
            <div style={{fontFamily: 'var(--font-pixel)', fontSize: 8, color: 'var(--ink-faint)', marginTop: 8}}>EEG: {s.brain}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function WholeNight() {
  // 5 cycles, REM grows, deep shrinks
  const stages = [
    0, 2, 3, 4, 4, 3, 2, 1, // cycle 1
    2, 3, 4, 3, 2, 1, 1,    // cycle 2
    2, 3, 3, 2, 1, 1, 1,    // cycle 3
    2, 2, 1, 1, 1, 1,       // cycle 4
    2, 1, 1, 0,             // cycle 5
  ];
  const labels = ['AWAKE', 'REM', 'N1', 'N2', 'N3'];
  const colors = ['#ff5c7a', '#ff8fb8', '#c490e4', '#8475d4', '#7de2d1'];
  const w = 520, h = 200, pad = 50;
  const stepX = (w - pad - 10) / (stages.length - 1);
  const rowH = (h - 40) / 4;

  return (
    <div className="cycle-diagram" style={{height: 'auto'}}>
      <svg viewBox={`0 0 ${w} ${h}`} width="100%" shapeRendering="crispEdges">
        {labels.map((lbl, i) => (
          <g key={lbl}>
            <rect x={pad} y={10 + i * rowH} width={w - pad - 10} height="1" fill="#4b3f8a" opacity="0.4" />
            <text x={pad - 6} y={14 + i * rowH} textAnchor="end" fontFamily="VT323" fontSize="14" fill={colors[i]}>{lbl}</text>
          </g>
        ))}
        {[0,1,2,3,4,5,6,7,8].map(hr => (
          <text key={hr} x={pad + (hr / 8) * (w - pad - 10)} y={h - 8} textAnchor="middle" fontFamily="VT323" fontSize="14" fill="#b8a8e0">
            {hr}h
          </text>
        ))}
        <path
          d={stages.map((s, i) => `${i === 0 ? 'M' : 'L'} ${pad + i * stepX} ${10 + s * rowH}`).join(' ')}
          fill="none" stroke="#ffe8a3" strokeWidth="2" />
        {/* highlight REM blocks */}
        {stages.map((s, i) => s === 1 && (
          <rect key={i} x={pad + (i - 0.5) * stepX} y={10 + rowH} width={stepX} height="3" fill="#ff8fb8" opacity="0.6" />
        ))}
        {stages.map((s, i) => s === 4 && (
          <rect key={`d${i}`} x={pad + (i - 0.5) * stepX} y={10 + 4 * rowH - 2} width={stepX} height="3" fill="#7de2d1" opacity="0.6" />
        ))}
      </svg>
      <div className="muted" style={{fontSize: 15, marginTop: 8}}>
        <span className="accent-cyan">DEEP SLEEP</span> dominates cycles 1–2. <span className="accent-rose">REM</span> lengthens each cycle — the last episode can run 60+ minutes.
      </div>
    </div>
  );
}

function CircadianClock() {
  // 24-hour ring with markers
  const events = [
    { t: 2,  label: 'Deepest sleep',     color: '#7de2d1' },
    { t: 4.5,label: 'Lowest body temp',  color: '#c490e4' },
    { t: 6,  label: 'Melatonin off',     color: '#ffe8a3' },
    { t: 9,  label: 'High alertness',    color: '#82e6a4' },
    { t: 14.5,label: 'Post-lunch dip',   color: '#ff8fb8' },
    { t: 17, label: 'Peak reaction time',color: '#7de2d1' },
    { t: 18.5,label: 'Highest body temp',color: '#ff5c7a' },
    { t: 21, label: 'Melatonin onset',   color: '#c490e4' },
    { t: 22.5,label: 'Bowel suppression',color: '#8475d4' },
  ];
  const size = 280;
  const cx = size / 2, cy = size / 2;
  const r = 110;
  const polar = (hour, rad) => {
    const a = (hour / 24) * Math.PI * 2 - Math.PI / 2;
    return [cx + Math.cos(a) * rad, cy + Math.sin(a) * rad];
  };

  return (
    <div className="circadian-grid" style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, alignItems: 'flex-start'}}>
      <svg viewBox={`0 0 ${size} ${size}`} width="100%" shapeRendering="crispEdges" style={{maxWidth: 320}}>
        {/* day half (light) */}
        <path d={`M ${cx},${cy} L ${cx},${cy - r} A ${r},${r} 0 0,1 ${cx},${cy + r} Z`} fill="#3a3380" />
        {/* night half */}
        <path d={`M ${cx},${cy} L ${cx},${cy + r} A ${r},${r} 0 0,1 ${cx},${cy - r} Z`} fill="#0e1230" />
        {/* hour ticks */}
        {Array.from({length: 24}).map((_, h) => {
          const [x1, y1] = polar(h, r);
          const [x2, y2] = polar(h, r - 8);
          return <line key={h} x1={x1} y1={y1} x2={x2} y2={y2} stroke="#8475d4" strokeWidth={h % 6 === 0 ? "2" : "1"} />;
        })}
        {/* big hour numbers */}
        {[0,6,12,18].map(h => {
          const [x, y] = polar(h, r + 14);
          return <text key={h} x={x} y={y + 4} textAnchor="middle" fontFamily="Press Start 2P" fontSize="9" fill="#ffe8a3">{h.toString().padStart(2,'0')}</text>;
        })}
        {/* events */}
        {events.map((e, i) => {
          const [x, y] = polar(e.t, r - 22);
          return <rect key={i} x={x - 3} y={y - 3} width="6" height="6" fill={e.color} />;
        })}
        {/* sun + moon */}
        <rect x={cx - 4} y={cy - r + 30} width="8" height="8" fill="#ffe8a3" />
        <rect x={cx - 4} y={cy + r - 38} width="8" height="8" fill="#c490e4" />
        <text x={cx} y={cy + 4} textAnchor="middle" fontFamily="Press Start 2P" fontSize="9" fill="#f6ecd6">24H</text>
      </svg>

      <div>
        <h4 style={{marginBottom: 10}}>BODY CLOCK MARKERS</h4>
        {events.map((e, i) => (
          <div key={i} style={{display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6, fontSize: 17}}>
            <div style={{width: 10, height: 10, background: e.color, flexShrink: 0}} />
            <span className="muted" style={{fontFamily: 'var(--font-pixel)', fontSize: 9, minWidth: 36}}>
              {Math.floor(e.t).toString().padStart(2,'0')}:{((e.t % 1) * 60).toString().padStart(2,'0')}
            </span>
            <span>{e.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── 2. DISORDERS ─────────────────────────────────────────────────────────
function DisordersWindow() {
  const [selected, setSelected] = useEdState('insomnia');
  const DISORDERS = {
    insomnia: {
      label: 'INSOMNIA', color: 'var(--rose)',
      prev: '~10% chronic / 30% acute',
      symptoms: ['Difficulty falling asleep (>30 min)', 'Frequent waking', 'Early-morning waking with inability to return', 'Daytime fatigue, irritability, focus loss'],
      cause: 'Hyperarousal — cortical and autonomic. Often paired with rumination, late caffeine, or conditioned anxiety about the bed itself.',
      treatment: 'CBT-I is first-line and beats sleeping pills long-term: stimulus control, sleep restriction, cognitive restructuring.',
    },
    apnea: {
      label: 'SLEEP APNEA', color: 'var(--moon)',
      prev: '~26% adults 30-70 (mod-severe in ~10%)',
      symptoms: ['Loud snoring + gasping', 'Witnessed pauses in breathing', 'Morning headache, dry mouth', 'Severe daytime sleepiness'],
      cause: 'Airway collapse during muscle relaxation. Each apnea triggers a micro-arousal — fragmenting sleep without you remembering.',
      treatment: 'CPAP is gold standard. Side-sleeping, weight management, oral appliances, surgery for select cases.',
    },
    narcolepsy: {
      label: 'NARCOLEPSY', color: 'var(--cyan)',
      prev: '~1 in 2,000',
      symptoms: ['Sudden sleep "attacks"', 'Cataplexy (muscle loss triggered by emotion)', 'Sleep paralysis on waking', 'Hypnagogic hallucinations'],
      cause: 'Loss of hypocretin (orexin) neurons in the hypothalamus — likely autoimmune. REM intrudes into wakefulness.',
      treatment: 'Stimulants (modafinil), sodium oxybate for cataplexy, scheduled naps.',
    },
    rls: {
      label: 'RESTLESS LEGS', color: 'var(--violet)',
      prev: '~5-10% adults',
      symptoms: ['Urge to move legs at rest', 'Worse in evening', 'Crawling / pulling / itching sensations', 'Relief on movement'],
      cause: 'Iron-dopamine pathway dysfunction in the basal ganglia. Often comorbid with iron deficiency, pregnancy, kidney disease.',
      treatment: 'Iron supplementation if ferritin is low; dopamine agonists; alpha-2-delta ligands (gabapentin).',
    },
    parasomnia: {
      label: 'PARASOMNIAS', color: 'var(--rose)',
      prev: '~4% adults, more common in children',
      symptoms: ['Sleepwalking, sleep talking', 'Night terrors (NREM-3)', 'REM behavior disorder — acting out dreams', 'Sleep-related eating'],
      cause: 'Partial arousal where motor systems wake before consciousness does. RBD specifically is a loss of REM atonia.',
      treatment: 'Safety-proof the room. Clonazepam for RBD. Address triggers: sleep deprivation, fever, alcohol.',
    },
    circadian: {
      label: 'CIRCADIAN', color: 'var(--moon)',
      prev: 'DSPS in ~7% adolescents',
      symptoms: ['Delayed sleep phase (night owl extreme)', 'Advanced phase (early bird extreme)', 'Shift work disorder', 'Jet lag'],
      cause: 'Internal clock misaligned with social/light schedule. Adolescents naturally phase-delay 2-3h vs. children.',
      treatment: 'Bright light at the right time, melatonin at the right time, chronotherapy. Schedule consistency.',
    },
  };
  const d = DISORDERS[selected];
  return (
    <div className="window-inner">
      <h1>SLEEP DISORDERS</h1>
      <p className="muted" style={{margin: '8px 0 16px'}}>
        ~50–70 million Americans live with a chronic sleep disorder. These are not "just bad sleep" — they have measurable brain and body signatures.
      </p>

      <div style={{display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 16}}>
        {Object.entries(DISORDERS).map(([k, v]) => (
          <button key={k}
            className={`pbtn ${selected === k ? 'primary' : 'ghost'}`}
            onClick={() => setSelected(k)}
            style={{fontSize: 9, padding: '8px 10px'}}>
            {v.label}
          </button>
        ))}
      </div>

      <div className="pixel-card">
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10}}>
          <h2 style={{color: d.color}}>{d.label}</h2>
          <span className="tag">{d.prev}</span>
        </div>

        <h4 style={{marginTop: 14, marginBottom: 6}}>SYMPTOMS</h4>
        <ul style={{margin: 0, paddingLeft: 22}}>
          {d.symptoms.map((s, i) => <li key={i} style={{marginBottom: 4}}>{s}</li>)}
        </ul>

        <h4 style={{marginTop: 16, marginBottom: 6}}>WHAT'S HAPPENING</h4>
        <p style={{fontSize: 19}}>{d.cause}</p>

        <h4 style={{marginTop: 16, marginBottom: 6}}>EVIDENCE-BASED TREATMENT</h4>
        <p style={{fontSize: 19}}>{d.treatment}</p>
      </div>

      <div className="pixel-divider" />
      <div className="pixel-card" style={{background: 'var(--bg-2)'}}>
        <h4 className="accent-rose">⚠ WHEN TO SEE A SPECIALIST</h4>
        <p style={{fontSize: 18, marginTop: 6}}>
          Persistent symptoms &gt;3 months, witnessed breathing pauses, sleep-disrupting movements, daytime sleepiness severe enough to affect driving or school — see a board-certified sleep medicine physician. Most disorders are highly treatable once diagnosed.
        </p>
      </div>
    </div>
  );
}

// ── 3. QUALITY & IMPROVEMENT ─────────────────────────────────────────────
function QualityWindow() {
  const FACTORS = [
    { label: 'LIGHT EXPOSURE', good: 'Bright light AM (10-30 min sun)', bad: 'Phone in bed, bright bedrooms after 22:00', why: 'Light shifts melatonin onset. 10 min of direct AM sunlight is worth more than 1000 lux of indoor light.' },
    { label: 'TEMPERATURE',    good: 'Cool room (15-19°C / 60-67°F)',   bad: 'Warm room, heavy blankets',                why: 'Core temp drops ~1°C for sleep. A cool room makes the drop easier.' },
    { label: 'CAFFEINE',       good: 'Cutoff by ~14:00',                bad: 'Late espresso',                            why: 'Half-life ~5-6h. A 16:00 coffee leaves a quarter of the dose in your brain at midnight.' },
    { label: 'ALCOHOL',        good: 'Skip near bedtime',               bad: 'Nightcap',                                 why: 'Sedating but wrecks REM and causes second-half fragmentation.' },
    { label: 'CONSISTENCY',    good: 'Same wake time daily (±30 min)',  bad: 'Weekend social jet lag',                   why: 'Wake time anchors the entire circadian system. Even on weekends.' },
    { label: 'EXERCISE',       good: 'Earlier in day, anytime works',   bad: 'Hard intervals 1h before bed',             why: 'Raises core temp & adrenaline. Easier sleep onset 3+ hours after.' },
    { label: 'WIND-DOWN',      good: '30 min low-stim routine',         bad: 'Doom-scrolling in bed',                    why: 'Bed = sleep + sex only (stimulus control). Phone in bed conditions wakefulness to the pillow.' },
    { label: 'NAPS',           good: '20 min before 15:00',             bad: '60+ min late nap',                         why: 'Long late naps eat into sleep pressure. Short power naps stay in NREM-2.' },
  ];
  return (
    <div className="window-inner">
      <h1>SLEEP QUALITY</h1>
      <p className="muted" style={{margin: '8px 0 16px'}}>
        Quality &gt; quantity, up to a point. 7 hours of deep, consolidated sleep beats 9 hours of fragmented. Here's what moves the needle, ranked by evidence.
      </p>

      <h3 style={{marginBottom: 10}}>SLEEP HYGIENE — RANKED</h3>
      {FACTORS.map((f, i) => (
        <div key={i} className="pixel-card">
          <div style={{display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6}}>
            <span style={{fontFamily: 'var(--font-pixel)', fontSize: 9, background: 'var(--moon)', color: 'var(--bg-0)', padding: '3px 6px'}}>#{i+1}</span>
            <h3 style={{margin: 0}}>{f.label}</h3>
          </div>
          <div className="row" style={{gap: 12, marginTop: 8, flexWrap: 'wrap'}}>
            <div style={{flex: 1, minWidth: 160}}>
              <div className="tag cyan">DO</div>
              <p style={{fontSize: 17, marginTop: 6}}>{f.good}</p>
            </div>
            <div style={{flex: 1, minWidth: 160}}>
              <div className="tag rose">AVOID</div>
              <p style={{fontSize: 17, marginTop: 6}}>{f.bad}</p>
            </div>
          </div>
          <div style={{fontFamily: 'var(--font-mono)', fontSize: 16, color: 'var(--ink-dim)', marginTop: 10, paddingTop: 10, borderTop: '1px dashed var(--chrome)'}}>
            <span className="accent-moon">WHY ↳ </span>{f.why}
          </div>
        </div>
      ))}

      <div className="pixel-divider" />

      <div className="pixel-card" style={{background: 'var(--bg-2)'}}>
        <h4>THE 4 MEASURES OF GOOD SLEEP</h4>
        <div className="measure-grid" style={{display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10, marginTop: 10}}>
          {[
            ['DURATION',    'Age-appropriate total. Adults: 7-9h.'],
            ['CONTINUITY',  'Few awakenings. Sleep efficiency &gt;85%.'],
            ['TIMING',      'Aligned with your circadian window.'],
            ['ALERTNESS',   'You feel awake within 30 min of waking.'],
          ].map(([l, d]) => (
            <div key={l} style={{padding: 8, background: 'var(--panel)', boxShadow: 'inset 0 0 0 1px var(--chrome-hi)'}}>
              <div className="accent-moon" style={{fontFamily: 'var(--font-pixel)', fontSize: 9, marginBottom: 4}}>{l}</div>
              <div style={{fontSize: 16}} dangerouslySetInnerHTML={{__html: d}} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── 4. MYTHS ─────────────────────────────────────────────────────────────
function MythsWindow() {
  const MYTHS = [
    { myth: 'You can "catch up" on sleep on weekends.', truth: 'Sleep debt is real but slow to repay. Weekend recovery does not fully restore cognitive performance lost to weekday deprivation, and the swing creates social jet lag.' },
    { myth: 'Everyone needs 8 hours.', truth: 'Adults need 7-9h. ~3% of people are true "short sleepers" with rare genetic variants (DEC2, ADRB1). Most "I only need 5" claims are unrecognized chronic deprivation.' },
    { myth: 'Snoring is harmless.', truth: 'Loud habitual snoring + daytime sleepiness is the textbook profile for obstructive sleep apnea — which raises cardiovascular and stroke risk if untreated.' },
    { myth: 'Alcohol helps you sleep.', truth: 'It speeds sleep onset but suppresses REM in the first half and causes rebound arousal in the second. Net effect: worse, lighter sleep.' },
    { myth: 'Lying in bed awake "still counts."', truth: 'Bed-time inflation is a top cause of chronic insomnia. Stimulus-control therapy says: if you cannot sleep in 20 minutes, get out of bed.' },
    { myth: 'Older adults need less sleep.', truth: 'They need about the same (7-8h) but are less able to consolidate it. Fragmentation rises with age — that\'s a feature of the sleeping brain, not a reduced requirement.' },
    { myth: 'Cheese / spicy food causes nightmares.', truth: 'No reliable evidence. Late heavy meals can disturb sleep generally (and that disturbed sleep means more dream recall on awakening), but no specific food is dream-altering.' },
    { myth: 'You only dream in REM.', truth: 'Dreaming occurs in NREM too — about 50% of NREM awakenings produce dream reports. REM dreams tend to be more narrative and bizarre.' },
    { myth: 'Naps ruin nighttime sleep.', truth: 'Short (<30 min) early-afternoon naps don\'t affect most adults\' night sleep. Long, late naps do, by reducing sleep pressure.' },
    { myth: 'Sleep is a passive "off" state.', truth: 'Sleep is one of the most metabolically active states for the brain. Memories are replayed, synapses are pruned, and waste proteins are cleared via the glymphatic system.' },
  ];

  return (
    <div className="window-inner">
      <h1>MYTHS & MISCONCEPTIONS</h1>
      <p className="muted" style={{margin: '8px 0 16px'}}>
        Sleep is one of the most folklore-prone topics in biology. Here are ten ideas that need correcting, paired with what the research actually shows.
      </p>

      <ul className="factlist">
        {MYTHS.map((m, i) => (
          <li key={i} className="myth" style={{marginBottom: 16, paddingBottom: 14, paddingTop: 12, position: 'relative'}}>
            <div style={{display: 'flex', gap: 10, marginBottom: 8}}>
              <span className="tag rose">MYTH #{i+1}</span>
              <span style={{fontFamily: 'var(--font-pixel)', fontSize: 11, color: 'var(--rose)', lineHeight: 1.6}}>"{m.myth}"</span>
            </div>
            <div style={{display: 'flex', gap: 10}}>
              <span className="tag cyan" style={{flexShrink: 0}}>TRUTH</span>
              <span style={{fontFamily: 'var(--font-mono)', fontSize: 19, color: 'var(--ink)'}}>{m.truth}</span>
            </div>
          </li>
        ))}
      </ul>

      <div className="pixel-card" style={{background: 'var(--bg-2)', marginTop: 18}}>
        <h4 className="accent-moon">SOURCE</h4>
        <p style={{fontSize: 17, marginTop: 6}}>
          Adapted for the Stanford Sleep & Dreams outreach curriculum (PSYC 135). Verify specific claims with your physician — these are educational, not diagnostic.
        </p>
      </div>
    </div>
  );
}

// ── DROWSINESS RED ALERT ─────────────────────────────────────────────────
function DrowsinessRedAlertWindow() {
  return (
    <div className="window-inner">
      <h1>DROWSINESS IS RED ALERT</h1>
      <p className="muted" style={{margin: '8px 0 16px'}}>
        SOMNIA raises this warning when your most recent 3-night average drops below 7 hours. That pattern predicts reduced attention, slower reaction time, and riskier choices.
      </p>

      <div className="red-alert-hero">
        <window.IconAlert size={34} />
        <div>
          <h4>DO NOT JUST PUSH THROUGH</h4>
          <p style={{fontSize: 18, marginTop: 6}}>
            Sleep loss is not only feeling tired. It changes vigilance, judgment, emotion regulation, and the speed at which you notice hazards.
          </p>
        </div>
      </div>

      <div className="red-alert-grid">
        <div className="pixel-card">
          <h4 className="accent-rose">WHAT IT MEANS</h4>
          <p style={{fontSize: 18, marginTop: 6}}>
            A sub-7-hour rolling average means your brain has had several nights with too little recovery. Attention lapses become more likely even when you feel functional.
          </p>
        </div>
        <div className="pixel-card">
          <h4 className="accent-moon">WHY IT MATTERS</h4>
          <p style={{fontSize: 18, marginTop: 6}}>
            Around 17+ hours awake, reaction time impairment can resemble a 0.05% blood alcohol concentration. Chronic short sleep stacks a similar safety risk across days.
          </p>
        </div>
        <div className="pixel-card">
          <h4 className="accent-cyan">TONIGHT'S MOVE</h4>
          <p style={{fontSize: 18, marginTop: 6}}>
            Set a protected sleep window, move bedtime 30-60 minutes earlier, avoid late caffeine or alcohol, and use a calm wind-down instead of screens in bed.
          </p>
        </div>
        <div className="pixel-card">
          <h4 className="accent-violet">SAFETY RULE</h4>
          <p style={{fontSize: 18, marginTop: 6}}>
            If you are fighting sleep, do not drive or do high-risk work. A short nap, a ride, or stopping the task is a safety intervention, not a weakness.
          </p>
        </div>
      </div>

      <div className="pixel-card" style={{background: 'var(--bg-2)'}}>
        <h4>TRACKER CONNECTION</h4>
        <p style={{fontSize: 18, marginTop: 6}}>
          Add your next sleep entry in the Tracker. The alert clears when your latest 3-night average returns to 7 hours or more.
        </p>
      </div>
    </div>
  );
}

// ── ABOUT / WELCOME ──────────────────────────────────────────────────────
function AboutWindow() {
  return (
    <div className="window-inner">
      <h1>SOMNIA v1.0</h1>
      <p style={{margin: '8px 0 4px', fontSize: 18}}>
        A pixel sleep workstation built for Stanford University's <span className="accent-cyan">Dement's Sleep and Dreams</span> Course.
      </p>
      <p style={{margin: '4px 0 16px', fontSize: 16}}>
        Created by <span className="accent-moon">Mario Sumali</span>, <span className="accent-cyan">Evan Sing</span>, <span className="accent-rose">Aditya Udaygiri</span>, &amp; <span className="accent-violet">Colin McKhann</span>
      </p>

      <div className="pixel-card">
        <h4>WHAT'S INSIDE</h4>
        <ul style={{paddingLeft: 22, marginTop: 8}}>
          <li style={{marginBottom: 6}}><span className="accent-moon">Sleep Tracker</span> — log nights, see your debt, predict cycle wake times, journal dreams</li>
          <li style={{marginBottom: 6}}><span className="accent-cyan">Cycle &amp; Rhythm</span> — interactive stages, full-night hypnogram, 24-hour circadian clock</li>
          <li style={{marginBottom: 6}}><span className="accent-rose">Disorders</span> — six common conditions with symptoms, causes, treatments</li>
          <li style={{marginBottom: 6}}><span className="accent-violet">Quality</span> — sleep hygiene ranked by evidence</li>
          <li style={{marginBottom: 6}}><span className="accent-moon">Myths</span> — ten common misconceptions, debunked</li>
          <li style={{marginBottom: 6}}><span className="accent-cyan">Ambience</span> — nine pixel environments, four with procedural WebAudio</li>
        </ul>
      </div>

      <div className="pixel-card">
        <h4>HOW TO USE</h4>
        <p style={{fontSize: 18, marginTop: 6}}>
          Double-click any desktop icon to open a window. Drag titles to move them. The taskbar tracks open windows; click again to focus or minimize. Use the <span className="accent-moon">tweaks panel</span> for palette + CRT effects.
        </p>
      </div>

      <div className="pixel-card" style={{background: 'var(--bg-2)'}}>
        <h4>DROWSINESS ALERT</h4>
        <p style={{fontSize: 18, marginTop: 6}}>
          SOMNIA tracks your hours awake. When you cross your threshold (default 17h), an alert appears in the corner — that's roughly when reaction time matches a 0.05% BAC.
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { CyclesWindow, DisordersWindow, QualityWindow, MythsWindow, DrowsinessRedAlertWindow, AboutWindow });
