/*!
 * MazeCore — 确定性完美迷宫（无环、全连通）核心算法
 * ------------------------------------------------------------------
 * 本文件为 UMD 模块，可同时运行于：
 *   - 浏览器：<script src="maze-core.js"></script>  → 全局变量 MazeCore
 *   - Node：  const MazeCore = require('./maze-core.js')
 *
 * 导出核心 API：
 *   generateMaze(width, height, seed)  → 生成迷宫对象（纯函数，固定种子可复现）
 *   solveMaze(maze)                    → 返回从起点到终点的最短路径（纯函数）
 *   （另附若干只读辅助函数与常量，便于复用）
 *
 * 迷宫结构（见 README）：
 *   {
 *     width:  number,   // 列数（x 方向，0..width-1）
 *     height: number,   // 行数（y 方向，0..height-1）
 *     cells:  number[], // 长度 = width*height；cells[y*width+x] 为格子的墙位掩码 0..15
 *     seed:   string,   // 归一化后的种子字符串
 *     start:  [0, 0],
 *     goal:   [width-1, height-1]
 *   }
 *
 * 墙位掩码（位为 1 表示该方向有墙）：
 *   N(北)=1, E(东)=2, S(南)=4, W(西)=8；初始全墙 = 15。
 * ------------------------------------------------------------------
 */
