// QuizPlayer — runs the timed quiz: question → answer/timeout → reveal blink → next.
// State machine: 'intro' | 'playing' | 'reveal' | 'done'
// Light theme: white surfaces, Ibmec blue + yellow accents.
// We never tell the user whether THEIR answer was right — only the correct option
// blinks during the reveal interstitial, and points earned for the question pop in.

const QuizPlayer = ({ quiz, onClose }) => {
  const existing = getResult();
  const [step, setStep] = React.useState(existing ? 'done' : 'intro');
  const [qIndex, setQIndex] = React.useState(0);
  const [perQuestion, setPerQuestion] = React.useState(existing?.perQuestion || []);
  const [picked, setPicked] = React.useState(null);
  const [questionStart, setQuestionStart] = React.useState(0);
  const [now, setNow] = React.useState(Date.now());
  const submittedRef = React.useRef(false);

  React.useEffect(() => {
    if (step !== 'playing') return;
    const t = setInterval(() => setNow(Date.now()), 100);
    return () => clearInterval(t);
  }, [step]);

  const q = quiz.questions[qIndex];
  const elapsed = step === 'playing' ? now - questionStart : 0;
  const remaining = Math.max(0, SECONDS_PER_QUESTION * 1000 - elapsed);
  const remainingSec = Math.ceil(remaining / 1000);

  const beginQuestion = (idx) => {
    submittedRef.current = false;
    setPicked(null);
    setQuestionStart(Date.now());
    setNow(Date.now());
    setQIndex(idx);
    setStep('playing');
  };

  const beginQuiz = () => {
    setPerQuestion([]);
    beginQuestion(0);
  };

  const submitAnswer = (optId) => {
    if (submittedRef.current) return;
    submittedRef.current = true;
    const elapsedMs = Date.now() - questionStart;
    setPicked(optId);
    const correct = q.options.find(o => o.correct);
    const isCorrect = optId === correct.id;
    const pts = calcPoints(elapsedMs, isCorrect);
    setPerQuestion(p => [...p, { picked: optId, pts, elapsedMs, correctId: correct.id }]);
    setStep('reveal');
  };

  React.useEffect(() => {
    if (step === 'playing' && remaining <= 0 && !submittedRef.current) {
      submitAnswer(null);
    }
  }, [remaining, step]); // eslint-disable-line

  React.useEffect(() => {
    if (step !== 'reveal') return;
    const t = setTimeout(() => {
      if (qIndex + 1 < quiz.questions.length) {
        beginQuestion(qIndex + 1);
      } else {
        const total = perQuestion.reduce((a, e) => a + e.pts, 0);
        const r = { perQuestion, total, at: Date.now() };
        saveResult(r);
        setStep('done');
      }
    }, REVEAL_MS);
    return () => clearTimeout(t);
  }, [step]); // eslint-disable-line

  const totalSoFar = perQuestion.reduce((a, e) => a + e.pts, 0);
  const progress = step === 'intro' ? 0
                 : step === 'done' ? 1
                 : (qIndex + (step === 'reveal' ? 1 : (1 - remaining / (SECONDS_PER_QUESTION * 1000)))) / quiz.questions.length;

  return (
    <div className="screen quiz-screen" style={{
      background: '#FFFFFF',
      color: Q_INK,
      display: 'flex', flexDirection: 'column',
    }}>
      <StatusBar />

      <div style={{ padding: '6px 20px 14px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <button onClick={onClose} aria-label="Fechar" style={{
            width: 36, height: 36, padding: 0, borderRadius: 12,
            background: Q_SURFACE_2, color: Q_INK,
            border: `1px solid ${Q_HAIRLINE}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}>
            <IconClose size={16} />
          </button>
          <div style={{ flex: 1, textAlign: 'center' }}>
            <div className="mono" style={{ fontSize: 9, letterSpacing: '0.22em', color: Q_MUTED, fontWeight: 600 }}>
              {step === 'intro' ? 'QUIZ DA SEMANA'
               : step === 'done' ? 'CONCLUÍDO'
               : `${String(qIndex + 1).padStart(2,'0')} / ${String(quiz.questions.length).padStart(2,'0')}`}
            </div>
          </div>
          <div style={{
            minWidth: 64, textAlign: 'right',
            fontFamily: 'Geist Mono, monospace',
            fontSize: 13, fontWeight: 700,
            color: step === 'intro' ? 'transparent' : Q_BLUE,
            letterSpacing: '-0.01em',
          }}>
            {step !== 'intro' && `${totalSoFar} pts`}
          </div>
        </div>

        <div style={{ height: 4, background: Q_SURFACE_2, borderRadius: 2, overflow: 'hidden' }}>
          <div style={{
            width: `${Math.min(100, progress * 100)}%`,
            height: '100%',
            background: Q_BLUE,
            transition: step === 'playing' ? 'width .12s linear' : 'width .35s ease',
          }} />
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '6px 24px 32px', position: 'relative' }}>
        {step === 'intro'   && <QuizIntro quiz={quiz} onStart={beginQuiz} onClose={onClose} />}
        {step === 'playing' && <QuizQuestion key={qIndex}
                                  question={q} index={qIndex} total={quiz.questions.length}
                                  remainingMs={remaining} remainingSec={remainingSec}
                                  onPick={submitAnswer} />}
        {step === 'reveal'  && <QuizReveal key={'r'+qIndex}
                                  question={q}
                                  entry={perQuestion[perQuestion.length - 1]} />}
        {step === 'done'    && <QuizSummary quiz={quiz}
                                  result={existing || { perQuestion, total: totalSoFar }}
                                  onClose={onClose} />}
      </div>
    </div>
  );
};

// ============================================================
// Intro — minimal: scoring rules, timer, single attempt
// ============================================================
const QuizIntro = ({ quiz, onStart, onClose }) => (
  <div className="fade-in" style={{ paddingTop: 12 }}>
    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: Q_BLUE, fontWeight: 700, marginBottom: 14 }}>
      ★ PRONTO?
    </div>
    <h2 style={{ fontSize: 36, margin: '0 0 6px', fontWeight: 600, letterSpacing: '-0.025em', lineHeight: 1.05, color: Q_INK }}>
      {quiz.title}
    </h2>
    <p style={{ fontSize: 15, color: Q_MUTED, margin: '0 0 28px' }}>{quiz.tagline}</p>

    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14,
    }}>
      <IntroStat big={quiz.questions.length} label="perguntas" />
      <IntroStat big="60s" label="por pergunta" />
      <IntroStat big={MAX_POINTS} label="pts máx por pergunta" accent />
      <IntroStat big={MIN_POINTS} label="pts mín se acertar" />
    </div>

    <div style={{
      padding: '16px 18px', borderRadius: 14,
      background: '#FFFFFF', border: `1px solid ${Q_HAIRLINE}`,
      marginBottom: 28,
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <RuleLine n="01" t="Quanto mais rápido, mais pontos" s="100 pts no início, vai caindo até 20 pts ao apertar o tempo." />
        <RuleLine n="02" t="Errou ou estourou o tempo" s="Zero pontos naquela pergunta. A próxima vem em seguida." />
        <RuleLine n="03" t="Uma única tentativa" s="Quando você começar, vai até o fim. Não dá pra refazer." />
      </div>
    </div>

    <div style={{ display: 'flex', gap: 8 }}>
      <button onClick={onClose} style={{
        flex: 1, padding: '14px 20px',
        background: Q_SURFACE_2, color: Q_INK,
        border: `1px solid ${Q_HAIRLINE}`, borderRadius: 14,
        fontFamily: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer',
      }}>Agora não</button>
      <button onClick={onStart} style={{
        flex: 2, padding: '14px 20px',
        background: Q_BLUE, color: '#FFFFFF',
        border: 'none', borderRadius: 14,
        fontFamily: 'inherit', fontSize: 15, fontWeight: 600, cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        boxShadow: '0 8px 22px -8px rgba(17,69,255,0.55)',
      }}>
        Começar quiz <IconArrowRight size={16} />
      </button>
    </div>
  </div>
);

const IntroStat = ({ big, label, accent }) => (
  <div style={{
    background: accent ? Q_BLUE : '#FFFFFF',
    color: accent ? '#FFFFFF' : Q_INK,
    border: accent ? '1px solid transparent' : `1px solid ${Q_HAIRLINE}`,
    borderRadius: 14, padding: '14px 16px',
  }}>
    <div className="mono" style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1 }}>{big}</div>
    <div style={{
      fontSize: 11,
      color: accent ? 'rgba(255,255,255,0.75)' : Q_MUTED,
      marginTop: 6, letterSpacing: 0,
    }}>{label}</div>
  </div>
);

const RuleLine = ({ n, t, s }) => (
  <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
    <span className="mono" style={{ fontSize: 11, color: Q_BLUE, fontWeight: 700, paddingTop: 2 }}>{n}</span>
    <div>
      <div style={{ fontSize: 13, fontWeight: 600, color: Q_INK }}>{t}</div>
      <div style={{ fontSize: 11, color: Q_MUTED, marginTop: 2, lineHeight: 1.5 }}>{s}</div>
    </div>
  </div>
);

// ============================================================
// Question — 60s timer bar, multiple choice. Live "potential points" indicator.
// ============================================================
const QuizQuestion = ({ question, index, total, remainingMs, remainingSec, onPick }) => {
  const pct = (remainingMs / (SECONDS_PER_QUESTION * 1000)) * 100;
  const elapsedMs = SECONDS_PER_QUESTION * 1000 - remainingMs;
  const potential = calcPoints(elapsedMs, true);
  const urgent = remainingSec <= 10;

  return (
    <div className="fade-in">
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        marginBottom: 10,
      }}>
        <div>
          <div className="mono" style={{
            fontSize: 11, letterSpacing: '0.2em', color: Q_MUTED, fontWeight: 600, marginBottom: 4,
          }}>
            PERGUNTA {String(index + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}
          </div>
          <div className="mono" style={{
            fontSize: 32, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1,
            color: urgent ? '#D94E55' : Q_INK,
            transition: 'color .2s',
          }}>
            {String(remainingSec).padStart(2, '0')}<span style={{ fontSize: 16, color: Q_MUTED, marginLeft: 4 }}>s</span>
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="mono" style={{ fontSize: 9, color: Q_MUTED, letterSpacing: '0.18em', marginBottom: 4, fontWeight: 600 }}>
            VALENDO
          </div>
          <div className="mono" style={{
            fontSize: 24, fontWeight: 600, color: Q_BLUE, letterSpacing: '-0.02em', lineHeight: 1,
          }}>
            {potential}<span style={{ fontSize: 12, color: Q_MUTED, marginLeft: 3 }}>pts</span>
          </div>
        </div>
      </div>

      <div style={{
        height: 8, background: Q_SURFACE_2, borderRadius: 4,
        overflow: 'hidden', marginBottom: 26,
        boxShadow: urgent ? '0 0 18px rgba(217,78,85,0.35)' : 'none',
      }}>
        <div style={{
          width: `${pct}%`, height: '100%',
          background: urgent
            ? 'linear-gradient(90deg, #D94E55 0%, #FF8085 100%)'
            : `linear-gradient(90deg, ${Q_YELLOW_DEEP} 0%, ${Q_YELLOW} 100%)`,
          transition: 'width .12s linear',
          borderRadius: 4,
        }} />
      </div>

      <h3 style={{
        fontSize: 22, margin: '0 0 22px', fontWeight: 600,
        letterSpacing: '-0.015em', lineHeight: 1.3, color: Q_INK,
        textWrap: 'pretty',
      }}>
        {question.q}
      </h3>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {question.options.map((opt, i) => (
          <button key={opt.id} onClick={() => onPick(opt.id)} style={{
            width: '100%', padding: '15px 16px',
            background: '#FFFFFF',
            border: `1.5px solid ${Q_HAIRLINE}`,
            color: Q_INK, borderRadius: 14,
            cursor: 'pointer', font: 'inherit',
            textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12,
            transition: 'all .15s',
          }}
          onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; e.currentTarget.style.borderColor = Q_BLUE; }}
          onMouseUp={(e) => { e.currentTarget.style.transform = ''; e.currentTarget.style.borderColor = Q_HAIRLINE; }}
          onMouseLeave={(e) => { e.currentTarget.style.transform = ''; e.currentTarget.style.borderColor = Q_HAIRLINE; }}>
            <span className="mono" style={{
              width: 30, height: 30, borderRadius: 8,
              background: Q_SURFACE_2,
              color: Q_BLUE,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 13, fontWeight: 700, flexShrink: 0,
            }}>{String.fromCharCode(65 + i)}</span>
            <span style={{ fontSize: 15, flex: 1, lineHeight: 1.35, color: Q_INK }}>{opt.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
};

// ============================================================
// Reveal — between questions: correct option blinks; points-gained pops in.
// We don't tell the user whether THEIR answer was right — only what the right
// answer was, and how many points they earned.
// ============================================================
const QuizReveal = ({ question, entry }) => {
  const earned = entry.pts;
  const isTimeout = entry.picked == null;
  return (
    <div className="fade-in" style={{
      minHeight: 480,
      display: 'flex', flexDirection: 'column', justifyContent: 'center',
      alignItems: 'stretch', paddingTop: 0,
    }}>
      <div style={{ textAlign: 'center', marginBottom: 26 }}>
        <div className="mono" style={{
          fontSize: 10, letterSpacing: '0.22em', color: Q_MUTED, fontWeight: 600, marginBottom: 14,
        }}>
          RESPOSTA CORRETA
        </div>
        <div className="mono reveal-pts" style={{
          fontSize: 64, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1,
          color: earned > 0 ? Q_BLUE : '#B6BAC6',
        }}>
          +{earned}
        </div>
        <div style={{ fontSize: 12, color: Q_MUTED, marginTop: 6, letterSpacing: '0.05em' }}>
          {isTimeout ? 'tempo esgotado'
            : earned === 0 ? 'sem pontos nesta'
            : 'pontos somados'}
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {question.options.map((opt, i) => {
          const isCorrect = !!opt.correct;
          return (
            <div key={opt.id} className={isCorrect ? 'reveal-blink' : ''} style={{
              padding: '15px 16px', borderRadius: 14,
              background: isCorrect ? '#FFF8DD' : '#FFFFFF',
              border: `1.5px solid ${isCorrect ? Q_YELLOW_DEEP : Q_HAIRLINE}`,
              color: isCorrect ? Q_INK : '#B6BAC6',
              display: 'flex', alignItems: 'center', gap: 12,
              opacity: isCorrect ? 1 : 0.55,
              transition: 'all .2s',
            }}>
              <span className="mono" style={{
                width: 30, height: 30, borderRadius: 8,
                background: isCorrect ? Q_YELLOW : Q_SURFACE_2,
                color: isCorrect ? Q_INK : '#B6BAC6',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 13, fontWeight: 700, flexShrink: 0,
              }}>{String.fromCharCode(65 + i)}</span>
              <span style={{ fontSize: 14, flex: 1, lineHeight: 1.35, fontWeight: isCorrect ? 600 : 400 }}>
                {opt.label}
              </span>
              {isCorrect && <IconCheck size={16} stroke={2.4} style={{ color: Q_YELLOW_DEEP }} />}
            </div>
          );
        })}
      </div>
    </div>
  );
};

Object.assign(window, { QuizPlayer, QuizIntro, QuizQuestion, QuizReveal, IntroStat, RuleLine });
