// ============ NayanTrack bundle (auto-concatenated) ============
const { useState, useEffect, useRef, useMemo } = React;


// ---------- app-shell.jsx ----------
// App shell — persona nav, top bar, page routing

const SCREENS = [
  { id: 'home',        label: 'Overview',            group: 'Start',   crumb: 'NayanTrack / Overview' },
  { id: 'calibration', label: 'Calibration',         group: 'Capture', crumb: 'Capture / Calibration' },
  { id: 'recorder',    label: 'Session Recorder',    group: 'Capture', crumb: 'Capture / Live Session' },
  { id: 'assessment',  label: 'Assessment Battery',  group: 'Capture', crumb: 'Capture / Assessment' },
  { id: 'training',    label: 'Vision Training',     group: 'Train',   crumb: 'Train / Vision Drills' },
  { id: 'vr',          label: 'VR / AR Training',     group: 'Train',   crumb: 'Train / VR & AR' },
  { id: 'scientist',   label: 'Sports Scientist',    group: 'Analyze', crumb: 'Analyze / Athlete Profile' },
  { id: 'video',       label: 'Video Analysis',      group: 'Analyze', crumb: 'Analyze / Match Video' },
  { id: 'coach',       label: 'Coach Portal',        group: 'Analyze', crumb: 'Analyze / Squad' },
  { id: 'athlete',     label: 'Athlete Portal',      group: 'Analyze', crumb: 'Analyze / My Performance' },
  { id: 'talent',      label: 'Talent ID',           group: 'Analyze', crumb: 'Analyze / Talent Identification' },
  { id: 'medical',     label: 'Medical & Rehab',     group: 'Analyze', crumb: 'Analyze / Rehabilitation' },
  { id: 'centre',      label: 'Centre Admin',        group: 'Manage',  crumb: 'Manage / Centre Ops' },
  { id: 'command',     label: 'National Command',    group: 'Manage',  crumb: 'Manage / SAI Command' },
  { id: 'lab',         label: 'Test Designer',       group: 'Manage',  crumb: 'Manage / Test Designer' },
  { id: 'reports',     label: 'Reports & Export',    group: 'Manage',  crumb: 'Manage / Reports' },
];

function BrandMark({ size = 28 }) {
  return (
    <div className="brand-mark" style={{ width: size, height: size }} />
  );
}

function Sidebar({ current, onNav }) {
  const groups = ['Start', 'Capture', 'Train', 'Analyze', 'Manage'];
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-row">
          <BrandMark />
          <div>
            <div className="brand-name">
              NayanTrack <span className="brand-devanagari">नयन</span>
            </div>
            <div className="brand-sub">SAI · v0.4 Alpha</div>
          </div>
        </div>
      </div>

      {groups.map(g => (
        <div key={g}>
          <div className="nav-section">
            <div className="nav-section-title">{g}</div>
          </div>
          {SCREENS.filter(s => s.group === g).map(s => (
            <button
              key={s.id}
              className={`nav-item ${current === s.id ? 'active' : ''}`}
              onClick={() => onNav(s.id)}
            >
              <span className="nav-item-dot" />
              {s.label}
            </button>
          ))}
        </div>
      ))}

      <div className="sidebar-footer">
        Sports Authority of India<br/>
        Bengaluru NCoE
      </div>
    </aside>
  );
}

function TopBar({ current }) {
  const meta = SCREENS.find(s => s.id === current) || SCREENS[0];
  const [time, setTime] = useState(new Date());
  useEffect(() => {
    const t = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  const tstr = time.toLocaleTimeString('en-IN', { hour12: false });

  const showRec = current === 'recorder';

  return (
    <header className="topbar">
      <div className="topbar-left">
        <div className="topbar-crumb">
          {meta.crumb.split(' / ').map((p, i, arr) => (
            <React.Fragment key={i}>
              <span className={i === arr.length - 1 ? 'active' : ''}>{p}</span>
              {i < arr.length - 1 && <span style={{ margin: '0 8px', color: 'var(--fg-4)' }}>/</span>}
            </React.Fragment>
          ))}
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {showRec && (
          <span className="status-pill rec">
            <span className="pulse-dot" />
            REC · 03:47
          </span>
        )}
        <span className="status-pill live">
          <span className="pulse-dot" />
          Tracker Online
        </span>
        <span className="status-pill">
          <span className="mono">{tstr}</span> · IST
        </span>
        <div style={{ width: 1, height: 24, background: 'var(--line)' }} />
        <div className="avatar" title="Dr. R. Menon — Sports Scientist">RM</div>
      </div>
    </header>
  );
}

/* ============================= HOME HUB ============================= */

function HomeHub({ onNav }) {
  const personas = [
    { id: 'recorder',    num: '01', title: 'Session Recorder',     desc: 'Live gaze capture, calibration and event marking during athlete assessment.', tags: ['LIVE', 'GAZE'] },
    { id: 'calibration', num: '02', title: 'Calibration',          desc: 'Interactive 3/5/9/13-point eye-tracker calibration and accuracy validation.', tags: ['SETUP', 'ACCURACY'] },
    { id: 'assessment',  num: '03', title: 'Assessment Battery',   desc: 'Sports-vision and cognitive test suite — reaction, tracking, decision, memory.', tags: ['VISION', 'COGNITIVE'] },
    { id: 'training',    num: '04', title: 'Vision Training',      desc: 'AI-generated drill library — peripheral, tracking, reflex and decision training.', tags: ['DRILLS', 'REFLEX'] },
    { id: 'vr',          num: '05', title: 'VR / AR Training',     desc: 'Immersive scenario training on eye-tracked headsets with foveated rendering.', tags: ['IMMERSIVE', 'XR'] },
    { id: 'scientist',   num: '06', title: 'Sports Scientist',     desc: 'Deep visual-attention analytics, benchmarking and quiet-eye analysis.', tags: ['ANALYTICS', 'BENCHMARK'] },
    { id: 'video',       num: '07', title: 'Video Analysis',       desc: 'Import match footage and sync gaze, head, player and ball tracking frame-by-frame.', tags: ['FOOTAGE', 'SYNC'] },
    { id: 'coach',       num: '08', title: 'Coach Portal',         desc: 'Squad progress, drill recommendations and week-over-week attention trends.', tags: ['SQUAD', 'DRILLS'] },
    { id: 'athlete',     num: '09', title: 'Athlete Portal',       desc: 'Personal scorecards, streaks, upcoming tests and self-training drills.', tags: ['SCORECARD', 'STREAKS'] },
    { id: 'talent',      num: '10', title: 'Talent Identification',desc: 'AI ranking of young athletes across the Khelo India pipeline — vision-led scouting.', tags: ['KHELO INDIA', 'RANKING'] },
    { id: 'medical',     num: '11', title: 'Medical & Rehab',      desc: 'Baseline vs post-injury, concussion assessment, return-to-play readiness.', tags: ['REHAB', 'CONCUSSION'] },
    { id: 'centre',      num: '12', title: 'Centre Administrator', desc: 'Device fleet, calibration health, scheduling and coach adoption at one facility.', tags: ['DEVICES', 'OPS'] },
    { id: 'command',     num: '13', title: 'National Command',     desc: 'Multi-centre KPIs, high-potential athlete alerts and sport-wise distribution.', tags: ['NATIONAL', 'MAP'] },
    { id: 'lab',         num: '14', title: 'Test Designer',        desc: 'Configure sport-specific stimuli, AOIs, scoring rules and normative bands.', tags: ['STIMULI', 'AOI'] },
    { id: 'reports',     num: '15', title: 'Reports & Export',     desc: 'Build athlete, coach, tournament and medical reports — PDF, Excel, dashboards.', tags: ['PDF', 'EXPORT'] },
    { id: 'console',     num: '16', title: 'Admin Console',        desc: 'Audit logs, consent management, RBAC and device provisioning across the platform.', tags: ['SOON'], disabled: true },
  ];

  return (
    <div className="hub">
      <div className="hub-header">
        <div className="hub-brand">
          <div className="hub-brand-mark" />
          <div>
            <div className="hub-brand-title">
              NayanTrack <span style={{ color: 'var(--fg-2)', fontWeight: 400, fontSize: 14, marginLeft: 6 }}>नयन</span>
            </div>
            <div className="hub-brand-sub">Sports Authority of India · Visual Performance Platform</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <span className="status-pill ok"><span className="pulse-dot" />24 CENTRES ONLINE</span>
          <span className="chip saffron">SAI · CLASSIFIED</span>
        </div>
      </div>

      <div className="hero">
        <div className="hero-eyebrow">━━ Eye tracking · attention · anticipation</div>
        <h1 className="hero-title">
          See what your<br/>athletes <em>see.</em><br/>Coach what they <em>miss.</em>
        </h1>
        <p className="hero-sub">
          NayanTrack turns gaze, pupil and blink data into decision-quality metrics — quiet-eye,
          anticipation, peripheral awareness — for cricket, hockey, shooting, archery and ten more Indian sports.
        </p>

        <div className="hero-stats">
          <div>
            <div className="hero-stat-num">18,<em>240</em></div>
            <div className="hero-stat-label">Athletes Enrolled</div>
          </div>
          <div>
            <div className="hero-stat-num">1.<em>2</em>M</div>
            <div className="hero-stat-label">Gaze Samples / Session</div>
          </div>
          <div>
            <div className="hero-stat-num">0.<em>48</em>°</div>
            <div className="hero-stat-label">Median Accuracy</div>
          </div>
          <div>
            <div className="hero-stat-num"><em>13</em> / 24</div>
            <div className="hero-stat-label">Sports · Centres</div>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
        <div className="tick-strong">Choose a workspace</div>
        <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
        <div className="tick">16 · MODULES</div>
      </div>

      <div className="persona-grid">
        {personas.map(p => (
          <div
            key={p.id}
            className="persona-card"
            style={p.disabled ? { opacity: 0.4, cursor: 'not-allowed' } : {}}
            onClick={() => !p.disabled && onNav(p.id)}
          >
            <div className="persona-num">/ {p.num}</div>
            <div className="persona-arrow">↗</div>
            <div className="persona-title">{p.title}</div>
            <div className="persona-desc">{p.desc}</div>
            <div className="persona-tags">
              {p.tags.map(t => (
                <span key={t} className={`chip ${t === 'LIVE' ? 'accent' : t === 'SOON' ? '' : ''}`}>{t}</span>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 60, paddingTop: 24, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', color: 'var(--fg-3)', fontFamily: 'var(--font-mono)', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.14em' }}>
        <div>NayanTrack Platform · Build 2026.07 · Bengaluru NCoE</div>
        <div>SAI · Confidential · v0.4 Alpha</div>
      </div>
    </div>
  );
}

/* ============================= APP ROOT ============================= */

function App() {
  const [screen, setScreen] = useState(() => {
    return localStorage.getItem('nt.screen') || 'home';
  });

  useEffect(() => { localStorage.setItem('nt.screen', screen); }, [screen]);

  // Home hub has its own layout (no sidebar)
  if (screen === 'home') {
    return <HomeHub onNav={setScreen} />;
  }

  const ScreenComp = window.NT_SCREENS?.[screen] || (() => (
    <div className="page"><div className="page-header"><div><div className="page-eyebrow">Loading</div><div className="page-title">Preparing screen…</div></div></div></div>
  ));

  return (
    <div className="shell" data-screen-label={screen}>
      <Sidebar current={screen} onNav={setScreen} />
      <div className="main">
        <TopBar current={screen} />
        <ScreenComp onNav={setScreen} />
      </div>
    </div>
  );
}

Object.assign(window, { App, BrandMark });


// ---------- screens/calibration.jsx ----------
// Calibration Wizard — interactive 3/5/9/13-point eye-tracker calibration

const CAL_PATTERNS = {
  3:  [[50,50],[15,50],[85,50]],
  5:  [[50,50],[15,15],[85,15],[15,85],[85,85]],
  9:  [[15,15],[50,15],[85,15],[15,50],[50,50],[85,50],[15,85],[50,85],[85,85]],
  13: [[15,15],[50,15],[85,15],[15,50],[50,50],[85,50],[15,85],[50,85],[85,85],[32,32],[68,32],[32,68],[68,68]],
};

function qualityColor(q) {
  if (q == null) return 'var(--fg-4)';
  if (q < 0.40) return 'var(--accent)';
  if (q < 0.50) return 'var(--cyan)';
  if (q < 0.65) return 'var(--saffron)';
  return 'var(--red)';
}

// Deterministic-ish pseudo quality so re-renders don't jitter each point
function seedQuality(i) {
  const base = [0.42, 0.38, 0.51, 0.44, 0.29, 0.47, 0.55, 0.41, 0.62, 0.36, 0.49, 0.58, 0.33];
  return base[i % base.length];
}

function CalibrationStage({ pattern, phase, active, results }) {
  const pts = CAL_PATTERNS[pattern];
  return (
    <div style={{
      position: 'relative', aspectRatio: '16 / 10', background: 'var(--bg-2)',
      border: '1px solid var(--line)', borderRadius: 'var(--radius)', overflow: 'hidden',
    }}>
      {/* faint grid backdrop */}
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.5 }}>
        {[20,40,60,80].map(v => <line key={'h'+v} x1="0" x2="100" y1={v} y2={v} stroke="var(--line)" strokeWidth="0.2" />)}
        {[20,40,60,80].map(v => <line key={'v'+v} x1={v} x2={v} y1="0" y2="100" stroke="var(--line)" strokeWidth="0.2" />)}
      </svg>

      {pts.map((p, i) => {
        const done = results[i] != null;
        const isActive = phase === 'running' && i === active;
        const c = done ? qualityColor(results[i]) : isActive ? 'var(--accent)' : 'var(--fg-4)';
        return (
          <div key={i} style={{
            position: 'absolute', left: `${p[0]}%`, top: `${p[1]}%`,
            transform: 'translate(-50%, -50%)', textAlign: 'center',
          }}>
            <div style={{
              width: isActive ? 24 : 14, height: isActive ? 24 : 14, borderRadius: '50%',
              background: isActive ? 'transparent' : c,
              border: isActive ? `2px solid var(--accent)` : 'none',
              boxShadow: '0 0 0 3px rgba(0,0,0,0.4)',
              display: 'grid', placeItems: 'center',
              transition: 'all 0.25s',
              margin: '0 auto',
            }}>
              {isActive && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', animation: 'pulse 1.2s ease-in-out infinite' }} />}
            </div>
            {done && <div className="mono" style={{ fontSize: 9, color: 'var(--fg-2)', marginTop: 4 }}>{results[i].toFixed(2)}°</div>}
          </div>
        );
      })}

      {/* overlays */}
      <div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', gap: 8, alignItems: 'center' }}>
        {phase === 'running'
          ? <span className="status-pill rec"><span className="pulse-dot" />CALIBRATING</span>
          : phase === 'done'
          ? <span className="status-pill ok"><span className="pulse-dot" />VALIDATED</span>
          : <span className="status-pill">READY</span>}
        <span className="tick-strong" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px' }}>{pattern}-POINT · TOBII SPECTRUM · 300 HZ</span>
      </div>
      <div style={{ position: 'absolute', bottom: 12, left: 12, right: 12, display: 'flex', justifyContent: 'space-between' }}>
        <span className="tick" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px' }}>
          {phase === 'idle' ? 'FIXATE EACH TARGET · KEEP HEAD STILL' : phase === 'running' ? `TARGET ${active + 1}/${pattern}` : 'ACCEPT OR RE-RUN BELOW'}
        </span>
        <span className="tick" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px' }}>SCREEN · 1920×1080 · 27"</span>
      </div>
    </div>
  );
}

function EyeTraceCard({ eye, deg, conf }) {
  return (
    <div style={{ background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 2, padding: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <span className="tick" style={{ color: 'var(--fg-1)' }}>{eye} EYE</span>
        <span className="mono" style={{ fontSize: 11, color: qualityColor(deg) }}>{deg.toFixed(2)}°</span>
      </div>
      {/* mock eye + pupil crosshair */}
      <div style={{ position: 'relative', aspectRatio: '5/3', background: 'var(--bg-1)', borderRadius: 2, overflow: 'hidden' }}>
        <svg viewBox="0 0 100 60" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
          <ellipse cx="50" cy="30" rx="34" ry="17" fill="none" stroke="var(--line-strong)" strokeWidth="0.6" />
          <circle cx="50" cy="30" r="9" fill="var(--bg-3)" stroke="var(--cyan)" strokeWidth="0.6" />
          <circle cx="50" cy="30" r="3.5" fill="var(--cyan)" />
          <line x1="50" y1="8" x2="50" y2="52" stroke="var(--cyan)" strokeWidth="0.25" strokeDasharray="1 1" opacity="0.5" />
          <line x1="12" y1="30" x2="88" y2="30" stroke="var(--cyan)" strokeWidth="0.25" strokeDasharray="1 1" opacity="0.5" />
          {/* glints */}
          <circle cx="47" cy="27" r="0.8" fill="var(--fg-0)" />
          <circle cx="53" cy="28" r="0.8" fill="var(--fg-0)" />
        </svg>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 10 }}>
        <div><div className="tick">Pupil</div><div className="mono" style={{ fontSize: 12, color: 'var(--fg-0)' }}>3.2 mm</div></div>
        <div><div className="tick">Track Conf.</div><div className="mono" style={{ fontSize: 12, color: 'var(--accent)' }}>{conf}%</div></div>
      </div>
    </div>
  );
}

function CalibrationScreen({ onNav }) {
  const [pattern, setPattern] = useState(9);
  const [phase, setPhase] = useState('idle'); // idle | running | done
  const [active, setActive] = useState(0);
  const [results, setResults] = useState({});
  const timer = useRef(null);

  const pts = CAL_PATTERNS[pattern];

  const stop = () => { if (timer.current) clearInterval(timer.current); timer.current = null; };
  useEffect(() => stop, []);

  const reset = (p = pattern) => {
    stop();
    setPattern(p);
    setPhase('idle');
    setActive(0);
    setResults({});
  };

  const start = () => {
    stop();
    setResults({});
    setActive(0);
    setPhase('running');
    let i = 0;
    timer.current = setInterval(() => {
      setResults(r => ({ ...r, [i]: seedQuality(i) + (Math.random() - 0.5) * 0.06 }));
      i += 1;
      if (i >= pts.length) {
        stop();
        setPhase('done');
        setActive(pts.length - 1);
      } else {
        setActive(i);
      }
    }, 650);
  };

  const collected = Object.values(results);
  const avg = collected.length ? (collected.reduce((s, v) => s + v, 0) / collected.length) : null;
  const worst = collected.length ? Math.max(...collected) : null;
  const passed = avg != null && avg < 0.55 && worst < 0.75;
  const progress = Math.round((collected.length / pts.length) * 100);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Pre-session setup · Athlete #SAI-BLR-1284</div>
          <div className="page-title">Eye-Tracker Calibration</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {[3, 5, 9, 13].map(p => (
            <button key={p} className={`chip ${p === pattern ? 'filled' : ''}`} style={{ cursor: 'pointer' }} onClick={() => reset(p)}>{p}-PT</button>
          ))}
          <div className="vdivider" style={{ height: 24 }} />
          {phase !== 'running'
            ? <button className="btn primary" onClick={start}>{phase === 'done' ? '↻ Re-run' : '▶ Start Calibration'}</button>
            : <button className="btn danger" onClick={() => reset()}>■ Abort</button>}
          {passed && <button className="btn" onClick={() => onNav && onNav('recorder')}>Accept → Recorder →</button>}
        </div>
      </div>

      {/* device banner */}
      <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', alignItems: 'center', gap: 20, padding: '14px 20px', background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 'var(--radius)', marginBottom: 16 }}>
        <div className="avatar lg">AP</div>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ fontSize: 18, fontWeight: 500 }}>Arjun Prakash</div>
            <span className="chip accent">U-19 · CRICKET</span>
            <span className="chip">NT-LAB-01 · TOBII SPECTRUM</span>
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', marginTop: 6, letterSpacing: '0.12em', textTransform: 'uppercase' }}>
            Lab 1 · Bengaluru NCoE · 300 Hz · Binocular · Glasses: none
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="tick">Progress</div>
          <div className="num-md mono" style={{ color: passed ? 'var(--accent)' : phase === 'done' ? 'var(--saffron)' : 'var(--fg-0)' }}>{progress}<span style={{ fontSize: 12, color: 'var(--fg-3)' }}>%</span></div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16 }}>
        {/* Left: stage + validation */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <CalibrationStage pattern={pattern} phase={phase} active={active} results={results} />

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Validation Result</div>
              {phase === 'done'
                ? <span className={`chip ${passed ? 'green' : 'saffron'}`}>{passed ? '✓ PASS' : '△ RETRY ADVISED'} · {avg != null ? avg.toFixed(2) : '—'}°</span>
                : <span className="chip">AWAITING RUN</span>}
            </div>
            <div className="panel-body">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
                <div><div className="tick">Mean Accuracy</div><div className="num-sm mono" style={{ color: avg != null ? qualityColor(avg) : 'var(--fg-3)' }}>{avg != null ? avg.toFixed(2) + '°' : '—'}</div></div>
                <div><div className="tick">Worst Point</div><div className="num-sm mono" style={{ color: worst != null ? qualityColor(worst) : 'var(--fg-3)' }}>{worst != null ? worst.toFixed(2) + '°' : '—'}</div></div>
                <div><div className="tick">Precision (RMS)</div><div className="num-sm mono">{phase === 'done' ? '0.11°' : '—'}</div></div>
                <div><div className="tick">Head Range</div><div className="num-sm mono">±35°</div></div>
              </div>
              <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span className="tick" style={{ color: 'var(--fg-1)' }}>SAI Acceptance Threshold</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-2)' }}>mean &lt; 0.55° · worst &lt; 0.75°</span>
                </div>
                <div style={{ position: 'relative', height: 6, background: 'var(--bg-3)', borderRadius: 1 }}>
                  <div style={{ position: 'absolute', inset: 0, width: `${avg != null ? Math.min(100, (avg / 0.9) * 100) : 0}%`, background: passed ? 'var(--accent)' : 'var(--saffron)' }} />
                  <div style={{ position: 'absolute', left: `${(0.55 / 0.9) * 100}%`, top: -2, bottom: -2, width: 2, background: 'var(--saffron)' }} />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Right: eye traces + per-point + tips */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Live Eye Tracking</div>
              <span className="chip cyan"><span className="pulse-dot" style={{ background: 'var(--cyan)' }} />BINOCULAR</span>
            </div>
            <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <EyeTraceCard eye="LEFT" deg={avg != null ? avg - 0.03 : 0.44} conf={97} />
              <EyeTraceCard eye="RIGHT" deg={avg != null ? avg + 0.04 : 0.51} conf={96} />
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Per-Point Accuracy</div>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>{collected.length}/{pts.length}</span>
            </div>
            <div className="panel-body" style={{ padding: 0, maxHeight: 220, overflowY: 'auto' }}>
              {pts.map((p, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '40px 1fr auto', gap: 10, padding: '9px 16px', borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-3)' }}>P{String(i + 1).padStart(2, '0')}</span>
                  <div className="bar"><div className="bar-fill" style={{ width: results[i] != null ? `${Math.min(100, (results[i] / 0.9) * 100)}%` : '0%', background: qualityColor(results[i]) }} /></div>
                  <span className="mono" style={{ fontSize: 11, color: qualityColor(results[i]), minWidth: 42, textAlign: 'right' }}>{results[i] != null ? results[i].toFixed(2) + '°' : '—'}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header"><div className="panel-title">Setup Checklist</div></div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                ['✓', 'Ambient light 300–500 lux', true],
                ['✓', 'Eye-to-screen 60–70 cm', true],
                ['✓', 'No reflective eyewear', true],
                ['△', 'Head within tracking box', false],
              ].map((c, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--fg-1)' }}>
                  <span style={{ color: c[2] ? 'var(--accent)' : 'var(--saffron)' }}>{c[0]}</span> {c[1]}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.calibration = CalibrationScreen;


// ---------- screens/recorder.jsx ----------
// Session Recorder — live gaze capture + calibration

const SPORTS = [
  { id: 'cricket',   name: 'Cricket',       scenario: 'Bowler Release · Anticipation Test' },
  { id: 'hockey',    name: 'Hockey',        scenario: 'Passing-Lane Recognition' },
  { id: 'football',  name: 'Football',      scenario: 'Pre-Reception Scan' },
  { id: 'badminton', name: 'Badminton',     scenario: 'Shuttle Trajectory Prediction' },
  { id: 'archery',   name: 'Archery',       scenario: 'Quiet-Eye · Aim Stability' },
  { id: 'shooting',  name: 'Shooting',      scenario: 'Target Acquisition Time' },
  { id: 'boxing',    name: 'Boxing',        scenario: 'Punch Anticipation Cues' },
  { id: 'tennis',    name: 'Tennis',        scenario: 'Serve Anticipation' },
  { id: 'tt',        name: 'Table Tennis',  scenario: 'Rapid Gaze Transitions' },
  { id: 'kabaddi',   name: 'Kabaddi',       scenario: 'Peripheral Defender Track' },
  { id: 'wrestling', name: 'Wrestling',     scenario: 'Movement Prediction' },
  { id: 'esports',   name: 'Esports',       scenario: 'Interface Scan · Fatigue' },
  { id: 'para',      name: 'Para Sports',   scenario: 'Accessible Attention Test' },
];

/* ============ Gaze scene: animated cursor + trail over placeholder video ============ */

function GazeScene({ sport }) {
  const canvasRef = useRef(null);
  const [gaze, setGaze] = useState({ x: 50, y: 50, pupilL: 3.2, pupilR: 3.3 });
  const trailRef = useRef([]);

  // Predefined gaze paths per sport (percent coords)
  const paths = {
    cricket:   [[35,30],[40,45],[52,55],[60,62],[70,68],[65,55],[55,50],[45,42],[40,38]],
    hockey:    [[20,55],[35,60],[52,50],[65,45],[75,60],[60,70],[45,65],[30,55]],
    football:  [[25,40],[45,35],[60,50],[75,55],[70,70],[50,60],[35,50],[20,45]],
    archery:   [[50,50],[51,50],[50,49],[50,51],[50,50],[49,50],[50,50],[51,49],[50,50]],
    shooting:  [[50,50],[50.5,49.5],[50,50],[49.5,50],[50,50.5],[50,50]],
    badminton: [[40,25],[55,35],[65,50],[55,65],[45,55],[35,45]],
    tennis:    [[30,40],[50,30],[70,50],[65,65],[45,60],[30,50]],
    tt:        [[35,45],[55,40],[70,50],[60,60],[40,55]],
    kabaddi:   [[25,50],[45,45],[65,55],[75,50],[55,65],[35,60]],
    boxing:    [[45,40],[55,45],[60,50],[50,55],[45,50]],
    wrestling: [[40,50],[55,55],[65,50],[55,45],[45,50]],
    esports:   [[20,20],[70,25],[75,70],[25,75],[50,50],[80,50],[20,50]],
    para:      [[40,40],[55,50],[60,55],[45,50]],
  };

  useEffect(() => {
    let t = 0;
    let raf;
    const path = paths[sport.id] || paths.cricket;
    const tick = () => {
      t += 0.008;
      const idx = (t * path.length) % path.length;
      const i0 = Math.floor(idx) % path.length;
      const i1 = (i0 + 1) % path.length;
      const f = idx - Math.floor(idx);
      const [x0, y0] = path[i0];
      const [x1, y1] = path[i1];
      // slight jitter (saccadic micro-movement)
      const jitter = () => (Math.random() - 0.5) * 0.4;
      const x = x0 + (x1 - x0) * f + jitter();
      const y = y0 + (y1 - y0) * f + jitter();
      setGaze({
        x, y,
        pupilL: 3.2 + Math.sin(t * 3) * 0.15 + (Math.random() - 0.5) * 0.05,
        pupilR: 3.3 + Math.sin(t * 3 + 0.2) * 0.15 + (Math.random() - 0.5) * 0.05,
      });
      trailRef.current.push({ x, y });
      if (trailRef.current.length > 60) trailRef.current.shift();
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [sport.id]);

  // Draw trail
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dpr = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);
    ctx.clearRect(0, 0, rect.width, rect.height);

    const pts = trailRef.current;
    if (pts.length < 2) return;

    for (let i = 1; i < pts.length; i++) {
      const alpha = (i / pts.length) * 0.7;
      const p0 = pts[i - 1];
      const p1 = pts[i];
      ctx.beginPath();
      ctx.strokeStyle = `oklch(0.82 0.14 210 / ${alpha})`;
      ctx.lineWidth = 2;
      ctx.lineCap = 'round';
      ctx.moveTo((p0.x / 100) * rect.width, (p0.y / 100) * rect.height);
      ctx.lineTo((p1.x / 100) * rect.width, (p1.y / 100) * rect.height);
      ctx.stroke();
    }
  }, [gaze]);

  return (
    <div style={{
      position: 'relative',
      background: 'var(--bg-2)',
      aspectRatio: '16 / 9',
      overflow: 'hidden',
      borderRadius: 'var(--radius)',
      border: '1px solid var(--line)',
    }}>
      {/* Placeholder "scene" — diagonal stripes with label */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'repeating-linear-gradient(135deg, var(--bg-2) 0 20px, var(--bg-1) 20px 21px)',
      }} />

      {/* Sport-specific mock scene diagram */}
      <SportSceneDiagram sport={sport.id} />

      {/* AOIs (Areas of Interest) — dashed rectangles */}
      <AOIs sport={sport.id} />

      {/* Gaze trail */}
      <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }} />

      {/* Gaze cursor */}
      <div style={{
        position: 'absolute',
        left: `${gaze.x}%`, top: `${gaze.y}%`,
        transform: 'translate(-50%, -50%)',
        pointerEvents: 'none',
      }}>
        <div style={{ width: 40, height: 40, border: '2px solid var(--cyan)', borderRadius: '50%', boxShadow: '0 0 0 2px rgba(0,0,0,0.4)' }} />
        <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 6, height: 6, background: 'var(--cyan)', borderRadius: '50%' }} />
        <div style={{ position: 'absolute', top: '50%', left: 50, transform: 'translateY(-50%)', fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--cyan)', letterSpacing: '0.14em', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
          GAZE · {gaze.x.toFixed(1)}, {gaze.y.toFixed(1)}
        </div>
      </div>

      {/* Corner overlays */}
      <div style={{ position: 'absolute', top: 14, left: 14, display: 'flex', gap: 8, alignItems: 'center' }}>
        <span className="status-pill rec"><span className="pulse-dot" />REC</span>
        <span className="tick-strong" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px', borderRadius: 2 }}>
          SCENE FEED · 1920×1080 · 240 FPS
        </span>
      </div>
      <div style={{ position: 'absolute', top: 14, right: 14, textAlign: 'right' }}>
        <div className="tick-strong" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px', borderRadius: 2 }}>
          {sport.name.toUpperCase()} · TRIAL 07/12
        </div>
      </div>
      <div style={{ position: 'absolute', bottom: 14, left: 14, right: 14, display: 'flex', justifyContent: 'space-between' }}>
        <div className="tick" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px' }}>
          T+00:03.847 · SACCADE +12°/s · FIX #24
        </div>
        <div className="tick" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px' }}>
          PUPIL L {gaze.pupilL.toFixed(2)}mm · R {gaze.pupilR.toFixed(2)}mm
        </div>
      </div>
    </div>
  );
}

