// Quiz feature — timed competition event; top score when timer expires wins

const QUIZZES = [
  {
    id: 'q1', status: 'live',
    title: 'Quiz do Dia',
    subtitle: 'Quem tiver mais pontos quando o tempo acabar, ganha',
    badge: 'AO VIVO',
    scheduledAt: 'Encerra em 00:47',
    prize: 'Mentoria 1:1 com ex-aluno',
    participants: 312,
    sessionSeconds: 90,
    questions: [
      {
        q: 'Segundo a talk de abertura, qual é o primeiro passo antes de escolher um curso?',
        options: [
          { id: 'a', label: 'Listar as faculdades mais bem colocadas' },
          { id: 'b', label: 'Entender como você aprende melhor', correct: true },
          { id: 'c', label: 'Escolher pelo salário inicial' },
          { id: 'd', label: 'Seguir a área da família' },
        ],
      },
      {
        q: 'No workshop de portfólio, quanto tempo um curador leva em média lendo o primeiro slide?',
        options: [
          { id: 'a', label: 'Menos de 10 segundos' },
          { id: 'b', label: 'Cerca de 30 segundos' },
          { id: 'c', label: 'Cerca de 60 segundos', correct: true },
          { id: 'd', label: 'Mais de 3 minutos' },
        ],
      },
      {
        q: 'Quantos cursos a IBMEC apresenta na feira de sexta-feira?',
        options: [
          { id: 'a', label: '12' }, { id: 'b', label: '18' },
          { id: 'c', label: '24', correct: true }, { id: 'd', label: '32' },
        ],
      },
      {
        q: 'Qual linguagem foi usada no workshop de dados para iniciantes?',
        options: [
          { id: 'a', label: 'JavaScript' }, { id: 'b', label: 'Python', correct: true },
          { id: 'c', label: 'R' }, { id: 'd', label: 'SQL' },
        ],
      },
      {
        q: 'No keynote sobre empreendedorismo, quantas empresas a Luna Ferraz fundou em 4 anos?',
        options: [
          { id: 'a', label: 'Uma' }, { id: 'b', label: 'Duas' },
          { id: 'c', label: 'Três', correct: true }, { id: 'd', label: 'Cinco' },
        ],
      },
    ],
  },
  {
    id: 'q2', status: 'upcoming',
    title: 'Quiz: Você conhece a IBMEC?',
    subtitle: 'Um esquenta sobre história, cursos e cultura da casa',
    badge: 'AMANHÃ · 11:30',
    scheduledAt: 'Amanhã, 11:30',
    prize: 'Brinde oficial + acesso à área VIP',
    participants: 0, waiting: 84,
    sessionSeconds: 90,
    questions: [],
  },
  {
    id: 'q3', status: 'past', won: false,
    title: 'Quiz da Abertura',
    subtitle: 'O que você absorveu do primeiro dia',
    badge: 'ENCERRADO',
    scheduledAt: 'Ontem, 18:00',
    prize: 'Caderno Forma Tour',
    participants: 248,
    myScore: 1840, myRank: 14,
    winner: { name: 'Pedro Hanazaki', avatar: 'PH', color: '#3A56B0', score: 3420 },
  },
  {
    id: 'q4', status: 'past', won: true,
    title: 'Quiz das Profissões',
    subtitle: 'Uma rodada sobre carreiras do futuro',
    badge: 'ENCERRADO',
    scheduledAt: 'Seg, 19:00',
    prize: 'Livro "Do Sonho ao Plano"',
    participants: 180,
    myScore: 3180, myRank: 1,
    winner: null, // me
  },
];

const SESSION_PLAYERS = [
  { name: 'Pedro Hanazaki', handle: 'p.hana', avatar: 'PH', color: '#3A56B0', targetScore: 820 },
  { name: 'Júlia Arruda', handle: 'juu.arruda', avatar: 'JA', color: '#E0457B', targetScore: 640 },
  { name: 'Marina Castro', handle: 'marina.c', avatar: 'MC', color: '#F5A623', targetScore: 520 },
  { name: 'Isa Ventura', handle: 'isaventura', avatar: 'IV', color: '#6B2EA8', targetScore: 410 },
];

