/*!
 * checkin-core.js — W28 离线签到台核心逻辑（UMD，浏览器 / Node 双端可用）
 * 数据为合成练习数据，不收集任何真人数据。
 * 依赖：无（纯 JavaScript）。
 */
(function (root, factory) {
  'use strict';
  if (typeof module === 'object' && typeof module.exports === 'object') {
    module.exports = factory();
  } else {
    root.CheckinCore = factory();
  }
})(typeof self !== 'undefined' ? self : this, function () {
  'use strict';

  var STORAGE_KEY = 'W28-checkin-state-v1';

  /** 默认存储适配器：浏览器用 localStorage；Node/无 localStorage 时退化为内存。 */
  function defaultStorage() {
    try {
      if (typeof window !== 'undefined' && window.localStorage) return window.localStorage;
    } catch (e) { /* 隐私模式等场景下访问 localStorage 可能抛错 */ }
    var mem = {};
    return {
      getItem: function (k) { return Object.prototype.hasOwnProperty.call(mem, k) ? mem[k] : null; },
      setItem: function (k, v) { mem[k] = String(v); },
      removeItem: function (k) { delete mem[k]; }
    };
  }

  /** 报名码规范化：去首尾空白、去内部空白、转大写。 */
  function normalizeCode(raw) {
    if (raw === null || raw === undefined) return '';
    return String(raw).replace(/\s+/g, '').toUpperCase();
  }

  /** 本地时间格式化：YYYY-MM-DD HH:mm:ss */
  function formatTime(d) {
    function p(n) { return (n < 10 ? '0' : '') + n; }
    return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) +
      ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds());
  }

  function clone(o) { return JSON.parse(JSON.stringify(o)); }

  /** CSV 字段转义：含引号/逗号/换行时用双引号包裹，内部引号翻倍。 */
  function csvEscape(s) {
    s = String(s);
    if (/[",\n\r]/.test(s)) return '"' + s.replace(/"/g, '""') + '"';
    return s;
  }

  /**
   * 创建签到台应用。
   * @param {Object} spec 题目规格（event + attendees[]，含 id/name/seat/code）
   * @param {Object} [storage] 存储适配器 {getItem,setItem,removeItem}
   * @param {Object} [opts] { now: function 返回 Date }（测试可注入固定时钟）
   */
  function createApp(spec, storage, opts) {
    storage = storage || defaultStorage();
    opts = opts || {};
    var nowFn = typeof opts.now === 'function' ? opts.now : function () { return new Date(); };

    // 参会者索引：报名码 -> 记录（报名码规范化后唯一）
    var byCode = {};
    var byId = {};
    (spec.attendees || []).forEach(function (a) {
      if (!a || !a.code) return;
      var rec = {
        id: a.id,
        name: a.name,
        seat: a.seat,
        code: normalizeCode(a.code)
      };
      byCode[rec.code] = rec;
      byId[rec.id] = rec;
    });

    /** 内部状态：checkedIn[attendeeId] = { time, method }；保持签到顺序 log 数组。 */
    var state = { version: 1, checkedIn: {}, log: [] };

    function persist() {
      try { storage.setItem(STORAGE_KEY, JSON.stringify(state)); } catch (e) { /* 存储失败不阻塞签到 */ }
    }

    function restore() {
      var raw = null;
      try { raw = storage.getItem(STORAGE_KEY); } catch (e) { raw = null; }
      state = { version: 1, checkedIn: {}, log: [] };
      if (!raw) return false;
      try {
        var parsed = JSON.parse(raw);
        if (parsed && parsed.version === 1) {
          // 只接受属于本活动名册的记录（防止脏数据混入）
          Object.keys(parsed.checkedIn || {}).forEach(function (id) {
            if (byId[id]) state.checkedIn[id] = parsed.checkedIn[id];
          });
          (parsed.log || []).forEach(function (entry) {
            if (entry && byId[entry.id]) state.log.push(entry);
          });
          return true;
        }
      } catch (e) { /* 解析失败按无历史处理 */ }
      return false;
    }

    restore(); // 创建即恢复 localStorage 中的历史进度

    /**
     * 签到（幂等）。
     * @returns {Object}
     *   status: 'ok'        — 签到成功
     *           'duplicate' — 重复签到（状态不变，附首次签到时间）
     *           'unknown'   — 未知报名码，拒绝
     */
    function checkIn(rawCode, method) {
      var code = normalizeCode(rawCode);
      var attendee = byCode[code];
      if (!attendee) {
        return { status: 'unknown', code: code, message: '未知报名码，已拒绝' };
      }
      if (state.checkedIn[attendee.id]) {
        return {
          status: 'duplicate',
          attendee: clone(attendee),
          firstTime: state.checkedIn[attendee.id].time,
          message: attendee.name + ' 已签到（' + state.checkedIn[attendee.id].time + '），不重复记录'
        };
      }
      var time = formatTime(nowFn());
      state.checkedIn[attendee.id] = { time: time, method: method || '手动输入' };
      state.log.push({ id: attendee.id, time: time, method: method || '手动输入' });
      persist();
      return {
        status: 'ok',
        attendee: clone(attendee),
        time: time,
        message: attendee.name + ' 签到成功，座位 ' + attendee.seat
      };
    }

    /**
     * 撤销指定人的签到（可传编号 id、报名码或姓名）。
     */
    function undo(idOrCodeOrName) {
      var key = normalizeCode(idOrCodeOrName);
      var attendee = byCode[key] || byId[key];
      if (!attendee) {
        attendee = null;
        for (var id in byId) {
          if (byId[id].name === String(idOrCodeOrName)) { attendee = byId[id]; break; }
        }
      }
      if (!attendee) return { status: 'unknown', message: '未找到该参会者' };
      if (!state.checkedIn[attendee.id]) {
        return { status: 'not-checked-in', attendee: clone(attendee), message: attendee.name + ' 本来就未签到' };
      }
      delete state.checkedIn[attendee.id];
      state.log = state.log.filter(function (e) { return e.id !== attendee.id; });
      persist();
      return { status: 'ok', attendee: clone(attendee), message: '已撤销 ' + attendee.name + ' 的签到' };
    }

    /** 清空全部签到进度（UI 层应在确认后调用）。 */
    function reset() {
      state = { version: 1, checkedIn: {}, log: [] };
      try { storage.removeItem(STORAGE_KEY); } catch (e) { /* 忽略 */ }
      persist();
    }

    /** 按名册顺序返回全部参会者及签到状态。 */
    function listAll() {
      return (spec.attendees || []).map(function (a) {
        var rec = byId[a.id];
        var ci = state.checkedIn[a.id];
        return {
          id: rec.id, name: rec.name, seat: rec.seat, code: rec.code,
          checkedIn: !!ci,
          time: ci ? ci.time : null,
          method: ci ? ci.method : null
        };
      });
    }

    /** 查询（报名码/编号）→ 参会者（含座位匹配信息），未知返回 null。 */
    function find(codeOrId) {
      var key = normalizeCode(codeOrId);
      var rec = byCode[key] || byId[key];
      return rec ? clone(rec) : null;
    }

    /** 导出 CSV（含 UTF-8 BOM，便于 Excel 直接打开）。 */
    function exportCSV() {
      var rows = [['编号', '姓名', '座位', '报名码', '状态', '签到时间', '签到方式']];
      listAll().forEach(function (a) {
        rows.push([a.id, a.name, a.seat, a.code,
          a.checkedIn ? '已签到' : '未签到',
          a.time || '', a.method || '']);
      });
      return '\uFEFF' + rows.map(function (r) { return r.map(csvEscape).join(','); }).join('\r\n');
    }

    /** 导出 JSON。 */
    function exportJSON() {
      return JSON.stringify({
        event: spec.event || '',
        exportedAt: formatTime(nowFn()),
        total: (spec.attendees || []).length,
        checkedInCount: countCheckedIn(),
        attendees: listAll()
      }, null, 2);
    }

    function countCheckedIn() { return Object.keys(state.checkedIn).length; }

    return {
      normalizeCode: normalizeCode,
      checkIn: checkIn,
      undo: undo,
      reset: reset,
      find: find,
      listAll: listAll,
      exportCSV: exportCSV,
      exportJSON: exportJSON,
      countCheckedIn: countCheckedIn,
      restore: restore,
      STORAGE_KEY: STORAGE_KEY,
      _state: function () { return clone(state); }
    };
  }

  return {
    createApp: createApp,
    normalizeCode: normalizeCode,
    STORAGE_KEY: STORAGE_KEY,
    version: '1.0.0'
  };
});