function SportSceneDiagram({ sport }) {
  // Minimal SVG hints to make scenes distinct
  const common = { position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.6 };
  if (sport === 'cricket') {
    return (
      <svg viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={common}>
        {/* Pitch */}
        <rect x="70" y="20" width="20" height="55" fill="var(--bg-3)" opacity="0.5" />
        <line x1="80" y1="20" x2="80" y2="75" stroke="var(--fg-4)" strokeWidth="0.3" strokeDasharray="1 1" />
        {/* Stumps far */}
        <g transform="translate(80,25)">
          <line x1="-2" y1="0" x2="-2" y2="-3" stroke="var(--fg-3)" strokeWidth="0.5" />
          <line x1="0" y1="0" x2="0" y2="-3" stroke="var(--fg-3)" strokeWidth="0.5" />
          <line x1="2" y1="0" x2="2" y2="-3" stroke="var(--fg-3)" strokeWidth="0.5" />
        </g>
        {/* Bowler figure */}
        <circle cx="80" cy="30" r="1.5" fill="var(--fg-2)" />
        <line x1="80" y1="31" x2="80" y2="36" stroke="var(--fg-2)" strokeWidth="0.5" />
        {/* Ball trajectory */}
        <path d="M 80 30 Q 78 45 65 62" stroke="var(--accent)" strokeWidth="0.4" fill="none" strokeDasharray="1 1" opacity="0.5" />
        {/* Batsman */}
        <circle cx="65" cy="62" r="2" fill="var(--fg-1)" />
      </svg>
    );
  }
  if (sport === 'archery' || sport === 'shooting') {
    return (
      <svg viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={common}>
        <g transform="translate(80,45)">
          <circle r="22" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
          <circle r="16" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
          <circle r="11" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
          <circle r="6" fill="none" stroke="var(--fg-3)" strokeWidth="0.5" />
          <circle r="2" fill="var(--saffron)" opacity="0.6" />
          <line x1="-25" y1="0" x2="25" y2="0" stroke="var(--fg-4)" strokeWidth="0.2" strokeDasharray="0.5 0.5" />
          <line x1="0" y1="-25" x2="0" y2="25" stroke="var(--fg-4)" strokeWidth="0.2" strokeDasharray="0.5 0.5" />
        </g>
      </svg>
    );
  }
  if (sport === 'football' || sport === 'hockey' || sport === 'kabaddi') {
    return (
      <svg viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={common}>
        <rect x="10" y="10" width="140" height="70" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
        <line x1="80" y1="10" x2="80" y2="80" stroke="var(--fg-4)" strokeWidth="0.4" />
        <circle cx="80" cy="45" r="8" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
        {/* Players */}
        {[[30,30],[45,45],[60,55],[75,35],[95,50],[110,40],[125,55],[40,65],[70,70]].map((p,i)=>(
          <circle key={i} cx={p[0]} cy={p[1]} r="1.2" fill={i===2 ? 'var(--accent)' : 'var(--fg-2)'} />
        ))}
      </svg>
    );
  }
  if (sport === 'tennis' || sport === 'badminton' || sport === 'tt') {
    return (
      <svg viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={common}>
        <rect x="30" y="15" width="100" height="60" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
        <line x1="80" y1="15" x2="80" y2="75" stroke="var(--fg-3)" strokeWidth="0.6" />
        <circle cx="50" cy="45" r="1.8" fill="var(--fg-2)" />
        <circle cx="110" cy="45" r="1.8" fill="var(--fg-1)" />
        <path d="M 50 45 Q 80 20 110 45" stroke="var(--accent)" strokeWidth="0.3" fill="none" strokeDasharray="1 1" opacity="0.5" />
      </svg>
    );
  }
  return null;
}

function AOIs({ sport }) {
  const aois = {
    cricket:  [{x:75,y:22,w:12,h:14,l:'RELEASE POINT'},{x:35,y:50,w:22,h:20,l:'BAT/BODY'}],
    archery:  [{x:44,y:44,w:12,h:12,l:'TARGET GOLD'}],
    shooting: [{x:46,y:46,w:8,h:8,l:'BULLSEYE'}],
    football: [{x:20,y:35,w:15,h:18,l:'PASS OPT A'},{x:65,y:55,w:15,h:15,l:'DEFENDER'},{x:75,y:25,w:12,h:15,l:'PASS OPT B'}],
    hockey:   [{x:25,y:50,w:15,h:18,l:'BALL CARRIER'},{x:60,y:35,w:15,h:15,l:'LANE'}],
    kabaddi:  [{x:30,y:40,w:15,h:20,l:'RAIDER'},{x:60,y:45,w:20,h:20,l:'DEFENDERS'}],
    tennis:   [{x:22,y:25,w:20,h:35,l:'OPPONENT'},{x:60,y:60,w:15,h:15,l:'BALL LAND'}],
    badminton:[{x:30,y:20,w:25,h:20,l:'SHUTTLE PEAK'}],
    tt:       [{x:60,y:45,w:15,h:15,l:'BOUNCE'}],
    boxing:   [{x:35,y:30,w:25,h:30,l:'OPPONENT SHOULDERS'}],
    wrestling:[{x:35,y:35,w:30,h:35,l:'HIPS/GRIP'}],
    esports:  [{x:5,y:5,w:15,h:15,l:'MINIMAP'},{x:75,y:70,w:15,h:15,l:'HUD'},{x:40,y:40,w:20,h:20,l:'CROSSHAIR'}],
    para:     [{x:40,y:40,w:20,h:20,l:'STIMULUS'}],
  };
  const list = aois[sport] || aois.cricket;
  return (
    <>
      {list.map((a, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: `${a.x}%`, top: `${a.y}%`,
          width: `${a.w}%`, height: `${a.h}%`,
          border: '1px dashed var(--accent)',
          borderRadius: 2,
          pointerEvents: 'none',
        }}>
          <div style={{
            position: 'absolute', top: -8, left: 0,
            background: 'var(--accent)',
            color: '#0a0b0d',
            fontFamily: 'var(--font-mono)',
            fontSize: 8,
            padding: '2px 4px',
            letterSpacing: '0.12em',
            fontWeight: 700,
          }}>{a.l}</div>
        </div>
      ))}
    </>
  );
}

/* ============ Live sidebar metrics ============ */

function LiveMeter({ label, value, unit, max = 100, color = 'accent' }) {
  const pct = Math.min(100, (value / max) * 100);
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
        <div className="tick">{label}</div>
        <div className="mono" style={{ fontSize: 14, color: 'var(--fg-0)' }}>
          {typeof value === 'number' ? value.toFixed(1) : value}
          <span style={{ color: 'var(--fg-3)', fontSize: 10, marginLeft: 4 }}>{unit}</span>
        </div>
      </div>
      <div className="bar"><div className={`bar-fill ${color}`} style={{ width: `${pct}%` }} /></div>
    </div>
  );
}

function LiveMetrics() {
  const [t, setT] = useState(0);
  useEffect(() => {
    const i = setInterval(() => setT(x => x + 1), 200);
    return () => clearInterval(i);
  }, []);
  const wobble = (base, amp) => base + Math.sin(t / 6) * amp + (Math.random() - 0.5) * amp * 0.3;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <LiveMeter label="Fixation Duration" value={wobble(240, 30)} unit="ms" max={500} color="accent" />
      <LiveMeter label="Saccade Velocity"  value={wobble(180, 60)} unit="°/s" max={400} color="cyan" />
      <LiveMeter label="Pupil (L)"         value={wobble(3.2, 0.2)} unit="mm" max={6} color="saffron" />
      <LiveMeter label="Pupil (R)"         value={wobble(3.3, 0.2)} unit="mm" max={6} color="saffron" />
      <LiveMeter label="Blink Rate"        value={wobble(14, 3)} unit="/min" max={30} color="accent" />
      <LiveMeter label="Head Yaw"          value={wobble(2.1, 1.4)} unit="°" max={15} color="cyan" />
      <LiveMeter label="Tracking Conf."    value={wobble(97, 1.5)} unit="%" max={100} color="accent" />
    </div>
  );
}

/* ============ Calibration grid ============ */

function CalibrationGrid() {
  // 9 points on a 3x3 grid with quality scores
  const points = [
    { q: 0.42, x: 15, y: 20 }, { q: 0.38, x: 50, y: 20 }, { q: 0.51, x: 85, y: 20 },
    { q: 0.44, x: 15, y: 50 }, { q: 0.29, x: 50, y: 50 }, { q: 0.47, x: 85, y: 50 },
    { q: 0.55, x: 15, y: 80 }, { q: 0.41, x: 50, y: 80 }, { q: 0.62, x: 85, y: 80 },
  ];
  const avg = (points.reduce((s, p) => s + p.q, 0) / points.length).toFixed(2);
  return (
    <div className="panel">
      <div className="panel-header">
        <div className="panel-title">Calibration · 9-point</div>
        <span className="chip green">PASS · {avg}°</span>
      </div>
      <div className="panel-body">
        <div style={{ position: 'relative', aspectRatio: '4/3', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 2 }}>
          {points.map((p, i) => (
            <div key={i} style={{
              position: 'absolute',
              left: `${p.x}%`, top: `${p.y}%`,
              transform: 'translate(-50%, -50%)',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            }}>
              <div style={{
                width: 10, height: 10, borderRadius: '50%',
                background: p.q < 0.4 ? 'var(--accent)' : p.q < 0.5 ? 'var(--cyan)' : 'var(--saffron)',
                boxShadow: '0 0 0 3px rgba(0,0,0,0.4)',
              }} />
              <div className="mono" style={{ fontSize: 9, color: 'var(--fg-2)' }}>{p.q.toFixed(2)}°</div>
            </div>
          ))}
          <div style={{ position: 'absolute', top: 8, left: 8 }} className="tick">3×3 GRID</div>
        </div>

        <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <div className="tick">Left Eye</div>
            <div className="num-sm mono">0.44°</div>
          </div>
          <div>
            <div className="tick">Right Eye</div>
            <div className="num-sm mono">0.51°</div>
          </div>
          <div>
            <div className="tick">Drift</div>
            <div className="num-sm mono" style={{ color: 'var(--accent)' }}>0.08°</div>
          </div>
          <div>
            <div className="tick">Head Range</div>
            <div className="num-sm mono">±35°</div>
          </div>
        </div>

        <button className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 16 }}>Re-calibrate</button>
      </div>
    </div>
  );
}

/* ============ Sport switcher ============ */

