// ============================================================
// WASIED · Course player + Quiz
// ============================================================

function AppCoursePlayer({ slug }) {
  const sample = DATA.formations.sampleCourse;
  const quiz = DATA.formations.sampleQuiz;
  const [activeModule, setActiveModule] = React.useState(sample.modules[2]);
  const [playing, setPlaying] = React.useState(false);
  const [position, setPosition] = React.useState(7 * 60 + 23); // 7:23
  const [showQuiz, setShowQuiz] = React.useState(false);
  const [quizAnswer, setQuizAnswer] = React.useState(null);
  const [quizSubmitted, setQuizSubmitted] = React.useState(false);

  // Fake playback progression
  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setPosition(p => Math.min(p + 1, 18 * 60 + 42)), 1000);
    return () => clearInterval(id);
  }, [playing]);

  const fmt = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
  const totalSeconds = 18 * 60 + 42;
  const pct = (position / totalSeconds) * 100;

  return (
    <AppShell
      title="GLua Mastery"
      breadcrumbs={[{ label: 'Formations', path: '/app/formations' }, { label: 'GLua Mastery' }]}
      sectionPadding={false}
      actions={<><Badge tone="formations">Pack Expert</Badge><Button variant="ghost" size="sm" icon="calendar">RDV 1:1</Button></>}>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', minHeight: 'calc(100vh - 56px)', borderTop: '1px solid var(--border-1)' }}>
        {/* Player column */}
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {/* Video */}
          {showQuiz ? <QuizPlayer quiz={quiz} answer={quizAnswer} setAnswer={setQuizAnswer} submitted={quizSubmitted} setSubmitted={setQuizSubmitted} onClose={() => { setShowQuiz(false); setQuizAnswer(null); setQuizSubmitted(false); }}/> : (
          <div style={{ background: '#000', position: 'relative', aspectRatio: '16/9' }}>
            {/* Mock video frame */}
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(135deg, #0F1115 0%, #232936 100%)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <div style={{ width: '70%', maxWidth: 720, padding: 32, background: 'var(--surface-1)', border: '1px solid var(--border-2)', borderRadius: 12, fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.8, color: 'var(--fg-2)' }}>
                <div style={{ color: 'var(--fg-3)', marginBottom: 12, fontSize: 11 }}>-- swep_base.lua</div>
                <div><span style={{ color: 'var(--accent)' }}>SWEP</span>.PrintName <span style={{ color: 'var(--fg-3)' }}>=</span> <span style={{ color: 'var(--cash)' }}>"Lance-grappin"</span></div>
                <div><span style={{ color: 'var(--accent)' }}>SWEP</span>.Author <span style={{ color: 'var(--fg-3)' }}>=</span> <span style={{ color: 'var(--cash)' }}>"Spacev"</span></div>
                <div><span style={{ color: 'var(--accent)' }}>SWEP</span>.Spawnable <span style={{ color: 'var(--fg-3)' }}>=</span> <span style={{ color: 'var(--xp)' }}>true</span></div>
                <div style={{ height: 10 }}/>
                <div><span style={{ color: 'var(--service-formations)' }}>function</span> <span style={{ color: 'var(--accent)' }}>SWEP</span>:<span style={{ color: 'var(--cash)' }}>PrimaryAttack</span>()</div>
                <div>{'  '}<span style={{ color: 'var(--accent)' }}>self</span>:SetNextPrimaryFire(<span style={{ color: 'var(--accent)' }}>CurTime</span>() <span style={{ color: 'var(--fg-3)' }}>+</span> <span style={{ color: 'var(--xp)' }}>0.5</span>)</div>
                <div>{'  '}<span style={{ color: 'var(--service-formations)' }}>if</span> <span style={{ color: 'var(--accent)' }}>SERVER</span> <span style={{ color: 'var(--service-formations)' }}>then</span></div>
                <div>{'    '}<span style={{ color: 'var(--accent)' }}>self</span>.<span style={{ color: 'var(--cash)' }}>Owner</span>:FireBullets({'{'}<span style={{ color: 'var(--fg-3)' }}>...</span>{'}'})</div>
                <div>{'  '}<span style={{ color: 'var(--service-formations)' }}>end</span></div>
                <div><span style={{ color: 'var(--service-formations)' }}>end</span></div>
              </div>
            </div>
            {/* Play overlay */}
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: playing ? 'none' : 'auto' }}>
            <button onClick={() => setPlaying(!playing)} style={{ width: 76, height: 76, borderRadius: '50%', background: 'rgba(0,0,0,0.5)', border: '1px solid rgba(255,255,255,0.2)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', opacity: playing ? 0 : 1, transition: 'opacity 200ms ease' }}>
              <Icon name={playing ? 'pause' : 'play'} size={28} color="#fff" style={{ fill: '#fff', marginLeft: playing ? 0 : 4 }}/>
            </button>
          </div>
            {/* Controls bar */}
            <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '24px 24px 18px', background: 'linear-gradient(to top, rgba(0,0,0,0.7), transparent)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: '#fff', minWidth: 90 }}>{fmt(position)} / 18:42</span>
                <div style={{ flex: 1, position: 'relative', height: 4, background: 'rgba(255,255,255,0.2)', borderRadius: 2, cursor: 'pointer' }}>
                  <div style={{ width: `${pct}%`, height: '100%', background: 'var(--service-formations)', borderRadius: 2 }}/>
                  <div style={{ position: 'absolute', top: -3, left: `calc(${pct}% - 5px)`, width: 10, height: 10, borderRadius: '50%', background: 'var(--service-formations)' }}/>
                </div>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: '#fff', opacity: 0.8 }}>1×</span>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: '#fff', opacity: 0.8 }}>1080p</span>
                <Icon name="volume" size={16} color="#fff"/>
              </div>
              <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                {[
                  { name: 'Intro', pct: 0 },
                  { name: 'Structure', pct: 15 },
                  { name: 'Hooks', pct: 38 },
                  { name: 'Network', pct: 65 },
                  { name: 'Conclusion', pct: 88 },
                ].map((c, i) => (
                  <span key={i} style={{ fontSize: 10, color: '#fff', opacity: pct >= c.pct ? 1 : 0.5, padding: '2px 7px', background: pct >= c.pct ? 'rgba(255,255,255,0.15)' : 'transparent', borderRadius: 999, fontFamily: 'var(--font-mono)' }}>
                    {c.name}
                  </span>
                ))}
              </div>
            </div>
          </div>
          )}

          {/* Below player */}
          <div style={{ padding: 24, flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
              <Badge tone="formations" size="md">{sample.chapter}</Badge>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>Module {activeModule.num}</span>
            </div>
            <h2 className="h-display" style={{ fontSize: 24, margin: 0, marginBottom: 18 }}>{activeModule.title}</h2>

            <div style={{ display: 'flex', gap: 18, borderBottom: '1px solid var(--border-1)', marginBottom: 24 }}>
              {['Notes', 'Ressources', 'Discussion'].map((t, i) => (
                <button key={t} style={{ padding: '12px 0', background: 'transparent', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: i === 0 ? 'var(--fg-1)' : 'var(--fg-3)', borderBottom: `2px solid ${i === 0 ? 'var(--accent)' : 'transparent'}`, marginBottom: -1 }}>{t}</button>
              ))}
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, fontSize: 14, color: 'var(--fg-2)', lineHeight: 1.75, maxWidth: 760 }}>
              <p style={{ margin: 0 }}>Dans ce module, on attaque enfin le SWEP : la base de toute arme, outil ou interaction dans Garry's Mod. On va couvrir les trois points essentiels.</p>
              <h3 style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)', margin: '14px 0 4px' }}>1. La structure obligatoire</h3>
              <p style={{ margin: 0 }}>Tout SWEP commence par déclarer un tableau global <code style={{ background: 'var(--surface-2)', padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>SWEP</code>. Les champs minimaux sont <code style={{ background: 'var(--surface-2)', padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>PrintName</code>, <code style={{ background: 'var(--surface-2)', padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>Spawnable</code> et au moins un hook d'action.</p>
              <h3 style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)', margin: '14px 0 4px' }}>2. Les hooks essentiels</h3>
              <p style={{ margin: 0 }}><strong style={{ color: 'var(--fg-1)' }}>PrimaryAttack</strong> est appelé côté serveur dès que le joueur clique. C'est là qu'on consomme une munition, on joue un son, on tire un bullet. <strong style={{ color: 'var(--fg-1)' }}>Think</strong> tourne en continu - à éviter pour du code lourd.</p>
              <h3 style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)', margin: '14px 0 4px' }}>3. Synchroniser client / serveur</h3>
              <p style={{ margin: 0 }}>Le piège classique : exécuter du code visuel côté serveur (rendu, son local) ou des changements de state côté client (fait crash). Toujours wrapper avec <code style={{ background: 'var(--surface-2)', padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>if SERVER then</code> ou <code style={{ background: 'var(--surface-2)', padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>if CLIENT then</code>.</p>
            </div>

            <div style={{ marginTop: 32, display: 'flex', gap: 10 }}>
              <Button variant="ghost" icon="arrowLeft" disabled>Module précédent</Button>
              <Button variant="primary" onClick={() => setShowQuiz(true)}>Passer au quiz 04.04</Button>
            </div>
          </div>
        </div>

        {/* Sidebar - curriculum */}
        <aside style={{ borderLeft: '1px solid var(--border-1)', background: 'var(--surface-0)', position: 'sticky', top: 56, height: 'calc(100vh - 56px)', overflowY: 'auto' }}>
          <div style={{ padding: '18px 20px', borderBottom: '1px solid var(--border-1)' }}>
            <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, marginBottom: 8 }}>PROGRESSION GLOBALE</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ flex: 1, height: 6, background: 'var(--surface-3)', borderRadius: 3, overflow: 'hidden' }}>
                <div style={{ width: '42%', height: '100%', background: 'var(--service-formations)' }}/>
              </div>
              <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--service-formations)', fontVariantNumeric: 'tabular-nums' }}>42 %</span>
            </div>
          </div>

          <div style={{ padding: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 10px' }}>
              <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-1)' }}>Chapitre 04 · Entités et SWEPs</span>
              <Icon name="chevronUp" size={12} color="var(--fg-3)"/>
            </div>
            {sample.modules.map(m => (
              <button key={m.num} onClick={() => setActiveModule(m)} style={{
                display: 'flex', width: '100%', alignItems: 'flex-start', gap: 10,
                padding: '10px 10px', background: m === activeModule ? 'var(--accent-soft)' : 'transparent',
                border: 'none', borderRadius: 7, cursor: 'pointer', textAlign: 'left',
                color: m === activeModule ? 'var(--fg-1)' : 'var(--fg-2)',
              }}>
                <div style={{ width: 24, height: 24, borderRadius: 6, background: m.done ? 'var(--cash)' : m === activeModule ? 'var(--accent)' : 'var(--surface-2)', color: m.done ? 'var(--fg-inv)' : m === activeModule ? 'var(--fg-inv)' : 'var(--fg-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 10 }}>
                  {m.done ? <Icon name="check" size={11}/> : m.kind === 'quiz' ? <Icon name="helpCircle" size={11}/> : m.kind === 'practice' ? <Icon name="code" size={11}/> : <Icon name="play" size={11}/>}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--fg-3)' }}>{m.num}</div>
                  <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.4 }}>{m.title}</div>
                  <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{m.duration} · {m.kind === 'quiz' ? 'Quiz' : m.kind === 'practice' ? 'TP' : 'Vidéo'}</div>
                </div>
              </button>
            ))}
          </div>

          <div style={{ padding: 12 }}>
            <div style={{ padding: '8px 10px', fontSize: 12, fontWeight: 600, color: 'var(--fg-3)' }}>Chapitre 05 · UI et VGUI</div>
            <div style={{ padding: '8px 10px', fontSize: 12, fontWeight: 600, color: 'var(--fg-3)' }}>Chapitre 06 · Persistance SQL <Icon name="lock" size={10} style={{ marginLeft: 4 }}/></div>
            <div style={{ padding: '8px 10px', fontSize: 12, fontWeight: 600, color: 'var(--fg-3)' }}>Chapitre 07 · Architecture <Icon name="lock" size={10} style={{ marginLeft: 4 }}/></div>
          </div>

          <div style={{ padding: 16, margin: 12, background: 'rgba(196,181,253,0.06)', border: '1px solid rgba(196,181,253,0.16)', borderRadius: 10 }}>
            <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-1)', marginBottom: 6 }}>Demande de certificat</div>
            <div style={{ fontSize: 11, color: 'var(--fg-3)', marginBottom: 10, lineHeight: 1.5 }}>À 100 % de progression, demandez votre certificat officiel signé par Wasied.</div>
            <Button variant="ghost" size="sm" fullWidth icon="award" disabled>Disponible à 100 %</Button>
          </div>
        </aside>
      </div>

      <style>{`
        @media (max-width: 1100px) { aside { display: none; } }
      `}</style>
    </AppShell>
  );
}

