(function (root, factory) {
  if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else {
    root.LighthouseEngine = factory();
  }
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
  "use strict";

  var SCHEMA = "cyberfete.d07.lighthouse";
  var SAVE_VERSION = 1;
  var STORAGE_KEY = "cyberfete.d07.lighthouse.save";
  var MAX_HISTORY = 256;

  function hasOwn(object, key) {
    return Object.prototype.hasOwnProperty.call(object, key);
  }

  function isPlainObject(value) {
    return value !== null && typeof value === "object" && !Array.isArray(value);
  }

  function isStringArray(value) {
    return Array.isArray(value) && value.every(function (item) {
      return typeof item === "string";
    });
  }

  function cleanState(fields) {
    return {
      schema: SCHEMA,
      version: SAVE_VERSION,
      current: fields.current,
      history: fields.history.slice(),
      endings: fields.endings.slice()
    };
  }

  function createEngine(story) {
    if (
      !isPlainObject(story) ||
      !isPlainObject(story.nodes) ||
      typeof story.start !== "string" ||
      !hasOwn(story.nodes, story.start)
    ) {
      throw new TypeError("剧情结构无效：缺少 start 或 nodes。");
    }

    var nodes = story.nodes;
    var startId = story.start;
    var nodeIds = Object.keys(nodes);

    if (nodeIds.length === 0) {
      throw new TypeError("剧情结构无效：nodes 为空。");
    }

    nodeIds.forEach(function (id) {
      var node = nodes[id];
      if (!isPlainObject(node) || typeof node.text !== "string" || node.text.trim() === "") {
        throw new TypeError("剧情节点 " + id + " 缺少正文。");
      }
      if (node.ending !== undefined && (typeof node.ending !== "string" || node.ending.trim() === "")) {
        throw new TypeError("剧情节点 " + id + " 的结局名称无效。");
      }
      if (node.choices !== undefined && !Array.isArray(node.choices)) {
        throw new TypeError("剧情节点 " + id + " 的 choices 无效。");
      }
    });

    var endingDefs = nodeIds
      .filter(function (id) {
        return typeof nodes[id].ending === "string";
      })
      .map(function (id, index) {
        return {
          id: id,
          name: nodes[id].ending,
          index: index + 1
        };
      });

    var endingNames = endingDefs.map(function (entry) {
      return entry.name;
    });

    if (new Set(endingNames).size !== endingNames.length) {
      throw new TypeError("剧情结构无效：结局名称重复。");
    }

    var endingNameSet = new Set(endingNames);

    function getNode(id) {
      return hasOwn(nodes, id) ? nodes[id] : null;
    }

    function getChoices(id) {
      var node = getNode(id);
      return node && Array.isArray(node.choices) ? node.choices : [];
    }

    function choiceTargets(id) {
      return getChoices(id).map(function (choice) {
        return isPlainObject(choice) ? choice.next : undefined;
      });
    }

    function canGo(from, to) {
      var fromNode = getNode(from);
      if (!fromNode || typeof to !== "string" || !hasOwn(nodes, to)) {
        return false;
      }
      if (typeof fromNode.ending === "string") {
        return false;
      }
      return getChoices(from).some(function (choice) {
        return isPlainObject(choice) && choice.next === to;
      });
    }

    function freshState() {
      return cleanState({
        current: startId,
        history: [startId],
        endings: []
      });
    }

    function fail(reason) {
      return {
        ok: false,
        state: null,
        reason: reason
      };
    }

    function validateStateData(data) {
      if (!isPlainObject(data)) {
        return fail("shape");
      }

      var allowedKeys = {
        schema: true,
        version: true,
        current: true,
        history: true,
        endings: true
      };

      var keys = Object.keys(data);
      if (
        keys.some(function (key) {
          return !hasOwn(allowedKeys, key);
        })
      ) {
        return fail("shape");
      }

      if (data.version !== SAVE_VERSION) {
        return fail("version");
      }
      if (data.schema !== SCHEMA) {
        return fail("schema");
      }
      if (typeof data.current !== "string" || !hasOwn(nodes, data.current)) {
        return fail("current");
      }
      if (
        !Array.isArray(data.history) ||
        data.history.length === 0 ||
        data.history.length > MAX_HISTORY ||
        !isStringArray(data.history)
      ) {
        return fail("history");
      }

      var history = data.history;
      if (history[0] !== startId) {
        return fail("history-start");
      }
      if (history[history.length - 1] !== data.current) {
        return fail("history-current");
      }

      for (var index = 0; index < history.length; index += 1) {
        if (!hasOwn(nodes, history[index])) {
          return fail("history");
        }
        if (index < history.length - 1 && !canGo(history[index], history[index + 1])) {
          return fail("path");
        }
      }

      if (
        !Array.isArray(data.endings) ||
        data.endings.length > endingDefs.length ||
        !isStringArray(data.endings)
      ) {
        return fail("endings");
      }

      var seen = new Set();
      for (var endingIndex = 0; endingIndex < data.endings.length; endingIndex += 1) {
        var endingName = data.endings[endingIndex];
        if (!endingNameSet.has(endingName) || seen.has(endingName)) {
          return fail("endings");
        }
        seen.add(endingName);
      }

      var currentNode = getNode(data.current);
      if (
        currentNode &&
        typeof currentNode.ending === "string" &&
        !seen.has(currentNode.ending)
      ) {
        return fail("ending-missing");
      }

      return {
        ok: true,
        state: cleanState({
          current: data.current,
          history: history,
          endings: data.endings
        }),
        reason: null
      };
    }

    function validateSave(raw) {
      var data = raw;
      if (typeof raw === "string") {
        try {
          data = JSON.parse(raw);
        } catch (error) {
          return fail("json");
        }
      }
      if (!isPlainObject(data)) {
        return fail("shape");
      }
      if (data.version !== SAVE_VERSION) {
        return fail("version");
      }
      if (data.schema !== SCHEMA) {
        return fail("schema");
      }
      return validateStateData(data);
    }

    function applyChoice(state, next) {
      var checked = validateStateData(state);
      if (!checked.ok) {
        return null;
      }
      if (!canGo(checked.state.current, next)) {
        return null;
      }

      var nextNode = getNode(next);
      var endings = checked.state.endings.slice();
      if (
        nextNode &&
        typeof nextNode.ending === "string" &&
        endings.indexOf(nextNode.ending) === -1
      ) {
        endings.push(nextNode.ending);
      }

      return cleanState({
        current: next,
        history: checked.state.history.concat([next]),
        endings: endings
      });
    }

    function undo(state) {
      var checked = validateStateData(state);
      if (!checked.ok) {
        return null;
      }
      if (checked.state.history.length <= 1) {
        return checked.state;
      }

      var history = checked.state.history.slice(0, -1);
      return cleanState({
        current: history[history.length - 1],
        history: history,
        endings: checked.state.endings
      });
    }

    function restart(state) {
      var checked = validateStateData(state);
      if (!checked.ok) {
        return null;
      }
      return cleanState({
        current: startId,
        history: [startId],
        endings: checked.state.endings
      });
    }

    function clear() {
      return freshState();
    }

    function progress(state) {
      var found = isPlainObject(state) && Array.isArray(state.endings) ? state.endings.length : 0;
      var total = endingDefs.length;
      return {
        found: found,
        total: total,
        percent: total === 0 ? 0 : Math.round((found / total) * 100)
      };
    }

    function serialize(state) {
      var checked = validateStateData(state);
      if (!checked.ok) {
        throw new TypeError("无法序列化无效存档：" + checked.reason);
      }
      return JSON.stringify(checked.state);
    }

    return Object.freeze({
      schema: SCHEMA,
      version: SAVE_VERSION,
      storageKey: STORAGE_KEY,
      start: startId,
      nodeIds: nodeIds.slice(),
      endings: endingDefs.map(function (entry) {
        return {
          id: entry.id,
          name: entry.name,
          index: entry.index
        };
      }),
      freshState: freshState,
      getNode: getNode,
      getChoices: getChoices,
      canGo: canGo,
      applyChoice: applyChoice,
      undo: undo,
      restart: restart,
      clear: clear,
      progress: progress,
      serialize: serialize,
      validateSave: validateSave,
      validateState: validateStateData
    });
  }

  return Object.freeze({
    SCHEMA: SCHEMA,
    SAVE_VERSION: SAVE_VERSION,
    STORAGE_KEY: STORAGE_KEY,
    createEngine: createEngine
  });
});