function SportSwitcher({ sport, onChange }) {
  return (
    <div className="panel">
      <div className="panel-header">
        <div className="panel-title">Assessment Protocol</div>
        <span className="chip accent">{sport.name.toUpperCase()}</span>
      </div>
      <div className="panel-body" style={{ padding: 0 }}>
        <div style={{ maxHeight: 240, overflowY: 'auto' }}>
          {SPORTS.map(s => (
            <button
              key={s.id}
              onClick={() => onChange(s)}
              style={{
                width: '100%',
                padding: '10px 18px',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                borderBottom: '1px solid var(--line)',
                background: s.id === sport.id ? 'var(--bg-2)' : 'transparent',
                borderLeft: s.id === sport.id ? '2px solid var(--accent)' : '2px solid transparent',
                textAlign: 'left',
              }}
            >
              <div>
                <div style={{ fontSize: 13, color: 'var(--fg-0)' }}>{s.name}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-2)', marginTop: 2 }}>
                  {s.scenario}
                </div>
              </div>
              <span className="mono" style={{ color: 'var(--fg-3)', fontSize: 11 }}>→</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============ Athlete info card ============ */

function AthleteBanner() {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'auto 1fr auto',
      alignItems: 'center',
      gap: 20,
      padding: '16px 20px',
      background: 'var(--bg-1)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--radius)',
      marginBottom: 16,
    }}>
      <div className="avatar lg">AP</div>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ fontSize: 20, fontWeight: 500 }}>Arjun Prakash</div>
          <span className="chip">SAI-BLR-1284</span>
          <span className="chip accent">U-19 · CRICKET</span>
          <span className="chip">RIGHT · RIGHT</span>
        </div>
        <div style={{ display: 'flex', gap: 24, marginTop: 6, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
          <span>Age 17 · M · Bengaluru NCoE</span>
          <span>Session 04 · 15 Jul 2026 · 09:42 IST</span>
          <span>Tracker · Tobii Pro Spectrum · 300 Hz</span>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <button className="btn danger">■ Stop</button>
        <button className="btn">⏸ Pause</button>
        <button className="btn primary">✚ Mark Event</button>
      </div>
    </div>
  );
}

/* ============ Event log ============ */

function EventLog() {
  const events = [
    { t: '00:03.847', tag: 'FIX',  label: 'Fixation → RELEASE POINT', color: 'var(--accent)' },
    { t: '00:03.612', tag: 'SAC',  label: 'Saccade 12°/s to bowler', color: 'var(--cyan)' },
    { t: '00:03.140', tag: 'FIX',  label: 'Fixation → BAT/BODY', color: 'var(--accent)' },
    { t: '00:02.980', tag: 'RSP',  label: 'Response · CORRECT (short-length)', color: 'var(--green)' },
    { t: '00:02.740', tag: 'BLNK', label: 'Blink · 87ms', color: 'var(--fg-2)' },
    { t: '00:02.410', tag: 'STIM', label: 'Trial 07 · stimulus onset', color: 'var(--saffron)' },
    { t: '00:01.980', tag: 'SAC',  label: 'Saccade 28°/s to release', color: 'var(--cyan)' },
    { t: '00:01.610', tag: 'FIX',  label: 'Fixation → RELEASE POINT', color: 'var(--accent)' },
  ];
  return (
    <div className="panel" style={{ height: '100%' }}>
      <div className="panel-header">
        <div className="panel-title">Event Stream</div>
        <span className="chip"><span className="pulse-dot" style={{ background: 'var(--cyan)' }} />LIVE</span>
      </div>
      <div className="panel-body" style={{ padding: 0, maxHeight: 260, overflowY: 'auto', overflowX: 'hidden' }}>
        {events.map((e, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '78px 44px 1fr', gap: 8, padding: '10px 14px', borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
            <span className="mono" style={{ fontSize: 11, color: 'var(--fg-2)' }}>{e.t}</span>
            <span className="mono" style={{ fontSize: 10, color: e.color, fontWeight: 700, letterSpacing: '0.14em' }}>{e.tag}</span>
            <span style={{ fontSize: 12, color: 'var(--fg-1)' }}>{e.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============ Main screen ============ */

function RecorderScreen() {
  const [sport, setSport] = useState(SPORTS[0]);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Live capture · session 04</div>
          <div className="page-title">Session Recorder</div>
        </div>
        <div style={{ display: 'flex', gap: 20, alignItems: 'flex-end' }}>
          <div style={{ textAlign: 'right' }}>
            <div className="tick">Duration</div>
            <div className="num-md mono">03:47.<span style={{ color: 'var(--fg-3)' }}>28</span></div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="tick">Samples</div>
            <div className="num-md mono">68<span style={{ color: 'var(--fg-3)' }}>,412</span></div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="tick">Trials</div>
            <div className="num-md mono">7<span style={{ color: 'var(--fg-3)' }}>/12</span></div>
          </div>
        </div>
      </div>

      <AthleteBanner />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <GazeScene sport={sport} />

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div className="panel">
              <div className="panel-header">
                <div className="panel-title">Live Metrics</div>
                <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>@ 300Hz</span>
              </div>
              <div className="panel-body">
                <LiveMetrics />
              </div>
            </div>
            <EventLog />
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <CalibrationGrid />
          <SportSwitcher sport={sport} onChange={setSport} />
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.recorder = RecorderScreen;


// ---------- screens/assessment.jsx ----------
// Assessment Battery — sports-vision + cognitive test suite

const VISION_TESTS = [
  { t: 'Static Visual Acuity',    v: '20/12',  p: 94, st: 'done' },
  { t: 'Dynamic Visual Acuity',   v: '20/18',  p: 88, st: 'done' },
  { t: 'Peripheral Vision',       v: '184°',   p: 71, st: 'watch' },
  { t: 'Depth Perception',        v: '22"arc', p: 90, st: 'done' },
  { t: 'Contrast Sensitivity',    v: '2.1',    p: 86, st: 'done' },
  { t: 'Eye–Hand Coordination',   v: '312ms',  p: 82, st: 'done' },
  { t: 'Eye–Foot Coordination',   v: '358ms',  p: 77, st: 'done' },
  { t: 'Visual Memory',           v: '9/10',   p: 91, st: 'done' },
  { t: 'Multiple Object Tracking',v: '5 obj',  p: 84, st: 'active' },
  { t: 'Anticipation Ability',    v: '—',      p: 0,  st: 'pending' },
  { t: 'Visual Search Speed',     v: '—',      p: 0,  st: 'pending' },
  { t: 'Decision Time',           v: '—',      p: 0,  st: 'pending' },
];

const COGNITIVE_TESTS = [
  { t: 'Reaction Time',        v: '248ms', p: 89, st: 'done' },
  { t: 'Choice Reaction',      v: '412ms', p: 81, st: 'done' },
  { t: 'Working Memory',       v: '7 span',p: 85, st: 'done' },
  { t: 'Focus',                v: '92%',   p: 88, st: 'done' },
  { t: 'Concentration',        v: '87%',   p: 80, st: 'done' },
  { t: 'Processing Speed',     v: '1.8/s', p: 83, st: 'done' },
  { t: 'Attention Switching',  v: '540ms', p: 74, st: 'watch' },
  { t: 'Inhibitory Control',   v: '94%',   p: 90, st: 'done' },
  { t: 'Executive Function',   v: '78',    p: 79, st: 'done' },
  { t: 'Mental Fatigue',       v: 'Low',   p: 86, st: 'done' },
  { t: 'Decision Accuracy',    v: '88%',   p: 84, st: 'active' },
];

function pctColor(p) {
  if (p >= 85) return 'var(--accent)';
  if (p >= 75) return 'var(--cyan)';
  if (p > 0)   return 'var(--saffron)';
  return 'var(--fg-4)';
}

function TestCard({ test }) {
  const statusMap = {
    done:    <span className="chip green" style={{ fontSize: 8 }}>✓</span>,
    active:  <span className="chip accent" style={{ fontSize: 8 }}><span className="pulse-dot" style={{ background: 'var(--accent)' }} />LIVE</span>,
    watch:   <span className="chip saffron" style={{ fontSize: 8 }}>△</span>,
    pending: <span className="chip" style={{ fontSize: 8 }}>QUEUED</span>,
  };
  return (
    <div style={{
      background: test.st === 'active' ? 'var(--bg-2)' : 'var(--bg-1)',
      borderLeft: test.st === 'active' ? '2px solid var(--accent)' : '2px solid transparent',
      padding: 14,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: test.st === 'pending' ? 'var(--fg-3)' : 'var(--fg-0)', lineHeight: 1.2 }}>{test.t}</div>
        {statusMap[test.st]}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
        <span className="num-sm mono" style={{ color: test.st === 'pending' ? 'var(--fg-3)' : 'var(--fg-0)' }}>{test.v}</span>
        <span className="mono" style={{ fontSize: 10, color: pctColor(test.p) }}>{test.p ? test.p + '%ile' : ''}</span>
      </div>
      <div className="bar"><div className="bar-fill" style={{ width: `${test.p}%`, background: pctColor(test.p) }} /></div>
    </div>
  );
}

// Live choice-reaction runner — target lights in one of 6 zones, RT ticks
function LiveTestRunner() {
  const [lit, setLit] = useState(2);
  const [rt, setRt] = useState(248);
  const [trial, setTrial] = useState(7);
  useEffect(() => {
    const i = setInterval(() => {
      setLit(Math.floor(Math.random() * 6));
      setRt(220 + Math.floor(Math.random() * 90));
      setTrial(t => (t % 12) + 1);
    }, 1100);
    return () => clearInterval(i);
  }, []);
  return (
    <div className="panel">
      <div className="panel-header">
        <div className="panel-title">Now Running · Choice Reaction</div>
        <span className="chip accent"><span className="pulse-dot" style={{ background: 'var(--accent)' }} />TRIAL {trial}/12</span>
      </div>
      <div className="panel-body">
        <div style={{ position: 'relative', aspectRatio: '3/2', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 2, overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: '12%', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gridTemplateRows: 'repeat(2, 1fr)', gap: '8%' }}>
            {Array.from({ length: 6 }, (_, i) => (
              <div key={i} style={{
                borderRadius: '50%',
                background: i === lit ? 'var(--accent)' : 'var(--bg-3)',
                border: i === lit ? '2px solid var(--accent)' : '1px solid var(--line-strong)',
                boxShadow: i === lit ? '0 0 24px oklch(0.92 0.19 115 / 0.5)' : 'none',
                transition: 'all 0.12s',
              }} />
            ))}
          </div>
          <div style={{ position: 'absolute', top: 10, left: 12 }} className="tick-strong">GO / NO-GO · CENTRAL FIXATION</div>
          <div className="mono" style={{ position: 'absolute', bottom: 10, right: 12, fontSize: 22, color: 'var(--accent)', letterSpacing: '-0.02em' }}>{rt}<span style={{ fontSize: 11, color: 'var(--fg-3)' }}>ms</span></div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginTop: 14 }}>
          <div><div className="tick">Mean RT</div><div className="num-sm mono" style={{ color: 'var(--accent)' }}>248ms</div></div>
          <div><div className="tick">Accuracy</div><div className="num-sm mono">11/12</div></div>
          <div><div className="tick">False Starts</div><div className="num-sm mono" style={{ color: 'var(--saffron)' }}>1</div></div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
          <button className="btn danger">■ Stop</button>
          <button className="btn">⏸ Pause</button>
          <button className="btn primary" style={{ marginLeft: 'auto' }}>Next Test →</button>
        </div>
      </div>
    </div>
  );
}

function AssessmentScreen({ onNav }) {
  const done = [...VISION_TESTS, ...COGNITIVE_TESTS].filter(t => t.st === 'done' || t.st === 'watch').length;
  const total = VISION_TESTS.length + COGNITIVE_TESTS.length;
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Baseline battery · Arjun Prakash · Session 04</div>
          <div className="page-title">Assessment Battery</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">⚙ Configure</button>
          <button className="btn" onClick={() => onNav && onNav('scientist')}>↗ View Analysis</button>
          <button className="btn primary">▶ Resume Battery</button>
        </div>
      </div>

      {/* KPI row */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Tests Completed</div>
          <div className="kpi-value">{done}<span className="kpi-unit">/ {total}</span></div>
          <div className="kpi-delta" style={{ color: 'var(--accent)' }}>{Math.round((done / total) * 100)}% · ~14 min left</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Visual Performance Score</div>
          <div className="kpi-value">86</div>
          <div className="kpi-delta up">▲ +4 vs baseline</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Reaction Index</div>
          <div className="kpi-value">248<span className="kpi-unit">ms</span></div>
          <div className="kpi-delta up">▲ 89th pctl</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Visual IQ</div>
          <div className="kpi-value" style={{ color: 'var(--accent)' }}>128</div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>Cognitive composite</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 16 }}>
        {/* Test catalog */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Sports Vision Assessment · 12 tests</div>
              <span className="chip cyan">MODULE 03</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, background: 'var(--line)' }}>
              {VISION_TESTS.map((t, i) => <TestCard key={i} test={t} />)}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Cognitive Performance · 11 tests</div>
              <span className="chip cyan">MODULE 04</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, background: 'var(--line)' }}>
              {COGNITIVE_TESTS.map((t, i) => <TestCard key={i} test={t} />)}
            </div>
          </div>
        </div>

        {/* Live runner + summary */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <LiveTestRunner />

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Battery Protocol</div>
              <span className="chip">SAI STANDARD</span>
            </div>
            <div className="panel-body" style={{ padding: 0 }}>
              {[
                { l: 'Sports Vision block', s: '8/12 done', c: 'var(--accent)' },
                { l: 'Cognitive block', s: '9/11 done', c: 'var(--accent)' },
                { l: 'Sport-specific (Cricket)', s: 'queued', c: 'var(--fg-3)' },
                { l: 'Fatigue re-test', s: 'queued', c: 'var(--fg-3)' },
              ].map((r, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', borderBottom: '1px solid var(--line)' }}>
                  <span style={{ fontSize: 12, color: 'var(--fg-1)' }}>{r.l}</span>
                  <span className="mono" style={{ fontSize: 10, color: r.c, textTransform: 'uppercase', letterSpacing: '0.1em' }}>{r.s}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="panel" style={{ borderLeft: '3px solid var(--accent)' }}>
            <div className="panel-header"><div className="panel-title" style={{ color: 'var(--accent)' }}>◆ AI Note</div></div>
            <div className="panel-body">
              <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.55 }}>
                Peripheral vision (71st pctl) and attention switching (74th) trail this athlete's other measures. Recommend the <strong>Peripheral Cue Detection</strong> and <strong>Task-Switch</strong> drills before the next retest.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.assessment = AssessmentScreen;


// ---------- screens/training.jsx ----------
// Vision Training Studio — AI drill library + live reflex board

const TRAIN_DRILLS = [
  { t: 'Peripheral Cue Detection', cat: 'PERIPHERAL', dur: '12 min', diff: 3, sport: 'All', done: 74 },
  { t: 'Multiple Object Tracking', cat: 'TRACKING',   dur: '15 min', diff: 4, sport: 'Team',  done: 61 },
  { t: 'Multiple Ball Tracking',   cat: 'TRACKING',   dur: '10 min', diff: 4, sport: 'Cricket', done: 55 },
  { t: 'Color Recognition',        cat: 'RECOGNITION',dur: '6 min',  diff: 2, sport: 'All', done: 88 },
  { t: 'Speed Recognition',        cat: 'RECOGNITION',dur: '8 min',  diff: 3, sport: 'Racket', done: 70 },
  { t: 'Dynamic Target Training',  cat: 'TARGET',     dur: '14 min', diff: 4, sport: 'Shooting', done: 66 },
  { t: 'Light Board Reflex',       cat: 'REFLEX',     dur: '9 min',  diff: 3, sport: 'All', done: 82 },
  { t: 'Reflex Reaction Grid',     cat: 'REFLEX',     dur: '7 min',  diff: 2, sport: 'Boxing', done: 79 },
  { t: 'Decision Training',        cat: 'DECISION',   dur: '16 min', diff: 5, sport: 'Team', done: 48 },
  { t: 'Quiet-Eye Fixation',       cat: 'FIXATION',   dur: '10 min', diff: 3, sport: 'Archery', done: 90 },
  { t: 'Anticipation Video',       cat: 'ANTICIPATE', dur: '20 min', diff: 4, sport: 'Cricket', done: 52 },
  { t: 'Distraction Resistance',   cat: 'FOCUS',      dur: '12 min', diff: 3, sport: 'All', done: 64 },
];

const CATS = ['ALL', 'PERIPHERAL', 'TRACKING', 'REFLEX', 'DECISION', 'FIXATION'];

function Difficulty({ n }) {
  return (
    <span style={{ display: 'inline-flex', gap: 2 }}>
      {[1,2,3,4,5].map(i => (
        <span key={i} style={{ width: 4, height: 10, background: i <= n ? 'var(--accent)' : 'var(--bg-3)', borderRadius: 1 }} />
      ))}
    </span>
  );
}

// Live "light board" — cells illuminate in sequence, athlete taps them
function LightBoard() {
  const [lit, setLit] = useState([5, 11]);
  const [hits, setHits] = useState(0);
  useEffect(() => {
    const i = setInterval(() => {
      const a = Math.floor(Math.random() * 16);
      let b = Math.floor(Math.random() * 16);
      if (b === a) b = (b + 1) % 16;
      setLit([a, b]);
      setHits(h => h + 1);
    }, 850);
    return () => clearInterval(i);
  }, []);
  return (
    <div style={{ position: 'relative', aspectRatio: '1', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 2, padding: '8%', overflow: 'hidden' }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '6%', height: '100%' }}>
        {Array.from({ length: 16 }, (_, i) => {
          const on = lit.includes(i);
          return (
            <div key={i} style={{
              borderRadius: 2,
              background: on ? 'var(--accent)' : 'var(--bg-3)',
              border: on ? '1px solid var(--accent)' : '1px solid var(--line)',
              boxShadow: on ? '0 0 18px oklch(0.92 0.19 115 / 0.55)' : 'none',
              transition: 'all 0.1s',
            }} />
          );
        })}
      </div>
    </div>
  );
}

function TrainingScreen({ onNav }) {
  const [cat, setCat] = useState('ALL');
  const filtered = cat === 'ALL' ? TRAIN_DRILLS : TRAIN_DRILLS.filter(d => d.cat === cat);
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ AI-generated drills · 10 categories</div>
          <div className="page-title">Vision Training Studio</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">+ Custom Drill</button>
          <button className="btn" onClick={() => onNav && onNav('vr')}>◈ VR Mode</button>
          <button className="btn primary">▶ Start Session</button>
        </div>
      </div>

      {/* KPI row */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Drill Library</div>
          <div className="kpi-value">42</div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>10 categories · 13 sports</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Assigned · This Week</div>
          <div className="kpi-value">6</div>
          <div className="kpi-delta up">▲ 4 completed · 67%</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Training Minutes · MTD</div>
          <div className="kpi-value">284</div>
          <div className="kpi-delta up">▲ +38 vs last month</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Avg Improvement</div>
          <div className="kpi-value" style={{ color: 'var(--accent)' }}>+7.2<span className="kpi-unit">%</span></div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>peripheral +11%</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 16 }}>
        {/* Drill library */}
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Drill Library</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {CATS.map(c => (
                <button key={c} className={`chip ${c === cat ? 'filled' : ''}`} style={{ cursor: 'pointer' }} onClick={() => setCat(c)}>{c}</button>
              ))}
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1, background: 'var(--line)' }}>
            {filtered.map((d, i) => (
              <div key={i} style={{ background: 'var(--bg-1)', padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <span className="mono" style={{ fontSize: 9, color: 'var(--accent)', letterSpacing: '0.12em' }}>◆ {d.cat}</span>
                  <Difficulty n={d.diff} />
                </div>
                <div style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.2 }}>{d.t}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>{d.dur} · {d.sport}</div>
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                    <span className="tick">Mastery</span>
                    <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>{d.done}%</span>
                  </div>
                  <div className="bar"><div className="bar-fill" style={{ width: `${d.done}%` }} /></div>
                </div>
                <button className="btn primary" style={{ width: '100%', justifyContent: 'center', marginTop: 2 }}>▶ Start</button>
              </div>
            ))}
          </div>
        </div>

        {/* Live drill + plan */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Live · Light Board Reflex</div>
              <span className="chip accent"><span className="pulse-dot" style={{ background: 'var(--accent)' }} />ROUND 3</span>
            </div>
            <div className="panel-body">
              <LightBoard />
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginTop: 14 }}>
                <div><div className="tick">Hits</div><div className="num-sm mono" style={{ color: 'var(--accent)' }}>47</div></div>
                <div><div className="tick">Avg RT</div><div className="num-sm mono">412ms</div></div>
                <div><div className="tick">Streak</div><div className="num-sm mono">12</div></div>
              </div>
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">This Week's Plan</div>
              <span className="chip cyan">6 DRILLS</span>
            </div>
            <div className="panel-body" style={{ padding: 0 }}>
              {[
                { t: 'Peripheral Cue Detection', d: 'Mon · done', ok: true },
                { t: 'Multiple Object Tracking', d: 'Tue · done', ok: true },
                { t: 'Decision Training',        d: 'Wed · today', ok: false },
                { t: 'Reflex Reaction Grid',     d: 'Thu', ok: false },
                { t: 'Anticipation Video',       d: 'Fri', ok: false },
              ].map((r, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '11px 16px', borderBottom: '1px solid var(--line)' }}>
                  <span style={{ fontSize: 12, color: r.ok ? 'var(--fg-3)' : 'var(--fg-0)', textDecoration: r.ok ? 'line-through' : 'none' }}>{r.t}</span>
                  <span className="mono" style={{ fontSize: 10, color: r.ok ? 'var(--accent)' : 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{r.ok ? '✓ ' : ''}{r.d}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.training = TrainingScreen;


// ---------- screens/vr.jsx ----------
// VR / AR Training — immersive scenario training with eye-tracked headsets

const VR_SCENARIOS = [
  { t: 'Penalty Simulation',   sport: 'Football', dev: 'Quest 3',      diff: 4, active: true },
  { t: 'Cricket Batting',      sport: 'Cricket',  dev: 'Quest Pro',    diff: 5 },
  { t: 'Goalkeeper Vision',    sport: 'Football', dev: 'Vive Focus',   diff: 4 },
  { t: 'Tennis Return',        sport: 'Tennis',   dev: 'Quest 3',      diff: 3 },
  { t: 'Hockey Goalkeeping',   sport: 'Hockey',   dev: 'Vision Pro',   diff: 4 },
  { t: 'Boxing Reaction',      sport: 'Boxing',   dev: 'Quest Pro',    diff: 5 },
  { t: 'Shooting Stability',   sport: 'Shooting', dev: 'Vive Focus',   diff: 3 },
  { t: 'Archery Steadiness',   sport: 'Archery',  dev: 'Vision Pro',   diff: 3 },
];

const HEADSETS = [
  { id: 'Meta Quest 3',      n: 2, st: 'ok' },
  { id: 'Meta Quest Pro',    n: 2, st: 'ok' },
  { id: 'HTC Vive Focus',    n: 1, st: 'ok' },
  { id: 'Apple Vision Pro',  n: 1, st: 'charging' },
  { id: 'Pico / OpenXR',     n: 1, st: 'offline' },
];

// First-person penalty scene with animated eye-tracked reticle + foveation ring
function HeadsetView() {
  const [g, setG] = useState({ x: 50, y: 46 });
  useEffect(() => {
    const path = [[50,46],[36,42],[62,40],[54,52],[44,48],[58,45]];
    let t = 0, raf;
    const tick = () => {
      t += 0.006;
      const idx = (t * path.length) % path.length;
      const i0 = Math.floor(idx) % path.length, i1 = (i0 + 1) % path.length, f = idx - Math.floor(idx);
      setG({
        x: path[i0][0] + (path[i1][0] - path[i0][0]) * f + (Math.random() - 0.5) * 0.5,
        y: path[i0][1] + (path[i1][1] - path[i0][1]) * f + (Math.random() - 0.5) * 0.5,
      });
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <div style={{ position: 'relative', aspectRatio: '16/9', background: 'radial-gradient(circle at 50% 40%, var(--bg-2), var(--bg-0) 85%)', border: '1px solid var(--line)', borderRadius: 2, overflow: 'hidden' }}>
      {/* Stadium / pitch scene */}
      <svg viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.7 }}>
        {/* ground */}
        <path d="M0,58 L160,58 L160,90 L0,90 Z" fill="var(--bg-2)" />
        {[0,1,2,3,4].map(i => <line key={i} x1={20 + i*30} y1="58" x2={-40 + i*60} y2="90" stroke="var(--line)" strokeWidth="0.3" />)}
        <line x1="0" y1="58" x2="160" y2="58" stroke="var(--line-strong)" strokeWidth="0.4" />
        {/* goal frame */}
        <g stroke="var(--fg-2)" strokeWidth="0.8" fill="none">
          <rect x="60" y="34" width="40" height="22" />
          <line x1="60" y1="34" x2="63" y2="37" /><line x1="100" y1="34" x2="97" y2="37" />
        </g>
        {/* net hint */}
        <g stroke="var(--line)" strokeWidth="0.2">
          {[64,68,72,76,80,84,88,92,96].map(x => <line key={x} x1={x} y1="37" x2={x} y2="56" />)}
          {[40,44,48,52].map(y => <line key={y} x1="63" y1={y} x2="97" y2={y} />)}
        </g>
        {/* keeper */}
        <g transform="translate(80,50)">
          <circle cx="0" cy="-4" r="2" fill="var(--saffron)" />
          <rect x="-2.5" y="-2" width="5" height="7" fill="var(--saffron)" opacity="0.8" />
        </g>
        {/* ball */}
        <circle cx="54" cy="72" r="2.4" fill="var(--fg-0)" stroke="var(--fg-3)" strokeWidth="0.3" />
        {/* trajectory */}
        <path d="M54,72 Q66,50 88,42" stroke="var(--accent)" strokeWidth="0.4" fill="none" strokeDasharray="1.5 1.5" opacity="0.5" />
      </svg>

      {/* foveation ring around gaze */}
      <div style={{ position: 'absolute', left: `${g.x}%`, top: `${g.y}%`, transform: 'translate(-50%, -50%)', width: '30%', aspectRatio: '1', borderRadius: '50%', boxShadow: '0 0 0 2000px rgba(7,8,10,0.35)', pointerEvents: 'none' }} />
      {/* gaze reticle */}
      <div style={{ position: 'absolute', left: `${g.x}%`, top: `${g.y}%`, transform: 'translate(-50%,-50%)', pointerEvents: 'none' }}>
        <div style={{ width: 34, height: 34, border: '1.5px solid var(--cyan)', borderRadius: '50%' }} />
        <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 4, height: 4, background: 'var(--cyan)', borderRadius: '50%' }} />
      </div>

      {/* HUD */}
      <div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', gap: 8, alignItems: 'center' }}>
        <span className="status-pill live"><span className="pulse-dot" />VR LIVE</span>
        <span className="tick-strong" style={{ background: 'rgba(7,8,10,0.6)', padding: '4px 8px' }}>PENALTY SIM · QUEST 3 · 90 FPS · FOVEATED</span>
      </div>
      <div className="tick-strong" style={{ position: 'absolute', top: 12, right: 12, background: 'rgba(7,8,10,0.6)', padding: '4px 8px' }}>SHOT 07/15</div>
      <div style={{ position: 'absolute', bottom: 12, left: 12, right: 12, display: 'flex', justifyContent: 'space-between' }}>
        <span className="tick" style={{ background: 'rgba(7,8,10,0.6)', padding: '4px 8px' }}>GAZE {g.x.toFixed(0)},{g.y.toFixed(0)} · IPD 63mm</span>
        <span className="tick" style={{ background: 'rgba(7,8,10,0.6)', padding: '4px 8px' }}>DIVE READ · +0.34s EARLIER</span>
      </div>
    </div>
  );
}

function VRScreen({ onNav }) {
  const [t, setT] = useState(0);
  useEffect(() => { const i = setInterval(() => setT(x => x + 1), 900); return () => clearInterval(i); }, []);
  const hr = 118 + Math.round(Math.sin(t / 3) * 6);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Immersive training · Arjun Prakash</div>
          <div className="page-title">VR / AR Training</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn" onClick={() => onNav && onNav('training')}>← 2D Drills</button>
          <button className="btn">⚙ Calibrate Headset</button>
          <button className="btn primary">▶ Launch Scenario</button>
        </div>
      </div>

      {/* KPI row */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Headsets Online</div>
          <div className="kpi-value">6<span className="kpi-unit">/ 7</span></div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>Quest · Vive · Vision Pro</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Scenarios</div>
          <div className="kpi-value">18</div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>8 sports · OpenXR</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Anticipation Gain</div>
          <div className="kpi-value" style={{ color: 'var(--accent)' }}>+0.34<span className="kpi-unit">s</span></div>
          <div className="kpi-delta up">▲ earlier dive-read</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Foveation Efficiency</div>
          <div className="kpi-value">3.1<span className="kpi-unit">×</span></div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>GPU savings · gaze-driven</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16 }}>
        {/* Headset view + scenario library */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <HeadsetView />

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Scenario Library</div>
              <span className="chip">MODULE 11 · VR / AR</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, background: 'var(--line)' }}>
              {VR_SCENARIOS.map((s, i) => (
                <div key={i} style={{ background: s.active ? 'var(--bg-2)' : 'var(--bg-1)', borderLeft: s.active ? '2px solid var(--accent)' : '2px solid transparent', padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span className="mono" style={{ fontSize: 9, color: 'var(--cyan)', letterSpacing: '0.1em' }}>◈ {s.dev}</span>
                    {s.active && <span className="chip accent" style={{ fontSize: 8 }}>LOADED</span>}
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.2 }}>{s.t}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>{s.sport}</div>
                  <button className={`btn ${s.active ? 'primary' : ''}`} style={{ width: '100%', justifyContent: 'center', marginTop: 'auto' }}>{s.active ? '▶ Resume' : 'Load'}</button>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Live metrics + fleet */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Live Session · Biometrics</div>
              <span className="chip red"><span className="pulse-dot" style={{ background: 'var(--red)' }} />REC</span>
            </div>
            <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div><div className="tick">Heart Rate</div><div className="num-md mono" style={{ color: 'var(--red)' }}>{hr}<span style={{ fontSize: 11, color: 'var(--fg-3)' }}>bpm</span></div></div>
              <div><div className="tick">Immersion</div><div className="num-md mono" style={{ color: 'var(--accent)' }}>High</div></div>
              <div><div className="tick">Gaze-on-Ball</div><div className="num-md mono">78<span style={{ fontSize: 11, color: 'var(--fg-3)' }}>%</span></div></div>
              <div><div className="tick">Motion Comfort</div><div className="num-md mono" style={{ color: 'var(--accent)' }}>OK</div></div>
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Headset Fleet</div>
              <span className="chip cyan">6 READY</span>
            </div>
            <div className="panel-body" style={{ padding: 0 }}>
              {HEADSETS.map((h, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 10, padding: '11px 16px', borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 500, color: h.st === 'offline' ? 'var(--fg-3)' : 'var(--fg-0)' }}>{h.id}</div>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{h.n} unit{h.n > 1 ? 's' : ''}</div>
                  </div>
                  {h.st === 'ok' && <span className="chip green">◆ READY</span>}
                  {h.st === 'charging' && <span className="chip saffron">⚡ CHARGING</span>}
                  {h.st === 'offline' && <span className="chip red">◯ OFFLINE</span>}
                </div>
              ))}
            </div>
          </div>

          <div className="panel" style={{ borderLeft: '3px solid var(--cyan)' }}>
            <div className="panel-header"><div className="panel-title" style={{ color: 'var(--cyan)' }}>◈ Transfer Note</div></div>
            <div className="panel-body">
              <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.55 }}>
                VR penalty-read gains transfer to on-field: dive-decision now begins <strong>0.34 s earlier</strong> than baseline. Continue 2 sessions/week; re-test on-field in the Recorder.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.vr = VRScreen;


