/**
 * quiz-core.js — 刮刮卡答题核心逻辑（纯函数，无 DOM / 无存储依赖）
 *
 * UMD 封装：
 *   - Node:   const QuizCore = require('./quiz-core.js')
 *   - 浏览器: <script src="quiz-core.js"></script> → window.QuizCore
 *
 * 计分规则：
 *   - 不作答（未选择选项就提交 / 从不提交）不计分
 *   - 每题只记第一次提交的结果，重复提交不重复加分
 */
(function (root, factory) {
  if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else {
    root.QuizCore = factory();
  }
})(typeof self !== 'undefined' ? self : this, function () {
  'use strict';

  var SESSION_VERSION = 1;

  function isInt(n) {
    return typeof n === 'number' && isFinite(n) && Math.floor(n) === n;
  }

  function clamp(n, min, max) {
    return Math.min(Math.max(n, min), max);
  }

  /**
   * 校验并规范化题目数组（不做任何内容改写，只校验结构）。
   */
  function normalizeQuestions(questions) {
    if (!Array.isArray(questions)) {
      throw new Error('questions 必须是数组');
    }
    if (questions.length === 0) {
      throw new Error('questions 不能为空');
    }
    var seen = {};
    return questions.map(function (q, i) {
      if (!q || typeof q !== 'object') {
        throw new Error('第 ' + (i + 1) + ' 题不是对象');
      }
      if (typeof q.id !== 'string' || !q.id) {
        throw new Error('第 ' + (i + 1) + ' 题缺少字符串 id');
      }
      if (seen[q.id]) {
        throw new Error('题目 id 重复: ' + q.id);
      }
      seen[q.id] = true;
      if (typeof q.question !== 'string' || !q.question) {
        throw new Error(q.id + ' 缺少题干');
      }
      if (!Array.isArray(q.options) || q.options.length < 2) {
        throw new Error(q.id + ' 的 options 至少需要 2 项');
      }
      for (var k = 0; k < q.options.length; k++) {
        if (typeof q.options[k] !== 'string') {
          throw new Error(q.id + ' 的第 ' + (k + 1) + ' 个选项必须是字符串');
        }
      }
      if (!isInt(q.answerIndex) || q.answerIndex < 0 || q.answerIndex >= q.options.length) {
        throw new Error(q.id + ' 的 answerIndex 越界');
      }
      return {
        id: q.id,
        question: q.question,
        options: q.options.slice(),
        answerIndex: q.answerIndex
      };
    });
  }

  function blankItem() {
    return {
      revealed: false,
      answered: false,
      selectedIndex: null,
      isCorrect: null
    };
  }

  /**
   * 创建全新会话（未揭示、未作答、停在第 1 题）。
   */
  function createSession(questions) {
    var qs = normalizeQuestions(questions);
    var items = {};
    var order = [];
    qs.forEach(function (q) {
      items[q.id] = blankItem();
      order.push(q.id);
    });
    return {
      version: SESSION_VERSION,
      currentIndex: 0,
      order: order,
      items: items
    };
  }

  /** 重新开始：等价于全新会话（进度清空由调用方负责删除持久化）。 */
  function resetSession(questions) {
    return createSession(questions);
  }

  function cloneSession(session) {
    var items = {};
    Object.keys(session.items).forEach(function (id) {
      var it = session.items[id] || blankItem();
      items[id] = {
        revealed: !!it.revealed,
        answered: !!it.answered,
        selectedIndex: isInt(it.selectedIndex) ? it.selectedIndex : null,
        isCorrect: typeof it.isCorrect === 'boolean' ? it.isCorrect : null
      };
    });
    return {
      version: SESSION_VERSION,
      currentIndex: session.currentIndex,
      order: session.order.slice(),
      items: items
    };
  }

  function indexOfId(session, id) {
    for (var i = 0; i < session.order.length; i++) {
      if (session.order[i] === id) return i;
    }
    return -1;
  }

  function questionById(questions, id) {
    for (var i = 0; i < questions.length; i++) {
      if (questions[i].id === id) return questions[i];
    }
    return null;
  }

  /**
   * 判分纯函数：给定题目与所选下标，返回是否正确。
   * 不修改任何入参。
   */
  function gradeAnswer(question, selectedIndex) {
    if (!question || !Array.isArray(question.options)) {
      throw new Error('question 非法');
    }
    var max = question.options.length;
    if (!isInt(selectedIndex) || selectedIndex < 0 || selectedIndex >= max) {
      return {
        ok: false,
        reason: 'invalid-selection',
        selectedIndex: selectedIndex,
        correctIndex: question.answerIndex,
        isCorrect: false
      };
    }
    return {
      ok: true,
      reason: null,
      selectedIndex: selectedIndex,
      correctIndex: question.answerIndex,
      isCorrect: selectedIndex === question.answerIndex
    };
  }

  /**
   * 揭晓某题（展示题干与选项）。幂等。
   * @returns {{session: object, changed: boolean}}
   */
  function revealQuestion(session, index) {
    var next = cloneSession(session);
    if (!isInt(index) || index < 0 || index >= next.order.length) {
      return { session: next, changed: false };
    }
    var id = next.order[index];
    if (next.items[id].revealed) {
      return { session: next, changed: false };
    }
    next.items[id].revealed = true;
    return { session: next, changed: true };
  }

  /**
   * 提交答案。计分只发生在第一次有效提交：
   *   - selectedIndex 为空 → 'no-selection'，不计分
   *   - 已提交过          → 'already-answered'，不重复计分（结果保持首次提交）
   *   - 首次有效提交      → 'scored'
   * @returns {{session: object, outcome: object}}
   */
  function submitAnswer(session, questions, index, selectedIndex) {
    var qs = normalizeQuestions(questions);
    var next = cloneSession(session);

    function outcome(status, extra) {
      var base = {
        status: status,
        index: index,
        selectedIndex: selectedIndex,
        correctIndex: null,
        isCorrect: null
      };
      if (extra) {
        Object.keys(extra).forEach(function (k) { base[k] = extra[k]; });
      }
      return { session: next, outcome: base };
    }

    if (!isInt(index) || index < 0 || index >= next.order.length) {
      return outcome('invalid-index');
    }

    var id = next.order[index];
    var item = next.items[id];
    var q = questionById(qs, id);

    if (item.answered) {
      // 重复提交：不重复加分，返回首次结果
      return outcome('already-answered', {
        correctIndex: q ? q.answerIndex : null,
        isCorrect: item.isCorrect,
        selectedIndex: item.selectedIndex
      });
    }

    if (selectedIndex === null || selectedIndex === undefined) {
      return outcome('no-selection');
    }

    var graded = gradeAnswer(q, selectedIndex);
    if (!graded.ok) {
      return outcome('invalid-selection', { correctIndex: q.answerIndex });
    }

    item.revealed = true;
    item.answered = true;
    item.selectedIndex = graded.selectedIndex;
    item.isCorrect = graded.isCorrect;

    return outcome('scored', {
      correctIndex: graded.correctIndex,
      isCorrect: graded.isCorrect
    });
  }

  /**
   * 移动到指定题（越界自动夹取）。
   */
  function moveTo(session, index) {
    var next = cloneSession(session);
    if (next.order.length === 0) return next;
    next.currentIndex = clamp(isInt(index) ? index : 0, 0, next.order.length - 1);
    return next;
  }

  /**
   * 相对移动（上一题 delta=-1 / 下一题 delta=+1，越界夹取）。
   */
  function moveBy(session, delta) {
    var d = isInt(delta) ? delta : 0;
    return moveTo(session, session.currentIndex + d);
  }

  /**
   * 计数：已答 / 答对 / 总题数。
   * 未作答不计入已答；重复提交不会让计数增加。
   */
  function getStats(session) {
    var answered = 0;
    var correct = 0;
    var total = session.order.length;
    session.order.forEach(function (id) {
      var it = session.items[id];
      if (it && it.answered) {
        answered += 1;
        if (it.isCorrect === true) correct += 1;
      }
    });
    return { answered: answered, correct: correct, total: total };
  }

  /**
   * 读取单题状态（只读视图）。
   */
  function getItem(session, index) {
    if (!isInt(index) || index < 0 || index >= session.order.length) return null;
    var id = session.order[index];
    var it = session.items[id] || blankItem();
    return {
      id: id,
      index: index,
      revealed: !!it.revealed,
      answered: !!it.answered,
      selectedIndex: isInt(it.selectedIndex) ? it.selectedIndex : null,
      isCorrect: typeof it.isCorrect === 'boolean' ? it.isCorrect : null
    };
  }

  /**
   * 序列化为可 JSON 化的纯对象（用于进度持久化）。
   */
  function serializeSession(session) {
    return cloneSession(session);
  }

  /**
   * 从持久化数据还原会话；任何不一致都会被安全修正，
   * isCorrect 一律用 answerIndex 重算，避免脏数据伪造对错。
   */
  function deserializeSession(raw, questions) {
    var qs = normalizeQuestions(questions);
    if (!raw || typeof raw !== 'object') {
      throw new Error('进度数据非法');
    }
    if (raw.version !== SESSION_VERSION) {
      throw new Error('进度版本不兼容: ' + raw.version);
    }
    var session = createSession(qs);
    if (raw.items && typeof raw.items === 'object') {
      qs.forEach(function (q) {
        var it = raw.items[q.id];
        if (!it || typeof it !== 'object') return;
        session.items[q.id].revealed = !!it.revealed;
        if (it.answered) {
          var sel = it.selectedIndex;
          if (isInt(sel) && sel >= 0 && sel < q.options.length) {
            session.items[q.id].answered = true;
            session.items[q.id].selectedIndex = sel;
            session.items[q.id].isCorrect = sel === q.answerIndex;
            session.items[q.id].revealed = true;
          }
        }
      });
    }
    session.currentIndex = clamp(
      isInt(raw.currentIndex) ? raw.currentIndex : 0,
      0,
      qs.length - 1
    );
    return session;
  }

  return {
    SESSION_VERSION: SESSION_VERSION,
    normalizeQuestions: normalizeQuestions,
    createSession: createSession,
    resetSession: resetSession,
    gradeAnswer: gradeAnswer,
    revealQuestion: revealQuestion,
    submitAnswer: submitAnswer,
    moveTo: moveTo,
    moveBy: moveBy,
    getStats: getStats,
    getItem: getItem,
    serializeSession: serializeSession,
    deserializeSession: deserializeSession
  };
});
