// QuizListScreen — Quiz tab landing.
// White / Ibmec-blue / Ibmec-yellow theme to match the rest of the app.
// Three states: open (not yet taken, deadline in future), done (already taken),
// and locked (deadline passed without taking). No prize copy, no leaderboard.

// ---------- Quiz tab landing ----------
const QuizListScreen = ({ onPlay }) => {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 30 * 1000);
    return () => clearInterval(t);
  }, []);
  const deadline = getDeadline();
  const remaining = deadline - now;
  const expired = remaining <= 0;
  const result = getResult();
  const taken = !!result;
  const state = taken ? 'done' : expired ? 'locked' : 'open';

  return (
    <div className="screen" style={{ background: '#FFFFFF', color: Q_INK }}>
      <StatusBar />

      <div style={{ padding: '6px 20px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10 }}>
          <img
            src="assets/ibmec-logo.svg"
            alt="Ibmec"
            style={{ height: 20, width: 'auto', display: 'block', transform: 'translateY(3px)' }}
          />
          <span style={{
            fontFamily: "'Instrument Serif', serif",
            fontStyle: 'italic',
            fontSize: 22,
            lineHeight: 1,
            color: Q_YELLOW,
            letterSpacing: '-0.01em',
          }}>experience</span>
        </div>
        <h1 style={{ fontSize: 30, margin: 0, fontWeight: 600, letterSpacing: '-0.025em', lineHeight: 1.05, color: Q_INK }}>
          Quiz da semana
        </h1>
        <p style={{ fontSize: 14, color: Q_MUTED, margin: '8px 0 0', lineHeight: 1.45, maxWidth: 320 }}>
          Responda rápido, pontue alto, concorra.
        </p>
      </div>

      <div style={{ padding: '24px 20px 32px' }}>
        {state === 'open'   && <OpenQuizCard quiz={QUIZ} deadline={deadline} remaining={remaining} onPlay={() => onPlay(QUIZ)} />}
        {state === 'done'   && <DoneQuizCard quiz={QUIZ} result={result} onReview={() => onPlay(QUIZ)} />}
        {state === 'locked' && <LockedQuizCard quiz={QUIZ} deadline={deadline} />}
      </div>
    </div>
  );
};

const OpenQuizCard = ({ quiz, deadline, remaining, onPlay }) => (
  <div style={{
    position: 'relative', overflow: 'hidden',
    background: Q_BLUE,
    borderRadius: 22,
    padding: '24px 22px 22px',
    color: '#FFFFFF',
    boxShadow: '0 14px 30px -14px rgba(17,69,255,0.45)',
  }}>
    {/* diagonal stripe pattern as bg texture */}
    <div style={{
      position: 'absolute', inset: 0,
      backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,0.06) 0 14px, transparent 14px 28px)',
      pointerEvents: 'none',
    }} />

    {/* corner badge */}
    <div style={{
      position: 'absolute', top: 0, right: 0,
      background: Q_YELLOW, color: Q_INK,
      padding: '6px 14px 6px 16px',
      borderBottomLeftRadius: 14,
      fontFamily: 'Geist Mono, monospace', fontSize: 10, fontWeight: 700, letterSpacing: '0.15em',
    }}>ABERTO</div>

    <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18 }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: Q_YELLOW }} className="pulse-dot" />
      <span className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: Q_YELLOW, fontWeight: 700 }}>
        {fmtRemainingShort(remaining).toUpperCase()}
      </span>
    </div>

    <div style={{ position: 'relative', fontSize: 14, color: 'rgba(255,255,255,0.92)', lineHeight: 1.5, marginBottom: 22, maxWidth: 300 }}>
      Um único quiz, no seu tempo, contra o relógio. Pontue agora e fique em jogo durante toda a semana.
    </div>

    <div style={{
      position: 'relative',
      display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 1,
      background: 'rgba(255,255,255,0.18)',
      border: '1px solid rgba(255,255,255,0.18)',
      borderRadius: 14,
      overflow: 'hidden', marginBottom: 20,
    }}>
      <MiniStat top={quiz.questions.length} bottom="perguntas" />
      <MiniStat top="60s" bottom="por pergunta" />
      <MiniStat top={`${MAX_POINTS}`} bottom="pts máx cada" />
    </div>

    <div style={{
      position: 'relative',
      fontFamily: 'Geist Mono, monospace', fontSize: 11, color: 'rgba(255,255,255,0.7)',
      letterSpacing: '0.05em', marginBottom: 14, textAlign: 'center',
    }}>
      encerra {fmtDeadline(deadline)}
    </div>

    <button onClick={onPlay} style={{
      position: 'relative',
      width: '100%', padding: '16px 20px',
      background: Q_YELLOW, color: Q_INK,
      border: 'none', borderRadius: 14,
      fontFamily: 'inherit', fontSize: 16, fontWeight: 600, letterSpacing: '-0.005em',
      cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      boxShadow: '0 8px 22px -8px rgba(255,214,10,0.7)',
      transition: 'transform .12s ease, background .2s',
    }}
    onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.985)'}
    onMouseUp={(e) => e.currentTarget.style.transform = ''}
    onMouseLeave={(e) => e.currentTarget.style.transform = ''}>
      Começar quiz <IconArrowRight size={16} />
    </button>
  </div>
);