// ---------- screens/scientist.jsx ----------
// Sports Scientist — deep analytics for one athlete

/* ============ Heatmap over scene ============ */

function Heatmap() {
  // Concentrated hotspots over an archery target (quiet-eye canonical example)
  const hotspots = [
    { x: 50, y: 48, r: 8, i: 1.0 },
    { x: 49, y: 47, r: 5, i: 0.9 },
    { x: 52, y: 51, r: 6, i: 0.7 },
    { x: 45, y: 40, r: 4, i: 0.4 },
    { x: 58, y: 55, r: 3, i: 0.3 },
    { x: 30, y: 30, r: 3, i: 0.2 },
    { x: 70, y: 65, r: 3, i: 0.2 },
  ];
  return (
    <div style={{ position: 'relative', aspectRatio: '16/9', background: 'var(--bg-2)', borderRadius: 2, overflow: 'hidden', border: '1px solid var(--line)' }}>
      {/* Archery target */}
      <svg viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.5 }}>
        <g transform="translate(80,45)">
          <circle r="28" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
          <circle r="22" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
          <circle r="16" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
          <circle r="10" fill="none" stroke="var(--fg-3)" strokeWidth="0.4" />
          <circle r="5" fill="var(--saffron)" opacity="0.3" />
        </g>
      </svg>
      {/* Heat blobs */}
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <defs>
          <radialGradient id="hot" cx="50%" cy="50%">
            <stop offset="0%" stopColor="oklch(0.92 0.19 115)" stopOpacity="0.9" />
            <stop offset="30%" stopColor="oklch(0.85 0.18 80)" stopOpacity="0.6" />
            <stop offset="60%" stopColor="oklch(0.68 0.22 25)" stopOpacity="0.3" />
            <stop offset="100%" stopColor="oklch(0.68 0.22 25)" stopOpacity="0" />
          </radialGradient>
        </defs>
        {hotspots.map((h, i) => (
          <circle key={i} cx={h.x} cy={h.y} r={h.r} fill="url(#hot)" opacity={h.i} />
        ))}
      </svg>
      {/* Overlay labels */}
      <div style={{ position: 'absolute', top: 12, left: 12 }} className="tick-strong">HEATMAP · 12 TRIALS AGGREGATE</div>
      <div style={{ position: 'absolute', bottom: 12, right: 12, display: 'flex', gap: 4, alignItems: 'center' }}>
        <span className="tick">LOW</span>
        <div style={{ width: 100, height: 8, background: 'linear-gradient(to right, oklch(0.68 0.22 25 / 0.2), oklch(0.85 0.18 80 / 0.6), oklch(0.92 0.19 115))' }} />
        <span className="tick">HIGH</span>
      </div>
    </div>
  );
}

/* ============ Radar chart of composite indicators ============ */

function RadarChart() {
  const metrics = [
    { label: 'Quiet Eye',        athlete: 78, elite: 88 },
    { label: 'Anticipation',     athlete: 82, elite: 90 },
    { label: 'Search Efficiency', athlete: 74, elite: 85 },
    { label: 'Peripheral',       athlete: 65, elite: 82 },
    { label: 'Attention Stab.',  athlete: 88, elite: 91 },
    { label: 'Decision Speed',   athlete: 71, elite: 87 },
    { label: 'Gaze Economy',     athlete: 80, elite: 86 },
    { label: 'Consistency',      athlete: 76, elite: 88 },
  ];

  const cx = 160, cy = 160, R = 120;
  const N = metrics.length;

  const pointAt = (i, r) => {
    const a = (i / N) * Math.PI * 2 - Math.PI / 2;
    return [cx + Math.cos(a) * r, cy + Math.sin(a) * r];
  };

  const polyPoints = (values) =>
    values.map((v, i) => pointAt(i, (v / 100) * R).join(',')).join(' ');

  return (
    <svg viewBox="0 0 400 320" style={{ width: '100%', height: 320 }}>
      {/* Grid rings */}
      {[0.25, 0.5, 0.75, 1].map(f => (
        <polygon
          key={f}
          points={Array.from({ length: N }, (_, i) => pointAt(i, R * f).join(',')).join(' ')}
          fill="none"
          stroke="var(--line)"
          strokeWidth="1"
        />
      ))}
      {/* Spokes */}
      {metrics.map((_, i) => {
        const [x, y] = pointAt(i, R);
        return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="var(--line)" strokeWidth="1" />;
      })}
      {/* Elite ghost */}
      <polygon
        points={polyPoints(metrics.map(m => m.elite))}
        fill="oklch(0.82 0.14 210 / 0.1)"
        stroke="oklch(0.82 0.14 210)"
        strokeWidth="1"
        strokeDasharray="3 3"
      />
      {/* Athlete */}
      <polygon
        points={polyPoints(metrics.map(m => m.athlete))}
        fill="oklch(0.92 0.19 115 / 0.25)"
        stroke="oklch(0.92 0.19 115)"
        strokeWidth="2"
      />
      {/* Athlete points */}
      {metrics.map((m, i) => {
        const [x, y] = pointAt(i, (m.athlete / 100) * R);
        return <circle key={i} cx={x} cy={y} r="3" fill="oklch(0.92 0.19 115)" />;
      })}
      {/* Labels */}
      {metrics.map((m, i) => {
        const [x, y] = pointAt(i, R + 22);
        return (
          <text key={i} x={x} y={y} textAnchor="middle" dominantBaseline="middle"
            fontFamily="var(--font-mono)" fontSize="9" fill="var(--fg-1)"
            letterSpacing="0.08em">
            <tspan>{m.label.toUpperCase()}</tspan>
            <tspan x={x} dy="10" fill="var(--fg-3)">{m.athlete}</tspan>
          </text>
        );
      })}
    </svg>
  );
}

/* ============ Fixation timeline ============ */

function FixationTimeline() {
  const total = 8.0; // 8 seconds
  const aois = ['RELEASE', 'BAT', 'PITCH', 'FIELDER'];
  // Fixation blocks
  const fixations = [
    { aoi: 0, start: 0.2, dur: 0.4 },
    { aoi: 2, start: 0.7, dur: 0.3 },
    { aoi: 0, start: 1.1, dur: 0.5 },
    { aoi: 1, start: 1.8, dur: 0.4 },
    { aoi: 0, start: 2.3, dur: 0.6 },
    { aoi: 2, start: 3.0, dur: 0.3 },
    { aoi: 0, start: 3.4, dur: 0.7 },
    { aoi: 1, start: 4.2, dur: 0.5 },
    { aoi: 0, start: 4.8, dur: 0.8 },
    { aoi: 3, start: 5.7, dur: 0.4 },
    { aoi: 0, start: 6.2, dur: 0.5 },
    { aoi: 1, start: 6.8, dur: 0.4 },
    { aoi: 0, start: 7.3, dur: 0.6 },
  ];
  const colors = ['var(--accent)', 'var(--cyan)', 'var(--saffron)', 'var(--purple)'];

  return (
    <div>
      {aois.map((aoi, i) => (
        <div key={aoi} style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 12, alignItems: 'center', marginBottom: 10 }}>
          <div className="tick" style={{ color: 'var(--fg-1)' }}>{aoi}</div>
          <div style={{ position: 'relative', height: 20, background: 'var(--bg-3)', borderRadius: 1 }}>
            {fixations.filter(f => f.aoi === i).map((f, j) => (
              <div key={j} style={{
                position: 'absolute',
                left: `${(f.start / total) * 100}%`,
                width: `${(f.dur / total) * 100}%`,
                top: 2, bottom: 2,
                background: colors[i],
                borderRadius: 1,
              }} title={`${f.dur.toFixed(2)}s`} />
            ))}
          </div>
        </div>
      ))}
      {/* Time axis */}
      <div style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 12, marginTop: 10 }}>
        <div />
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          {[0, 2, 4, 6, 8].map(t => <span key={t} className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>{t.toFixed(1)}s</span>)}
        </div>
      </div>
      {/* Event markers */}
      <div style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 12, marginTop: 12, alignItems: 'center' }}>
        <div className="tick" style={{ color: 'var(--red)' }}>EVENT</div>
        <div style={{ position: 'relative', height: 18 }}>
          {[
            { t: 0.1, l: 'STIM' },
            { t: 2.4, l: 'BALL RELEASE' },
            { t: 6.5, l: 'BAT CONTACT' },
          ].map((e, i) => (
            <div key={i} style={{ position: 'absolute', left: `${(e.t / total) * 100}%` }}>
              <div style={{ width: 1, height: 12, background: 'var(--red)' }} />
              <div className="mono" style={{ fontSize: 9, color: 'var(--red)', marginTop: 2, whiteSpace: 'nowrap', transform: 'translateX(-50%)' }}>{e.l}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============ Pupil / cognitive load timeline ============ */

function PupilChart() {
  const pts = Array.from({ length: 80 }, (_, i) => {
    const t = i / 80;
    return 3.2 + Math.sin(t * 6) * 0.4 + Math.sin(t * 14) * 0.15 + t * 0.6;
  });
  const max = Math.max(...pts), min = Math.min(...pts);
  const norm = pts.map(p => 1 - (p - min) / (max - min));
  const points = norm.map((v, i) => `${(i / (norm.length - 1)) * 100},${v * 90 + 5}`).join(' ');

  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: '100%', height: 140 }}>
      <defs>
        <linearGradient id="pupilFill" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="oklch(0.72 0.16 300 / 0.3)" />
          <stop offset="100%" stopColor="oklch(0.72 0.16 300 / 0)" />
        </linearGradient>
      </defs>
      {/* Grid lines */}
      {[25, 50, 75].map(y => (
        <line key={y} x1="0" x2="100" y1={y} y2={y} stroke="var(--line)" strokeWidth="0.3" />
      ))}
      <polygon points={`0,100 ${points} 100,100`} fill="url(#pupilFill)" />
      <polyline points={points} fill="none" stroke="oklch(0.72 0.16 300)" strokeWidth="0.8" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}

/* ============ Comparison bars ============ */

function CompareBar({ label, athlete, elite, unit = '', invert = false }) {
  const max = Math.max(athlete, elite) * 1.2;
  const winning = invert ? athlete < elite : athlete > elite * 0.9;
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
        <span className="tick" style={{ color: 'var(--fg-1)' }}>{label}</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--fg-2)' }}>
          <span style={{ color: 'var(--accent)' }}>{athlete}{unit}</span>
          {' vs '}
          <span style={{ color: 'var(--cyan)' }}>{elite}{unit}</span>
        </span>
      </div>
      <div style={{ position: 'relative', height: 4, background: 'var(--bg-3)' }}>
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${(elite / max) * 100}%`, background: 'var(--cyan)', opacity: 0.35 }} />
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${(athlete / max) * 100}%`, background: 'var(--accent)' }} />
        <div style={{ position: 'absolute', left: `${(elite / max) * 100}%`, top: -2, bottom: -2, width: 2, background: 'var(--cyan)' }} />
      </div>
    </div>
  );
}

/* ============ Session history sparkline ============ */

function SessionTrend() {
  const sessions = [72, 74, 71, 76, 78, 80, 79, 82, 81, 84, 86];
  const max = 100, min = 60;
  const w = 100, h = 40;
  const points = sessions.map((v, i) => `${(i / (sessions.length - 1)) * w},${h - ((v - min) / (max - min)) * h}`).join(' ');
  return (
    <div>
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height: 60 }}>
        <polyline points={points} fill="none" stroke="var(--accent)" strokeWidth="1.5" vectorEffect="non-scaling-stroke" />
        {sessions.map((v, i) => (
          <circle key={i}
            cx={(i / (sessions.length - 1)) * w}
            cy={h - ((v - min) / (max - min)) * h}
            r="1.2" fill="var(--accent)" />
        ))}
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
        <span className="mono" style={{ fontSize: 9, color: 'var(--fg-3)' }}>S-01</span>
        <span className="mono" style={{ fontSize: 9, color: 'var(--fg-3)' }}>S-11 · TODAY</span>
      </div>
    </div>
  );
}

/* ============ Main screen ============ */