(function (root, factory) {
  'use strict';
  if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else {
    root.MazeCore = factory();
  }
})(typeof self !== 'undefined' ? self : this, function () {
  'use strict';

  // ---------------------------------------------------------------
  // 常量
  // ---------------------------------------------------------------
  var DIRS = { N: 1, E: 2, S: 4, W: 8 };
  var ALL_WALLS = 15;
  var MIN_SIZE = 1;
  var MAX_SIZE = 512; // 单边尺寸上限，防止病态内存占用

  // ---------------------------------------------------------------
  // 确定性随机数（跨浏览器 / Node 完全一致）
  // ---------------------------------------------------------------
  // FNV-1a 32 位字符串哈希
  function fnv1a(str) {
    var h = 0x811c9dc5;
    for (var i = 0; i < str.length; i++) {
      h ^= str.charCodeAt(i);
      h = Math.imul(h, 0x01000193);
    }
    return h >>> 0;
  }

  // Mulberry32 伪随机数生成器，返回 [0, 1) 的浮点数
  function mulberry32(a) {
    return function () {
      a |= 0;
      a = (a + 0x6d2b79f5) | 0;
      var t = Math.imul(a ^ (a >>> 15), 1 | a);
      t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
      return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
    };
  }

  // ---------------------------------------------------------------
  // 输入归一化与校验
  // ---------------------------------------------------------------
  function normalizeSeed(seed) {
    var s;
    if (typeof seed === 'number') {
      if (!isFinite(seed)) {
        throw new TypeError('非法的种子：数字种子必须是有限数值（不能是 NaN/Infinity）');
      }
      s = String(seed);
    } else if (typeof seed === 'string') {
      if (seed.trim().length === 0) {
        throw new TypeError('非法的种子：字符串种子不能为空或被空白填充');
      }
      s = seed; // 保留原始字符串，保证 "carnival" 与 " carnival " 生成的迷宫不同
    } else {
      throw new TypeError(
        '非法的种子：只接受非空字符串或有限数字，当前类型为 ' + Object.prototype.toString.call(seed)
      );
    }
    return s;
  }

  function normalizeSize(value, name) {
    if (typeof value !== 'number' || !isFinite(value) || Math.floor(value) !== value) {
      throw new TypeError(name + ' 必须是整数，当前值为 ' + JSON.stringify(value));
    }
    if (value < MIN_SIZE) {
      throw new RangeError(name + ' 必须 >= ' + MIN_SIZE + '，当前值为 ' + value);
    }
    if (value > MAX_SIZE) {
      throw new RangeError(name + ' 必须 <= ' + MAX_SIZE + '，当前值为 ' + value);
    }
    return value;
  }

  // ---------------------------------------------------------------
  // 迷宫生成：递归回溯（深度优先），生成的都是「完美迷宫」——
  // 无环（是一棵生成树）、全连通（每格可达）。
  // ---------------------------------------------------------------
  function generateMaze(width, height, seed) {
    var w = normalizeSize(width, 'width');
    var h = normalizeSize(height, 'height');
    var s = normalizeSeed(seed);

    var rand = mulberry32(fnv1a(s));
    var n = w * h;
    var cells = new Array(n);
    for (var i = 0; i < n; i++) cells[i] = ALL_WALLS;

    var visited = new Uint8Array(n);
    visited[0] = 1;

    // 显式栈，避免深迷宫递归爆栈
    var stack = [0];
    while (stack.length > 0) {
      var cur = stack[stack.length - 1];
      var cx = cur % w;
      var cy = (cur - cx) / w;

      // 收集未访问邻居：[邻居索引, 当前格去墙方向, 邻居格去墙方向]
      var neighbors = [];
      if (cy > 0 && !visited[cur - w]) neighbors.push([cur - w, DIRS.N, DIRS.S]);
      if (cx < w - 1 && !visited[cur + 1]) neighbors.push([cur + 1, DIRS.E, DIRS.W]);
      if (cy < h - 1 && !visited[cur + w]) neighbors.push([cur + w, DIRS.S, DIRS.N]);
      if (cx > 0 && !visited[cur - 1]) neighbors.push([cur - 1, DIRS.W, DIRS.E]);

      if (neighbors.length === 0) {
        stack.pop();
        continue;
      }

      var pick = neighbors[Math.floor(rand() * neighbors.length)];
      var nidx = pick[0];
      cells[cur] &= ~pick[1]; // 去掉当前格对应墙
      cells[nidx] &= ~pick[2]; // 去掉邻居格对应墙
      visited[nidx] = 1;
      stack.push(nidx);
    }

    return {
      width: w,
      height: h,
      cells: cells,
      seed: s,
      start: [0, 0],
      goal: [w - 1, h - 1]
    };
  }

  // ---------------------------------------------------------------
  // 迷宫结构校验（solveMaze / 辅助函数共用的防御性检查）
  // ---------------------------------------------------------------
  function assertMaze(maze) {
    if (!maze || typeof maze !== 'object') {
      throw new TypeError('非法的迷宫：必须是由 generateMaze 返回的对象');
    }
    var w = maze.width;
    var h = maze.height;
    if (typeof w !== 'number' || typeof h !== 'number' || w < 1 || h < 1 ||
        Math.floor(w) !== w || Math.floor(h) !== h) {
      throw new TypeError('非法的迷宫：width/height 必须是 >= 1 的整数');
    }
    var cells = maze.cells;
    if (!Array.isArray(cells) || cells.length !== w * h) {
      throw new TypeError('非法的迷宫：cells 必须是长度为 width*height 的数组');
    }
    for (var i = 0; i < cells.length; i++) {
      var c = cells[i];
      if (typeof c !== 'number' || c < 0 || c > 15 || Math.floor(c) !== c) {
        throw new TypeError('非法的迷宫：cells[' + i + '] 必须是 0..15 的整数墙位掩码');
      }
    }
  }

  // 从格子 (x,y) 朝 dir 方向是否有墙
  function rawHasWall(cells, w, x, y, dir) {
    return (cells[y * w + x] & dir) !== 0;
  }

  // ---------------------------------------------------------------
  // 求解：BFS 求最短路径（完美迷宫中即唯一路径）
  // 返回从 start 到 goal 的坐标数组 [[x,y], ...]，无解时返回 []
  // ---------------------------------------------------------------
  function solveMaze(maze) {
    assertMaze(maze);
    var w = maze.width;
    var h = maze.height;
    var n = w * h;
    var cells = maze.cells;
    var start = 0;
    var goal = n - 1;

    var prev = new Int32Array(n);
    for (var i = 0; i < n; i++) prev[i] = -1;
    var visited = new Uint8Array(n);
    var queue = new Int32Array(n);
    var qhead = 0;
    var qtail = 0;
    queue[qtail++] = start;
    visited[start] = 1;

    // 四个方向的 [(dx, dy), 从当前格离开时检查的墙方向]
    var steps = [
      [0, -1, DIRS.N],
      [1, 0, DIRS.E],
      [0, 1, DIRS.S],
      [-1, 0, DIRS.W]
    ];

    var found = false;
    while (qhead < qtail) {
      var cur = queue[qhead++];
      if (cur === goal) { found = true; break; }
      var cx = cur % w;
      var cy = (cur - cx) / w;
      for (var k = 0; k < 4; k++) {
        var nx = cx + steps[k][0];
        var ny = cy + steps[k][1];
        if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
        if (rawHasWall(cells, w, cx, cy, steps[k][2])) continue;
        var ni = ny * w + nx;
        if (!visited[ni]) {
          visited[ni] = 1;
          prev[ni] = cur;
          queue[qtail++] = ni;
        }
      }
    }

    if (!found) return [];

    var path = [];
    var c = goal;
    while (c !== -1) {
      var pcx = c % w;
      var pcy = (c - pcx) / w;
      path.push([pcx, pcy]);
      c = prev[c];
    }
    path.reverse();
    return path;
  }

  // ---------------------------------------------------------------
  // 只读辅助函数（可选，便于复用者免记墙位掩码）
  // ---------------------------------------------------------------
  function cellIndex(maze, x, y) {
    return y * maze.width + x;
  }

  function hasWall(maze, x, y, dir) {
    assertMaze(maze);
    if (x < 0 || y < 0 || x >= maze.width || y >= maze.height) return true;
    return rawHasWall(maze.cells, maze.width, x, y, dir);
  }

  // 能否从 (x,y) 朝 (dx,dy) 移动一步（dx/dy 必须恰有一个为 ±1，另一个为 0）
  function canStep(maze, x, y, dx, dy) {
    assertMaze(maze);
    var dir;
    if (dx === 1 && dy === 0) dir = DIRS.E;
    else if (dx === -1 && dy === 0) dir = DIRS.W;
    else if (dy === 1 && dx === 0) dir = DIRS.S;
    else if (dy === -1 && dx === 0) dir = DIRS.N;
    else return false;
    var nx = x + dx;
    var ny = y + dy;
    if (nx < 0 || ny < 0 || nx >= maze.width || ny >= maze.height) return false;
    return !rawHasWall(maze.cells, maze.width, x, y, dir);
  }

  // 统计迷宫中「被打通的内部通道」数量（即生成树边的数量），用于自检
  function openPassageCount(maze) {
    assertMaze(maze);
    var w = maze.width;
    var h = maze.height;
    var count = 0;
    for (var y = 0; y < h; y++) {
      for (var x = 0; x < w; x++) {
        var c = maze.cells[y * w + x];
        if (x < w - 1 && (c & DIRS.E) === 0) count++; // 向右打通
        if (y < h - 1 && (c & DIRS.S) === 0) count++; // 向下打通
      }
    }
    return count;
  }

  // ---------------------------------------------------------------
  // 导出
  // ---------------------------------------------------------------
  return {
    VERSION: '1.0.0',
    DIRS: DIRS,
    ALL_WALLS: ALL_WALLS,
    MIN_SIZE: MIN_SIZE,
    MAX_SIZE: MAX_SIZE,
    generateMaze: generateMaze,
    solveMaze: solveMaze,
    cellIndex: cellIndex,
    hasWall: hasWall,
    canStep: canStep,
    openPassageCount: openPassageCount
  };
});