/*!
 * packing-core.js — 收纳盒摆放核心逻辑（UMD）
 * D42 赛博游园会 · 三维等距摆放沙盘
 *
 * 坐标系约定：柜体左前下角为原点；
 *   x 为宽度方向（左右），y 为深度方向（前后），z 为高度方向（上下）。
 * 本模块只做几何判定，不模拟实体误差、不声称最优装箱。
 *
 * 可在三种环境加载：
 *   - CommonJS (Node)： require('./packing-core.js')
 *   - AMD：            define([], factory)
 *   - 浏览器全局：     window.PackingCore
 */
(function (root, factory) {
  if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else {
    root.PackingCore = factory();
  }
}(typeof self !== 'undefined' ? self : this, function () {
  'use strict';

  // ---------------------------------------------------------------------------
  // 基础类型工具
  // ---------------------------------------------------------------------------

  /** 是否为正整数（尺寸必须 > 0）。 */
  function isPositiveInt(n) {
    return Number.isInteger(n) && n > 0;
  }

  /** 归一化一个长方体描述 {width, depth, height}。 */
  function normalizeBox(box) {
    return {
      width: box.width,
      depth: box.depth,
      height: box.height
    };
  }

  /** 体积（立方厘米）。 */
  function volumeOf(box) {
    if (!box || !isPositiveInt(box.width) || !isPositiveInt(box.depth) || !isPositiveInt(box.height)) {
      throw new TypeError('volumeOf: 需要正整数 width/depth/height');
    }
    return box.width * box.depth * box.height;
  }

  /** 便捷：直接由三边求体积。 */
  function boxVolume(width, depth, height) {
    return volumeOf({ width: width, depth: depth, height: height });
  }

  // ---------------------------------------------------------------------------
  // 碰撞 / 越界
  // ---------------------------------------------------------------------------

  /**
   * 两个轴对齐长方体是否“重叠”。
   * 注意：采用严格不等号，因此“面贴面 / 边贴边 / 角贴角”均视为不重叠（允许边界接触）。
   * a、b 均需带 {x, y, z, width, depth, height}。
   */
  function intersects(a, b) {
    return a.x < b.x + b.width &&
           a.x + a.width > b.x &&
           a.y < b.y + b.depth &&
           a.y + a.depth > b.y &&
           a.z < b.z + b.height &&
           a.z + a.height > b.z;
  }

  /**
   * 是否完全位于柜体内部（允许贴到柜体内壁 / 顶面）。
   * cabinet 为 {width, depth, height}；box 带 {x, y, z, width, depth, height}。
   */
  function withinBounds(box, cabinet) {
    return box.x >= 0 &&
           box.y >= 0 &&
           box.z >= 0 &&
           box.x + box.width <= cabinet.width &&
           box.y + box.depth <= cabinet.depth &&
           box.z + box.height <= cabinet.height;
  }

  /**
   * 判断候选摆放是否合法（越界或与其它盒子重叠都拒绝）。
   * 返回 { ok: boolean, reason: 'ok'|'out-of-bounds'|'overlap' }。
   * others 为已放置的其它盒子数组（不含候选自身）。
   */
  function canPlace(placement, cabinet, others) {
    if (!withinBounds(placement, cabinet)) {
      return { ok: false, reason: 'out-of-bounds' };
    }
    for (let i = 0; i < others.length; i++) {
      if (intersects(placement, others[i])) {
        return { ok: false, reason: 'overlap' };
      }
    }
    return { ok: true, reason: 'ok' };
  }

  /** 越界描述（供 UI 提示中文原因）。 */
  function describeOutOfBounds(box, cabinet) {
    const problems = [];
    if (box.x < 0) problems.push('x<0');
    if (box.y < 0) problems.push('y<0');
    if (box.z < 0) problems.push('z<0');
    if (box.x + box.width > cabinet.width) problems.push('右侧超出柜体宽度');
    if (box.y + box.depth > cabinet.depth) problems.push('后侧超出柜体深度');
    if (box.z + box.height > cabinet.height) problems.push('顶部超出柜体高度');
    return problems.length ? problems.join('、') : '';
  }

  // ---------------------------------------------------------------------------
  // 旋转（交换宽/深）
  // ---------------------------------------------------------------------------

  /**
   * 交换宽/深得到旋转后的尺寸。
   * 高度保持不变。
   */
  function rotated(box) {
    return {
      width: box.depth,
      depth: box.width,
      height: box.height
    };
  }

  // ---------------------------------------------------------------------------
  // 体积利用率
  // ---------------------------------------------------------------------------

  /**
   * 计算已放置盒子的体积与柜体体积利用率。
   * placements 需带 {width, depth, height}。
   */
  function utilization(placements, cabinet) {
    let used = 0;
    for (let i = 0; i < placements.length; i++) {
      used += volumeOf(placements[i]);
    }
    const total = volumeOf(cabinet);
    return {
      used: used,
      total: total,
      ratio: total > 0 ? used / total : 0
    };
  }

  // ---------------------------------------------------------------------------
  // 放置求解（简单首次适配，非最优）
  // ---------------------------------------------------------------------------

  /**
   * 在柜体内找一个合法整数坐标位置（首次适配，不声称最优）。
   * 扫描顺序：z 从低到高 → y 从 0 到最大 → x 从 0 到最大。
   * 找不到返回 null。
   */
  function firstFit(box, cabinet, others, options) {
    const opt = options || {};
    const maxX = cabinet.width - box.width;
    const maxY = cabinet.depth - box.depth;
    const maxZ = cabinet.height - box.height;

    if (maxX < 0 || maxY < 0 || maxZ < 0) {
      return null; // 尺寸本身超限（或不允许旋转导致的超限）
    }

    const candidates = [];
    const rot = opt.allowRotate === true ? [box, rotated(box)] : [box];

    for (let r = 0; r < rot.length; r++) {
      const b = rot[r];
      const rx = cabinet.width - b.width;
      const ry = cabinet.depth - b.depth;
      const rz = cabinet.height - b.height;
      if (rx < 0 || ry < 0 || rz < 0) continue;

      for (let z = 0; z <= rz; z++) {
        for (let y = 0; y <= ry; y++) {
          for (let x = 0; x <= rx; x++) {
            const candidate = {
              x: x, y: y, z: z,
              width: b.width, depth: b.depth, height: b.height,
              rotated: r === 1
            };
            const res = canPlace(candidate, cabinet, others);
            if (res.ok) {
              candidates.push(candidate);
              if (!opt.all) return candidate; // 首次适配
            }
          }
        }
      }
    }
    return candidates.length ? candidates[0] : null;
  }

  /**
   * 判断某种尺寸（考虑是否允许旋转）在空柜中是否“根本放不下”。
   * 返回 { fit: boolean, reason: string }，reason 为中文说明（fit 时为空串）。
   */
  function typeFits(box, cabinet, allowRotate) {
    const orientations = allowRotate === true ? [box, rotated(box)] : [box];
    for (let i = 0; i < orientations.length; i++) {
      const b = orientations[i];
      if (b.width <= cabinet.width && b.depth <= cabinet.depth && b.height <= cabinet.height) {
        return { fit: true, reason: '' };
      }
    }
    const b = box;
    const reasons = [];
    if (b.width > cabinet.width) reasons.push('宽 ' + b.width + ' 超出柜宽 ' + cabinet.width);
    if (b.depth > cabinet.depth) reasons.push('深 ' + b.depth + ' 超出柜深 ' + cabinet.depth);
    if (b.height > cabinet.height) reasons.push('高 ' + b.height + ' 超出柜高 ' + cabinet.height);
    if (allowRotate !== true) {
      reasons.push('且该盒子不允许旋转');
    }
    return { fit: false, reason: reasons.join('；') };
  }

  // ---------------------------------------------------------------------------

  return {
    version: '1.0.0',
    isPositiveInt: isPositiveInt,
    normalizeBox: normalizeBox,
    volumeOf: volumeOf,
    boxVolume: boxVolume,
    intersects: intersects,
    withinBounds: withinBounds,
    canPlace: canPlace,
    describeOutOfBounds: describeOutOfBounds,
    rotated: rotated,
    utilization: utilization,
    firstFit: firstFit,
    typeFits: typeFits
  };
}));