const DoneQuizCard = ({ quiz, result, onReview }) => (
  <div style={{
    position: 'relative', overflow: 'hidden',
    background: '#FFFFFF', border: `1px solid ${Q_HAIRLINE}`,
    borderRadius: 22, padding: '22px',
    boxShadow: '0 12px 26px -16px rgba(20,30,80,0.18)',
  }}>
    <div style={{
      position: 'absolute', top: 0, right: 0,
      background: Q_BLUE, color: '#FFFFFF',
      padding: '6px 14px 6px 16px',
      borderBottomLeftRadius: 14,
      fontFamily: 'Geist Mono, monospace', fontSize: 10, fontWeight: 700, letterSpacing: '0.15em',
    }}>CONCLUÍDO</div>

    <div className="mono" style={{
      fontSize: 10, letterSpacing: '0.22em', color: Q_MUTED, fontWeight: 600, marginBottom: 14,
    }}>SUA PONTUAÇÃO</div>

    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
      <div className="mono" style={{
        fontSize: 64, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 0.95,
        color: Q_BLUE,
      }}>{result.total}</div>
      <div style={{ fontSize: 14, color: Q_MUTED }}>
        / {quiz.questions.length * MAX_POINTS}
      </div>
    </div>

    <p style={{ fontSize: 13, color: '#3A4055', lineHeight: 1.5, margin: '14px 0 18px' }}>
      Obrigado por participar! Sua pontuação foi registrada e você está concorrendo durante a semana.
    </p>

    <button onClick={onReview} style={{
      width: '100%', 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',
    }}>
      Ver resumo
    </button>
  </div>
);

