/**
 * app.js — 刮刮卡答题页面交互层（依赖 questions.js / quiz-core.js，无外部依赖）
 * 计分与状态规则全部走 quiz-core.js 纯函数；本文件只负责渲染、刮开手势与持久化。
 */
(function () {
  'use strict';

  var STORAGE_KEY = 'cyberfete-w17-scratch-quiz-progress-v1';
  var SCRATCH_DONE_RATIO = 0.42;   // 刮开面积达到该比例后自动揭晓
  var SCRATCH_RADIUS = 22;          // 刮开笔刷半径（CSS px）

  var data = window.QUIZ_DATA || { title: '刮开一点好奇心', description: '', questions: [] };
  var questions = data.questions || [];
  var Core = window.QuizCore;

  if (!Core || !questions.length) {
    document.body.innerHTML = '<p style="padding:2rem;font-family:sans-serif">题库或核心脚本未加载，请确认 questions.js / quiz-core.js 与 index.html 在同一目录。</p>';
    return;
  }

  /* ---------- DOM ---------- */
  var el = {
    title: document.getElementById('app-title'),
    desc: document.getElementById('app-desc'),
    statAnswered: document.getElementById('stat-answered'),
    statCorrect: document.getElementById('stat-correct'),
    btnPrev: document.getElementById('btn-prev'),
    btnNext: document.getElementById('btn-next'),
    btnReveal: document.getElementById('btn-reveal'),
    btnRestart: document.getElementById('btn-restart'),
    btnSubmit: document.getElementById('btn-submit'),
    saveHint: document.getElementById('save-hint'),
    qid: document.getElementById('q-id'),
    counter: document.getElementById('q-counter'),
    scratchWrap: document.getElementById('scratch-wrap'),
    canvas: document.getElementById('scratch-canvas'),
    quizPanel: document.getElementById('quiz-panel'),
    questionText: document.getElementById('question-text'),
    optionsBox: document.getElementById('options-box'),
    form: document.getElementById('answer-form'),
    feedback: document.getElementById('feedback')
  };

  if (data.title) el.title.textContent = data.title;
  if (data.description) el.desc.textContent = data.description;

  /* ---------- 会话状态（含进度恢复） ---------- */
  var storageOK = true;
  var session;

  function loadSession() {
    try {
      var raw = window.localStorage.getItem(STORAGE_KEY);
      if (!raw) return Core.createSession(questions);
      return Core.deserializeSession(JSON.parse(raw), questions);
    } catch (err) {
      return Core.createSession(questions);
    }
  }

  function saveSession() {
    if (!storageOK) return;
    try {
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(Core.serializeSession(session)));
      flashSave('✓ 进度已保存');
    } catch (err) {
      storageOK = false;
      flashSave('无法保存进度（浏览器限制），关闭页面后将丢失');
    }
  }

  function clearSaved() {
    try {
      window.localStorage.removeItem(STORAGE_KEY);
    } catch (err) { /* ignore */ }
  }

  var saveTimer = null;
  function flashSave(msg) {
    el.saveHint.textContent = msg;
    el.saveHint.classList.add('show');
    if (saveTimer) window.clearTimeout(saveTimer);
    saveTimer = window.setTimeout(function () {
      el.saveHint.classList.remove('show');
    }, 1600);
  }

  session = loadSession();

  /* ---------- 渲染 ---------- */
  var OPTION_KEYS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];

  function currentQuestion() {
    return questions[session.currentIndex];
  }

  function currentItem() {
    return Core.getItem(session, session.currentIndex);
  }

  function render() {
    var q = currentQuestion();
    var item = currentItem();
    var total = questions.length;

    el.qid.textContent = q.id;
    el.counter.textContent = '第 ' + (session.currentIndex + 1) + ' / ' + total + ' 题';

    var stats = Core.getStats(session);
    el.statAnswered.textContent = stats.answered + '/' + stats.total;
    el.statCorrect.textContent = String(stats.correct);

    el.btnPrev.disabled = session.currentIndex <= 0;
    el.btnNext.disabled = session.currentIndex >= total - 1;

    if (!item.revealed) {
      el.quizPanel.hidden = true;
      el.scratchWrap.hidden = false;
      el.btnReveal.disabled = false;
      paintCoating();
    } else {
      el.scratchWrap.hidden = true;
      el.quizPanel.hidden = false;
      renderQuestion(q, item);
    }
  }

  function renderQuestion(q, item) {
    el.questionText.textContent = q.question;

    el.optionsBox.innerHTML = '';
    var legend = document.createElement('legend');
    legend.className = 'sr-only';
    legend.textContent = '请选择一个答案';
    el.optionsBox.appendChild(legend);

    q.options.forEach(function (text, i) {
      var label = document.createElement('label');
      label.className = 'option';

      var input = document.createElement('input');
      input.type = 'radio';
      input.name = 'opt';
      input.value = String(i);
      if (item.answered) {
        input.disabled = true;
        input.checked = item.selectedIndex === i;
      }

      var body = document.createElement('span');
      body.className = 'opt-body';

      var key = document.createElement('span');
      key.className = 'opt-key';
      key.textContent = OPTION_KEYS[i] || String(i + 1);

      var span = document.createElement('span');
      span.className = 'opt-text';
      span.textContent = text;

      body.appendChild(key);
      body.appendChild(span);
      label.appendChild(input);
      label.appendChild(body);

      if (item.answered) {
        if (i === q.answerIndex) {
          label.classList.add('is-correct');
        } else if (item.selectedIndex === i) {
          label.classList.add('is-wrong');
        }
      }

      el.optionsBox.appendChild(label);
    });

    if (item.answered) {
      el.btnSubmit.disabled = true;
      el.btnSubmit.textContent = '已提交';
      renderFeedback(q, item, 'result');
    } else {
      el.btnSubmit.disabled = false;
      el.btnSubmit.textContent = '提交答案';
      el.feedback.textContent = '';
      el.feedback.className = 'feedback';
    }
  }

  function renderFeedback(q, item, mode) {
    var correctKey = (OPTION_KEYS[q.answerIndex] || String(q.answerIndex + 1));
    var correctText = q.options[q.answerIndex];

    if (mode === 'warn') {
      el.feedback.className = 'feedback is-warn';
      el.feedback.textContent = '请先选择一个选项再提交（不作答不计分）。';
      return;
    }
    if (mode === 'already') {
      el.feedback.className = 'feedback is-muted';
      el.feedback.textContent = '本题已提交过，不重复计分。' +
        (item.isCorrect ? '回答正确。' : '正确答案是 ' + correctKey + '．' + correctText);
      return;
    }
    if (item.isCorrect) {
      el.feedback.className = 'feedback is-ok';
      el.feedback.textContent = '回答正确！答案是 ' + correctKey + '．' + correctText;
    } else {
      el.feedback.className = 'feedback is-bad';
      var pickedKey = item.selectedIndex === null ? '—' : (OPTION_KEYS[item.selectedIndex] || String(item.selectedIndex + 1));
      el.feedback.textContent = '回答错误（你选了 ' + pickedKey + '）。正确答案是 ' + correctKey + '．' + correctText;
    }
  }

  /* ---------- 刮刮涂层绘制 ---------- */
  var ctx = null;
  var scratching = false;
  var lastPoint = null;
  var strokeCount = 0;

  function paintCoating() {
    var wrap = el.scratchWrap;
    if (wrap.hidden) return;

    var rect = wrap.getBoundingClientRect();
    var w = Math.max(1, Math.round(rect.width));
    var h = Math.max(1, Math.round(rect.height || 152));
    var dpr = window.devicePixelRatio || 1;

    el.canvas.width = Math.round(w * dpr);
    el.canvas.height = Math.round(h * dpr);
    el.canvas.style.width = w + 'px';
    el.canvas.style.height = h + 'px';

    ctx = el.canvas.getContext('2d');
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

    var grad = ctx.createLinearGradient(0, 0, w, h);
    grad.addColorStop(0, '#c7ccd6');
    grad.addColorStop(0.45, '#e9e2cf');
    grad.addColorStop(1, '#b6bcc7');
    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, w, h);

    ctx.save();
    ctx.globalAlpha = 0.14;
    ctx.strokeStyle = '#4b5563';
    ctx.lineWidth = 11;
    for (var x = -h; x < w + h; x += 26) {
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x + h, h);
      ctx.stroke();
    }
    ctx.restore();

    for (var i = 0; i < 160; i++) {
      var rx = Math.random() * w;
      var ry = Math.random() * h;
      var rr = Math.random() * 1.9 + 0.35;
      ctx.fillStyle = 'rgba(255,255,255,' + (0.12 + Math.random() * 0.55) + ')';
      ctx.beginPath();
      ctx.arc(rx, ry, rr, 0, Math.PI * 2);
      ctx.fill();
    }

    var fontFamily = '-apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = 'rgba(58, 52, 40, 0.62)';
    ctx.font = '700 17px ' + fontFamily;
    ctx.fillText('✨ 刮开涂层查看题目 ✨', w / 2, h / 2 - 12);
    ctx.font = '12px ' + fontFamily;
    ctx.fillStyle = 'rgba(58, 52, 40, 0.5)';
    ctx.fillText('支持鼠标 / 触摸刮开，也可点「揭晓题目」按钮', w / 2, h / 2 + 14);
  }

  function canvasPoint(evt) {
    var rect = el.canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
  }

  function scratchTo(pt) {
    if (!ctx) return;
    ctx.globalCompositeOperation = 'destination-out';
    ctx.lineWidth = SCRATCH_RADIUS * 2;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    ctx.beginPath();
    if (lastPoint) {
      ctx.moveTo(lastPoint.x, lastPoint.y);
      ctx.lineTo(pt.x, pt.y);
      ctx.stroke();
    } else {
      ctx.arc(pt.x, pt.y, SCRATCH_RADIUS, 0, Math.PI * 2);
      ctx.fill();
    }
    lastPoint = pt;
  }

  function scratchRatio() {
    if (!ctx) return 0;
    var w = el.canvas.width;
    var h = el.canvas.height;
    if (!w || !h) return 0;
    var img;
    try {
      img = ctx.getImageData(0, 0, w, h).data;
    } catch (err) {
      return 0;
    }
    var clear = 0;
    var total = 0;
    var step = 4 * 16; // 抽样
    for (var i = 3; i < img.length; i += step) {
      total += 1;
      if (img[i] < 128) clear += 1;
    }
    return total ? clear / total : 0;
  }

  function onPointerDown(evt) {
    if (currentItem().revealed) return;
    scratching = true;
    lastPoint = null;
    strokeCount = 0;
    if (el.canvas.setPointerCapture && evt.pointerId !== undefined) {
      try { el.canvas.setPointerCapture(evt.pointerId); } catch (err) { /* ignore */ }
    }
    scratchTo(canvasPoint(evt));
    evt.preventDefault();
  }

  function onPointerMove(evt) {
    if (!scratching || currentItem().revealed) return;
    scratchTo(canvasPoint(evt));
    strokeCount += 1;
    if (strokeCount % 8 === 0 && scratchRatio() >= SCRATCH_DONE_RATIO) {
      scratching = false;
      lastPoint = null;
      revealCurrent(false);
    }
    evt.preventDefault();
  }

  function onPointerUp() {
    if (!scratching) return;
    scratching = false;
    lastPoint = null;
    if (!currentItem().revealed && scratchRatio() >= SCRATCH_DONE_RATIO) {
      revealCurrent(false);
    }
  }

  el.canvas.addEventListener('pointerdown', onPointerDown);
  el.canvas.addEventListener('pointermove', onPointerMove);
  el.canvas.addEventListener('pointerup', onPointerUp);
  el.canvas.addEventListener('pointercancel', onPointerUp);
  el.canvas.addEventListener('pointerleave', onPointerUp);
  // 兼容不支持 Pointer Events 的老浏览器
  if (!window.PointerEvent) {
    el.canvas.addEventListener('mousedown', function (e) {
      onPointerDown({ clientX: e.clientX, clientY: e.clientY, preventDefault: function () { e.preventDefault(); } });
    });
    el.canvas.addEventListener('mousemove', function (e) {
      onPointerMove({ clientX: e.clientX, clientY: e.clientY, preventDefault: function () { e.preventDefault(); } });
    });
    el.canvas.addEventListener('mouseup', onPointerUp);
    el.canvas.addEventListener('touchstart', function (e) {
      var t = e.touches[0];
      onPointerDown({ clientX: t.clientX, clientY: t.clientY, preventDefault: function () { e.preventDefault(); } });
    }, { passive: false });
    el.canvas.addEventListener('touchmove', function (e) {
      var t = e.touches[0];
      onPointerMove({ clientX: t.clientX, clientY: t.clientY, preventDefault: function () { e.preventDefault(); } });
    }, { passive: false });
    el.canvas.addEventListener('touchend', onPointerUp);
    el.canvas.addEventListener('touchcancel', onPointerUp);
  }

  /* ---------- 揭晓 / 提交 / 导航 ---------- */
  function revealCurrent(moveFocus) {
    var res = Core.revealQuestion(session, session.currentIndex);
    session = res.session;
    if (res.changed) saveSession();
    render();
    if (moveFocus) {
      el.questionText.focus();
    }
  }

  el.btnReveal.addEventListener('click', function () {
    revealCurrent(true);
  });

  el.form.addEventListener('submit', function (evt) {
    evt.preventDefault();
    var checked = el.optionsBox.querySelector('input[name="opt"]:checked');
    var idx = checked ? parseInt(checked.value, 10) : null;
    var res = Core.submitAnswer(session, questions, session.currentIndex, idx);

    if (res.outcome.status === 'no-selection') {
      renderFeedback(currentQuestion(), currentItem(), 'warn');
      return;
    }

    var wasAlready = res.outcome.status === 'already-answered';
    session = res.session;
    saveSession();
    render();
    if (wasAlready) {
      renderFeedback(currentQuestion(), currentItem(), 'already');
    }
  });

  el.btnPrev.addEventListener('click', function () {
    session = Core.moveBy(session, -1);
    render();
  });

  el.btnNext.addEventListener('click', function () {
    session = Core.moveBy(session, 1);
    render();
  });

  el.btnRestart.addEventListener('click', function () {
    if (!window.confirm('重新开始将清除本轮全部进度（已答 / 答对 / 揭晓状态），确定吗？')) return;
    session = Core.resetSession(questions);
    clearSaved();
    render();
    flashSave('已重新开始，进度已清除');
  });

  /* ---------- 键盘快捷键（增强，不替代原生按钮可达性） ---------- */
  document.addEventListener('keydown', function (evt) {
    if (evt.altKey || evt.ctrlKey || evt.metaKey) return;
    var tag = (evt.target && evt.target.tagName) || '';
    if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
    if (evt.key === 'ArrowLeft') {
      session = Core.moveBy(session, -1);
      render();
    } else if (evt.key === 'ArrowRight') {
      session = Core.moveBy(session, 1);
      render();
    }
  });

  /* ---------- 尺寸变化：仅在仍需刮开时重绘涂层 ---------- */
  var resizeTimer = null;
  window.addEventListener('resize', function () {
    if (resizeTimer) window.clearTimeout(resizeTimer);
    resizeTimer = window.setTimeout(function () {
      if (!currentItem().revealed) paintCoating();
    }, 160);
  });

  /* ---------- 启动 ---------- */
  render();
})();
