/*!
 * pixel-core.js — 离线像素画 / 逐帧动画编辑器核心
 *
 * UMD 纯函数库：无 DOM、无网络、无浏览器依赖、无任何 IO。
 * 既可在浏览器 <script> 引入（window.PixelCore），也可在 Node 中 require。
 *
 * 功能分组：
 *   - 项目校验 / 规范化 / 序列化
 *   - 帧数据（空帧、克隆、增删复制）
 *   - 画笔 / 橡皮（颜色单元格操作）
 *   - 撤销 / 重做（历史快照）
 *   - PNG 编码（原始像素尺寸导出，不放大）
 *
 * 颜色约定：单元格取值 null 表示透明，其余为 "#rrggbb" 小写十六进制。
 * 坐标约定：零基，x 为列（左→右），y 为行（上→下）。
 */
(function (root, factory) {
  if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else {
    root.PixelCore = factory();
  }
}(typeof self !== 'undefined' ? self : this, function () {
  'use strict';

  var VERSION = '1.0.0';
  var DEFAULT_COLOR = '#ff0000';

  /* ------------------------------------------------------------------ *
   * 基础辅助
   * ------------------------------------------------------------------ */

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

  function isFiniteNumber(n) {
    return typeof n === 'number' && isFinite(n);
  }

  function toInt(n) {
    if (typeof n === 'number') return n;
    var v = parseInt(n, 10);
    return v;
  }

  /* ------------------------------------------------------------------ *
   * 颜色
   * ------------------------------------------------------------------ */

  // 归一化颜色；非法 / 透明输入返回 null。支持 #rgb、#rrggbb、transparent/none/''。
  function normalizeHex(color) {
    if (typeof color !== 'string') return null;
    var c = color.trim().toLowerCase();
    if (c === '' || c === 'transparent' || c === 'none') return null;
    if (c.charAt(0) === '#') c = c.slice(1);
    if (c.length === 3) c = c.charAt(0) + c.charAt(0) + c.charAt(1) + c.charAt(1) + c.charAt(2) + c.charAt(2);
    if (!/^[0-9a-f]{6}$/.test(c)) return null;
    return '#' + c;
  }

  function isHex(color) {
    return normalizeHex(color) !== null;
  }

  // 返回 [r, g, b, a]，非法/透明返回 null。
  function hexToRGBA(color) {
    var c = normalizeHex(color);
    if (c === null) return null;
    return [
      parseInt(c.slice(1, 3), 16),
      parseInt(c.slice(3, 5), 16),
      parseInt(c.slice(5, 7), 16),
      255
    ];
  }

  /* ------------------------------------------------------------------ *
   * 帧数据
   * ------------------------------------------------------------------ */

  function emptyFrame(width, height) {
    var w = (isInt(width) && width >= 1) ? width : 0;
    var h = (isInt(height) && height >= 1) ? height : 0;
    var frame = [];
    for (var y = 0; y < h; y++) {
      var row = [];
      for (var x = 0; x < w; x++) row.push(null);
      frame.push(row);
    }
    return frame;
  }

  function cloneFrame(frame) {
    if (!Array.isArray(frame)) return [];
    return frame.map(function (row) {
      return Array.isArray(row) ? row.slice() : [];
    });
  }

  function frameWidth(frame) {
    return (Array.isArray(frame) && Array.isArray(frame[0])) ? frame[0].length : 0;
  }

  function frameHeight(frame) {
    return Array.isArray(frame) ? frame.length : 0;
  }

  function inBounds(width, height, x, y) {
    return isInt(x) && isInt(y) && isInt(width) && isInt(height) &&
      x >= 0 && y >= 0 && x < width && y < height;
  }

  function getCell(frame, x, y) {
    if (!Array.isArray(frame) || !Array.isArray(frame[y])) return null;
    var v = frame[y][x];
    if (v === null || v === undefined) return null;
    var c = normalizeHex(v);
    return c === null ? null : c;
  }

  // 将任意帧数据结构（二维数组）规范化为合法帧：非法颜色与越界归为 null。
  function normalizeFrameMatrix(matrix, width, height) {
    var fr = emptyFrame(width, height);
    if (!Array.isArray(matrix)) return fr;
    for (var y = 0; y < height; y++) {
      if (!Array.isArray(matrix[y])) continue;
      for (var x = 0; x < width; x++) {
        var c = normalizeHex(matrix[y][x]);
        if (c !== null) fr[y][x] = c;
      }
    }
    return fr;
  }

  /* ------------------------------------------------------------------ *
   * 画笔 / 橡皮
   * ------------------------------------------------------------------ */

  function paintCell(frame, x, y, color) {
    var out = cloneFrame(frame);
    var c = normalizeHex(color);
    if (c !== null && inBounds(frameWidth(frame), frameHeight(frame), x, y)) {
      out[y][x] = c;
    }
    return out;
  }

  function eraseCell(frame, x, y) {
    var out = cloneFrame(frame);
    if (out[y]) out[y][x] = null;
    return out;
  }

  // tool: 'paint'（画笔，取 color）| 'erase'（橡皮）。
  function applyTool(frame, x, y, color, tool) {
    if (tool === 'erase') return eraseCell(frame, x, y);
    return paintCell(frame, x, y, color);
  }

  /* ------------------------------------------------------------------ *
   * 项目（project = { width, height, fps, frames }）
   * ------------------------------------------------------------------ */

  function cloneProject(project) {
    return {
      width: project.width,
      height: project.height,
      fps: project.fps,
      frames: (Array.isArray(project.frames) ? project.frames.map(cloneFrame) : [])
    };
  }

  function createProject(width, height, fps, frames) {
    var w = (isInt(width) && width >= 1) ? width : 8;
    var h = (isInt(height) && height >= 1) ? height : 8;
    var f = (isFiniteNumber(fps) && fps > 0) ? fps : 4;
    var fr = [];
    if (Array.isArray(frames) && frames.length > 0) {
      fr = frames.map(cloneFrame);
    } else {
      fr = [emptyFrame(w, h)];
    }
    return { width: w, height: h, fps: f, frames: fr };
  }

  // 项目校验：返回 { valid, errors }。校验规范化的内部结构。
  function validateProject(project) {
    var errors = [];
    if (!project || typeof project !== 'object') {
      return { valid: false, errors: ['project 必须是对象'] };
    }
    var w = project.width, h = project.height, fps = project.fps;
    if (!isInt(w) || w < 1) errors.push('width 必须是 ≥1 的整数');
    if (!isInt(h) || h < 1) errors.push('height 必须是 ≥1 的整数');
    if (!isFiniteNumber(fps) || fps <= 0) errors.push('fps 必须是 >0 的数字');
    if (!Array.isArray(project.frames) || project.frames.length === 0) {
      errors.push('frames 必须是非空数组');
      return { valid: false, errors: errors };
    }
    if (isInt(w) && w >= 1 && isInt(h) && h >= 1) {
      for (var i = 0; i < project.frames.length; i++) {
        var f = project.frames[i];
        if (!Array.isArray(f) || f.length !== h) {
          errors.push('第 ' + i + ' 帧应为高度 ' + h + ' 的数组');
          continue;
        }
        for (var y = 0; y < h; y++) {
          if (!Array.isArray(f[y]) || f[y].length !== w) {
            errors.push('第 ' + i + ' 帧第 ' + y + ' 行宽度应为 ' + w);
            break;
          }
          for (var x = 0; x < w; x++) {
            var cell = f[y][x];
            if (cell !== null && cell !== undefined && normalizeHex(cell) === null) {
              errors.push('第 ' + i + ' 帧 (' + x + ',' + y + ') 颜色非法：' + String(cell));
            }
          }
        }
      }
    }
    return { valid: errors.length === 0, errors: errors };
  }

  // 从 spec.json 结构构建项目：
  // { width, height, fps, frames: [{ redPixel? : [x,y], pixels? : [[...]] }], background, coordinates }
  function projectFromSpec(spec) {
    if (!spec || typeof spec !== 'object') throw new Error('spec 必须是对象');
    var w = toInt(spec.width);
    var h = toInt(spec.height);
    var fps = Number(spec.fps);
    if (!(isInt(w) && w >= 1)) throw new Error('spec.width 必须为 ≥1 的整数');
    if (!(isInt(h) && h >= 1)) throw new Error('spec.height 必须为 ≥1 的整数');
    if (!(isFiniteNumber(fps) && fps > 0)) throw new Error('spec.fps 必须为 >0 的数字');

    var frames = [];
    if (Array.isArray(spec.frames)) {
      spec.frames.forEach(function (f) {
        var fr = emptyFrame(w, h);
        if (f && Array.isArray(f.pixels)) {
          fr = normalizeFrameMatrix(f.pixels, w, h);
        } else if (f && Array.isArray(f.redPixel) && f.redPixel.length >= 2) {
          var x = toInt(f.redPixel[0]);
          var y = toInt(f.redPixel[1]);
          if (spec.coordinates === 'one-based') { x -= 1; y -= 1; }
          if (inBounds(w, h, x, y)) fr[y][x] = DEFAULT_COLOR;
        }
        frames.push(fr);
      });
    }
    if (frames.length === 0) frames = [emptyFrame(w, h)];
    return { width: w, height: h, fps: fps, frames: frames };
  }

  // 导出为可 JSON 序列化的项目对象（帧为二维颜色数组）。
  function projectToJSON(project) {
    var p = cloneProject(project);
    return {
      type: 'pixel-anim',
      version: 1,
      width: p.width,
      height: p.height,
      fps: p.fps,
      frames: p.frames
    };
  }

  // 从 JSON 数据导入：支持本库导出的规范格式，也兼容 spec 结构（每帧含 redPixel/pixels）。
  function projectFromJSON(data) {
    if (!data || typeof data !== 'object') throw new Error('JSON 内容必须是对象');
    var first = Array.isArray(data.frames) ? data.frames[0] : null;
    var specLike = first && typeof first === 'object' && !Array.isArray(first) &&
      (Array.isArray(first.redPixel) || Array.isArray(first.pixels));
    if (specLike) return projectFromSpec(data);

    var pr = {
      width: toInt(data.width),
      height: toInt(data.height),
      fps: Number(data.fps),
      frames: data.frames
    };
    var v = validateProject(pr);
    if (!v.valid) throw new Error('项目校验失败：' + v.errors.join('；'));
    return cloneProject(pr);
  }

  /* ------------------------------------------------------------------ *
   * 帧管理（均返回新项目，不修改入参）
   * ------------------------------------------------------------------ */

  function clampIndex(i, len) {
    if (!isInt(i)) return 0;
    if (i < 0) return 0;
    if (i >= len) return len - 1;
    return i;
  }

  function addFrame(project, frame) {
    var p = cloneProject(project);
    p.frames.push(frame ? cloneFrame(frame) : emptyFrame(p.width, p.height));
    return p;
  }

  // 在 index 之后插入一帧其副本。
  function duplicateFrame(project, index) {
    var p = cloneProject(project);
    var i = clampIndex(index, p.frames.length);
    p.frames.splice(i + 1, 0, cloneFrame(p.frames[i]));
    return p;
  }

  // 至少保留 1 帧。
  function deleteFrame(project, index) {
    var p = cloneProject(project);
    if (p.frames.length <= 1) return p;
    var i = clampIndex(index, p.frames.length);
    p.frames.splice(i, 1);
    return p;
  }

  function setFrame(project, index, frame) {
    var p = cloneProject(project);
    var i = clampIndex(index, p.frames.length);
    p.frames[i] = cloneFrame(frame);
    return p;
  }

  /* ------------------------------------------------------------------ *
   * 撤销 / 重做（历史快照）
   * history = { past:[...], future:[...] }，当前项目由调用方另行保存。
   * ------------------------------------------------------------------ */

  function createHistory() {
    return { past: [], future: [] };
  }

  // 记录一次编辑前状态：把当前项目压入 past，并清空 future。
  function record(history, project, limit) {
    var lim = (isInt(limit) && limit > 0) ? limit : 100;
    var past = (Array.isArray(history.past) ? history.past : []).concat([cloneProject(project)]);
    if (past.length > lim) past = past.slice(past.length - lim);
    return { past: past, future: [] };
  }

  function canUndo(history) {
    return !!(history && Array.isArray(history.past) && history.past.length > 0);
  }

  function canRedo(history) {
    return !!(history && Array.isArray(history.future) && history.future.length > 0);
  }

  function undo(history, project) {
    if (!canUndo(history)) return { changed: false, history: history, project: project };
    var prev = history.past[history.past.length - 1];
    return {
      changed: true,
      history: {
        past: history.past.slice(0, -1),
        future: [cloneProject(project)].concat(history.future)
      },
      project: prev
    };
  }

  function redo(history, project) {
    if (!canRedo(history)) return { changed: false, history: history, project: project };
    var next = history.future[0];
    return {
      changed: true,
      history: {
        past: history.past.concat([cloneProject(project)]),
        future: history.future.slice(1)
      },
      project: next
    };
  }

  /* ------------------------------------------------------------------ *
   * RGBA 像素流（用于 canvas 渲染与 PNG 编码）
   * ------------------------------------------------------------------ */

  // 帧 → RGBA 字节流（长度 width*height*4，行优先）。透明 = (0,0,0,0)。
  function frameToRGBA(frame, width, height) {
    var out = new Uint8Array(width * height * 4);
    var p = 0;
    for (var y = 0; y < height; y++) {
      for (var x = 0; x < width; x++) {
        var rgba = getCell(frame, x, y);
        if (rgba === null) {
          out[p++] = 0; out[p++] = 0; out[p++] = 0; out[p++] = 0;
        } else {
          var c = hexToRGBA(rgba);
          out[p++] = c[0]; out[p++] = c[1]; out[p++] = c[2]; out[p++] = 255;
        }
      }
    }
    return out;
  }

  // 横向精灵图：所有帧从左到右拼接，尺寸 (width*frames.length) × height。
  function spriteSheetToRGBA(project) {
    var n = project.frames.length;
    var w = project.width * n;
    var h = project.height;
    var out = new Uint8Array(w * h * 4);
    for (var f = 0; f < n; f++) {
      var rgba = frameToRGBA(project.frames[f], project.width, project.height);
      var srcRowBytes = project.width * 4;
      for (var y = 0; y < h; y++) {
        var srcOff = y * srcRowBytes;
        var dstOff = (y * w + f * project.width) * 4;
        for (var k = 0; k < srcRowBytes; k++) {
          out[dstOff + k] = rgba[srcOff + k];
        }
      }
    }
    return out;
  }

  /* ------------------------------------------------------------------ *
   * PNG 编码（无压缩依赖：使用 DEFLATE stored 块 + Adler-32）
   * ------------------------------------------------------------------ */

  function crc32(bytes) {
    var table = [];
    var c, n, k;
    for (n = 0; n < 256; n++) {
      c = n;
      for (k = 0; k < 8; k++) {
        c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
      }
      table[n] = c >>> 0;
    }
    var crc = 0xFFFFFFFF;
    for (var i = 0; i < bytes.length; i++) {
      crc = (crc >>> 8) ^ table[(crc ^ bytes[i]) & 0xFF];
    }
    return (crc ^ 0xFFFFFFFF) >>> 0;
  }

  function adler32(bytes) {
    var a = 1, b = 0;
    for (var i = 0; i < bytes.length; i++) {
      a = (a + bytes[i]) % 65521;
      b = (b + a) % 65521;
    }
    return ((b << 16) | a) >>> 0;
  }

  // zlib 包装的 DEFLATE stored（不压缩）流：header 0x78 0x9C + 块 + Adler-32。
  function zlibStore(data) {
    var MAX = 0xFFFF;
    var out = [0x78, 0x9C];
    for (var i = 0; i < data.length; i += MAX) {
      var end = Math.min(i + MAX, data.length);
      var len = end - i;
      var final = (end >= data.length);
      out.push(final ? 1 : 0);
      out.push(len & 0xFF, (len >>> 8) & 0xFF);
      var nlen = (~len) & 0xFFFF;
      out.push(nlen & 0xFF, (nlen >>> 8) & 0xFF);
      for (var j = i; j < end; j++) out.push(data[j]);
    }
    var adler = adler32(data);
    out.push((adler >>> 24) & 0xFF, (adler >>> 16) & 0xFF, (adler >>> 8) & 0xFF, adler & 0xFF);
    return new Uint8Array(out);
  }

  function pngChunk(type, data) {
    var out = new Uint8Array(12 + data.length);
    var len = data.length;
    out[0] = (len >>> 24) & 0xFF;
    out[1] = (len >>> 16) & 0xFF;
    out[2] = (len >>> 8) & 0xFF;
    out[3] = len & 0xFF;
    for (var i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
    out.set(data, 8);
    var crcBuf = new Uint8Array(4 + data.length);
    for (var t = 0; t < 4; t++) crcBuf[t] = type.charCodeAt(t);
    crcBuf.set(data, 4);
    var crc = crc32(crcBuf);
    out[8 + data.length] = (crc >>> 24) & 0xFF;
    out[9 + data.length] = (crc >>> 16) & 0xFF;
    out[10 + data.length] = (crc >>> 8) & 0xFF;
    out[11 + data.length] = crc & 0xFF;
    return out;
  }

  // 编码原始像素 PNG（RGBA，8 bit，color type 6）。
  function encodePNG(width, height, rgba) {
    var sig = [137, 80, 78, 71, 13, 10, 26, 10];

    var ihdr = new Uint8Array(13);
    ihdr[0] = (width >>> 24) & 0xFF;
    ihdr[1] = (width >>> 16) & 0xFF;
    ihdr[2] = (width >>> 8) & 0xFF;
    ihdr[3] = width & 0xFF;
    ihdr[4] = (height >>> 24) & 0xFF;
    ihdr[5] = (height >>> 16) & 0xFF;
    ihdr[6] = (height >>> 8) & 0xFF;
    ihdr[7] = height & 0xFF;
    ihdr[8] = 8;   // bit depth
    ihdr[9] = 6;   // color type RGBA
    ihdr[10] = 0;  // compression
    ihdr[11] = 0;  // filter
    ihdr[12] = 0;  // interlace

    // 原始数据：每行 1 字节 filter(0) + width*4 字节 RGBA。
    var stride = width * 4;
    var raw = new Uint8Array((stride + 1) * height);
    var p = 0;
    for (var y = 0; y < height; y++) {
      raw[p++] = 0;
      for (var x = 0; x < stride; x++) raw[p++] = rgba[y * stride + x];
    }
    var idat = zlibStore(raw);

    var parts = [
      new Uint8Array(sig),
      pngChunk('IHDR', ihdr),
      pngChunk('IDAT', idat),
      pngChunk('IEND', new Uint8Array(0))
    ];
    var total = 0;
    for (var i = 0; i < parts.length; i++) total += parts[i].length;
    var out = new Uint8Array(total);
    var off = 0;
    for (var q = 0; q < parts.length; q++) {
      out.set(parts[q], off);
      off += parts[q].length;
    }
    return out;
  }

  function exportFramePNG(project, index) {
    var i = clampIndex(index, project.frames.length);
    var rgba = frameToRGBA(project.frames[i], project.width, project.height);
    return encodePNG(project.width, project.height, rgba);
  }

  function exportSpriteSheetPNG(project) {
    var rgba = spriteSheetToRGBA(project);
    return encodePNG(project.width * project.frames.length, project.height, rgba);
  }

  /* ------------------------------------------------------------------ *
   * 导出 API
   * ------------------------------------------------------------------ */

  return {
    VERSION: VERSION,
    DEFAULT_COLOR: DEFAULT_COLOR,

    // 颜色
    normalizeHex: normalizeHex,
    isHex: isHex,
    hexToRGBA: hexToRGBA,

    // 帧数据
    emptyFrame: emptyFrame,
    cloneFrame: cloneFrame,
    frameWidth: frameWidth,
    frameHeight: frameHeight,
    inBounds: inBounds,
    getCell: getCell,
    normalizeFrameMatrix: normalizeFrameMatrix,

    // 画笔 / 橡皮
    paintCell: paintCell,
    eraseCell: eraseCell,
    applyTool: applyTool,

    // 项目
    createProject: createProject,
    cloneProject: cloneProject,
    validateProject: validateProject,
    projectFromSpec: projectFromSpec,
    projectToJSON: projectToJSON,
    projectFromJSON: projectFromJSON,

    // 帧管理
    addFrame: addFrame,
    duplicateFrame: duplicateFrame,
    deleteFrame: deleteFrame,
    setFrame: setFrame,

    // 撤销 / 重做
    createHistory: createHistory,
    record: record,
    canUndo: canUndo,
    canRedo: canRedo,
    undo: undo,
    redo: redo,

    // RGBA 与 PNG
    frameToRGBA: frameToRGBA,
    spriteSheetToRGBA: spriteSheetToRGBA,
    crc32: crc32,
    adler32: adler32,
    encodePNG: encodePNG,
    exportFramePNG: exportFramePNG,
    exportSpriteSheetPNG: exportSpriteSheetPNG
  };
}));