/* ============================================================
   INDIC LEAGUE NEWS — Political Spectrum Quiz
   10 questions, 4 options, mean → score → label.
   Per plan §3.10. State NOT persisted mid-quiz (by design).
   ============================================================ */

function Quiz({ onComplete, onCancel }) {
  const [idx, setIdx] = React.useState(0);
  const [answers, setAnswers] = React.useState({}); // { questionIdx: score }
  const [done, setDone] = React.useState(false);

  const Q = window.IL_QUIZ;
  const total = Q.length;
  const current = Q[idx];

  const pick = (score) => {
    window.IL_Sounds && window.IL_Sounds.pick();
    window.IL_Util && window.IL_Util.Haptics.pick();
    setAnswers(prev => ({ ...prev, [idx]: score }));
    if (idx + 1 < total) {
      setTimeout(() => setIdx(idx + 1), 220);
    } else {
      setTimeout(() => {
        window.IL_Sounds && window.IL_Sounds.success();
        window.IL_Util && window.IL_Util.Haptics.success();
        setDone(true);
      }, 220);
    }
  };

  const goPrev = () => {
    if (idx === 0) {
      onCancel && onCancel();
      return;
    }
    window.IL_Sounds && window.IL_Sounds.tap();
    setIdx(idx - 1);
  };

  // RESULT screen
  if (done) {
    const scores = Object.values(answers);
    const raw = scores.reduce((a, b) => a + b, 0) / scores.length;
    const position = window.IL_Util.clamp(raw, -1, 1);
    const label = window.IL_LABEL_FROM_SCORE(position);
    // Marker position on 0–100% based on -1..+1
    const markerPct = ((position + 1) / 2) * 100;

    // Find closest option ID so onboarding can pre-fill
    const closest = window.IL_POLITICAL_OPTIONS
      .map(o => ({ id: o.id, dist: Math.abs(o.position - position) }))
      .sort((a, b) => a.dist - b.dist)[0];

    return (
      <div className="screen">
        <div className="quiz-result">
          <div className="quiz-result-confetti">All set</div>
          <div className="quiz-result-heading">Your political position</div>
          <div className="quiz-result-label">{label}</div>

          <div className="spectrum-bar">
            <div
              className="spectrum-marker"
              style={{ left: `${markerPct}%` }}
            />
          </div>
          <div className="spectrum-labels">
            <span>Left</span>
            <span>Centre</span>
            <span>Right</span>
          </div>

          <p className="quiz-result-body">
            This shapes how we balance your feed — not who you are. You can adjust the diversity dial anytime.
          </p>

          <div style={{ width: '100%', maxWidth: 360, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <button
              className="btn"
              onClick={() => {
                onComplete && onComplete({
                  position,
                  label,
                  optionId: closest.id,
                  method: 'quiz',
                });
              }}
            >
              Apply to my feed
              <Icon name="arrow-right" size={18} stroke={2.2} color="#fff" />
            </button>
            <button
              className="btn btn-secondary"
              onClick={() => {
                window.IL_Sounds && window.IL_Sounds.tap();
                setAnswers({});
                setIdx(0);
                setDone(false);
              }}
            >
              Retake quiz
            </button>
          </div>
        </div>
      </div>
    );
  }

  // QUESTION screen
  const progress = ((idx) / total) * 100;
  const picked = answers[idx];

  return (
    <div className="screen">
      <div className="quiz-screen">
        <div className="quiz-top">
          <button aria-label="Back" onClick={goPrev}>
            <Icon name="chevron-left" size={18} stroke={2} />
          </button>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 }}>
            Political Quiz
          </div>
          <span className="quiz-counter">{idx + 1} / {total}</span>
        </div>

        <div className="quiz-progress">
          <div className="quiz-progress-fill" style={{ width: `${progress + (100 / total)}%` }} />
        </div>

        <h2 className="quiz-question">{current.q}</h2>

        <div className="quiz-options">
          {current.options.map((opt, i) => (
            <button
              key={i}
              className={'quiz-option' + (picked === opt.score ? ' picked' : '')}
              onClick={() => pick(opt.score)}
            >
              {opt.text}
            </button>
          ))}
        </div>

        {idx > 0 && (
          <a
            href="#"
            className="quiz-back-link"
            onClick={(e) => { e.preventDefault(); goPrev(); }}
          >
            ← Previous
          </a>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Quiz });
