// Quiz screen — 5 dynamic questions, sound effects, animated feedback
const QUESTIONS = [
  {
    q: 'Qual a maior estrela portuguesa de sempre em Mundiais?',
    sub: 'Há mais do que uma resposta certa 😉',
    type: 'choice',
    options: [
      { label: 'Eusébio', emoji: '🏆', correct: true },
      { label: 'Figo', emoji: '⭐', correct: true },
      { label: 'Pauleta', emoji: '⚽', correct: true },
      { label: 'Cristiano', emoji: '🐐', correct: true },
    ],
    hint: 'Todos contam! +5%',
  },
  {
    q: 'Quantos craques tem o álbum completo?',
    sub: '48 seleções no Mundial 2026',
    type: 'choice',
    options: [
      { label: '512', correct: false },
      { label: '736', correct: true },
      { label: '850', correct: false },
      { label: '1024', correct: false },
    ],
    hint: '736 cromos · acerta para +10%',
  },
  {
    q: 'Que tipo de colecionador és tu?',
    sub: 'Não há resposta errada — só perfis!',
    type: 'persona',
    options: [
      { label: 'Casual', sub: 'Só os meus favoritos', emoji: '😎', kit: 'Basic' },
      { label: 'Sério', sub: 'Quero a maioria', emoji: '🎯', kit: 'Inicial' },
      { label: 'Competitivo', sub: 'Tenho de completar', emoji: '🔥', kit: 'Campeão' },
      { label: 'Lenda', sub: 'Coleção + duplicados', emoji: '👑', kit: 'Colecionador' },
    ],
  },
  {
    q: 'Vais ver quantos jogos do Mundial?',
    sub: 'Arrasta o slider',
    type: 'slider',
    min: 0, max: 64, default: 20,
    labels: ['0', 'só finais', 'metade', 'todos!'],
  },
  {
    q: 'Qual é o teu cromo dos sonhos?',
    sub: 'Toca no que te chama mais',
    type: 'cromo',
    options: [
      { team: 'POR', num: 7, name: 'Cristiano Ronaldo', pos: 'AVA', img: 'uploads/ronaldo-figurinha.webp', rare: true },
      { team: 'POR', num: 22, name: 'Diogo Costa', pos: 'GR', img: 'uploads/diogo-costa-figurinha.jpg' },
      { team: 'POR', num: 18, name: 'Rúben Neves', pos: 'MEI', img: 'uploads/ruben-neves-figurinha.jpg' },
      { team: 'POR', num: 17, name: 'Francisco Trincão', pos: 'AVA', img: 'uploads/francisco-trincao-figurinha.jpg' },
    ],
  },
];

