const fmt = t => '0:' + String(t).padStart(2, '0');

function DrillTabs({ active, onSelect }) {
  const { Segmented } = window.GG;
  const { DRILLS, DRILL_ORDER } = window.GGData;
  return <Segmented options={DRILL_ORDER.map(id => ({ value: id, label: DRILLS[id].title, color: DRILLS[id].color }))} value={active} onChange={onSelect} />;
}

function DrillDemo({ drillId, onBack, onPlay }) {
  const { DRILLS } = window.GGData;
  const d = DRILLS[drillId];
  return <PracticeDemo key={drillId} Frame={PlainFrame} title={d.title} color={d.color} rule={d.shortRule} no={d.nonTargetBtnLabel} yes={d.targetBtnLabel}
    trials={d.demo.map(x => ({ cue: x.num, spoken: String(x.num), isTrue: x.isTarget, explain: x.explanation }))} onBack={onBack} onPlay={onPlay} />;
}

const SURFACES = ['in_app', 'ios', 'android'];
function Session({ drillId, voice, onEnd, onFinish, fromDemo }) {
  const { DRILLS, isTarget, speak, tone } = window.GGData;
  const d = DRILLS[drillId];
  const [surface, setSurface] = React.useState('in_app');
  const T = useTrials({ countdown: !fromDemo, count: d.stimuli.length, baseMs: 2200, isTarget: i => isTarget(d.id, d.stimuli, i), onCue: i => speak(d.stimuli[i], voice),
    labels: { yes: d.targetBtnLabel, no: d.nonTargetBtnLabel }, onDone: r => onFinish({ hits: r.correct, total: r.total, best: r.best }) });
  const cur = d.stimuli[T.i];
  const lockBtn = <button type="button" aria-label="Preview lock-screen controls" onClick={() => { tone(500); setSurface(x => SURFACES[(SURFACES.indexOf(x) + 1) % 3]); }} style={{ width: 56, height: 56, borderRadius: '50%', border: '2px solid var(--gg-line-strong)', background: surface === 'in_app' ? 'var(--gg-fill-glass)' : 'color-mix(in srgb, var(--gg-cyan) 18%, transparent)', color: surface === 'in_app' ? '#fff' : 'var(--gg-cyan)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}><span className="material-symbols-outlined" style={{ fontSize: 26 }}>{surface === 'in_app' ? 'smartphone' : 'lock'}</span></button>;
  return (
    <PlainFrame>
      <GameFrame T={T} color={d.color} title={d.title} rule={d.shortRule} onEnd={onEnd} right={lockBtn}>
        {surface === 'in_app'
          ? <TrialStage color={d.color} cue={cur} no={d.nonTargetBtnLabel} yes={d.targetBtnLabel} onAnswer={T.answer} fb={T.fb} running={T.running && !T.fb} windowMs={T.windowMs} runKey={T.i} />
          : <LockScreen android={surface === 'android'} d={d} cur={cur} t={(T.i + 1) + '/' + d.stimuli.length} fb={T.fb} answer={T.answer} />}
      </GameFrame>
    </PlainFrame>
  );
}

function LockScreen({ android, d, cur, t, fb, answer }) {
  const { Icon } = window.GG;
  const btn = target => ({ height: 64, borderRadius: android ? 16 : 20, border: target ? 0 : '1px solid rgba(255,255,255,0.12)', cursor: 'pointer', fontFamily: 'var(--font-ui)', fontSize: 15, fontWeight: 800,
    background: target ? d.color : 'rgba(255,255,255,0.14)', color: target ? '#050608' : '#fff', boxShadow: target ? `0 0 20px color-mix(in srgb, ${d.color} 45%, transparent)` : 'none' });
  return (
    <div style={{ flex: 1, marginTop: 14, borderRadius: 32, padding: 20, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', background: `radial-gradient(120% 70% at 50% 0%, color-mix(in srgb, ${d.color} 22%, #0b0d14), #05060a)`, border: '1px solid var(--gg-line)' }}>
      <div style={{ textAlign: 'center', paddingTop: 16 }}>
        {!android && <div style={{ fontSize: 15, fontWeight: 600, color: 'rgba(255,255,255,0.7)' }}>Monday, September 28</div>}
        <div style={{ fontSize: android ? 64 : 80, fontWeight: android ? 600 : 800, letterSpacing: '-0.03em', lineHeight: 1, marginTop: 4, color: 'rgba(255,255,255,0.95)' }}>9:41</div>
        {android && <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.7)', marginTop: 6 }}>Mon, Sep 28</div>}
      </div>
      <div style={{ borderRadius: android ? 24 : 30, padding: 16, background: 'rgba(28,30,42,0.85)', backdropFilter: 'blur(24px)', border: '1px solid rgba(255,255,255,0.12)', boxShadow: '0 20px 40px rgba(0,0,0,0.5)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, fontWeight: 800 }}><span style={{ color: d.color, display: 'flex' }}><Icon name={d.icon} size={20} /></span>{d.title}</span>
          <span style={{ fontSize: 14, fontWeight: 800, color: d.color, fontVariantNumeric: 'tabular-nums' }}>{t}</span>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <div style={{ width: 64, height: 64, flex: 'none', borderRadius: 18, background: 'rgba(255,255,255,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 34, fontWeight: 800 }}>{cur}</div>
          <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <button type="button" style={btn(false)} onClick={() => answer(false)}>{d.nonTargetBtnLabel}</button>
            <button type="button" style={btn(true)} onClick={() => answer(true)}>{d.targetBtnLabel}</button>
          </div>
        </div>
        <div style={{ height: 18, marginTop: 10, textAlign: 'center' }}>{fb && <Meta color={fb.k === 'correct' ? 'var(--gg-domain-composure)' : 'var(--gg-domain-speed)'}>{fb.t}</Meta>}</div>
      </div>
    </div>
  );
}

function Complete({ drillId, result, completed, voice, onReplay, onNext, onHome }) {
  const { PhoneShell, BackButton, ActivityRings, Button, Icon } = window.GG;
  const { DRILLS, DRILL_ORDER, nextDrill, speak, hush, fanfare, tone } = window.GGData;
  const d = DRILLS[drillId];
  const nid = nextDrill(drillId); const n = nid && DRILLS[nid];
  const acc = result.total ? Math.round((result.hits / result.total) * 100) : 100;
  const [count, setCount] = React.useState(5);
  const [paused, setPaused] = React.useState(false);
  const say = () => speak(n ? `${d.title} complete! ${acc} percent accuracy. Keep pedaling! Next up is ${n.title}, starting in 5 seconds.` : `Ride complete! You finished all 3 bike brain drills with ${acc} percent accuracy!`, true, 1.04);
  React.useEffect(() => { fanfare(); const t = setTimeout(() => voice && say(), 400); return () => { clearTimeout(t); hush(); }; }, [drillId]);
  React.useEffect(() => { if (!n || paused) return; const id = setInterval(() => setCount(c => { if (c <= 1) { clearInterval(id); setTimeout(() => onNext(nid)); return 0; } return c - 1; }), 1000); return () => clearInterval(id); }, [paused, nid]);
  const Stat = ({ label, value, sub, color = '#fff' }) => (
    <div style={{ borderRadius: 'var(--radius-card)', padding: 16, background: 'var(--surface-card)', border: '1px solid var(--gg-line)', textAlign: 'center' }}>
      <Meta>{label}</Meta>
      <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: '-0.02em', color, marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div style={{ fontSize: 12, color: 'var(--text-muted)', fontWeight: 600 }}>{sub}</div>
    </div>
  );
  return (
    <PhoneShell>
      <Screen glowColors={[d.color, '#30d158', '#ff9f0a']} footer={n ? <Button tone="ghost" icon={null} onClick={onHome}>Back to Home</Button> : <Button icon="home" onClick={onHome}>Back to Home</Button>}>
        <TopBar left={<BackButton label="Replay" onClick={onReplay} />} right={<Meta>Drill {d.order} of 3 · {completed.length}/3 done</Meta>} />
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', marginTop: 16 }}>
          <ActivityRings size={132} rings={DRILL_ORDER.map(id => ({ value: completed.includes(id) ? 1 : 0.02, color: DRILLS[id].color }))}><span style={{ color: d.color, display: 'flex' }}><Icon name="check" size={34} weight={700} /></span></ActivityRings>
          <h1 style={{ margin: '18px 0 0', fontSize: 30, fontWeight: 800, letterSpacing: '-0.025em', lineHeight: 1.08 }}>{n ? <>{d.title} <span style={{ color: d.color, textShadow: `0 0 24px color-mix(in srgb, ${d.color} 55%, transparent)` }}>complete!</span></> : <>Ride <Hi>complete!</Hi></>}</h1>
          <button type="button" onClick={() => { tone(580); say(); }} style={{ marginTop: 12, minHeight: 36, padding: '0 14px', borderRadius: 9999, border: '1px solid var(--gg-line-strong)', background: 'var(--gg-fill-glass)', color: 'var(--gg-cyan)', fontFamily: 'var(--font-ui)', fontSize: 12, fontWeight: 800, letterSpacing: '0.05em', textTransform: 'uppercase', display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}><Icon name="volume_up" size={16} />Replay audio results</button>
        </div>
        <div style={{ marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Stat label="Accuracy" value={acc + '%'} sub={result.total ? `${result.hits} / ${result.total} correct` : 'Calibrated'} />
          <Stat label="Best streak" value={result.best || 0} sub="in a row" color="var(--gg-domain-memory)" />
        </div>
        {n && <div style={{ marginTop: 20 }}><HydrationCard /></div>}
        {n ? (
          <div style={{ marginTop: 12, borderRadius: 'var(--radius-panel)', padding: 16, background: 'var(--surface-panel)', border: `1px solid color-mix(in srgb, ${n.color} 40%, transparent)`, boxShadow: `0 0 24px color-mix(in srgb, ${n.color} 20%, transparent)`, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Meta color={n.color}>{paused ? 'Paused · up next' : `Auto-starting in ${count}s`}</Meta>
              <QuietLink color="#fff" onClick={() => { tone(460); setPaused(p => !p); }}>{paused ? 'Resume' : 'Pause'}</QuietLink>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ width: 48, height: 48, borderRadius: 14, flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', color: n.color, background: `color-mix(in srgb, ${n.color} 15%, transparent)`, border: `1px solid color-mix(in srgb, ${n.color} 30%, transparent)` }}><Icon name={n.icon} size={26} /></span>
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 17, fontWeight: 800 }}>Drill {n.order}: {n.title}</div><div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>{n.domain} · {n.durationLabel}</div></div>
            </div>
            <Button icon="play_arrow" onClick={() => { tone(640); onNext(nid); }}>Start Next Drill</Button>
          </div>
        ) : (
          <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 12 }}><HydrationCard final /><div style={{ textAlign: 'center', fontSize: 15, fontWeight: 600, color: 'var(--text-muted)' }}>All 3 drills done for today.</div></div>
        )}
      </Screen>
    </PhoneShell>
  );
}
Object.assign(window, { DrillDemo, Session, Complete });