// ============================================================
// Quiz tab — lists live / upcoming / past quizzes
// ============================================================
const QuizListScreen = ({ onPlay }) => {
  const live = QUIZZES.filter(q => q.status === 'live');
  const upcoming = QUIZZES.filter(q => q.status === 'upcoming');
  const past = QUIZZES.filter(q => q.status === 'past');

  return (
    <div className="screen">
      <StatusBar />
      <div style={{ padding: '4px 20px 18px' }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--text-mute)', marginBottom: 6 }}>
          QUIZZES · FORMA TOUR
        </div>
        <h1 style={{ fontSize: 28, margin: 0, fontWeight: 600, letterSpacing: '-0.02em' }}>
          Jogue e ganhe prêmios
        </h1>
        <p style={{ fontSize: 13, color: 'var(--text-mute)', margin: '6px 0 0', lineHeight: 1.45 }}>
          Pulse quizzes rápidos disparados ao longo do evento. Cada sessão tem um prêmio para o topo do placar.
        </p>
      </div>

      <div style={{ padding: '0 20px 32px' }}>
        {live.length > 0 && (
          <>
            <SectionHeader label="Ao vivo" accent />
            {live.map(q => <QuizCardLive key={q.id} quiz={q} onPlay={() => onPlay(q)} />)}
          </>
        )}

        {upcoming.length > 0 && (
          <>
            <SectionHeader label="Em breve" />
            {upcoming.map(q => <QuizCardUpcoming key={q.id} quiz={q} />)}
          </>
        )}

        {past.length > 0 && (
          <>
            <SectionHeader label="Anteriores" />
            {past.map(q => <QuizCardPast key={q.id} quiz={q} />)}
          </>
        )}
      </div>
    </div>
  );
};

const SectionHeader = ({ label, accent }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '8px 0 12px' }}>
    {accent && <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--amber)' }} className="pulse-dot" />}
    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: accent ? 'var(--amber)' : 'var(--text-mute)' }}>
      {label.toUpperCase()}
    </div>
  </div>
);

const QuizCardLive = ({ quiz, onPlay }) => (
  <div style={{
    background: 'linear-gradient(135deg, rgba(245,166,35,0.12) 0%, rgba(245,166,35,0.03) 60%)',
    border: '1px solid rgba(245,166,35,0.3)',
    borderRadius: 18, padding: 18, marginBottom: 14,
    position: 'relative', overflow: 'hidden',
  }}>
    <div style={{
      position: 'absolute', top: 0, right: 0, bottom: 0, width: 160,
      background: 'radial-gradient(circle at 100% 0%, rgba(245,166,35,0.25), transparent 60%)',
      pointerEvents: 'none',
    }} />
    <div style={{ position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--amber)' }} className="pulse-dot" />
        <span className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--amber)', fontWeight: 600 }}>
          AO VIVO · {quiz.scheduledAt}
        </span>
      </div>
      <h3 style={{ fontSize: 20, margin: '0 0 4px', fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1.15 }}>
        {quiz.title}
      </h3>
      <p style={{ fontSize: 13, color: 'var(--text-dim)', margin: '0 0 14px', lineHeight: 1.4 }}>
        {quiz.subtitle}
      </p>
      <div style={{
        display: 'flex', gap: 10, padding: '10px 12px', marginBottom: 14,
        background: 'rgba(5,8,15,0.5)', border: '1px solid var(--line)', borderRadius: 12,
      }}>
        <div style={{ fontSize: 18, lineHeight: 1.1 }}>🏆</div>
        <div style={{ flex: 1 }}>
          <div className="mono" style={{ fontSize: 9, color: 'var(--text-mute)', letterSpacing: '0.15em', marginBottom: 2 }}>PRÊMIO</div>
          <div style={{ fontSize: 12, fontWeight: 500 }}>{quiz.prize}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="mono" style={{ fontSize: 9, color: 'var(--text-mute)', letterSpacing: '0.15em', marginBottom: 2 }}>JOGANDO</div>
          <div style={{ fontSize: 12, fontWeight: 600 }}>{quiz.participants}</div>
        </div>
      </div>
      <button className="btn btn-primary" onClick={onPlay} style={{ width: '100%' }}>
        Entrar agora <IconArrowRight size={16} />
      </button>
    </div>
  </div>
);