// ---------- Quiz player ----------
function QuizPlayer({ quiz, answer, setAnswer, submitted, setSubmitted, onClose }) {
  const correct = answer === quiz.correct;
  return (
    <div style={{ background: 'linear-gradient(135deg, var(--surface-1) 0%, rgba(196,181,253,0.04) 100%)', padding: '56px 48px', position: 'relative', minHeight: 480 }}>
      <button onClick={onClose} style={{ position: 'absolute', top: 18, right: 18, background: 'transparent', border: 'none', color: 'var(--fg-3)', cursor: 'pointer', padding: 8 }}>
        <Icon name="close" size={16}/>
      </button>
      <div style={{ maxWidth: 760, margin: '0 auto' }}>
        <Badge tone="formations">Quiz 04.04 · hooks et networking</Badge>
        <h2 className="h-display" style={{ fontSize: 28, margin: '14px 0 28px', lineHeight: 1.3 }}>{quiz.q}</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {quiz.options.map(o => {
            const selected = answer === o.id;
            const isCorrect = o.id === quiz.correct;
            const showState = submitted && (selected || isCorrect);
            return (
              <button key={o.id} onClick={() => !submitted && setAnswer(o.id)} disabled={submitted} style={{
                display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px',
                background: showState ? (isCorrect ? 'rgba(110,231,167,0.08)' : selected ? 'rgba(251,113,133,0.08)' : 'var(--surface-2)') : (selected ? 'var(--accent-soft)' : 'var(--surface-2)'),
                border: `1px solid ${showState ? (isCorrect ? 'rgba(110,231,167,0.3)' : selected ? 'rgba(251,113,133,0.3)' : 'var(--border-1)') : selected ? 'var(--accent)' : 'var(--border-1)'}`,
                borderRadius: 10, cursor: submitted ? 'default' : 'pointer', textAlign: 'left',
                transition: 'all 120ms ease',
              }}>
                <div style={{ width: 28, height: 28, borderRadius: 6, background: showState ? (isCorrect ? 'var(--cash)' : selected ? 'var(--hp)' : 'var(--surface-3)') : selected ? 'var(--accent)' : 'var(--surface-3)', color: 'var(--fg-inv)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600, flexShrink: 0 }}>
                  {showState ? (isCorrect ? <Icon name="check" size={14}/> : selected ? <Icon name="x" size={14}/> : o.id.toUpperCase()) : o.id.toUpperCase()}
                </div>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--fg-1)' }}>{o.label}</span>
              </button>
            );
          })}
        </div>
        {submitted ? (
          <div style={{ marginTop: 28, padding: 20, background: correct ? 'rgba(110,231,167,0.06)' : 'rgba(251,113,133,0.06)', border: `1px solid ${correct ? 'rgba(110,231,167,0.16)' : 'rgba(251,113,133,0.16)'}`, borderRadius: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <Icon name={correct ? 'checkCircle' : 'alert'} size={20} color={correct ? 'var(--cash)' : 'var(--hp)'}/>
              <span style={{ fontSize: 14, fontWeight: 600, color: correct ? 'var(--cash)' : 'var(--hp)' }}>{correct ? 'Bonne réponse' : 'Réponse incorrecte'}</span>
            </div>
            <p style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.65, margin: 0 }}>{quiz.explanation}</p>
            <div style={{ marginTop: 14, display: 'flex', gap: 8 }}>
              <Button variant="primary" onClick={onClose}>Module suivant</Button>
              {!correct && <Button variant="ghost" onClick={() => { setAnswer(null); setSubmitted(false); }}>Réessayer</Button>}
            </div>
          </div>
        ) : (
          <div style={{ marginTop: 24 }}>
            <Button variant="primary" disabled={!answer} onClick={() => setSubmitted(true)}>Valider ma réponse</Button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AppCoursePlayer, QuizPlayer });