function ScientistScreen() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Athlete profile · report 04</div>
          <div className="page-title">Visual Performance Analysis</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">⤓ Export CSV</button>
          <button className="btn">⤓ Export PDF</button>
          <button className="btn primary">↗ Send to Coach</button>
        </div>
      </div>

      {/* Athlete banner + composite score */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 16, marginBottom: 20, padding: 20, background: 'var(--bg-1)', border: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
          <div className="avatar xl">MK</div>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em' }}>Meera Krishnan</div>
              <span className="chip accent">ELITE · ARCHERY</span>
              <span className="chip">SAI-PUN-0472</span>
            </div>
            <div style={{ marginTop: 6, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
              21 F · Pune NCoE · Right dominant · 11 sessions · 2024–2026
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 32, alignItems: 'center' }}>
          <div>
            <div className="tick">Composite Score</div>
            <div style={{ fontSize: 56, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em', color: 'var(--accent)', fontVariantNumeric: 'tabular-nums' }}>
              84<span style={{ fontSize: 20, color: 'var(--fg-3)' }}>/100</span>
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--accent)', marginTop: 4 }}>▲ +6 vs baseline · 92nd pctl</div>
          </div>
          <div className="vdivider" />
          <div style={{ width: 200 }}>
            <div className="tick">Trend · 11 Sessions</div>
            <SessionTrend />
          </div>
        </div>
      </div>

      {/* KPI row */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Quiet Eye</div>
          <div className="kpi-value">1.24<span className="kpi-unit">s</span></div>
          <div className="kpi-delta up">▲ +180ms vs baseline</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Reaction Time</div>
          <div className="kpi-value">248<span className="kpi-unit">ms</span></div>
          <div className="kpi-delta up">▲ 12ms faster</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Aim-Point Deviation</div>
          <div className="kpi-value">0.42<span className="kpi-unit">°</span></div>
          <div className="kpi-delta up">▲ tighter than elite</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Cognitive Load</div>
          <div className="kpi-value">Low<span className="kpi-unit"></span></div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>Pupil Δ 0.18mm</div>
        </div>
      </div>

      {/* Row 1: Heatmap + Radar */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Gaze Heatmap · Archery Target</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <span className="chip filled">HEATMAP</span>
              <span className="chip">TRAIL</span>
              <span className="chip">FIXATION</span>
              <span className="chip">SACCADE</span>
            </div>
          </div>
          <div className="panel-body">
            <Heatmap />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
              <div>
                <div className="tick">Fixations</div>
                <div className="num-sm mono">142</div>
              </div>
              <div>
                <div className="tick">Avg Fix. Dur.</div>
                <div className="num-sm mono">312ms</div>
              </div>
              <div>
                <div className="tick">Saccades</div>
                <div className="num-sm mono">138</div>
              </div>
              <div>
                <div className="tick">Blinks</div>
                <div className="num-sm mono">44</div>
              </div>
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Composite Indicators</div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <span style={{ width: 8, height: 8, background: 'var(--accent)' }} />
                <span className="tick">Athlete</span>
              </span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <span style={{ width: 8, height: 8, border: '1px dashed var(--cyan)' }} />
                <span className="tick">Elite Avg</span>
              </span>
            </div>
          </div>
          <div className="panel-body">
            <RadarChart />
          </div>
        </div>
      </div>

      {/* Row 2: Timeline + Pupil */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Fixation Sequence · Trial 07</div>
            <span className="chip">8.0s · 4 AOIs</span>
          </div>
          <div className="panel-body">
            <FixationTimeline />
          </div>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Pupil / Cognitive Load</div>
            <span className="mono" style={{ fontSize: 10, color: 'var(--purple)' }}>+18% ONSET</span>
          </div>
          <div className="panel-body">
            <PupilChart />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginTop: 12 }}>
              <div><div className="tick">Baseline</div><div className="num-sm mono">3.14mm</div></div>
              <div><div className="tick">Peak</div><div className="num-sm mono">3.72mm</div></div>
              <div><div className="tick">Δ Load</div><div className="num-sm mono" style={{ color: 'var(--purple)' }}>0.58</div></div>
            </div>
          </div>
        </div>
      </div>

      {/* Row 3: Benchmark + AI insights */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Benchmark · vs Elite Recurve (n=42)</div>
            <span className="chip cyan">92ND PCTL</span>
          </div>
          <div className="panel-body">
            <CompareBar label="Quiet Eye (s)" athlete={1.24} elite={1.32} unit="s" />
            <CompareBar label="First Fixation (ms)" athlete={185} elite={168} unit="ms" invert />
            <CompareBar label="Aim Deviation (°)" athlete={0.42} elite={0.51} unit="°" invert />
            <CompareBar label="Final Fixation (ms)" athlete={980} elite={1120} unit="ms" invert />
            <CompareBar label="Blink Suppression (%)" athlete={88} elite={92} unit="%" />
            <CompareBar label="Fixation Stability (%)" athlete={91} elite={89} unit="%" />
          </div>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">AI Interpretation · Explainable</div>
            <span className="chip"><span className="pulse-dot" style={{ background: 'var(--accent)' }} />COACH REVIEW</span>
          </div>
          <div className="panel-body" style={{ padding: 0 }}>
            {[
              { tag: 'STRENGTH', color: 'var(--accent)', title: 'Exceptional aim-point stability',
                body: 'Final 800ms before release shows deviation of 0.42° — 18% tighter than elite median. Consistent across 11 of 12 trials.' },
              { tag: 'STRENGTH', color: 'var(--accent)', title: 'Quiet-eye onset earlier than baseline',
                body: 'First stable fixation begins 180ms earlier than session 01. Indicates improved pre-shot routine.' },
              { tag: 'WATCH',    color: 'var(--saffron)', title: 'First fixation slightly delayed',
                body: '17ms slower than elite average on target acquisition. Suggests visual search inefficiency at trial onset.' },
              { tag: 'CAUTION',  color: 'var(--red)',    title: 'Blink suppression below elite band',
                body: 'Two blink events within the 300ms pre-release window on trials 04 and 09. Recommend blink-timing drill.' },
            ].map((n, i) => (
              <div key={i} style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)' }}>
                <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 6 }}>
                  <span className="mono" style={{ fontSize: 10, color: n.color, fontWeight: 700, letterSpacing: '0.14em' }}>◆ {n.tag}</span>
                  <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-0)' }}>{n.title}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--fg-1)', lineHeight: 1.5, paddingLeft: 20 }}>{n.body}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.scientist = ScientistScreen;


// ---------- screens/video.jsx ----------
// Match Video Analysis — import footage, sync gaze + ball + player tracking

const CLIPS = [
  { t: 'Ranji QF · vs MH · Over 14', src: 'BROADCAST', dur: '0:48', active: true },
  { t: 'Net practice · bouncer set',  src: 'PRACTICE',  dur: '2:12' },
  { t: 'Drone · field spacing',       src: 'DRONE',     dur: '1:36' },
  { t: 'Slip-catch reaction reel',    src: 'TRAINING',  dur: '0:54' },
  { t: 'Spin anticipation montage',   src: 'BROADCAST', dur: '1:20' },
];

const SYNC_LAYERS = [
  { l: 'Eye Movement',    c: 'var(--cyan)',    on: true },
  { l: 'Head Movement',   c: 'var(--purple)',  on: true },
  { l: 'Player Position', c: 'var(--saffron)', on: true },
  { l: 'Ball Trajectory', c: 'var(--accent)',  on: true },
  { l: 'Event Timeline',  c: 'var(--red)',     on: true },
];

function VideoStage({ playing }) {
  const [p, setP] = useState(0.42); // playhead 0..1
  const [ball, setBall] = useState({ x: 52, y: 60 });
  const [gaze, setGaze] = useState({ x: 50, y: 40 });
  useEffect(() => {
    if (!playing) return;
    let raf, t = p;
    const tick = () => {
      t += 0.0025; if (t > 1) t = 0;
      setP(t);
      // ball follows a delivery arc; gaze leads slightly
      const bx = 22 + t * 60, by = 30 + Math.sin(t * Math.PI) * -22 + 40;
      setBall({ x: bx, y: by });
      setGaze({ x: bx + 6 + (Math.random() - 0.5) * 2, y: by - 6 + (Math.random() - 0.5) * 2 });
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing]);

  const players = [[30, 66], [70, 50], [58, 72]];
  return (
    <div style={{ position: 'relative', aspectRatio: '16/9', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 2, overflow: 'hidden' }}>
      {/* pitch backdrop */}
      <div style={{ position: 'absolute', inset: 0, background: 'repeating-linear-gradient(115deg, var(--bg-2) 0 24px, var(--bg-1) 24px 25px)' }} />
      <svg viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.55 }}>
        <ellipse cx="80" cy="48" rx="70" ry="40" fill="none" stroke="var(--fg-4)" strokeWidth="0.4" />
        <rect x="72" y="26" width="16" height="44" fill="var(--bg-3)" opacity="0.4" />
        <line x1="80" y1="26" x2="80" y2="70" stroke="var(--fg-4)" strokeWidth="0.3" strokeDasharray="1 1" />
      </svg>

      {/* player tracking boxes */}
      {players.map((pl, i) => (
        <div key={i} style={{ position: 'absolute', left: `${pl[0]}%`, top: `${pl[1]}%`, transform: 'translate(-50%,-50%)', width: 44, height: 60, border: '1px solid var(--saffron)', borderRadius: 2, pointerEvents: 'none' }}>
          <div style={{ position: 'absolute', top: -8, left: 0, background: 'var(--saffron)', color: '#0a0b0d', fontFamily: 'var(--font-mono)', fontSize: 8, padding: '1px 4px', fontWeight: 700 }}>P{i + 1} · 0.9{i + 2}</div>
        </div>
      ))}

      {/* ball tracker */}
      <div style={{ position: 'absolute', left: `${ball.x}%`, top: `${ball.y}%`, transform: 'translate(-50%,-50%)', pointerEvents: 'none' }}>
        <div style={{ width: 12, height: 12, border: '2px solid var(--accent)', borderRadius: '50%' }} />
        <div className="mono" style={{ position: 'absolute', left: 16, top: -2, fontSize: 8, color: 'var(--accent)', whiteSpace: 'nowrap' }}>BALL 138 KM/H</div>
      </div>

      {/* gaze */}
      <div style={{ position: 'absolute', left: `${gaze.x}%`, top: `${gaze.y}%`, transform: 'translate(-50%,-50%)', pointerEvents: 'none' }}>
        <div style={{ width: 30, height: 30, border: '1.5px solid var(--cyan)', borderRadius: '50%' }} />
        <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 4, height: 4, background: 'var(--cyan)', borderRadius: '50%' }} />
      </div>

      {/* HUD */}
      <div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', gap: 8 }}>
        <span className="tick-strong" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px' }}>BROADCAST · 1080p50 · SYNCED</span>
      </div>
      <div style={{ position: 'absolute', top: 12, right: 12 }}>
        <span className="tick-strong" style={{ background: 'rgba(7,8,10,0.7)', padding: '4px 8px' }}>GAZE↔BALL Δ 0.18s</span>
      </div>

      {/* scrub bar */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '10px 12px', background: 'linear-gradient(transparent, rgba(7,8,10,0.85))' }}>
        <div style={{ position: 'relative', height: 4, background: 'var(--bg-4)', borderRadius: 2 }}>
          <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${p * 100}%`, background: 'var(--accent)', borderRadius: 2 }} />
          {[0.18, 0.42, 0.61, 0.83].map((m, i) => (
            <div key={i} style={{ position: 'absolute', left: `${m * 100}%`, top: -3, width: 2, height: 10, background: 'var(--red)' }} />
          ))}
          <div style={{ position: 'absolute', left: `${p * 100}%`, top: -4, transform: 'translateX(-50%)', width: 3, height: 12, background: 'var(--fg-0)' }} />
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
          <span className="mono" style={{ fontSize: 10, color: 'var(--fg-1)' }}>00:{String(Math.floor(p * 48)).padStart(2, '0')} / 00:48</span>
          <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>BALL RELEASE · FIX · BAT CONTACT · APPEAL</span>
        </div>
      </div>
    </div>
  );
}

function VideoScreen({ onNav }) {
  const [playing, setPlaying] = useState(true);
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Meera Krishnan · Ranji QF review</div>
          <div className="page-title">Match Video Analysis</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">⤓ Import Video</button>
          <button className="btn">✚ Mark Event</button>
          <button className="btn primary" onClick={() => onNav && onNav('scientist')}>↗ To Analysis</button>
        </div>
      </div>

      {/* import source chips */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, alignItems: 'center' }}>
        <span className="tick">SOURCES</span>
        {['Broadcast', 'Practice', 'Drone', 'Training'].map((s, i) => (
          <span key={s} className={`chip ${i === 0 ? 'filled' : ''}`}>{s}</span>
        ))}
        <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', marginLeft: 'auto' }}>AI SYNC · EYE · HEAD · PLAYER · BALL · EVENTS</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16 }}>
        {/* Video + tracks */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <VideoStage playing={playing} />

          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn" onClick={() => setPlaying(p => !p)}>{playing ? '⏸ Pause' : '▶ Play'}</button>
            <button className="btn">⟲ −1 Frame</button>
            <button className="btn">⟳ +1 Frame</button>
            <button className="btn">◐ 0.25×</button>
            <button className="btn primary" style={{ marginLeft: 'auto' }}>↻ Loop Event</button>
          </div>

          {/* synchronized tracks */}
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Synchronized Tracks · 0:48</div>
              <span className="chip cyan">5 LAYERS</span>
            </div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {SYNC_LAYERS.map((ly, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 12, alignItems: 'center' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 8, height: 8, background: ly.c, borderRadius: 1 }} />
                    <span className="tick" style={{ color: 'var(--fg-1)' }}>{ly.l}</span>
                  </div>
                  <div style={{ position: 'relative', height: 16, background: 'var(--bg-3)', borderRadius: 1, overflow: 'hidden' }}>
                    {ly.l === 'Event Timeline'
                      ? [0.18, 0.42, 0.61, 0.83].map((m, j) => <div key={j} style={{ position: 'absolute', left: `${m * 100}%`, top: 0, bottom: 0, width: 2, background: ly.c }} />)
                      : Array.from({ length: 24 }, (_, j) => {
                          const h = 4 + Math.abs(Math.sin(j * 0.7 + i)) * 11;
                          return <div key={j} style={{ position: 'absolute', left: `${(j / 24) * 100}%`, bottom: 0, width: '3%', height: h, background: ly.c, opacity: 0.7 }} />;
                        })}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Right: clips + insights */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Clip Library</div>
              <span className="chip">5 CLIPS</span>
            </div>
            <div className="panel-body" style={{ padding: 0 }}>
              {CLIPS.map((c, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 8, padding: '12px 16px', borderBottom: '1px solid var(--line)', background: c.active ? 'var(--bg-2)' : 'transparent', borderLeft: c.active ? '2px solid var(--accent)' : '2px solid transparent', cursor: 'pointer' }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 500 }}>{c.t}</div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--fg-3)', marginTop: 2 }}>{c.src} · {c.dur}</div>
                  </div>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', alignSelf: 'center' }}>▶</span>
                </div>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Frame Metrics</div>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>@ 00:20</span>
            </div>
            <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div><div className="tick">Ball Speed</div><div className="num-sm mono" style={{ color: 'var(--accent)' }}>138 km/h</div></div>
              <div><div className="tick">Gaze↔Ball Lag</div><div className="num-sm mono">0.18s</div></div>
              <div><div className="tick">Head Yaw</div><div className="num-sm mono">14°</div></div>
              <div><div className="tick">Tracked Objects</div><div className="num-sm mono">4</div></div>
            </div>
          </div>

          <div className="panel" style={{ borderLeft: '3px solid var(--accent)' }}>
            <div className="panel-header"><div className="panel-title" style={{ color: 'var(--accent)' }}>◆ AI Sync Insight</div></div>
            <div className="panel-body">
              <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.55 }}>
                On the 00:20 delivery the batter's gaze tracked the ball with an <strong>0.18 s lag</strong> — 40 ms tighter than her season average. Head rotation led the eyes, indicating good pre-movement anticipation.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.video = VideoScreen;


// ---------- screens/coach.jsx ----------
// Coach Portal — squad progress, drill recommendations

const SQUAD = [
  { id: 'AP', name: 'Arjun Prakash',   sport: 'Cricket',   score: 78, delta: +4, drills: 2, status: 'ON TRACK',   flag: null },
  { id: 'MK', name: 'Meera Krishnan',  sport: 'Archery',   score: 84, delta: +6, drills: 1, status: 'ELITE',      flag: 'star' },
  { id: 'RS', name: 'Rohan Shetty',    sport: 'Hockey',    score: 71, delta: -2, drills: 3, status: 'WATCH',      flag: 'watch' },
  { id: 'PP', name: 'Priya Patel',     sport: 'Badminton', score: 76, delta: +1, drills: 2, status: 'ON TRACK',   flag: null },
  { id: 'VK', name: 'Vikram Kumar',    sport: 'Shooting',  score: 82, delta: +3, drills: 0, status: 'ELITE',      flag: 'star' },
  { id: 'AN', name: 'Ananya Nair',     sport: 'Tennis',    score: 69, delta: -5, drills: 4, status: 'AT RISK',    flag: 'risk' },
  { id: 'SG', name: 'Suresh Ganesan',  sport: 'Cricket',   score: 73, delta: +2, drills: 2, status: 'ON TRACK',   flag: null },
  { id: 'RD', name: 'Riya Deshmukh',   sport: 'Kabaddi',   score: 80, delta: +5, drills: 1, status: 'ELITE',      flag: 'star' },
  { id: 'HG', name: 'Harpreet Gill',   sport: 'Boxing',    score: 68, delta: -1, drills: 3, status: 'WATCH',      flag: 'watch' },
];

const DRILLS = [
  { title: 'Peripheral Cue Detection',   dur: '12 min', sport: 'Hockey · Cricket', athletes: 4, tag: 'PERIPHERAL' },
  { title: 'Quiet-Eye Fixation Training', dur: '8 min',  sport: 'Archery · Shooting', athletes: 2, tag: 'QUIET EYE' },
  { title: 'Multi-Object Tracking',       dur: '15 min', sport: 'Team sports', athletes: 6, tag: 'TRACKING' },
  { title: 'Serve Anticipation Video',    dur: '20 min', sport: 'Tennis · Badminton', athletes: 3, tag: 'ANTICIPATION' },
  { title: 'Distraction Resistance',      dur: '10 min', sport: 'All', athletes: 5, tag: 'FOCUS' },
];

function StatusChip({ status }) {
  const map = {
    'ELITE':    { cls: 'accent' },
    'ON TRACK': { cls: 'cyan' },
    'WATCH':    { cls: 'saffron' },
    'AT RISK':  { cls: 'red' },
  };
  const m = map[status] || {};
  return <span className={`chip ${m.cls}`}>{status}</span>;
}

function MiniSpark({ values, color = 'var(--accent)' }) {
  const max = Math.max(...values), min = Math.min(...values);
  const w = 60, h = 20;
  const range = max - min || 1;
  const pts = values.map((v, i) => `${(i / (values.length - 1)) * w},${h - ((v - min) / range) * h}`).join(' ');
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width={w} height={h}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.2" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}

function CoachScreen({ onNav }) {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Coach K. Iyengar · Squad view</div>
          <div className="page-title">Bengaluru Cricket &amp; All-Sports Squad</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">+ Assign Drill</button>
          <button className="btn">Schedule Session</button>
          <button className="btn primary">↗ Weekly Report</button>
        </div>
      </div>

      {/* KPI row */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Squad Size</div>
          <div className="kpi-value">28</div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>9 sports · 6 elite</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Avg Attention Score</div>
          <div className="kpi-value">75.<span style={{ color: 'var(--fg-3)' }}>4</span></div>
          <div className="kpi-delta up">▲ +2.1 wk-over-wk</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Drills Assigned · This Week</div>
          <div className="kpi-value">18</div>
          <div className="kpi-delta" style={{ color: 'var(--accent)' }}>14 completed · 78%</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Athletes At Risk</div>
          <div className="kpi-value" style={{ color: 'var(--red)' }}>2</div>
          <div className="kpi-delta down">▼ Attention drop &gt; 5pt</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }}>
        {/* Squad table */}
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Squad · Attention Trajectory</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <span className="chip filled">ALL</span>
              <span className="chip">ELITE</span>
              <span className="chip">AT RISK</span>
              <span className="chip">CRICKET</span>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Athlete</th>
                <th>Sport</th>
                <th>Score</th>
                <th>4-Wk Trend</th>
                <th>Δ Week</th>
                <th>Drills</th>
                <th>Status</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {SQUAD.map(a => (
                <tr key={a.id} style={{ cursor: 'pointer' }} onClick={() => onNav('scientist')}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div className="avatar" style={{ width: 28, height: 28, fontSize: 10 }}>{a.id}</div>
                      <span style={{ fontWeight: 500, color: 'var(--fg-0)' }}>{a.name}</span>
                      {a.flag === 'star' && <span className="chip accent" style={{ fontSize: 8 }}>★</span>}
                    </div>
                  </td>
                  <td>{a.sport}</td>
                  <td className="num">{a.score}</td>
                  <td>
                    <MiniSpark
                      values={Array.from({length: 8}, (_, i) => a.score - 8 + i + (Math.random() - 0.5) * 4)}
                      color={a.delta >= 0 ? 'var(--accent)' : 'var(--red)'}
                    />
                  </td>
                  <td className="num" style={{ color: a.delta >= 0 ? 'var(--accent)' : 'var(--red)' }}>
                    {a.delta >= 0 ? '▲' : '▼'} {Math.abs(a.delta)}
                  </td>
                  <td className="num">{a.drills}</td>
                  <td><StatusChip status={a.status} /></td>
                  <td><span className="mono" style={{ color: 'var(--fg-3)' }}>→</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Recommended drills */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">AI Drill Recommendations</div>
              <span className="chip"><span className="pulse-dot" style={{ background: 'var(--accent)' }} />5 NEW</span>
            </div>
            <div className="panel-body" style={{ padding: 0 }}>
              {DRILLS.map((d, i) => (
                <div key={i} style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-0)' }}>{d.title}</div>
                    <span className="chip accent" style={{ fontSize: 8 }}>{d.tag}</span>
                  </div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', letterSpacing: '0.12em' }}>
                    {d.dur} · {d.sport}
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
                    <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{d.athletes} ATHLETES</span>
                    <button className="btn" style={{ padding: '4px 10px', fontSize: 10 }}>Assign</button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Today's Schedule</div>
            </div>
            <div className="panel-body" style={{ padding: 0 }}>
              {[
                { t: '09:00', a: 'M. Krishnan', p: 'Archery · Full Assessment', dur: '45m' },
                { t: '10:30', a: 'A. Prakash',  p: 'Cricket · Anticipation',   dur: '30m' },
                { t: '13:00', a: 'Squad (6)',   p: 'Peripheral Cue Drill',     dur: '20m' },
                { t: '15:00', a: 'A. Nair',     p: 'Tennis · Rehab check-in',  dur: '25m' },
              ].map((s, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '54px 1fr auto', gap: 10, padding: '12px 18px', borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
                  <span className="mono" style={{ fontSize: 12, color: 'var(--accent)' }}>{s.t}</span>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 500 }}>{s.a}</div>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>{s.p}</div>
                  </div>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{s.dur}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.coach = CoachScreen;


// ---------- screens/athlete.jsx ----------
// Athlete Portal — personal scorecard, streaks, drills

function ScoreDial({ value, max = 100, size = 200, label }) {
  const R = size / 2 - 12;
  const C = 2 * Math.PI * R;
  const pct = value / max;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={size/2} cy={size/2} r={R} fill="none" stroke="var(--bg-3)" strokeWidth="10" />
      <circle
        cx={size/2} cy={size/2} r={R}
        fill="none"
        stroke="var(--accent)"
        strokeWidth="10"
        strokeDasharray={`${C * pct} ${C}`}
        strokeDashoffset={C / 4}
        transform={`rotate(-90 ${size/2} ${size/2})`}
        strokeLinecap="butt"
      />
      <text x={size/2} y={size/2 - 8} textAnchor="middle" dominantBaseline="middle"
        fill="var(--fg-0)" fontFamily="var(--font-display)" fontWeight="500" fontSize="48" letterSpacing="-0.02em">
        {value}
      </text>
      <text x={size/2} y={size/2 + 22} textAnchor="middle" dominantBaseline="middle"
        fill="var(--fg-2)" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em">
        {label}
      </text>
    </svg>
  );
}

function Streak() {
  const days = Array.from({ length: 28 }, (_, i) => {
    const active = i < 24 && Math.random() > 0.15;
    const intensity = active ? Math.random() * 0.7 + 0.3 : 0;
    return { active, intensity };
  });
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(14, 1fr)', gap: 4 }}>
      {days.map((d, i) => (
        <div key={i} style={{
          aspectRatio: '1',
          background: d.active ? `oklch(0.92 0.19 115 / ${d.intensity})` : 'var(--bg-3)',
          borderRadius: 1,
        }} />
      ))}
    </div>
  );
}

function AthleteScreen({ onNav }) {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ नमस्ते, Arjun · Session 04 complete</div>
          <div className="page-title">Your Vision Report</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">↗ Share with Family</button>
          <button className="btn primary">▶ Start Today's Drill</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
        {/* Big score */}
        <div className="panel" style={{ padding: 32, display: 'flex', gap: 32, alignItems: 'center' }}>
          <ScoreDial value={78} label="ATTENTION SCORE" size={200} />
          <div style={{ flex: 1 }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', letterSpacing: '0.14em', marginBottom: 6 }}>▲ +4 vs LAST WEEK</div>
            <div style={{ fontSize: 20, fontWeight: 500, lineHeight: 1.2, marginBottom: 12 }}>
              You're in the top <span style={{ color: 'var(--accent)' }}>18%</span> of U-19 cricketers nationally.
            </div>
            <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.5 }}>
              Your bowler tracking has improved sharply. Focus this week on peripheral awareness — that's holding your score back.
            </div>
            <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
              <div>
                <div className="tick">Streak</div>
                <div className="num-md mono">17d</div>
              </div>
              <div className="vdivider" style={{ height: 40 }} />
              <div>
                <div className="tick">Sessions</div>
                <div className="num-md mono">04</div>
              </div>
              <div className="vdivider" style={{ height: 40 }} />
              <div>
                <div className="tick">Level</div>
                <div className="num-md mono">B+</div>
              </div>
            </div>
          </div>
        </div>

        {/* What you did well / to improve */}
        <div style={{ display: 'grid', gridTemplateRows: '1fr 1fr', gap: 16 }}>
          <div className="panel" style={{ borderLeft: '3px solid var(--accent)' }}>
            <div className="panel-header">
              <div className="panel-title" style={{ color: 'var(--accent)' }}>✓ What you did well</div>
            </div>
            <div className="panel-body" style={{ paddingTop: 12 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div style={{ fontSize: 14 }}><strong>Release-point fixation</strong> — you found the bowler's hand 40ms faster than last session.</div>
                <div style={{ fontSize: 14 }}><strong>Reaction time</strong> — 248ms on choice-reaction, personal best.</div>
              </div>
            </div>
          </div>
          <div className="panel" style={{ borderLeft: '3px solid var(--saffron)' }}>
            <div className="panel-header">
              <div className="panel-title" style={{ color: 'var(--saffron)' }}>▲ To improve</div>
            </div>
            <div className="panel-body" style={{ paddingTop: 12 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div style={{ fontSize: 14 }}><strong>Peripheral awareness</strong> — missed 3 of 8 wide-field cues.</div>
                <div style={{ fontSize: 14 }}><strong>Blink control</strong> — 2 blinks during ball flight. Coach suggests blink-timing drill.</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Drills row */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Your Drills · Week 03</div>
            <span className="chip cyan">3 REMAINING</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1, background: 'var(--line)' }}>
            {[
              { t: 'Peripheral Cue Detection', d: '12 min', done: true,  today: false, tag: 'PERIPHERAL' },
              { t: 'Multi-Object Tracking',    d: '15 min', done: false, today: true,  tag: 'TRACKING' },
              { t: 'Blink Timing Drill',       d: '8 min',  done: false, today: false, tag: 'CONTROL' },
              { t: 'Bowler Anticipation Video', d: '20 min', done: true,  today: false, tag: 'ANTICIPATE' },
              { t: 'Quiet-Eye Fixation',        d: '10 min', done: false, today: false, tag: 'FIXATION' },
              { t: 'Distraction Resistance',    d: '12 min', done: false, today: false, tag: 'FOCUS' },
            ].map((d, i) => (
              <div key={i} style={{
                background: d.today ? 'var(--bg-2)' : 'var(--bg-1)',
                padding: 18,
                position: 'relative',
                borderLeft: d.today ? '2px solid var(--accent)' : 'none',
              }}>
                {d.today && <span className="chip accent" style={{ position: 'absolute', top: 12, right: 12, fontSize: 8 }}>TODAY</span>}
                {d.done && <span className="chip green" style={{ position: 'absolute', top: 12, right: 12, fontSize: 8 }}>✓ DONE</span>}
                <div className="mono" style={{ fontSize: 9, color: 'var(--fg-2)', letterSpacing: '0.14em', marginBottom: 8 }}>◆ {d.tag}</div>
                <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 6, opacity: d.done ? 0.5 : 1 }}>{d.t}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{d.d}</div>
                {!d.done && (
                  <button className={`btn ${d.today ? 'primary' : ''}`} style={{ marginTop: 14, width: '100%', justifyContent: 'center' }}>
                    {d.today ? '▶ Start Now' : 'Preview'}
                  </button>
                )}
              </div>
            ))}
          </div>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">28-Day Streak</div>
            <span className="chip accent">17 · PERSONAL BEST</span>
          </div>
          <div className="panel-body">
            <Streak />
            <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
              <div className="tick">Next milestone</div>
              <div style={{ fontSize: 16, fontWeight: 500, margin: '4px 0 8px' }}>30-day badge · <span style={{ color: 'var(--accent)' }}>13 days to go</span></div>
              <div className="bar"><div className="bar-fill" style={{ width: '57%' }} /></div>
            </div>
          </div>
        </div>
      </div>

      {/* Upcoming + achievements */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Upcoming Assessments</div>
          </div>
          <div className="panel-body" style={{ padding: 0 }}>
            {[
              { d: 'TUE · 21 JUL', t: '10:30', p: 'Cricket · Bowler anticipation retest', loc: 'Bengaluru NCoE · Lab 2' },
              { d: 'FRI · 24 JUL', t: '14:00', p: 'Peripheral awareness batch',           loc: 'Bengaluru NCoE · Lab 1' },
              { d: 'MON · 27 JUL', t: '09:00', p: 'Talent-ID panel review',               loc: 'Regional · Virtual'    },
            ].map((s, i) => (
              <div key={i} style={{ padding: '16px 18px', borderBottom: '1px solid var(--line)', display: 'grid', gridTemplateColumns: '120px 1fr auto', gap: 12, alignItems: 'center' }}>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', letterSpacing: '0.14em' }}>{s.d}</div>
                  <div className="num-sm mono" style={{ color: 'var(--accent)' }}>{s.t}</div>
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{s.p}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{s.loc}</div>
                </div>
                <button className="btn" style={{ padding: '4px 10px', fontSize: 10 }}>Details</button>
              </div>
            ))}
          </div>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Achievements</div>
          </div>
          <div className="panel-body">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
              {[
                { i: '★', l: 'First 250ms',    d: 'Sub-250ms reaction', got: true },
                { i: '◈', l: '10-Day Streak', d: 'Trained daily',      got: true },
                { i: '◉', l: 'Bowler Sniper',  d: '95% release-point',  got: true },
                { i: '▲', l: 'Top 20 U-19',    d: 'National ranking',   got: true },
                { i: '◆', l: 'Quiet Master',   d: '1.5s quiet-eye',     got: false },
                { i: '◇', l: '30-Day',         d: 'Streak milestone',   got: false },
                { i: '☆', l: 'Peripheral',     d: '90% wide cues',      got: false },
                { i: '⬢', l: 'Elite Match',    d: 'Match elite band',   got: false },
              ].map((b, i) => (
                <div key={i} style={{
                  padding: 12,
                  border: '1px solid var(--line)',
                  borderRadius: 2,
                  textAlign: 'center',
                  opacity: b.got ? 1 : 0.35,
                  background: b.got ? 'var(--bg-2)' : 'transparent',
                }}>
                  <div style={{ fontSize: 24, color: b.got ? 'var(--accent)' : 'var(--fg-3)', lineHeight: 1 }}>{b.i}</div>
                  <div className="mono" style={{ fontSize: 9, letterSpacing: '0.12em', marginTop: 8, color: 'var(--fg-0)' }}>{b.l.toUpperCase()}</div>
                  <div className="mono" style={{ fontSize: 8, color: 'var(--fg-3)', marginTop: 2 }}>{b.d}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.athlete = AthleteScreen;


// ---------- screens/talent.jsx ----------
// Talent Identification — AI ranking of young athletes across the pipeline

const FUNNEL = [
  { l: 'School Competitions', v: 48200, c: 'var(--fg-2)' },
  { l: 'District Screening',  v: 18600, c: 'var(--cyan)' },
  { l: 'Khelo India Pool',    v: 6240,  c: 'var(--cyan)' },
  { l: 'Academy Intake',      v: 1820,  c: 'var(--accent)' },
  { l: 'NCoE High-Potential', v: 247,   c: 'var(--accent)' },
];

// vision, reflex, tracking, decision, coordination
const PROSPECTS = [
  { n: 'Aditya Rane',    age: 15, sport: 'Cricket',   region: 'Maharashtra', s: [92, 88, 90, 85, 87], comp: 91, tag: 'ELITE' },
  { n: 'Sneha Barman',   age: 14, sport: 'Archery',   region: 'Assam',       s: [95, 82, 91, 89, 84], comp: 90, tag: 'ELITE' },
  { n: 'Karan Bhullar',  age: 16, sport: 'Boxing',    region: 'Punjab',      s: [84, 94, 86, 82, 90], comp: 88, tag: 'RISING' },
  { n: 'Divya Menon',    age: 15, sport: 'Badminton', region: 'Kerala',      s: [88, 90, 92, 80, 83], comp: 87, tag: 'RISING' },
  { n: 'Rohit Yadav',    age: 13, sport: 'Shooting',  region: 'UP',          s: [90, 79, 88, 91, 78], comp: 86, tag: 'RISING' },
  { n: 'Tara Singh',     age: 16, sport: 'Hockey',    region: 'Haryana',     s: [82, 86, 89, 84, 88], comp: 85, tag: 'WATCH' },
  { n: 'Ishaan Nair',    age: 14, sport: 'Football',  region: 'Goa',         s: [80, 88, 84, 86, 85], comp: 84, tag: 'WATCH' },
  { n: 'Meghna Das',     age: 15, sport: 'Kabaddi',   region: 'W. Bengal',   s: [78, 90, 82, 80, 89], comp: 83, tag: 'WATCH' },
];

const SUBS = ['Vision', 'Reflex', 'Track', 'Decide', 'Coord'];

function tagChip(tag) {
  const m = { ELITE: 'accent', RISING: 'cyan', WATCH: 'saffron' };
  return <span className={`chip ${m[tag] || ''}`}>{tag}</span>;
}

function ScoreBars({ s }) {
  return (
    <div style={{ display: 'flex', gap: 4, alignItems: 'flex-end', height: 26 }}>
      {s.map((v, i) => (
        <div key={i} title={`${SUBS[i]} ${v}`} style={{ width: 6, height: `${(v / 100) * 26}px`, background: v >= 88 ? 'var(--accent)' : v >= 80 ? 'var(--cyan)' : 'var(--saffron)', borderRadius: 1 }} />
      ))}
    </div>
  );
}

function TalentScreen({ onNav }) {
  const [sport, setSport] = useState('ALL');
  const sports = ['ALL', 'Cricket', 'Archery', 'Boxing', 'Shooting'];
  const rows = sport === 'ALL' ? PROSPECTS : PROSPECTS.filter(p => p.sport === sport);
  const maxF = FUNNEL[0].v;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Khelo India · talent pipeline · FY 2026–27</div>
          <div className="page-title">Talent Identification</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">⤓ Export Shortlist</button>
          <button className="btn">◆ Panel Review</button>
          <button className="btn primary">↗ Nominate to NCoE</button>
        </div>
      </div>

      {/* KPI row */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Athletes Screened · YTD</div>
          <div className="kpi-value">48,<span style={{ color: 'var(--fg-3)' }}>200</span></div>
          <div className="kpi-delta up">▲ +12,400 this quarter</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">High-Potential Flagged</div>
          <div className="kpi-value" style={{ color: 'var(--accent)' }}>247</div>
          <div className="kpi-delta" style={{ color: 'var(--accent)' }}>Top 0.5% · AI-ranked</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Khelo India Candidates</div>
          <div className="kpi-value">6,<span style={{ color: 'var(--fg-3)' }}>240</span></div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>28 states · 13 sports</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Avg Composite · Flagged</div>
          <div className="kpi-value">86.<span style={{ color: 'var(--fg-3)' }}>4</span></div>
          <div className="kpi-delta up">▲ vision-led profile</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16 }}>
        {/* Funnel + leaderboard */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Identification Pipeline</div>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>0.5% CONVERSION · SCHOOL → NCoE</span>
            </div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {FUNNEL.map((f, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '160px 1fr 70px', gap: 12, alignItems: 'center' }}>
                  <span className="tick" style={{ color: 'var(--fg-1)' }}>{f.l}</span>
                  <div style={{ height: 18, background: 'var(--bg-3)', borderRadius: 1, overflow: 'hidden' }}>
                    <div style={{ width: `${(f.v / maxF) * 100}%`, height: '100%', background: f.c, opacity: 0.85 }} />
                  </div>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-1)', textAlign: 'right' }}>{f.v.toLocaleString()}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">High-Potential Leaderboard</div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {sports.map(s => (
                  <button key={s} className={`chip ${s === sport ? 'filled' : ''}`} style={{ cursor: 'pointer' }} onClick={() => setSport(s)}>{s.toUpperCase()}</button>
                ))}
              </div>
            </div>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Rank</th><th>Athlete</th><th>Age</th><th>Sport</th><th>Region</th>
                  <th>V·Rf·Tr·Dc·Co</th><th>Composite</th><th>Band</th><th></th>
                </tr>
              </thead>
              <tbody>
                {rows.map((p, i) => (
                  <tr key={p.n} style={{ cursor: 'pointer' }} onClick={() => onNav && onNav('scientist')}>
                    <td className="mono" style={{ color: i < 3 ? 'var(--accent)' : 'var(--fg-2)' }}>#{String(i + 1).padStart(2, '0')}</td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <div className="avatar" style={{ width: 28, height: 28, fontSize: 10 }}>{p.n.split(' ').map(w => w[0]).join('')}</div>
                        <span style={{ fontWeight: 500, color: 'var(--fg-0)' }}>{p.n}</span>
                      </div>
                    </td>
                    <td className="num">{p.age}</td>
                    <td>{p.sport}</td>
                    <td className="mono" style={{ fontSize: 11, color: 'var(--fg-2)' }}>{p.region}</td>
                    <td><ScoreBars s={p.s} /></td>
                    <td className="num" style={{ fontSize: 16, color: p.comp >= 88 ? 'var(--accent)' : 'var(--fg-0)' }}>{p.comp}</td>
                    <td>{tagChip(p.tag)}</td>
                    <td><span className="mono" style={{ color: 'var(--fg-3)' }}>→</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Right: spotlight + AI eval + filters */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel" style={{ borderLeft: '3px solid var(--accent)' }}>
            <div className="panel-header">
              <div className="panel-title" style={{ color: 'var(--accent)' }}>★ Rising Star</div>
              <span className="chip accent">91 COMPOSITE</span>
            </div>
            <div className="panel-body">
              <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 14 }}>
                <div className="avatar xl">AR</div>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 500 }}>Aditya Rane</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', marginTop: 4, textTransform: 'uppercase', letterSpacing: '0.12em' }}>15 · Cricket · Maharashtra</div>
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[['Vision', 92], ['Reflex', 88], ['Tracking', 90], ['Decision', 85], ['Coordination', 87]].map(([l, v]) => (
                  <div key={l}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 3 }}>
                      <span className="tick" style={{ color: 'var(--fg-1)' }}>{l}</span>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>{v}</span>
                    </div>
                    <div className="bar"><div className="bar-fill" style={{ width: `${v}%` }} /></div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="panel">
            <div className="panel-header"><div className="panel-title">AI Evaluation Basis</div></div>
            <div className="panel-body" style={{ padding: 0 }}>
              {[
                { l: 'Vision', d: 'acuity, tracking, peripheral' },
                { l: 'Reflexes', d: 'simple + choice reaction' },
                { l: 'Tracking', d: 'multi-object, pursuit gain' },
                { l: 'Decision Speed', d: 'anticipation, accuracy' },
                { l: 'Coordination', d: 'eye-hand, eye-foot' },
              ].map((r, i) => (
                <div key={i} style={{ padding: '11px 16px', borderBottom: '1px solid var(--line)' }}>
                  <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-0)' }}>{r.l}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{r.d}</div>
                </div>
              ))}
              <div style={{ padding: '12px 16px', fontSize: 11, color: 'var(--fg-2)', lineHeight: 1.5 }}>
                Age-normalized against national bands. Ranks are decision-support only — final selection requires SAI panel confirmation.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.talent = TalentScreen;


// ---------- screens/medical.jsx ----------
// Medical & Rehab — baseline vs post-injury, concussion, return-to-play

function DualLineChart({ baseline, current, height = 120 }) {
  const n = baseline.length;
  const all = [...baseline, ...current];
  const max = Math.max(...all) * 1.1;
  const min = Math.min(...all) * 0.9;
  const range = max - min || 1;
  const w = 100;
  const norm = arr => arr.map((v, i) => `${(i / (n - 1)) * w},${100 - ((v - min) / range) * 100}`).join(' ');
  return (
    <svg viewBox={`0 0 ${w} 100`} preserveAspectRatio="none" style={{ width: '100%', height }}>
      {[25, 50, 75].map(y => <line key={y} x1="0" x2={w} y1={y} y2={y} stroke="var(--line)" strokeWidth="0.3" />)}
      <polyline points={norm(baseline)} fill="none" stroke="var(--cyan)" strokeWidth="1" strokeDasharray="2 2" vectorEffect="non-scaling-stroke" />
      <polyline points={norm(current)} fill="none" stroke="var(--red)" strokeWidth="1.5" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}

function ReadinessGauge({ pct, label, threshold = 85 }) {
  const R = 60, C = Math.PI * R; // half circle
  const clamped = Math.max(0, Math.min(100, pct));
  const passed = pct >= threshold;
  return (
    <div style={{ textAlign: 'center' }}>
      <svg width="150" height="90" viewBox="0 0 150 90">
        <path d={`M 15,75 A 60,60 0 0 1 135,75`} fill="none" stroke="var(--bg-3)" strokeWidth="10" />
        <path d={`M 15,75 A 60,60 0 0 1 135,75`}
          fill="none"
          stroke={passed ? 'var(--accent)' : 'var(--red)'}
          strokeWidth="10"
          strokeDasharray={`${(C * clamped) / 100} ${C}`}
        />
        {/* Threshold tick */}
        <line
          x1={75 + Math.cos(Math.PI - (threshold / 100) * Math.PI) * 68}
          y1={75 + Math.sin(Math.PI - (threshold / 100) * Math.PI) * 68 * -1 * -1}
          x2={75 + Math.cos(Math.PI - (threshold / 100) * Math.PI) * 52}
          y2={75 + Math.sin(Math.PI - (threshold / 100) * Math.PI) * 52 * -1 * -1}
          stroke="var(--saffron)" strokeWidth="1.5"
        />
        <text x="75" y="65" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="500" fontSize="32" fill="var(--fg-0)" letterSpacing="-0.02em">
          {pct}
        </text>
      </svg>
      <div className="tick" style={{ marginTop: -4 }}>{label}</div>
    </div>
  );
}

function MedicalScreen() {
  const baseline = [82, 84, 83, 85, 86, 84, 85, 87, 88, 86, 87, 88];
  const current  = [42, 48, 52, 55, 58, 62, 65, 68, 72, 74, 76, 78];

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Confidential · Neuro-visual assessment</div>
          <div className="page-title">Rehabilitation · Athlete #SAI-BLR-1284</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">⤓ Clinical Report</button>
          <button className="btn primary">Sign RTP Decision</button>
        </div>
      </div>

      {/* Confidential notice */}
      <div style={{ padding: '12px 18px', border: '1px solid var(--red)', borderRadius: 2, marginBottom: 20, display: 'flex', gap: 12, alignItems: 'center', background: 'oklch(0.68 0.22 25 / 0.05)' }}>
        <span style={{ color: 'var(--red)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em' }}>◆ CONFIDENTIAL</span>
        <span style={{ fontSize: 12, color: 'var(--fg-1)' }}>Medical view. Access restricted to Dr. Sinha, Dr. Menon. Athlete + guardian consent on file. NayanTrack does not provide autonomous diagnosis.</span>
      </div>

      {/* Injury timeline */}
      <div className="panel" style={{ marginBottom: 20 }}>
        <div className="panel-header">
          <div className="panel-title">Injury Timeline</div>
          <span className="chip red">DAY 42 POST-INJURY</span>
        </div>
        <div className="panel-body">
          <div style={{ position: 'relative', height: 60 }}>
            {/* Line */}
            <div style={{ position: 'absolute', top: 30, left: 0, right: 0, height: 1, background: 'var(--line-strong)' }} />
            {[
              { at: 0,   l: 'INJURY',       d: 'Day 0',   c: 'var(--red)' },
              { at: 15,  l: 'BASELINE ×',   d: 'Day 3',   c: 'var(--saffron)' },
              { at: 33,  l: '1st RETEST',   d: 'Day 14',  c: 'var(--cyan)' },
              { at: 55,  l: '2nd RETEST',   d: 'Day 28',  c: 'var(--cyan)' },
              { at: 78,  l: '3rd RETEST',   d: 'Day 42',  c: 'var(--accent)' },
              { at: 100, l: 'RTP TARGET',   d: 'Day 56',  c: 'var(--fg-2)' },
            ].map((e, i) => (
              <div key={i} style={{ position: 'absolute', left: `${e.at}%`, top: 0 }}>
                <div style={{ width: 12, height: 12, background: e.c, borderRadius: '50%', marginLeft: -6, marginTop: 24, border: '2px solid var(--bg-1)' }} />
                <div className="mono" style={{ fontSize: 9, marginTop: 6, color: 'var(--fg-1)', letterSpacing: '0.12em', transform: 'translateX(-50%)', whiteSpace: 'nowrap' }}>{e.l}</div>
                <div className="mono" style={{ fontSize: 9, color: 'var(--fg-3)', transform: 'translateX(-50%)', whiteSpace: 'nowrap' }}>{e.d}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Row 1: Baseline vs current + Readiness */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Attention Score · Baseline vs Recovery</div>
            <div style={{ display: 'flex', gap: 12 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <span style={{ width: 12, height: 2, background: 'var(--cyan)', borderTop: '1px dashed' }} />
                <span className="tick">Pre-injury baseline</span>
              </span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                <span style={{ width: 12, height: 2, background: 'var(--red)' }} />
                <span className="tick">Post-injury recovery</span>
              </span>
            </div>
          </div>
          <div className="panel-body">
            <DualLineChart baseline={baseline} current={current} height={200} />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
              <div><div className="tick">Baseline avg</div><div className="num-sm mono">85.2</div></div>
              <div><div className="tick">Current</div><div className="num-sm mono" style={{ color: 'var(--saffron)' }}>78</div></div>
              <div><div className="tick">Gap</div><div className="num-sm mono" style={{ color: 'var(--red)' }}>−7.2</div></div>
              <div><div className="tick">Recovery rate</div><div className="num-sm mono" style={{ color: 'var(--accent)' }}>+1.1/day</div></div>
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Return-to-Play Readiness</div>
            <span className="chip saffron">HOLD · 78%</span>
          </div>
          <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 20, alignItems: 'center' }}>
            <ReadinessGauge pct={78} label="COMPOSITE" threshold={85} />
            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                { l: 'Oculomotor', v: 88, ok: true },
                { l: 'Attention',  v: 82, ok: false },
                { l: 'Reaction',   v: 76, ok: false },
                { l: 'Fixation',   v: 85, ok: true },
              ].map((r, i) => (
                <div key={i}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                    <span className="tick" style={{ color: r.ok ? 'var(--accent)' : 'var(--saffron)' }}>{r.ok ? '✓' : '△'} {r.l}</span>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--fg-1)' }}>{r.v}%</span>
                  </div>
                  <div className="bar"><div className={`bar-fill ${r.ok ? '' : 'saffron'}`} style={{ width: `${r.v}%` }} /></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Row 2: Concussion screening + clinician notes */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Oculomotor Battery · King-Devick / VOMS</div>
            <span className="chip">42/60 PASS</span>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>Test</th><th>Baseline</th><th>Current</th><th>Δ</th><th>Flag</th></tr>
            </thead>
            <tbody>
              {[
                { t: 'Smooth Pursuit',     b: '0.8°', c: '1.2°', d: '+0.4°', f: 'watch' },
                { t: 'Saccade Latency',    b: '210ms', c: '248ms', d: '+38ms', f: 'watch' },
                { t: 'Convergence Near-Pt', b: '5cm', c: '9cm', d: '+4cm', f: 'flag' },
                { t: 'VOR (Horizontal)',   b: '1.0', c: '0.88', d: '−0.12', f: 'ok' },
                { t: 'Visual Motion',      b: '2/10', c: '4/10', d: '+2', f: 'ok' },
                { t: 'Nystagmus',          b: 'None', c: 'None', d: '—', f: 'ok' },
              ].map((r, i) => (
                <tr key={i}>
                  <td>{r.t}</td>
                  <td className="num">{r.b}</td>
                  <td className="num">{r.c}</td>
                  <td className="num" style={{ color: r.f === 'ok' ? 'var(--fg-1)' : r.f === 'watch' ? 'var(--saffron)' : 'var(--red)' }}>{r.d}</td>
                  <td>{r.f === 'ok' ? <span className="chip green">OK</span> : r.f === 'watch' ? <span className="chip saffron">WATCH</span> : <span className="chip red">FLAG</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Clinician Notes &amp; Rehab Plan</div>
            <span className="chip">DR. SINHA · 15 JUL</span>
          </div>
          <div className="panel-body">
            <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.55, marginBottom: 16 }}>
              Athlete presents with persistent convergence insufficiency and mildly delayed saccadic latency, consistent with post-concussion oculomotor pattern. Attention score trajectory is positive (+1.1/day over 4 weeks) and matches expected recovery for grade-2 concussion.
            </div>
            <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.55, marginBottom: 20 }}>
              Recommend continuing convergence-focused rehab exercises and delaying return-to-play by 14 days. Retest scheduled for Day 56. No contact drills.
            </div>

            <div className="tick" style={{ marginBottom: 10 }}>Prescribed exercises · this week</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {[
                'Pencil push-ups · 3× daily · 10 reps',
                'Brock string convergence · 2× daily',
                'Saccadic training video · 15 min',
                'Slow smooth-pursuit drill · 10 min',
              ].map((e, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: 'var(--bg-2)', borderRadius: 2, fontSize: 12 }}>
                  <span style={{ color: 'var(--accent)' }}>◆</span> {e}
                </div>
              ))}
            </div>

            <div style={{ marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--line)', display: 'flex', gap: 8 }}>
              <button className="btn">Amend Plan</button>
              <button className="btn">Add Note</button>
              <button className="btn danger" style={{ marginLeft: 'auto' }}>Escalate</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.medical = MedicalScreen;


// ---------- screens/centre.jsx ----------
// Centre Administrator — device fleet, calibration health, schedule

function CentreScreen() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Bengaluru NCoE · Facility ops</div>
          <div className="page-title">Centre Administration</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">+ Book Slot</button>
          <button className="btn">+ Enroll Athlete</button>
          <button className="btn primary">↗ Weekly Ops Report</button>
        </div>
      </div>

      {/* KPI row */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Athletes Enrolled</div>
          <div className="kpi-value">842</div>
          <div className="kpi-delta up">▲ +23 this month</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Sessions · MTD</div>
          <div className="kpi-value">1,<span style={{ color: 'var(--fg-3)' }}>284</span></div>
          <div className="kpi-delta up">▲ 92% completion</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Device Fleet</div>
          <div className="kpi-value">14<span className="kpi-unit">units</span></div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>12 online · 1 maint · 1 offline</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Calibration Pass Rate</div>
          <div className="kpi-value">94.<span style={{ color: 'var(--fg-3)' }}>2</span>%</div>
          <div className="kpi-delta down">▼ 2.1% vs last wk</div>
        </div>
      </div>

      {/* Device fleet + Today's schedule */}
      <div style={{ display: 'grid', gridTemplateColumns: '3fr 2fr', gap: 16, marginBottom: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Device Fleet</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <span className="chip filled">ALL 14</span>
              <span className="chip">LAB</span>
              <span className="chip">FIELD</span>
              <span className="chip">WEAR</span>
              <span className="chip">VR</span>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>Device ID</th><th>Type</th><th>Lab</th><th>Cal. Quality</th><th>Sessions</th><th>Last Cal</th><th>Status</th></tr>
            </thead>
            <tbody>
              {[
                { id: 'NT-LAB-01', t: 'Lab · Tobii Spectrum',  l: 'Lab 1', q: 0.42, s: 128, lc: '2h ago',  st: 'ok' },
                { id: 'NT-LAB-02', t: 'Lab · Tobii Spectrum',  l: 'Lab 1', q: 0.51, s: 96,  lc: '4h ago',  st: 'ok' },
                { id: 'NT-LAB-03', t: 'Lab · SR EyeLink',      l: 'Lab 2', q: 0.38, s: 142, lc: '1h ago',  st: 'ok' },
                { id: 'NT-FLD-04', t: 'Field · Portable',     l: 'Field', q: 0.68, s: 84,  lc: '8h ago',  st: 'watch' },
                { id: 'NT-FLD-05', t: 'Field · Portable',     l: 'Field', q: 0.55, s: 71,  lc: '6h ago',  st: 'ok' },
                { id: 'NT-WER-06', t: 'Wearable · Pupil Neon', l: 'Field', q: 0.72, s: 43,  lc: '12h ago', st: 'watch' },
                { id: 'NT-WER-07', t: 'Wearable · Pupil Neon', l: 'Field', q: '—',   s: 0,   lc: '3d ago',  st: 'maint' },
                { id: 'NT-VR-08',  t: 'VR · Quest Pro',        l: 'VR',   q: 0.61, s: 32,  lc: '1d ago',  st: 'ok' },
                { id: 'NT-VR-09',  t: 'VR · Vive Focus',       l: 'VR',   q: '—',   s: 0,   lc: '—',       st: 'offline' },
              ].map(d => (
                <tr key={d.id}>
                  <td className="mono" style={{ color: 'var(--fg-0)' }}>{d.id}</td>
                  <td>{d.t}</td>
                  <td className="mono" style={{ fontSize: 11 }}>{d.l}</td>
                  <td className="num" style={{ color: typeof d.q === 'number' ? (d.q < 0.5 ? 'var(--accent)' : d.q < 0.65 ? 'var(--saffron)' : 'var(--red)') : 'var(--fg-3)' }}>
                    {typeof d.q === 'number' ? `${d.q.toFixed(2)}°` : '—'}
                  </td>
                  <td className="num">{d.s}</td>
                  <td className="mono" style={{ fontSize: 11, color: 'var(--fg-2)' }}>{d.lc}</td>
                  <td>
                    {d.st === 'ok'      && <span className="chip green">◆ ONLINE</span>}
                    {d.st === 'watch'   && <span className="chip saffron">△ CAL DRIFT</span>}
                    {d.st === 'maint'   && <span className="chip">⚙ MAINT</span>}
                    {d.st === 'offline' && <span className="chip red">◯ OFFLINE</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Today · Bookings</div>
            <span className="chip cyan">14 / 18 SLOTS</span>
          </div>
          <div className="panel-body" style={{ padding: 0 }}>
            {[
              { t: '08:00', a: 'Batch 04 · Cricket U-19 (8)', d: 'LAB-01', c: 'M. Rao' },
              { t: '09:30', a: 'M. Krishnan · Archery',        d: 'LAB-03', c: 'K. Iyengar', highlight: true },
              { t: '10:00', a: 'Talent-ID panel (14)',         d: 'LAB-01,02,03', c: 'Regional' },
              { t: '11:30', a: 'A. Prakash · Cricket',         d: 'LAB-02', c: 'K. Iyengar' },
              { t: '13:00', a: 'VR Session · Football (4)',    d: 'VR-08',  c: 'S. Rana' },
              { t: '14:30', a: 'Rehab · A. Nair · Tennis',     d: 'LAB-03', c: 'Dr. Sinha' },
              { t: '16:00', a: 'Field · Hockey squad',         d: 'FLD-04,05', c: 'B. Singh' },
              { t: '17:30', a: 'Research · Elite panel',       d: 'LAB-01', c: 'Dr. Menon' },
            ].map((s, i) => (
              <div key={i} style={{
                display: 'grid',
                gridTemplateColumns: '48px 1fr auto',
                gap: 10,
                padding: '12px 18px',
                borderBottom: '1px solid var(--line)',
                alignItems: 'center',
                background: s.highlight ? 'var(--bg-2)' : 'transparent',
                borderLeft: s.highlight ? '2px solid var(--accent)' : '2px solid transparent',
              }}>
                <span className="mono" style={{ fontSize: 12, color: s.highlight ? 'var(--accent)' : 'var(--fg-1)' }}>{s.t}</span>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{s.a}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{s.d} · {s.c}</div>
                </div>
                <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>→</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Row 2: Utilization + Coach adoption */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Lab Utilization · Last 14 days</div>
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>08:00–20:00 · IST</span>
          </div>
          <div className="panel-body">
            {['LAB-01', 'LAB-02', 'LAB-03', 'FIELD', 'VR'].map((lab, li) => (
              <div key={lab} style={{ display: 'grid', gridTemplateColumns: '80px 1fr 60px', gap: 12, marginBottom: 10, alignItems: 'center' }}>
                <div className="tick" style={{ color: 'var(--fg-1)' }}>{lab}</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(14, 1fr)', gap: 3 }}>
                  {Array.from({ length: 14 }, (_, i) => {
                    const v = Math.random();
                    const level = v > 0.7 ? 3 : v > 0.45 ? 2 : v > 0.2 ? 1 : 0;
                    const colors = ['var(--bg-3)', 'oklch(0.92 0.19 115 / 0.3)', 'oklch(0.92 0.19 115 / 0.65)', 'var(--accent)'];
                    return <div key={i} style={{ aspectRatio: '1', background: colors[level], borderRadius: 1 }} />;
                  })}
                </div>
                <span className="mono" style={{ fontSize: 11, color: 'var(--fg-1)', textAlign: 'right' }}>
                  {(60 + Math.random() * 30).toFixed(0)}%
                </span>
              </div>
            ))}
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--line)' }}>
              <span className="tick">2 WEEKS AGO</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                <span className="tick">LOW</span>
                {[0, 0.3, 0.65, 1].map((o, i) => (
                  <div key={i} style={{ width: 12, height: 12, background: i === 0 ? 'var(--bg-3)' : `oklch(0.92 0.19 115 / ${o})` }} />
                ))}
                <span className="tick">HIGH</span>
              </div>
              <span className="tick">TODAY</span>
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Coach Adoption</div>
            <span className="chip accent">6 / 8 ACTIVE</span>
          </div>
          <div className="panel-body" style={{ padding: 0 }}>
            {[
              { n: 'K. Iyengar', s: 'Cricket', a: 34, ac: true },
              { n: 'B. Singh',   s: 'Hockey',  a: 28, ac: true },
              { n: 'M. Rao',     s: 'Cricket', a: 26, ac: true },
              { n: 'S. Rana',    s: 'Football',a: 22, ac: true },
              { n: 'Dr. Sinha',  s: 'Medical', a: 18, ac: true },
              { n: 'P. Verma',   s: 'Boxing',  a: 12, ac: true },
              { n: 'R. Iyer',    s: 'Tennis',  a: 3,  ac: false },
              { n: 'A. Ghosh',   s: 'Wrestling', a: 0,ac: false },
            ].map((c, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 10, padding: '10px 18px', borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
                <div className="avatar" style={{ width: 28, height: 28, fontSize: 10, opacity: c.ac ? 1 : 0.4 }}>{c.n.split(' ').map(w => w[0]).join('')}</div>
                <div>
                  <div style={{ fontSize: 12, color: c.ac ? 'var(--fg-0)' : 'var(--fg-3)' }}>{c.n}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{c.s}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="mono" style={{ fontSize: 12, color: c.ac ? 'var(--accent)' : 'var(--red)' }}>{c.a}</div>
                  <div className="mono" style={{ fontSize: 9, color: 'var(--fg-3)' }}>SESS · MTD</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.centre = CentreScreen;


// ---------- screens/command.jsx ----------
// National Command — SAI admin: India map, centre-wise KPIs, alerts

/* Approximate SAI NCoE / centre locations as % coords on a stylized India map bounding box */
const CENTRES = [
  { id: 'DEL', name: 'Delhi',       x: 40, y: 24, athletes: 1420, score: 76, trend: +2, sports: 11 },
  { id: 'BLR', name: 'Bengaluru',   x: 41, y: 70, athletes: 842,  score: 82, trend: +5, sports: 9,  highlight: true },
  { id: 'PUN', name: 'Pune',        x: 33, y: 60, athletes: 690,  score: 79, trend: +3, sports: 8 },
  { id: 'HYD', name: 'Hyderabad',   x: 44, y: 63, athletes: 720,  score: 74, trend: -1, sports: 7 },
  { id: 'KOL', name: 'Kolkata',     x: 68, y: 42, athletes: 810,  score: 71, trend: +1, sports: 8 },
  { id: 'GAN', name: 'Gandhinagar', x: 28, y: 45, athletes: 480,  score: 73, trend: +2, sports: 6 },
  { id: 'GUW', name: 'Guwahati',    x: 74, y: 33, athletes: 340,  score: 68, trend: -3, sports: 5, alert: true },
  { id: 'CHN', name: 'Chennai',     x: 44, y: 78, athletes: 620,  score: 77, trend: +4, sports: 8 },
  { id: 'BHO', name: 'Bhopal',      x: 42, y: 46, athletes: 410,  score: 70, trend: 0,  sports: 6 },
  { id: 'IMP', name: 'Imphal',      x: 82, y: 38, athletes: 210,  score: 65, trend: -2, sports: 4, alert: true },
  { id: 'PAT', name: 'Patiala',     x: 34, y: 20, athletes: 890,  score: 80, trend: +3, sports: 10 },
  { id: 'SON', name: 'Sonepat',     x: 40, y: 22, athletes: 520,  score: 74, trend: +1, sports: 6 },
  { id: 'ALK', name: 'Aurangabad',  x: 36, y: 56, athletes: 380,  score: 72, trend: +2, sports: 5 },
  { id: 'THI', name: 'Thiruvpm',    x: 38, y: 88, athletes: 290,  score: 76, trend: +1, sports: 5 },
];

/* Simplified India silhouette path — enough to feel like India without heavy geo data */
const INDIA_PATH = `
M 30,10 L 45,8 L 55,10 L 65,15 L 75,20 L 82,25 L 88,32 L 85,40 L 78,42 L 72,44
L 68,50 L 68,58 L 64,64 L 60,70 L 56,76 L 52,82 L 46,88 L 40,92 L 36,88 L 33,80
L 30,72 L 28,64 L 26,56 L 24,48 L 26,40 L 30,32 L 32,24 L 30,16 Z
`;

function IndiaMap() {
  const [hovered, setHovered] = useState(null);
  return (
    <div style={{ position: 'relative', aspectRatio: '4/5', maxHeight: 620 }}>
      <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
        {/* Faint grid */}
        <defs>
          <pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse">
            <path d="M 10 0 L 0 0 0 10" fill="none" stroke="var(--line)" strokeWidth="0.15" />
          </pattern>
        </defs>
        <rect width="100" height="100" fill="url(#grid)" opacity="0.4" />

        {/* India silhouette */}
        <path d={INDIA_PATH} fill="var(--bg-2)" stroke="var(--line-strong)" strokeWidth="0.4" />
        <path d={INDIA_PATH} fill="none" stroke="var(--accent)" strokeWidth="0.15" strokeDasharray="0.4 0.4" opacity="0.5" />

        {/* Compass */}
        <g transform="translate(88,10)" opacity="0.4">
          <circle r="4" fill="none" stroke="var(--fg-3)" strokeWidth="0.2" />
          <line x1="0" y1="-4" x2="0" y2="4" stroke="var(--fg-3)" strokeWidth="0.2" />
          <line x1="-4" y1="0" x2="4" y2="0" stroke="var(--fg-3)" strokeWidth="0.2" />
          <text y="-5" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="2" fill="var(--fg-2)">N</text>
        </g>

        {/* Centres */}
        {CENTRES.map(c => {
          const size = 0.6 + (c.athletes / 1500) * 2.4;
          const color = c.alert ? 'var(--red)' : c.highlight ? 'var(--accent)' : 'var(--cyan)';
          return (
            <g key={c.id}
               onMouseEnter={() => setHovered(c.id)}
               onMouseLeave={() => setHovered(null)}
               style={{ cursor: 'pointer' }}>
              {/* pulse for alerts */}
              {c.alert && (
                <circle cx={c.x} cy={c.y} r={size * 2.5} fill="none" stroke={color} strokeWidth="0.2" opacity="0.4">
                  <animate attributeName="r" from={size} to={size * 3.5} dur="2s" repeatCount="indefinite" />
                  <animate attributeName="opacity" from="0.6" to="0" dur="2s" repeatCount="indefinite" />
                </circle>
              )}
              <circle cx={c.x} cy={c.y} r={size} fill={color} opacity={hovered && hovered !== c.id ? 0.3 : 1} />
              <circle cx={c.x} cy={c.y} r={size + 0.5} fill="none" stroke={color} strokeWidth="0.2" opacity="0.4" />
              <text x={c.x + size + 1} y={c.y + 1} fontFamily="var(--font-mono)" fontSize="2" fill="var(--fg-1)" letterSpacing="0.05em">
                {c.name.toUpperCase()}
              </text>
            </g>
          );
        })}
      </svg>

      {/* Legend */}
      <div style={{ position: 'absolute', bottom: 12, left: 12, background: 'rgba(7,8,10,0.85)', padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 2 }}>
        <div className="tick" style={{ marginBottom: 8 }}>NCoE / SAI CENTRE</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--cyan)' }} />
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-1)' }}>ACTIVE</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--accent)' }} />
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-1)' }}>HIGH PERFORMANCE</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--red)' }} />
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-1)' }}>ATTENTION REQUIRED</span>
          </div>
        </div>
        <div className="mono" style={{ fontSize: 9, color: 'var(--fg-3)', marginTop: 8, letterSpacing: '0.12em' }}>SIZE ∝ ATHLETES ENROLLED</div>
      </div>

      {/* Attribution */}
      <div style={{ position: 'absolute', bottom: 12, right: 12 }} className="tick">SCHEMATIC · NOT TO SCALE</div>
    </div>
  );
}

function SportBar({ label, value, max, color = 'var(--accent)' }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr 50px', gap: 12, alignItems: 'center', marginBottom: 8 }}>
      <span style={{ fontSize: 12, color: 'var(--fg-1)' }}>{label}</span>
      <div className="bar"><div className="bar-fill" style={{ width: `${(value / max) * 100}%`, background: color }} /></div>
      <span className="mono" style={{ fontSize: 11, color: 'var(--fg-1)', textAlign: 'right' }}>{value.toLocaleString()}</span>
    </div>
  );
}

function CommandScreen() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Sports Authority of India · National view</div>
          <div className="page-title">National Command Dashboard</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <span className="chip cyan">FY 2026–27 · Q2</span>
          <span className="chip saffron">SAI · CLASSIFIED</span>
          <button className="btn primary">↗ Ministry Report</button>
        </div>
      </div>

      {/* Top KPI row */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Athletes Enrolled · Nationwide</div>
          <div className="kpi-value">18,<span style={{ color: 'var(--fg-3)' }}>240</span></div>
          <div className="kpi-delta up">▲ +1,240 QoQ</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Assessments · YTD</div>
          <div className="kpi-value">64,<span style={{ color: 'var(--fg-3)' }}>820</span></div>
          <div className="kpi-delta up">▲ 92% completion</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Centres Online</div>
          <div className="kpi-value">24<span className="kpi-unit">/ 26</span></div>
          <div className="kpi-delta" style={{ color: 'var(--fg-2)' }}>2 in commissioning</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">High-Potential Athletes</div>
          <div className="kpi-value" style={{ color: 'var(--accent)' }}>247</div>
          <div className="kpi-delta" style={{ color: 'var(--accent)' }}>Top 1.4% · AI-flagged</div>
        </div>
      </div>

      {/* Row 1: Map + right column stack */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Centre Performance · India</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <span className="chip filled">ATTENTION</span>
              <span className="chip">ENROLLMENT</span>
              <span className="chip">CAL. HEALTH</span>
            </div>
          </div>
          <div className="panel-body">
            <IndiaMap />
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* High-potential alerts */}
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">High-Potential Athlete Alerts</div>
              <span className="chip"><span className="pulse-dot" style={{ background: 'var(--accent)' }} />12 NEW</span>
            </div>
            <div className="panel-body" style={{ padding: 0 }}>
              {[
                { n: 'A. Prakash',   sp: 'Cricket',   c: 'BLR', pctl: 97, delta: '+8' },
                { n: 'V. Kumar',     sp: 'Shooting',  c: 'PUN', pctl: 96, delta: '+6' },
                { n: 'R. Deshmukh',  sp: 'Kabaddi',   c: 'GAN', pctl: 95, delta: '+9' },
                { n: 'S. Mehta',     sp: 'Archery',   c: 'PAT', pctl: 94, delta: '+5' },
                { n: 'K. Bora',      sp: 'Boxing',    c: 'GUW', pctl: 93, delta: '+7' },
              ].map((a, i) => (
                <div key={i} style={{ padding: '12px 18px', borderBottom: '1px solid var(--line)', display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 10, alignItems: 'center' }}>
                  <div className="avatar" style={{ width: 32, height: 32, fontSize: 11 }}>{a.n.split(' ').map(w => w[0]).join('')}</div>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 500 }}>{a.n}</div>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>{a.sp} · {a.c}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="mono" style={{ fontSize: 15, color: 'var(--accent)' }}>{a.pctl}<span style={{ fontSize: 10, color: 'var(--fg-3)' }}>%ile</span></div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--accent)' }}>▲ {a.delta}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Data quality */}
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Platform Health</div>
              <span className="chip green">◆ ALL SYSTEMS</span>
            </div>
            <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div>
                <div className="tick">Calibration Pass</div>
                <div className="num-md mono" style={{ color: 'var(--accent)' }}>93.4<span style={{ fontSize: 12, color: 'var(--fg-3)' }}>%</span></div>
              </div>
              <div>
                <div className="tick">Data Quality</div>
                <div className="num-md mono" style={{ color: 'var(--accent)' }}>96.8<span style={{ fontSize: 12, color: 'var(--fg-3)' }}>%</span></div>
              </div>
              <div>
                <div className="tick">Devices Online</div>
                <div className="num-md mono">218<span style={{ fontSize: 12, color: 'var(--fg-3)' }}>/240</span></div>
              </div>
              <div>
                <div className="tick">Storage · Encrypted</div>
                <div className="num-md mono">4.2<span style={{ fontSize: 12, color: 'var(--fg-3)' }}>TB</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Row 2: Sport distribution + centre table */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 16 }}>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Sport-wise Distribution</div>
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>13 SPORTS · 18,240 ATHLETES</span>
          </div>
          <div className="panel-body">
            {[
              { s: 'Cricket',      v: 4820, c: 'var(--accent)' },
              { s: 'Hockey',       v: 2140, c: 'var(--accent)' },
              { s: 'Football',     v: 1980, c: 'var(--accent)' },
              { s: 'Badminton',    v: 1620, c: 'var(--cyan)' },
              { s: 'Shooting',     v: 1240, c: 'var(--cyan)' },
              { s: 'Archery',      v: 1180, c: 'var(--cyan)' },
              { s: 'Boxing',       v: 980,  c: 'var(--cyan)' },
              { s: 'Kabaddi',      v: 890,  c: 'var(--saffron)' },
              { s: 'Tennis',       v: 780,  c: 'var(--saffron)' },
              { s: 'Wrestling',    v: 720,  c: 'var(--saffron)' },
              { s: 'Table Tennis', v: 640,  c: 'var(--saffron)' },
              { s: 'Para Sports',  v: 520,  c: 'var(--purple)' },
              { s: 'Esports',      v: 210,  c: 'var(--purple)' },
            ].map(sp => (
              <SportBar key={sp.s} label={sp.s} value={sp.v} max={5000} color={sp.c} />
            ))}
          </div>
        </div>

        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Centre Leaderboard</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <span className="chip filled">SCORE</span>
              <span className="chip">ENROLLMENT</span>
              <span className="chip">ADOPTION</span>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>Rank</th><th>Centre</th><th>Athletes</th><th>Sports</th><th>Avg Score</th><th>Δ Qtr</th><th>Status</th></tr>
            </thead>
            <tbody>
              {CENTRES
                .slice()
                .sort((a, b) => b.score - a.score)
                .map((c, i) => (
                  <tr key={c.id}>
                    <td className="mono" style={{ color: i < 3 ? 'var(--accent)' : 'var(--fg-2)' }}>#{String(i + 1).padStart(2, '0')}</td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <div style={{ width: 8, height: 8, borderRadius: '50%', background: c.alert ? 'var(--red)' : c.highlight ? 'var(--accent)' : 'var(--cyan)' }} />
                        <span style={{ fontWeight: 500 }}>{c.name}</span>
                      </div>
                    </td>
                    <td className="num">{c.athletes.toLocaleString()}</td>
                    <td className="num">{c.sports}</td>
                    <td className="num" style={{ fontSize: 15, color: c.score >= 78 ? 'var(--accent)' : 'var(--fg-0)' }}>{c.score}</td>
                    <td className="num" style={{ color: c.trend > 0 ? 'var(--accent)' : c.trend < 0 ? 'var(--red)' : 'var(--fg-2)' }}>
                      {c.trend > 0 ? '▲' : c.trend < 0 ? '▼' : '—'} {Math.abs(c.trend)}
                    </td>
                    <td>
                      {c.alert ? <span className="chip red">ATTENTION</span> :
                       c.highlight ? <span className="chip accent">FLAGSHIP</span> :
                       <span className="chip">ACTIVE</span>}
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.command = CommandScreen;


// ---------- screens/lab.jsx ----------
// Test Designer — author sport stimuli, AOIs, scoring rules, normative bands

const LAB_AOIS = [
  { id: 'aoi-release', l: 'RELEASE POINT', x: 62, y: 20, w: 16, h: 20, weight: 1.0, color: 'var(--accent)' },
  { id: 'aoi-bat',     l: 'BAT / BODY',    x: 30, y: 52, w: 22, h: 24, weight: 0.6, color: 'var(--cyan)' },
  { id: 'aoi-pitch',   l: 'PITCH LENGTH',  x: 48, y: 66, w: 26, h: 16, weight: 0.4, color: 'var(--saffron)' },
];

const SCORING_RULES = [
  { m: 'Quiet-Eye Onset',   op: '≥', v: '1.0 s',  pts: 30 },
  { m: 'First Fixation AOI', op: '=', v: 'RELEASE', pts: 25 },
  { m: 'Response Accuracy', op: '≥', v: '80 %',   pts: 25 },
  { m: 'Blink in Window',   op: '=', v: 'FALSE',   pts: 20 },
];

const NORM_BANDS = [
  { l: 'Elite',   lo: 88, hi: 100, c: 'var(--accent)' },
  { l: 'High',    lo: 76, hi: 88,  c: 'var(--cyan)' },
  { l: 'Developing', lo: 60, hi: 76, c: 'var(--saffron)' },
  { l: 'Baseline', lo: 0, hi: 60,  c: 'var(--red)' },
];

function LabScene({ selected, onSelect }) {
  return (
    <div style={{ position: 'relative', aspectRatio: '16/9', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 2, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'repeating-linear-gradient(135deg, var(--bg-2) 0 20px, var(--bg-1) 20px 21px)' }} />
      {/* cricket scene hint */}
      <svg viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.5 }}>
        <rect x="70" y="18" width="20" height="58" fill="var(--bg-3)" opacity="0.5" />
        <circle cx="80" cy="28" r="1.5" fill="var(--fg-2)" />
        <path d="M 80 28 Q 78 46 64 64" stroke="var(--accent)" strokeWidth="0.4" fill="none" strokeDasharray="1 1" opacity="0.5" />
        <circle cx="64" cy="64" r="2" fill="var(--fg-1)" />
      </svg>

      {/* AOI editor rectangles */}
      {LAB_AOIS.map(a => {
        const sel = a.id === selected;
        return (
          <div key={a.id} onClick={() => onSelect(a.id)} style={{
            position: 'absolute', left: `${a.x}%`, top: `${a.y}%`, width: `${a.w}%`, height: `${a.h}%`,
            border: `${sel ? 2 : 1}px dashed ${a.color}`,
            background: sel ? 'oklch(0.92 0.19 115 / 0.06)' : 'transparent',
            cursor: 'pointer',
          }}>
            <div style={{ position: 'absolute', top: -8, left: 0, background: a.color, color: '#0a0b0d', fontFamily: 'var(--font-mono)', fontSize: 8, padding: '2px 4px', fontWeight: 700, letterSpacing: '0.1em' }}>{a.l}</div>
            {/* resize handles when selected */}
            {sel && ['nw','ne','sw','se'].map(h => (
              <div key={h} style={{
                position: 'absolute', width: 6, height: 6, background: a.color, borderRadius: 1,
                top: h[0] === 'n' ? -3 : undefined, bottom: h[0] === 's' ? -3 : undefined,
                left: h[1] === 'w' ? -3 : undefined, right: h[1] === 'e' ? -3 : undefined,
              }} />
            ))}
          </div>
        );
      })}

      <div style={{ position: 'absolute', top: 12, left: 12 }} className="tick-strong">STIMULUS CANVAS · CRICKET · 1920×1080</div>
      <div style={{ position: 'absolute', bottom: 12, left: 12 }} className="tick">CLICK AN AOI TO EDIT · DRAG HANDLES TO RESIZE</div>
    </div>
  );
}

function LabScreen({ onNav }) {
  const [selected, setSelected] = useState('aoi-release');
  const aoi = LAB_AOIS.find(a => a.id === selected) || LAB_AOIS[0];

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Protocol authoring · draft v0.3</div>
          <div className="page-title">Test Designer</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">◷ Preview</button>
          <button className="btn">Save Draft</button>
          <button className="btn primary">▲ Publish Protocol</button>
        </div>
      </div>

      {/* meta bar */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, alignItems: 'center' }}>
        <span className="chip filled">CRICKET</span>
        <span className="chip">ANTICIPATION</span>
        <span className="chip">U-19</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', marginLeft: 12 }}>Bowler Release · Anticipation Test · 12 trials · 8.0 s window</span>
        <span className="chip cyan" style={{ marginLeft: 'auto' }}>3 AOIs · 4 RULES</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 16 }}>
        {/* Canvas + rules */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <LabScene selected={selected} onSelect={setSelected} />

          {/* stimulus timeline */}
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Stimulus Timeline · per trial</div>
              <span className="chip">8.0 s</span>
            </div>
            <div className="panel-body">
              <div style={{ position: 'relative', height: 30, background: 'var(--bg-3)', borderRadius: 1 }}>
                {[
                  { at: 5, w: 8, l: 'FIXATION CROSS', c: 'var(--fg-3)' },
                  { at: 18, w: 30, l: 'RUN-UP', c: 'var(--cyan)' },
                  { at: 48, w: 4, l: 'RELEASE', c: 'var(--accent)' },
                  { at: 60, w: 20, l: 'FLIGHT', c: 'var(--saffron)' },
                  { at: 82, w: 12, l: 'RESPONSE', c: 'var(--green)' },
                ].map((b, i) => (
                  <div key={i} style={{ position: 'absolute', left: `${b.at}%`, width: `${b.w}%`, top: 3, bottom: 3, background: b.c, opacity: 0.7, borderRadius: 1, display: 'grid', placeItems: 'center' }}>
                    <span className="mono" style={{ fontSize: 8, color: '#0a0b0d', fontWeight: 700, whiteSpace: 'nowrap' }}>{b.w > 8 ? b.l : ''}</span>
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
                {[0,2,4,6,8].map(t => <span key={t} className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{t.toFixed(1)}s</span>)}
              </div>
            </div>
          </div>

          {/* scoring rules */}
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Scoring Rules · 100 pts</div>
              <button className="btn" style={{ padding: '4px 10px', fontSize: 10 }}>+ Rule</button>
            </div>
            <table className="tbl">
              <thead><tr><th>Metric</th><th>Condition</th><th>Target</th><th>Points</th><th></th></tr></thead>
              <tbody>
                {SCORING_RULES.map((r, i) => (
                  <tr key={i}>
                    <td style={{ fontWeight: 500, color: 'var(--fg-0)' }}>{r.m}</td>
                    <td className="mono" style={{ color: 'var(--cyan)' }}>{r.op}</td>
                    <td className="num">{r.v}</td>
                    <td className="num" style={{ color: 'var(--accent)' }}>{r.pts}</td>
                    <td><span className="mono" style={{ color: 'var(--fg-3)', cursor: 'pointer' }}>✎</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Inspector column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">AOI Inspector</div>
              <span className="chip accent">{aoi.l}</span>
            </div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {[
                ['Label', aoi.l],
                ['ID', aoi.id],
                ['Shape', 'Rectangle'],
                ['Position', `${aoi.x}% , ${aoi.y}%`],
                ['Size', `${aoi.w}% × ${aoi.h}%`],
              ].map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span className="tick">{k}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-0)' }}>{v}</span>
                </div>
              ))}
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span className="tick">Scoring Weight</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{aoi.weight.toFixed(1)}</span>
                </div>
                <div className="bar"><div className="bar-fill" style={{ width: `${aoi.weight * 100}%` }} /></div>
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                {LAB_AOIS.map(a => (
                  <button key={a.id} className={`chip ${a.id === selected ? 'filled' : ''}`} style={{ cursor: 'pointer', fontSize: 8 }} onClick={() => setSelected(a.id)}>{a.l.split(' ')[0]}</button>
                ))}
              </div>
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Normative Bands</div>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>U-19 · NATIONAL</span>
            </div>
            <div className="panel-body">
              {/* stacked band bar */}
              <div style={{ display: 'flex', height: 14, borderRadius: 1, overflow: 'hidden', marginBottom: 12 }}>
                {NORM_BANDS.slice().reverse().map(b => (
                  <div key={b.l} title={`${b.l} ${b.lo}-${b.hi}`} style={{ width: `${b.hi - b.lo}%`, background: b.c, opacity: 0.85 }} />
                ))}
              </div>
              {NORM_BANDS.map(b => (
                <div key={b.l} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 10, alignItems: 'center', padding: '6px 0' }}>
                  <span style={{ width: 8, height: 8, background: b.c, borderRadius: 1 }} />
                  <span style={{ fontSize: 12, color: 'var(--fg-1)' }}>{b.l}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-2)' }}>{b.lo}–{b.hi}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header"><div className="panel-title">Component Palette</div></div>
            <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
              {['✚ AOI Rect', '◯ AOI Circle', '◆ Stimulus', '↕ Distractor', '⏱ Timer', '⌨ Response'].map(c => (
                <button key={c} className="btn" style={{ justifyContent: 'center', fontSize: 10 }}>{c}</button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.lab = LabScreen;


// ---------- screens/reports.jsx ----------
// Reports & Export — build and export athlete/coach/tournament/medical reports

const REPORT_TYPES = [
  { id: 'athlete',    t: 'Athlete Report',    d: 'Individual vision + cognitive profile', icon: '◉' },
  { id: 'coach',      t: 'Coach Report',      d: 'Squad trends + drill compliance',      icon: '◈' },
  { id: 'tournament', t: 'Tournament Report', d: 'Event-wide readiness + rankings',       icon: '★' },
  { id: 'medical',    t: 'Medical Report',    d: 'RTP status + oculomotor battery',       icon: '✚' },
  { id: 'vision',     t: 'Vision Report',     d: 'Sports-vision assessment summary',      icon: '◎' },
];

const RECENT = [
  { t: 'M. Krishnan · Vision Report', by: 'Dr. Menon', when: '2h ago', fmt: 'PDF' },
  { t: 'Bengaluru Squad · Weekly',    by: 'K. Iyengar', when: '1d ago', fmt: 'PDF' },
  { t: 'Khelo India · Talent Shortlist', by: 'SAI HQ', when: '2d ago', fmt: 'XLSX' },
  { t: 'A. Prakash · RTP Clearance',  by: 'Dr. Sinha', when: '3d ago', fmt: 'PDF' },
  { t: 'Q2 Ministry Dashboard',       by: 'SAI HQ', when: '5d ago', fmt: 'DASH' },
];

function MiniRadar() {
  const vals = [78, 82, 74, 65, 88, 71, 80, 76];
  const cx = 42, cy = 42, R = 34, N = vals.length;
  const pt = (i, r) => { const a = (i / N) * Math.PI * 2 - Math.PI / 2; return [cx + Math.cos(a) * r, cy + Math.sin(a) * r]; };
  const poly = vals.map((v, i) => pt(i, (v / 100) * R).join(',')).join(' ');
  return (
    <svg viewBox="0 0 84 84" style={{ width: '100%', height: 120 }}>
      {[0.5, 1].map(f => <polygon key={f} points={Array.from({ length: N }, (_, i) => pt(i, R * f).join(',')).join(' ')} fill="none" stroke="var(--line)" strokeWidth="0.6" />)}
      <polygon points={poly} fill="oklch(0.92 0.19 115 / 0.25)" stroke="var(--accent)" strokeWidth="1" />
    </svg>
  );
}

function ReportPreview({ type }) {
  const rt = REPORT_TYPES.find(r => r.id === type) || REPORT_TYPES[0];
  return (
    <div style={{ background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 2, padding: 28, minHeight: 560 }}>
      {/* doc header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', paddingBottom: 16, borderBottom: '2px solid var(--accent)' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <div className="brand-mark" style={{ width: 34, height: 34 }} />
          <div>
            <div style={{ fontSize: 18, fontWeight: 700 }}>NayanTrack <span style={{ fontSize: 11, color: 'var(--fg-2)' }}>नयन</span></div>
            <div className="mono" style={{ fontSize: 9, color: 'var(--fg-2)', letterSpacing: '0.16em', textTransform: 'uppercase' }}>Sports Authority of India · {rt.t}</div>
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)' }}>REF · NT-RPT-2026-0472</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>15 JUL 2026 · CONFIDENTIAL</div>
        </div>
      </div>

      {/* subject */}
      <div style={{ display: 'flex', gap: 16, alignItems: 'center', padding: '18px 0', borderBottom: '1px solid var(--line)' }}>
        <div className="avatar xl">MK</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 24, fontWeight: 500 }}>Meera Krishnan</div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', marginTop: 4, textTransform: 'uppercase', letterSpacing: '0.12em' }}>SAI-PUN-0472 · Archery · 21 F · Pune NCoE</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="tick">Composite</div>
          <div style={{ fontSize: 44, fontWeight: 500, color: 'var(--accent)', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>84</div>
        </div>
      </div>

      {/* body grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, paddingTop: 18 }}>
        <div>
          <div className="section-title">Composite Indicators</div>
          <MiniRadar />
        </div>
        <div>
          <div className="section-title">Key Metrics</div>
          {[['Quiet Eye', '1.24 s', 'up'], ['Reaction Time', '248 ms', 'up'], ['Aim Deviation', '0.42°', 'up'], ['Cognitive Load', 'Low', 'flat'], ['Percentile', '92nd', 'up']].map(([k, v, d]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', borderBottom: '1px solid var(--line)' }}>
              <span style={{ fontSize: 12, color: 'var(--fg-1)' }}>{k}</span>
              <span className="mono" style={{ fontSize: 12, color: d === 'up' ? 'var(--accent)' : 'var(--fg-0)' }}>{d === 'up' ? '▲ ' : ''}{v}</span>
            </div>
          ))}
        </div>
      </div>

      {/* AI summary */}
      <div style={{ marginTop: 20, padding: 16, background: 'var(--bg-2)', borderLeft: '3px solid var(--accent)', borderRadius: 2 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--accent)', letterSpacing: '0.14em', marginBottom: 8 }}>◆ AI SUMMARY · COACH-REVIEWED</div>
        <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.55 }}>
          Exceptional aim-point stability (0.42°, 18% tighter than elite median) with an earlier quiet-eye onset than baseline. Watch: first-fixation latency and pre-release blink suppression. Recommended: blink-timing and target-acquisition drills.
        </div>
      </div>

      <div className="mono" style={{ fontSize: 9, color: 'var(--fg-3)', letterSpacing: '0.12em', marginTop: 20, paddingTop: 12, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between' }}>
        <span>NayanTrack · Not for autonomous diagnosis · SAI Confidential</span>
        <span>Page 1 / 6</span>
      </div>
    </div>
  );
}

function ReportsScreen() {
  const [type, setType] = useState('vision');
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">━━ Reporting · export centre</div>
          <div className="page-title">Reports &amp; Export</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn">⤓ Export XLSX</button>
          <button className="btn">◱ Open Dashboard</button>
          <button className="btn primary">⤓ Export PDF</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr 300px', gap: 16 }}>
        {/* Report types */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Report Type</div></div>
            <div className="panel-body" style={{ padding: 0 }}>
              {REPORT_TYPES.map(r => (
                <button key={r.id} onClick={() => setType(r.id)} style={{
                  width: '100%', textAlign: 'left', display: 'flex', gap: 12, alignItems: 'flex-start',
                  padding: '14px 16px', borderBottom: '1px solid var(--line)',
                  background: r.id === type ? 'var(--bg-2)' : 'transparent',
                  borderLeft: r.id === type ? '2px solid var(--accent)' : '2px solid transparent',
                }}>
                  <span style={{ fontSize: 16, color: r.id === type ? 'var(--accent)' : 'var(--fg-2)' }}>{r.icon}</span>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-0)' }}>{r.t}</div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--fg-3)', marginTop: 3, lineHeight: 1.4 }}>{r.d}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header"><div className="panel-title">Sections</div></div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[['Cover + subject', true], ['Composite indicators', true], ['Key metrics', true], ['Heatmap + gaze', true], ['Benchmark vs elite', true], ['AI summary', true], ['Raw data appendix', false]].map(([l, on]) => (
                <div key={l} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: 12, color: on ? 'var(--fg-1)' : 'var(--fg-3)' }}>{l}</span>
                  <span style={{ width: 30, height: 16, borderRadius: 8, background: on ? 'var(--accent)' : 'var(--bg-3)', position: 'relative', border: '1px solid var(--line-strong)' }}>
                    <span style={{ position: 'absolute', top: 1, left: on ? 15 : 1, width: 12, height: 12, borderRadius: '50%', background: on ? '#0a0b0d' : 'var(--fg-3)', transition: 'all 0.12s' }} />
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Preview */}
        <ReportPreview type={type} />

        {/* Right: export + recent + scheduled */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Export Format</div></div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                { l: 'PDF Document', d: 'Print-ready · 6 pages', icon: '⤓', primary: true },
                { l: 'Excel Workbook', d: 'Raw metrics + pivots', icon: '⊞' },
                { l: 'Interactive Dashboard', d: 'Shareable web link', icon: '◱' },
              ].map(f => (
                <button key={f.l} className={`btn ${f.primary ? 'primary' : ''}`} style={{ justifyContent: 'flex-start', padding: '12px 14px' }}>
                  <span style={{ fontSize: 14 }}>{f.icon}</span>
                  <div style={{ textAlign: 'left' }}>
                    <div style={{ fontSize: 12 }}>{f.l}</div>
                    <div style={{ fontSize: 9, opacity: 0.7, textTransform: 'none', letterSpacing: 0 }}>{f.d}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          <div className="panel">
            <div className="panel-header">
              <div className="panel-title">Recent Reports</div>
              <span className="chip">32 THIS MONTH</span>
            </div>
            <div className="panel-body" style={{ padding: 0 }}>
              {RECENT.map((r, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 8, padding: '11px 16px', borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 500 }}>{r.t}</div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--fg-3)', marginTop: 2 }}>{r.by} · {r.when}</div>
                  </div>
                  <span className="chip" style={{ fontSize: 8 }}>{r.fmt}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="panel" style={{ borderLeft: '3px solid var(--cyan)' }}>
            <div className="panel-header"><div className="panel-title" style={{ color: 'var(--cyan)' }}>◷ Scheduled</div></div>
            <div className="panel-body">
              <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.5 }}>
                <strong>Weekly squad report</strong> auto-generates every Monday 07:00 IST and emails Coach Iyengar + Centre Admin.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (!window.NT_SCREENS) window.NT_SCREENS = {};
window.NT_SCREENS.reports = ReportsScreen;
