// ═══════════════════════════════════════════════════════════════════
//  QUIZ  v1.0.0
//  Questions loaded from php/quiz.php
// ═══════════════════════════════════════════════════════════════════

let QUESTIONS  = [];
let qIdx       = 0;
let qScore     = 0;
let qTotal     = 0;
let qAnswered  = false;
let qLoaded    = false;

// ── load questions from server ────────────────────────────────────
function loadQuestions() {
  return fetch('php/quiz.php')
    .then(r => {
      if (!r.ok) throw new Error('HTTP ' + r.status);
      return r.json();
    })
    .then(data => {
      QUESTIONS = data.questions;
      qLoaded   = true;
      console.log('Quiz: loaded', QUESTIONS.length, 'questions');
    })
    .catch(err => {
      console.error('Quiz load failed:', err);
      QUESTIONS = [];
      qLoaded   = false;
    });
}

// ── open quiz ─────────────────────────────────────────────────────
function openQuiz() {
  qIdx      = 0;
  qScore    = 0;
  qTotal    = 0;
  qAnswered = false;

  document.getElementById('qoverlay').classList.add('show');

  if (qLoaded && QUESTIONS.length > 0) {
    loadQuestion();
  } else {
    // show loading state
    document.getElementById('qq').textContent    = 'Loading questions…';
    document.getElementById('qopts').innerHTML   = '';
    document.getElementById('qsub').textContent  = '';
    document.getElementById('qscore').textContent = 'Score: 0 / 0';

    loadQuestions().then(() => {
      if (QUESTIONS.length > 0) {
        loadQuestion();
      } else {
        document.getElementById('qq').textContent = '⚠ Could not load questions.';
      }
    });
  }
}

// ── close quiz ────────────────────────────────────────────────────
function closeQuiz() {
  document.getElementById('qoverlay').classList.remove('show');
  // restore cube cuts that were there before quiz
  render();
}

// ── draw quiz preview ─────────────────────────────────────────────
function drawQuizPreview(setup) {
  const qcv  = document.getElementById('qcv');
  const qctx = qcv.getContext('2d');
  const W    = qcv.width;
  const H    = qcv.height;

  // save main canvas state
  const savedCuts = ST.cuts.map(c => ({
    ...c,
    cutFaces: c.cutFaces.map(f => f.map(v => [...v]))
  }));
  const savedZoom = ST.zoom;
  const savedRx   = ST.rx;
  const savedRy   = ST.ry;
  const savedW    = cv.width;
  const savedH    = cv.height;

  // set up preview
  if (setup === null) {
    ST.cuts = [];
  } else if (setup.snapId === 'all') {
    // all 8 corners
    ST.cuts = [0,1,2,3,4,5,6,7]
      .map(i => buildCut('corner', i))
      .filter(Boolean);
  } else {
    const cut = buildCut(setup.type, setup.snapId);
    ST.cuts   = cut ? [cut] : [];
  }

  ST.zoom   = 58;
  ST.ry     = 45  * Math.PI / 180;
  ST.rx     = 35  * Math.PI / 180;
  cv.width  = W;
  cv.height = H;

  render();

  // copy to quiz canvas
  qctx.clearRect(0, 0, W, H);
  qctx.drawImage(cv, 0, 0);

  // restore everything
  cv.width  = savedW;
  cv.height = savedH;
  ST.cuts   = savedCuts;
  ST.zoom   = savedZoom;
  ST.rx     = savedRx;
  ST.ry     = savedRy;
  render();
}

// ── load a question ───────────────────────────────────────────────
function loadQuestion() {
  if (!QUESTIONS.length) return;

  qAnswered = false;
  const q   = QUESTIONS[qIdx];

  document.getElementById('qsub').textContent =
    `Question ${qIdx + 1} of ${QUESTIONS.length}`;
  document.getElementById('qq').textContent = q.q;

  // reset feedback
  const fb    = document.getElementById('qfeedback');
  fb.className   = 'qfeedback';
  fb.textContent = '';

  // hide next button
  document.getElementById('nextBtn').style.display = 'none';

  // draw preview
  drawQuizPreview(q.setup);

  // build option buttons
  const optsEl = document.getElementById('qopts');
  optsEl.innerHTML = '';
  q.opts.forEach((opt, i) => {
    const btn       = document.createElement('button');
    btn.className   = 'qopt';
    btn.textContent = opt;
    btn.onclick     = () => answerQuestion(i, q.ans, q.explain);
    optsEl.appendChild(btn);
  });

  updateQuizScore();
}

// ── answer a question ─────────────────────────────────────────────
function answerQuestion(selected, correct, explain) {
  if (qAnswered) return;
  qAnswered = true;
  qTotal++;
  if (selected === correct) qScore++;

  // mark buttons
  document.querySelectorAll('.qopt').forEach((btn, i) => {
    btn.disabled = true;
    if (i === correct)                   btn.classList.add('correct');
    if (i === selected && i !== correct) btn.classList.add('wrong');
  });

  // show feedback
  const fb       = document.getElementById('qfeedback');
  const correct_ = selected === correct;
  fb.textContent = (correct_ ? '✓ Correct! — ' : '✗ Wrong — ') + explain;
  fb.className   = 'qfeedback show ' + (correct_ ? 'ok' : 'bad');

  // show next button
  document.getElementById('nextBtn').style.display = 'inline-block';

  updateQuizScore();
}

// ── next question ─────────────────────────────────────────────────
function nextQ() {
  qIdx = (qIdx + 1) % QUESTIONS.length;
  loadQuestion();
}

// ── update score display ──────────────────────────────────────────
function updateQuizScore() {
  document.getElementById('qscore').textContent =
    `Score: ${qScore} / ${qTotal}`;
}