const QuizCardUpcoming = ({ quiz }) => (
  <div className="card" style={{ padding: 16, marginBottom: 12 }}>
    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.15em', color: 'var(--text-mute)', marginBottom: 8 }}>
      {quiz.scheduledAt.toUpperCase()}
    </div>
    <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em', marginBottom: 4 }}>
      {quiz.title}
    </div>
    <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 12, lineHeight: 1.4 }}>
      {quiz.subtitle}
    </div>
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, fontSize: 11, color: 'var(--text-mute)' }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>🏆 {quiz.prize}</span>
      <span className="mono" style={{ fontSize: 10 }}>{quiz.waiting} interessados</span>
    </div>
  </div>
);

const QuizCardPast = ({ quiz }) => (
  <div className="card" style={{ padding: 14, marginBottom: 10, opacity: 0.9 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12, flexShrink: 0,
        background: quiz.won ? 'rgba(245,166,35,0.14)' : 'rgba(255,255,255,0.04)',
        border: `1px solid ${quiz.won ? 'rgba(245,166,35,0.3)' : 'var(--line)'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20,
      }}>{quiz.won ? '🥇' : '🎯'}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {quiz.title}
        </div>
        <div style={{ fontSize: 11, color: 'var(--text-mute)', marginBottom: 4 }}>{quiz.scheduledAt} · {quiz.participants} jogaram</div>
        <div className="mono" style={{ fontSize: 11, fontWeight: 600, color: quiz.won ? 'var(--amber)' : 'var(--text-dim)' }}>
          {quiz.won
            ? `VOCÊ GANHOU · ${quiz.myScore.toLocaleString('pt-BR')} pts`
            : `${quiz.myRank}º · ${quiz.myScore.toLocaleString('pt-BR')} pts`}
        </div>
      </div>
    </div>
  </div>
);

// ============================================================
// Full-screen quiz player (was QuizModal)
// ============================================================
const QuizScreen = ({ quiz, onClose }) => {
  const [step, setStep] = React.useState('intro'); // intro | live | result
  const [qIndex, setQIndex] = React.useState(0);
  const [picked, setPicked] = React.useState(null);
  const [revealed, setRevealed] = React.useState(false);
  const [score, setScore] = React.useState(0);
  const [correctCount, setCorrectCount] = React.useState(0);
  const [sessionLeft, setSessionLeft] = React.useState(quiz.sessionSeconds);
  const [players, setPlayers] = React.useState(() =>
    SESSION_PLAYERS.map(p => ({ ...p, score: 0 }))
  );

  React.useEffect(() => {
    if (step !== 'live') return;
    if (sessionLeft <= 0) { setStep('result'); return; }
    const t = setTimeout(() => setSessionLeft(s => s - 1), 1000);
    return () => clearTimeout(t);
  }, [sessionLeft, step]);

  React.useEffect(() => {
    if (step !== 'live') return;
    const elapsed = quiz.sessionSeconds - sessionLeft;
    const progress = Math.min(1, elapsed / quiz.sessionSeconds);
    setPlayers(prev => prev.map((p, i) => ({
      ...p,
      score: Math.round(p.targetScore * (progress + (Math.sin((elapsed + i * 7) / 3) * 0.04))),
    })));
  }, [sessionLeft, step]);

  const pickAnswer = (optId) => {
    if (revealed) return;
    const correctOpt = quiz.questions[qIndex].options.find(o => o.correct);
    const isCorrect = optId === correctOpt.id;
    const timeBonus = Math.round((sessionLeft / quiz.sessionSeconds) * 500);
    const pts = isCorrect ? 500 + timeBonus : 0;
    setPicked(optId);
    setRevealed(true);
    if (isCorrect) { setScore(s => s + pts); setCorrectCount(c => c + 1); }
    setTimeout(() => {
      if (qIndex + 1 < quiz.questions.length) {
        setQIndex(qIndex + 1);
        setPicked(null);
        setRevealed(false);
      }
    }, 1800);
  };

  const allDone = qIndex + 1 >= quiz.questions.length && revealed;
  const progress = step === 'intro' ? 0 : step === 'result' ? 1 : 1 - (sessionLeft / quiz.sessionSeconds);
  const mmss = (s) => `${Math.floor(s / 60)}:${String(Math.max(0, s % 60)).padStart(2, '0')}`;
  const urgent = sessionLeft <= 10;

  const allPlayers = [
    ...players,
    { name: CURRENT_USER.name, handle: CURRENT_USER.handle, avatar: CURRENT_USER.avatar, color: CURRENT_USER.color, score, me: true },
  ].sort((a, b) => b.score - a.score).map((p, i) => ({ ...p, rank: i + 1 }));
  const myRank = allPlayers.find(p => p.me).rank;
  const winner = allPlayers[0];

  return (
    <div className="screen" style={{
      background: 'linear-gradient(180deg, #0D1635 0%, #05080F 100%)',
      display: 'flex', flexDirection: 'column',
    }}>
      <StatusBar />
      <div style={{ padding: '8px 20px 14px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', color: 'var(--amber)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--amber)' }} className="pulse-dot" />
            {step === 'live' ? `${mmss(sessionLeft)} · ${score} pts` : quiz.badge}
          </span>
          <button onClick={onClose} className="btn btn-nav" style={{ width: 36, height: 36 }}>
            <IconClose size={16} />
          </button>
        </div>
        <div style={{ height: 3, background: 'rgba(255,255,255,0.06)', borderRadius: 2, overflow: 'hidden' }}>
          <div style={{
            width: `${progress * 100}%`, height: '100%',
            background: urgent && step === 'live' ? '#FF5A5F' : 'var(--amber)',
            transition: 'width 1s linear, background .3s',
          }} />
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 24px 32px' }}>
        {step === 'intro' && (
          <QuizIntro quiz={quiz} onStart={() => setStep('live')} onClose={onClose} />
        )}
        {step === 'live' && !allDone && (
          <QuizQuestion key={qIndex}
            question={quiz.questions[qIndex]} index={qIndex}
            total={quiz.questions.length} picked={picked} revealed={revealed}
            onPick={pickAnswer} />
        )}
        {step === 'live' && allDone && (
          <QuizWaiting sessionLeft={sessionLeft} mmss={mmss} players={allPlayers} myRank={myRank} score={score} />
        )}
        {step === 'result' && (
          <QuizResult quiz={quiz} score={score} correctCount={correctCount}
            total={quiz.questions.length} players={allPlayers} myRank={myRank} winner={winner} onClose={onClose} />
        )}
      </div>
    </div>
  );
};

const QuizIntro = ({ quiz, onStart, onClose }) => (
  <div className="fade-in">
    <div style={{
      width: 64, height: 64, borderRadius: 18,
      background: 'rgba(245,166,35,0.12)', border: '1px solid rgba(245,166,35,0.3)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28,
      marginBottom: 20,
    }}>🏆</div>
    <h2 style={{ fontSize: 30, margin: '0 0 6px', fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
      {quiz.title}
    </h2>
    <p style={{ fontSize: 14, color: 'var(--text-mute)', margin: '0 0 24px' }}>{quiz.subtitle}</p>

    <div style={{
      background: 'rgba(245,166,35,0.08)', border: '1px dashed rgba(245,166,35,0.3)',
      borderRadius: 14, padding: 14, marginBottom: 22,
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{ fontSize: 24 }}>🏆</div>
      <div>
        <div className="mono" style={{ fontSize: 9, letterSpacing: '0.18em', color: 'var(--text-mute)', marginBottom: 3 }}>PRÊMIO</div>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{quiz.prize}</div>
      </div>
    </div>

    <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 28 }}>
      <RuleRow label={`Você tem ${quiz.sessionSeconds}s`} sub="O quiz inteiro roda num tempo só. Quando acabar, termina." />
      <RuleRow label="500 pts por acerto" sub="+ bônus de velocidade (até 500 pts extras)" />
      <RuleRow label="Quem tiver mais pontos ao final, ganha" sub="A competição é só desta sessão. Nada de ranking global." />
    </div>

    <div style={{ display: 'flex', gap: 8 }}>
      <button className="btn btn-ghost" style={{ flex: 1 }} onClick={onClose}>Agora não</button>
      <button className="btn btn-primary" style={{ flex: 2 }} onClick={onStart}>
        Começar <IconArrowRight size={16} />
      </button>
    </div>
  </div>
);

const RuleRow = ({ label, sub }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
    <div style={{
      width: 28, height: 28, borderRadius: 8,
      background: 'rgba(245,166,35,0.12)', color: 'var(--amber)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
    }}><IconCheck size={14} stroke={2.4} /></div>
    <div>
      <div style={{ fontSize: 13, fontWeight: 500 }}>{label}</div>
      <div style={{ fontSize: 11, color: 'var(--text-mute)', marginTop: 1 }}>{sub}</div>
    </div>
  </div>
);

const QuizQuestion = ({ question, index, total, picked, revealed, onPick }) => (
  <div className="fade-in">
    <div className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', letterSpacing: '0.2em', marginBottom: 16 }}>
      PERGUNTA {String(index + 1).padStart(2, '0')} DE {String(total).padStart(2, '0')}
    </div>
    <h3 style={{ fontSize: 24, margin: '0 0 26px', fontWeight: 500, letterSpacing: '-0.01em', lineHeight: 1.25 }}>
      {question.q}
    </h3>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {question.options.map((opt, i) => {
        const isCorrect = opt.correct;
        const isPicked = picked === opt.id;
        let bg = 'rgba(255,255,255,0.04)';
        let border = 'var(--line)';
        let accent = null;
        if (revealed) {
          if (isCorrect) { bg = 'rgba(74,222,128,0.12)'; border = 'rgba(74,222,128,0.5)'; accent = '#4ADE80'; }
          else if (isPicked) { bg = 'rgba(255,90,95,0.1)'; border = 'rgba(255,90,95,0.4)'; accent = '#FF5A5F'; }
        }
        return (
          <button key={opt.id} onClick={() => onPick(opt.id)} disabled={revealed} style={{
            width: '100%', padding: '16px 18px', background: bg,
            border: `1px solid ${border}`, color: '#fff', borderRadius: 14,
            cursor: revealed ? 'default' : 'pointer', font: 'inherit',
            textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12,
            transition: 'all .2s',
          }}>
            <span className="mono" style={{
              width: 28, height: 28, borderRadius: 8,
              background: accent || 'rgba(255,255,255,0.05)',
              color: accent ? '#05080F' : 'var(--text-dim)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 12, fontWeight: 700, flexShrink: 0,
            }}>{String.fromCharCode(65 + i)}</span>
            <span style={{ fontSize: 15, flex: 1, lineHeight: 1.35 }}>{opt.label}</span>
            {revealed && isCorrect && <IconCheck size={16} stroke={2.4} style={{ color: '#4ADE80' }} />}
            {revealed && isPicked && !isCorrect && <IconClose size={16} stroke={2.4} style={{ color: '#FF5A5F' }} />}
          </button>
        );
      })}
    </div>
  </div>
);

const QuizWaiting = ({ sessionLeft, mmss, players, myRank, score }) => (
  <div className="fade-in">
    <div className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', letterSpacing: '0.2em', marginBottom: 6 }}>
      VOCÊ TERMINOU · AGUARDANDO OS OUTROS
    </div>
    <div className="serif" style={{ fontSize: 56, fontWeight: 400, letterSpacing: '-0.02em', color: 'var(--amber)', lineHeight: 1, marginBottom: 10 }}>
      {mmss(sessionLeft)}
    </div>
    <p style={{ fontSize: 14, color: 'var(--text-dim)', margin: '0 0 24px' }}>
      Sua pontuação final: <strong style={{ color: '#fff' }}>{score} pts</strong>. Você está em <strong style={{ color: 'var(--amber)' }}>{myRank}º</strong>.
    </p>
    <div className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', letterSpacing: '0.18em', marginBottom: 10 }}>PLACAR AO VIVO</div>
    <LiveBoard players={players} />
  </div>
);

const LiveBoard = ({ players }) => (
  <div style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
    {players.map((p, i) => (
      <LeaderRow key={p.handle} p={p} last={i === players.length - 1} />
    ))}
  </div>
);

const QuizResult = ({ quiz, score, correctCount, total, players, myRank, winner, onClose }) => {
  const won = winner.me;
  const medal = ['🥇', '🥈', '🥉'];
  return (
    <div className="fade-in">
      <div style={{
        width: 72, height: 72, borderRadius: 20,
        background: won ? 'rgba(245,166,35,0.18)' : 'rgba(255,255,255,0.05)',
        border: `1px solid ${won ? 'rgba(245,166,35,0.4)' : 'var(--line)'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 18, fontSize: 36,
      }}>
        {won ? '🥇' : myRank <= 3 ? medal[myRank - 1] : '🎯'}
      </div>

      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', color: 'var(--text-mute)', marginBottom: 6 }}>
        TEMPO ESGOTADO
      </div>
      <h2 style={{ fontSize: 28, margin: '0 0 6px', fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.15 }}>
        {won ? 'Você ganhou!' : `${winner.name.split(' ')[0]} ganhou esta sessão`}
      </h2>
      <p style={{ fontSize: 14, color: 'var(--text-dim)', margin: '0 0 22px' }}>
        {won
          ? `Você fechou com ${score} pts e leva: ${quiz.prize}.`
          : `Você fez ${score} pts (${correctCount}/${total} acertos) e ficou em ${myRank}º.`}
      </p>

      <div className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', letterSpacing: '0.18em', marginBottom: 10 }}>
        PLACAR FINAL
      </div>
      <div style={{ marginBottom: 18 }}>
        <LiveBoard players={players} />
      </div>

      {won && (
        <div style={{
          background: 'rgba(245,166,35,0.1)', border: '1px dashed rgba(245,166,35,0.35)',
          borderRadius: 14, padding: 14, marginBottom: 20,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ fontSize: 22 }}>🏆</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Prêmio: {quiz.prize}</div>
            <div style={{ fontSize: 11, color: 'var(--text-mute)', marginTop: 2 }}>A organização vai te chamar no balcão principal.</div>
          </div>
        </div>
      )}

      <div style={{ display: 'flex', gap: 8 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={onClose}>Fechar</button>
        <button className="btn btn-primary" style={{ flex: 1 }} onClick={onClose}>
          <IconShare size={14} /> Compartilhar
        </button>
      </div>
    </div>
  );
};

const LeaderRow = ({ p, last }) => (
  <div style={{
    padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 12,
    background: p.me ? 'rgba(245,166,35,0.08)' : 'transparent',
    borderBottom: last ? 'none' : '1px solid var(--line)',
  }}>
    <div style={{
      width: 24, textAlign: 'center', fontSize: 13, fontWeight: 700,
      color: p.rank === 1 ? 'var(--amber)' : p.me ? 'var(--amber)' : 'var(--text-dim)',
    }}>{p.rank === 1 ? '🥇' : p.rank === 2 ? '🥈' : p.rank === 3 ? '🥉' : p.rank}</div>
    <Avatar user={p} size={30} />
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
        {p.name.split(' ').slice(0, 2).join(' ')}
        {p.me && <span className="mono" style={{ fontSize: 9, color: 'var(--amber)', letterSpacing: '0.1em' }}>VOCÊ</span>}
      </div>
      <div style={{ fontSize: 11, color: 'var(--text-mute)' }}>@{p.handle}</div>
    </div>
    <div className="mono" style={{ fontSize: 13, fontWeight: 700, color: p.me ? 'var(--amber)' : '#fff' }}>
      {p.score.toLocaleString('pt-BR')}
    </div>
  </div>
);

Object.assign(window, { QUIZZES, QuizListScreen, QuizScreen });