function Quiz({ onComplete }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState([]);
  const [feedback, setFeedback] = React.useState(null); // {correct, points}
  const [sliderVal, setSliderVal] = React.useState(20);
  const [transitioning, setTransitioning] = React.useState(false);

  const Q = QUESTIONS[step];

  React.useEffect(() => {
    window.Sound?.playWhistle();
  }, []);

  const advance = (data) => {
    const next = [...answers, data];
    setAnswers(next);
    setTransitioning(true);
    setTimeout(() => {
      setFeedback(null);
      if (step + 1 >= QUESTIONS.length) {
        window.Sound?.playGoal();
        onComplete(next);
      } else {
        setStep(step + 1);
        setTransitioning(false);
      }
    }, 1100);
  };

  const onChoice = (opt) => {
    if (transitioning) return;
    const correct = opt.correct !== false;
    if (correct) window.Sound?.playGoal();
    else window.Sound?.playWrong();
    setFeedback({ correct, label: opt.label });
    advance({ q: step, choice: opt.label, correct, kit: opt.kit });
  };

  const onSlider = () => {
    window.Sound?.playWhistle();
    setFeedback({ correct: true, label: `${sliderVal} jogos` });
    setTransitioning(true);
    advance({ q: step, value: sliderVal });
  };

  return (
    <div style={{
      background: `linear-gradient(180deg, ${C.green} 0%, ${C.greenDeep} 100%)`,
      minHeight: '100vh', color: C.cream,
      position: 'relative', overflow: 'hidden',
    }}>
      {/* stadium stripes */}
      <div style={{
        position: 'absolute', inset: 0, opacity: 0.06,
        background: 'repeating-linear-gradient(90deg, transparent 0px, transparent 24px, #fff 24px, #fff 48px)',
        pointerEvents: 'none',
      }} />

      <div style={{ position: 'relative', padding: '14px 18px 24px' }}>
        {/* Top bar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <Logo size={16} light />
          <div style={{ flex: 1, height: 8, borderRadius: 999, background: 'rgba(255,255,255,0.18)', overflow: 'hidden' }}>
            <div style={{
              height: '100%', width: `${((step + (feedback ? 1 : 0)) / QUESTIONS.length) * 100}%`,
              background: `linear-gradient(90deg, ${C.gold}, ${C.red})`,
              transition: 'width 0.5s ease',
            }} />
          </div>
          <div style={{ fontFamily: '"Bebas Neue", sans-serif', fontSize: 14, color: C.gold }}>
            {step + 1}/{QUESTIONS.length}
          </div>
        </div>

        <div style={{
          background: 'rgba(255,255,255,0.06)', borderRadius: 8, padding: '6px 10px',
          fontSize: 11, letterSpacing: '0.08em', display: 'inline-block',
          color: C.gold, fontFamily: '"Bebas Neue", sans-serif', marginBottom: 8,
        }}>PERGUNTA {step + 1} · DESCONTO +{(step + 1) * 5}%</div>

        <div style={{
          fontFamily: '"Bebas Neue", "Arial Black", sans-serif',
          fontSize: 28, lineHeight: 1.08, marginBottom: 10,
        }}>{Q.q}</div>
        <div style={{ fontSize: 13, color: 'rgba(253,247,232,0.7)', marginBottom: 18, lineHeight: 1.35 }}>{Q.sub}</div>

        {/* Feedback flash */}
        {feedback && (
          <div style={{
            position: 'absolute', top: '40%', left: 0, right: 0,
            textAlign: 'center', zIndex: 10,
            animation: 'pop 1s ease',
          }}>
            <div style={{
              display: 'inline-block', padding: '18px 28px',
              background: feedback.correct ? C.gold : C.red,
              color: feedback.correct ? C.greenInk : '#fff',
              borderRadius: 20,
              fontFamily: '"Bebas Neue", sans-serif', fontSize: 36,
              letterSpacing: '0.04em',
              boxShadow: '0 12px 40px rgba(0,0,0,0.4)',
            }}>
              {feedback.correct ? '⚽ GOLO!' : 'PRÓXIMA!'}
              <div style={{ fontSize: 14, marginTop: 4, opacity: 0.85 }}>{feedback.label}</div>
            </div>
          </div>
        )}

        {/* Question content */}
        {Q.type === 'choice' && (
          <div style={{ display: 'grid', gap: 10, opacity: transitioning ? 0.3 : 1, transition: 'opacity 0.2s' }}>
            {Q.options.map((opt, i) => (
              <button key={i} onClick={() => onChoice(opt)} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '14px 16px', borderRadius: 14, border: 'none',
                background: 'rgba(255,255,255,0.1)',
                backdropFilter: 'blur(10px)',
                border: '1.5px solid rgba(255,255,255,0.18)',
                color: C.cream, fontSize: 16, textAlign: 'left',
                fontFamily: 'system-ui, sans-serif', fontWeight: 600,
                cursor: 'pointer', transition: 'all 0.15s',
              }}
              onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.97)'}
              onMouseUp={(e) => e.currentTarget.style.transform = ''}
              onMouseLeave={(e) => e.currentTarget.style.transform = ''}
              >
                {opt.emoji && <span style={{ fontSize: 24 }}>{opt.emoji}</span>}
                <span style={{ flex: 1 }}>{opt.label}</span>
                <span style={{ color: C.gold, fontSize: 22 }}>→</span>
              </button>
            ))}
          </div>
        )}

        {Q.type === 'persona' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, opacity: transitioning ? 0.3 : 1 }}>
            {Q.options.map((opt, i) => (
              <button key={i} onClick={() => onChoice(opt)} style={{
                padding: '16px 12px', borderRadius: 16, border: 'none',
                background: 'rgba(255,255,255,0.1)',
                border: '1.5px solid rgba(255,255,255,0.18)',
                color: C.cream, textAlign: 'center', cursor: 'pointer',
                transition: 'all 0.15s',
              }}
              onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.95)'}
              onMouseUp={(e) => e.currentTarget.style.transform = ''}
              onMouseLeave={(e) => e.currentTarget.style.transform = ''}
              >
                <div style={{ fontSize: 38, marginBottom: 6 }}>{opt.emoji}</div>
                <div style={{ fontFamily: '"Bebas Neue", sans-serif', fontSize: 22, letterSpacing: '0.04em' }}>{opt.label.toUpperCase()}</div>
                <div style={{ fontSize: 11, color: 'rgba(253,247,232,0.7)', marginTop: 2 }}>{opt.sub}</div>
              </button>
            ))}
          </div>
        )}

        {Q.type === 'slider' && (
          <div style={{
            background: 'rgba(255,255,255,0.08)', borderRadius: 20, padding: 20,
            border: '1.5px solid rgba(255,255,255,0.15)',
          }}>
            <div style={{
              textAlign: 'center',
              fontFamily: '"Bebas Neue", sans-serif', fontSize: 72,
              color: C.gold, lineHeight: 1, marginBottom: 4,
            }}>{sliderVal}</div>
            <div style={{ textAlign: 'center', fontSize: 13, color: 'rgba(253,247,232,0.7)', marginBottom: 18 }}>
              {sliderVal === 0 ? 'Vou estar a viver à parte 🙈'
                : sliderVal < 16 ? 'Os mais importantes'
                : sliderVal < 40 ? 'Dedicação séria 🎯'
                : sliderVal < 64 ? 'Fanático! 🔥' : 'TODOS? Lenda! 👑'}
            </div>
            <input type="range" min={Q.min} max={Q.max} value={sliderVal}
              onChange={(e) => { setSliderVal(+e.target.value); window.Sound?.playTick(); }}
              style={{
                width: '100%', accentColor: C.gold, height: 6,
              }}
            />
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'rgba(253,247,232,0.5)', marginTop: 6 }}>
              <span>0</span><span>16</span><span>32</span><span>48</span><span>64</span>
            </div>
            <div style={{ marginTop: 18 }}>
              <CTA color="gold" onClick={onSlider}>Confirmar →</CTA>
            </div>
          </div>
        )}

        {Q.type === 'cromo' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, justifyItems: 'center', opacity: transitioning ? 0.3 : 1 }}>
            {Q.options.map((opt, i) => (
              <button key={i} onClick={() => onChoice({ label: `${opt.team} #${opt.num}`, correct: true })}
                style={{
                  background: 'transparent', border: 'none', padding: 6,
                  cursor: 'pointer', borderRadius: 12, transition: 'transform 0.15s',
                }}
                onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.92)'}
                onMouseUp={(e) => e.currentTarget.style.transform = ''}
                onMouseLeave={(e) => e.currentTarget.style.transform = ''}
              >
                <Cromo {...opt} size={1.15} />
                <div style={{
                  marginTop: 8, fontFamily: '"Bebas Neue", sans-serif',
                  fontSize: 13, color: C.cream, letterSpacing: '0.06em',
                }}>{opt.team} · {opt.name.toUpperCase()}</div>
              </button>
            ))}
          </div>
        )}

        {/* Reward chip */}
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 20 }}>
          <div style={{
            fontSize: 11, color: 'rgba(253,247,232,0.6)',
            textAlign: 'center', maxWidth: 280,
          }}>
            Acumula <strong style={{ color: C.gold }}>+5% OFF</strong> a cada resposta · Até 35% no final
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Quiz, QUESTIONS });