const LockedQuizCard = ({ quiz, deadline }) => (
  <div style={{
    position: 'relative', overflow: 'hidden',
    background: Q_SURFACE_2,
    border: `1px solid ${Q_HAIRLINE}`,
    borderRadius: 22, padding: '24px 22px',
    color: '#3A4055',
  }}>
    <div style={{
      position: 'absolute', top: 0, right: 0,
      background: '#1F2330', color: '#FFFFFF',
      padding: '6px 14px 6px 16px',
      borderBottomLeftRadius: 14,
      fontFamily: 'Geist Mono, monospace', fontSize: 10, fontWeight: 700, letterSpacing: '0.15em',
    }}>ENCERRADO</div>

    <div style={{
      width: 52, height: 52, borderRadius: 14,
      background: '#FFFFFF', border: `1px solid ${Q_HAIRLINE}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      marginBottom: 16, color: Q_MUTED,
    }}>
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
        strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <rect x="5" y="11" width="14" height="9" rx="2" />
        <path d="M8 11V8a4 4 0 0 1 8 0v3" />
      </svg>
    </div>
    <div style={{ fontSize: 18, fontWeight: 600, color: Q_INK, marginBottom: 6, letterSpacing: '-0.01em' }}>
      O quiz desta semana já encerrou.
    </div>
    <p style={{ fontSize: 13, lineHeight: 1.5, margin: 0, color: Q_MUTED }}>
      Encerrou em {fmtDeadline(deadline)}. Fique de olho na próxima edição da Ibmec Experience.
    </p>
  </div>
);

const MiniStat = ({ top, bottom }) => (
  <div style={{ background: Q_BLUE_DARK, padding: '14px 10px', textAlign: 'center', color: '#FFFFFF' }}>
    <div className="mono" style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1 }}>{top}</div>
    <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.7)', marginTop: 6 }}>{bottom}</div>
  </div>
);

const ScoringStrip = () => (
  <div style={{
    marginTop: 18, padding: '18px 18px',
    background: '#FFFFFF',
    border: `1px solid ${Q_HAIRLINE}`, borderRadius: 16,
  }}>
    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: Q_MUTED, fontWeight: 600, marginBottom: 14 }}>
      COMO PONTUAR
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <ScoreLine
        big={`${MAX_POINTS}`}
        bigColor={Q_BLUE}
        title="Resposta na primeira fração"
        sub="Quanto antes você responder, mais perto de 100 fica."
      />
      <ScoreLine
        big={`${MIN_POINTS}`}
        bigColor={Q_YELLOW_DEEP}
        title="No fim do tempo"
        sub="Acertar tarde ainda dá pontos — só não tantos."
      />
      <ScoreLine
        big="0"
        bigColor={Q_MUTED}
        title="Errou ou estourou o tempo"
        sub="Sem pontos nessa pergunta. Próxima!"
      />
    </div>
  </div>
);

const ScoreLine = ({ big, bigColor, title, sub }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
    <div style={{
      minWidth: 56, textAlign: 'right',
      fontFamily: 'Geist Mono, monospace',
      fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em',
      color: bigColor,
    }}>{big}</div>
    <div>
      <div style={{ fontSize: 13, fontWeight: 600, color: Q_INK }}>{title}</div>
      <div style={{ fontSize: 11, color: Q_MUTED, marginTop: 2, lineHeight: 1.45 }}>{sub}</div>
    </div>
  </div>
);

// ============================================================
// QuizSummary — gamey end-of-quiz: total counts up, per-question points strip,
// thank-you. No correct/incorrect breakdown.
// ============================================================
const QuizSummary = ({ quiz, result, onClose }) => {
  const totalMax = quiz.questions.length * MAX_POINTS;
  const total = result.total ?? 0;
  const pct = totalMax ? total / totalMax : 0;

  // count-up animation for total
  const [shown, setShown] = React.useState(0);
  React.useEffect(() => {
    let raf, start;
    const dur = 1200;
    const tick = (ts) => {
      if (!start) start = ts;
      const p = Math.min(1, (ts - start) / dur);
      const ease = 1 - Math.pow(1 - p, 3);
      setShown(Math.round(total * ease));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [total]);

  const tier = pct >= 0.85 ? { tag: 'TOPO DA TABELA', line: 'Você jogou rápido e mirou bem.', glyph: '★' }
             : pct >= 0.6  ? { tag: 'BEM JOGADO',     line: 'Pontuação sólida — você tá no páreo.', glyph: '✦' }
             : pct >= 0.3  ? { tag: 'NA DISPUTA',     line: 'Toda pontuação conta pra essa semana.', glyph: '✧' }
             :               { tag: 'PARTICIPOU',     line: 'Obrigado por jogar! Toda pontuação conta.', glyph: '·' };

  const best = result.perQuestion?.reduce((b, e, i) => (e.pts > (b?.pts ?? -1) ? { ...e, i } : b), null);
  const fastest = result.perQuestion?.filter(e => e.pts > 0)
                  .reduce((b, e, i) => (b == null || e.elapsedMs < b.elapsedMs ? { ...e, i } : b), null);

  return (
    <div className="fade-in" style={{ paddingTop: 4, color: Q_INK }}>
      {/* Glyph + tag */}
      <div style={{ textAlign: 'center', marginBottom: 8 }}>
        <div className="mono summary-glyph" style={{
          fontSize: 56, fontWeight: 700, color: Q_YELLOW_DEEP, lineHeight: 1, marginBottom: 14,
        }}>{tier.glyph}</div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.28em', color: Q_BLUE, fontWeight: 700 }}>
          {tier.tag}
        </div>
      </div>

      {/* Big total */}
      <div style={{ textAlign: 'center', marginTop: 20, marginBottom: 8 }}>
        <div className="mono" style={{
          fontSize: 100, fontWeight: 700, letterSpacing: '-0.05em', lineHeight: 0.9,
          color: Q_INK,
        }}>{shown}</div>
        <div style={{
          fontFamily: 'Geist Mono, monospace', fontSize: 12, color: Q_MUTED,
          letterSpacing: '0.18em', marginTop: 8, fontWeight: 600,
        }}>
          / {totalMax} PONTOS
        </div>
      </div>

      <p style={{
        fontSize: 14, color: '#3A4055', textAlign: 'center',
        margin: '20px auto 28px', maxWidth: 280, lineHeight: 1.45,
      }}>{tier.line}</p>

      {/* Per-question chips */}
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: Q_MUTED, fontWeight: 600, marginBottom: 12 }}>
        POR PERGUNTA
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8,
        marginBottom: 22,
      }}>
        {(result.perQuestion || []).map((e, i) => {
          const ptsPct = e.pts / MAX_POINTS;
          return (
            <div key={i} style={{
              padding: '12px 12px 14px',
              borderRadius: 12,
              background: '#FFFFFF',
              border: `1px solid ${Q_HAIRLINE}`,
              position: 'relative', overflow: 'hidden',
            }}>
              <div style={{
                position: 'absolute', left: 0, bottom: 0, height: 3,
                width: `${Math.max(ptsPct * 100, e.pts > 0 ? 8 : 0)}%`,
                background: e.pts > 0 ? Q_YELLOW : '#E6E8EE',
              }} />
              <div className="mono" style={{ fontSize: 9, color: Q_MUTED, letterSpacing: '0.18em', marginBottom: 4, fontWeight: 600 }}>
                Q{String(i + 1).padStart(2, '0')}
              </div>
              <div className="mono" style={{
                fontSize: 20, fontWeight: 600, letterSpacing: '-0.02em',
                color: e.pts > 0 ? Q_INK : Q_MUTED,
              }}>
                {e.pts}
                <span style={{ fontSize: 10, color: Q_MUTED, marginLeft: 3 }}>pts</span>
              </div>
            </div>
          );
        })}
      </div>

      {/* Highlights row */}
      {best && best.pts > 0 && (
        <div style={{ display: 'flex', gap: 10, marginBottom: 26 }}>
          <Highlight label="Melhor pergunta" value={`Q${String((best.i ?? 0) + 1).padStart(2,'0')}`} sub={`${best.pts} pts`} />
          {fastest && (
            <Highlight label="Mais rápida" value={`${(fastest.elapsedMs / 1000).toFixed(1)}s`} sub={`Q${String((fastest.i ?? 0) + 1).padStart(2,'0')}`} />
          )}
        </div>
      )}

      {/* Thank-you block */}
      <div style={{
        background: Q_BLUE,
        color: '#FFFFFF',
        borderRadius: 16, padding: '18px 18px', marginBottom: 20,
        textAlign: 'center', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,0.06) 0 14px, transparent 14px 28px)',
          pointerEvents: 'none',
        }} />
        <div className="mono" style={{ position: 'relative', fontSize: 10, letterSpacing: '0.22em', color: Q_YELLOW, fontWeight: 700, marginBottom: 8 }}>
          OBRIGADO POR JOGAR
        </div>
        <div style={{ position: 'relative', fontSize: 14, lineHeight: 1.5 }}>
          Sua pontuação foi registrada. Boa sorte pelo resto da semana!
        </div>
      </div>

      <button onClick={onClose} style={{
        width: '100%', 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',
      }}>
        Voltar pro app
      </button>
    </div>
  );
};

const Highlight = ({ label, value, sub }) => (
  <div style={{
    flex: 1, padding: '12px 14px',
    background: '#FFFFFF', border: `1px solid ${Q_HAIRLINE}`,
    borderRadius: 12,
  }}>
    <div className="mono" style={{ fontSize: 9, color: Q_MUTED, letterSpacing: '0.18em', marginBottom: 6, fontWeight: 600 }}>
      {label.toUpperCase()}
    </div>
    <div className="mono" style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.02em', color: Q_INK }}>{value}</div>
    <div style={{ fontSize: 11, color: Q_MUTED, marginTop: 2 }}>{sub}</div>
  </div>
);

// QuizScreen kept as alias for back-compat
const QuizScreen = QuizPlayer;

Object.assign(window, {
  QuizListScreen, QuizScreen, QuizPlayer,
  QuizSummary, OpenQuizCard, DoneQuizCard, LockedQuizCard,
  Q_BLUE, Q_BLUE_DARK, Q_YELLOW, Q_YELLOW_DEEP, Q_INK, Q_MUTED, Q_HAIRLINE, Q_SURFACE_2,
});
