/*!
 * physics-core.js — 重力弹球实验桌 · 纯物理核心（UMD）
 * 单位：米、秒；y 轴向下。
 *
 * 设计要点：
 *  1. 物理与渲染完全分离：本文件不访问 document / window / canvas / rAF。
 *  2. 固定步长 1/240 s（与 inputs/spec.json 的 fixedStep 一致）。
 *  3. advance(state, elapsed, params) 先把真实经过时间换算成“固定步数”，
 *     只有凑满整数步才推进仿真，因此 30/60/120 fps 输入相同总时长后，
 *     步数与状态完全一致。
 *  4. 每个固定步内部按速度自适应分子步（最多 64 个子步），
 *     再做边界/障碍物穿透修正，避免高速穿越薄障碍物或边界。
 *
 * API：
 *   PhysicsCore.makeState(overrides?)             -> state
 *   PhysicsCore.advance(state, elapsed, params?)  -> state（原地修改并返回）
 *   PhysicsCore.step(state, params?)              -> state（推进恰好一个固定步）
 *   PhysicsCore.computeEnergy(state, params?)     -> {kinetic, potential, total, mass}
 *   PhysicsCore.FIXED_STEP / DEFAULT_PARAMS / SPEC
 */
(function (root, factory) {
  "use strict";
  if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else {
    root.PhysicsCore = factory();
  }
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
  "use strict";

  /** 固定物理步长，单位秒（1/240）。 */
  var FIXED_STEP = 1 / 240;

  /** 与 inputs/spec.json 对齐的初始实验参数。 */
  var SPEC = {
    world: { width: 10, height: 10 },
    ball: { x: 3, y: 2, radius: 0.2, vx: 1, vy: 0 },
    obstacle: { x: 6, y: 7, width: 2, height: 0.4 },
    gravity: 9.8,
    restitution: 0.8
  };

  var DEFAULT_PARAMS = {
    gravity: SPEC.gravity,
    restitution: SPEC.restitution,
    obstacleEnabled: true,
    mass: 1
  };

  /** 速度低于该阈值时不再反弹，避免无限微小抖动。 */
  var RESTING_SPEED = 0.12;
  /** 只有超过该撞击速度才计入“碰撞次数”，静置贴地不计数。 */
  var IMPACT_COUNT_SPEED = 0.15;
  /** advance 的单帧防呆上限，防止异常 elapsed 造成长时间卡死。 */
  var MAX_STEPS_PER_ADVANCE = 20000;
  /** 每个固定步内部最多拆分的子步数。 */
  var MAX_SUBSTEPS = 64;

  function isFiniteNumber(value) {
    return typeof value === "number" && isFinite(value);
  }

  function clamp(value, min, max) {
    return value < min ? min : value > max ? max : value;
  }

  function positiveNumber(value, fallback) {
    return isFiniteNumber(value) && value > 0 ? value : fallback;
  }

  /**
   * 规范化外部参数，保证核心面对滑杆/测试输入时行为稳定。
   * 不会修改调用方传入的对象。
   */
  function normalizeParams(params) {
    var source = params && typeof params === "object" ? params : {};
    var gravity = isFiniteNumber(source.gravity) ? source.gravity : DEFAULT_PARAMS.gravity;
    var restitution = isFiniteNumber(source.restitution)
      ? source.restitution
      : DEFAULT_PARAMS.restitution;
    var obstacleEnabled =
      typeof source.obstacleEnabled === "boolean"
        ? source.obstacleEnabled
        : DEFAULT_PARAMS.obstacleEnabled;
    var mass = positiveNumber(source.mass, DEFAULT_PARAMS.mass);

    return {
      gravity: clamp(gravity, 0, 100),
      restitution: clamp(restitution, 0, 1),
      obstacleEnabled: obstacleEnabled,
      mass: clamp(mass, 0.001, 1000)
    };
  }

  /**
   * 创建一份可序列化的初始状态。
   * overrides 支持局部覆盖 world / ball / obstacle，便于测试与课堂变式。
   */
  function makeState(overrides) {
    var state = {
      time: 0,
      steps: 0,
      // 不足一个固定步的余量，单位是“固定步”，不是秒
      acc: 0,
      collisions: 0,
      world: {
        width: SPEC.world.width,
        height: SPEC.world.height
      },
      ball: {
        x: SPEC.ball.x,
        y: SPEC.ball.y,
        vx: SPEC.ball.vx,
        vy: SPEC.ball.vy,
        radius: SPEC.ball.radius
      },
      obstacle: {
        x: SPEC.obstacle.x,
        y: SPEC.obstacle.y,
        width: SPEC.obstacle.width,
        height: SPEC.obstacle.height
      }
    };

    if (!overrides || typeof overrides !== "object") {
      return state;
    }

    if (overrides.world && typeof overrides.world === "object") {
      state.world.width = positiveNumber(overrides.world.width, state.world.width);
      state.world.height = positiveNumber(overrides.world.height, state.world.height);
    }
    if (overrides.ball && typeof overrides.ball === "object") {
      var ball = overrides.ball;
      if (isFiniteNumber(ball.x)) state.ball.x = ball.x;
      if (isFiniteNumber(ball.y)) state.ball.y = ball.y;
      if (isFiniteNumber(ball.vx)) state.ball.vx = ball.vx;
      if (isFiniteNumber(ball.vy)) state.ball.vy = ball.vy;
      state.ball.radius = positiveNumber(ball.radius, state.ball.radius);
    }
    if (overrides.obstacle && typeof overrides.obstacle === "object") {
      var obstacle = overrides.obstacle;
      if (isFiniteNumber(obstacle.x)) state.obstacle.x = obstacle.x;
      if (isFiniteNumber(obstacle.y)) state.obstacle.y = obstacle.y;
      state.obstacle.width = positiveNumber(obstacle.width, state.obstacle.width);
      state.obstacle.height = positiveNumber(obstacle.height, state.obstacle.height);
    }

    return state;
  }

  /**
   * 估算一个固定步需要拆成多少子步。
   * 保证每个子步的位移不超过半个球半径，薄障碍物（0.4 m）因此不可能被穿越。
   */
  function estimateSubsteps(ball, gravity, dt) {
    var speed = Math.sqrt(ball.vx * ball.vx + ball.vy * ball.vy);
    speed += Math.abs(gravity) * dt;
    var maxMove = Math.max(0.02, ball.radius * 0.5);
    var count = Math.ceil((speed * dt) / maxMove);
    return clamp(count, 1, MAX_SUBSTEPS);
  }

  function countImpact(state, normalSpeed) {
    if (normalSpeed > IMPACT_COUNT_SPEED) {
      state.collisions += 1;
    }
  }

  function bounceVelocity(normalVelocity, restitution) {
    if (Math.abs(normalVelocity) < RESTING_SPEED) {
      return 0;
    }
    return -normalVelocity * restitution;
  }

  /**
   * 极少数边界情况（例如球在障碍物内部时重新开启障碍物）会需要较大的
   * 向上位置修正。位置抬高会带来势能增加，这里从动能中扣除同等能量，
   * 保证“能量不无故增加”在参数切换时也成立。
   */
  function absorbLiftEnergy(state, params, lift) {
    if (!(lift > 0)) return;
    var ball = state.ball;
    var potentialGain = params.mass * params.gravity * lift;
    var speedSquared = ball.vx * ball.vx + ball.vy * ball.vy;
    var kinetic = 0.5 * params.mass * speedSquared;
    if (kinetic <= potentialGain) {
      ball.vx = 0;
      ball.vy = 0;
      return;
    }
    var scale = Math.sqrt((kinetic - potentialGain) / kinetic);
    ball.vx *= scale;
    ball.vy *= scale;
  }

  /**
   * 求“从 y0 出发、以 vy0 下抛、在重力 g 下到达 face”的撞击速度。
   * 用于把反弹速度建立在真正的接触时刻，而不是子步末尾的穿透深度上。
   * 这样位置修正不会凭空增加机械能。
   */
  function verticalContactVelocity(y0, vy0, face, gravity, maxTime) {
    var dy = y0 - face;
    var b = vy0;
    var a = 0.5 * gravity;
    var t = 0;

    if (Math.abs(a) < 1e-12) {
      if (Math.abs(b) > 1e-12) {
        t = -dy / b;
      }
    } else {
      var disc = b * b - 4 * a * dy;
      if (disc >= 0) {
        var root = Math.sqrt(disc);
        var t1 = (-b - root) / (2 * a);
        var t2 = (-b + root) / (2 * a);
        if (t1 >= -1e-12 && t2 >= -1e-12) {
          t = Math.min(Math.max(0, t1), Math.max(0, t2));
        } else if (t1 >= -1e-12) {
          t = Math.max(0, t1);
        } else if (t2 >= -1e-12) {
          t = Math.max(0, t2);
        }
      }
    }

    // 接触时间不可能超过本子步；越界时退回子步末速度。
    if (!isFinite(t) || t < 0) {
      return vy0;
    }
    t = Math.min(t, maxTime);
    return vy0 + gravity * t;
  }

  /** 把球心约束在 [radius, width-radius] × [radius, height-radius]。 */
  function resolveWalls(state, params, previous, h) {
    var ball = state.ball;
    var world = state.world;
    var r = ball.radius;
    var right = world.width - r;
    var bottom = world.height - r;
    var restitution = params.restitution;

    if (ball.x < r) {
      ball.x = r;
      if (ball.vx < 0) {
        countImpact(state, -ball.vx);
        ball.vx = bounceVelocity(ball.vx, restitution);
      }
    } else if (ball.x > right) {
      ball.x = right;
      if (ball.vx > 0) {
        countImpact(state, ball.vx);
        ball.vx = bounceVelocity(ball.vx, restitution);
      }
    }

    if (ball.y < r) {
      ball.y = r;
      if (ball.vy < 0) {
        var upSpeed = previous
          ? Math.abs(verticalContactVelocity(previous.y, previous.vy, r, params.gravity, h))
          : Math.abs(ball.vy);
        countImpact(state, upSpeed);
        ball.vy = bounceVelocity(-upSpeed, restitution);
      }
    } else if (ball.y > bottom) {
      ball.y = bottom;
      if (ball.vy > 0) {
        var downSpeed = previous
          ? Math.abs(verticalContactVelocity(previous.y, previous.vy, bottom, params.gravity, h))
          : Math.abs(ball.vy);
        countImpact(state, downSpeed);
        ball.vy = bounceVelocity(downSpeed, restitution);
      }
    }
  }

  /**
   * 球与矩形障碍物的碰撞。
   * 采用“球心 + 圆角膨胀”的 AABB 近似：障碍物向外扩张一个半径，
   * 球心一旦进入该区域，就沿最近的一条边推出并反射对应速度分量。
   * 子步足够小，因此最近边就是真实撞击面。
   */
  function resolveObstacle(state, params, previous, h) {
    var ball = state.ball;
    var obstacle = state.obstacle;
    var restitution = params.restitution;
    var r = ball.radius;
    var minX = obstacle.x - r;
    var maxX = obstacle.x + obstacle.width + r;
    var minY = obstacle.y - r;
    var maxY = obstacle.y + obstacle.height + r;

    if (ball.x <= minX || ball.x >= maxX || ball.y <= minY || ball.y >= maxY) {
      return;
    }

    var previousInside =
      previous &&
      previous.x > minX &&
      previous.x < maxX &&
      previous.y > minY &&
      previous.y < maxY;
    var oldY = ball.y;
    var toLeft = ball.x - minX;
    var toRight = maxX - ball.x;
    var toTop = ball.y - minY;
    var toBottom = maxY - ball.y;
    var nearest = Math.min(toLeft, toRight, toTop, toBottom);

    if (nearest === toLeft) {
      ball.x = minX;
      if (ball.vx > 0) {
        countImpact(state, ball.vx);
        ball.vx = bounceVelocity(ball.vx, restitution);
      }
    } else if (nearest === toRight) {
      ball.x = maxX;
      if (ball.vx < 0) {
        countImpact(state, -ball.vx);
        ball.vx = bounceVelocity(ball.vx, restitution);
      }
    } else if (nearest === toTop) {
      ball.y = minY;
      if (ball.vy > 0) {
        var downSpeed = previous
          ? Math.abs(verticalContactVelocity(previous.y, previous.vy, minY, params.gravity, h))
          : Math.abs(ball.vy);
        countImpact(state, downSpeed);
        ball.vy = bounceVelocity(downSpeed, restitution);
      }
      if (previousInside && ball.y < oldY) {
        absorbLiftEnergy(state, params, oldY - ball.y);
      }
    } else {
      ball.y = maxY;
      if (ball.vy < 0) {
        var upSpeed = previous
          ? Math.abs(verticalContactVelocity(previous.y, previous.vy, maxY, params.gravity, h))
          : Math.abs(ball.vy);
        countImpact(state, upSpeed);
        ball.vy = bounceVelocity(-upSpeed, restitution);
      }
    }
  }

  function resolveContacts(state, params, previous, h) {
    resolveWalls(state, params, previous, h);
    if (params.obstacleEnabled) {
      resolveObstacle(state, params, previous, h);
      // 障碍物贴边时，推出动作仍可能把球推入墙外，再夹一次。
      // 这一次只做位置约束：速度若已朝外，不会再次反弹。
      resolveWalls(state, params, previous, h);
    }
  }

  /**
   * 在一个固定步内使用速度 Verlet 积分：
   *   p' = p + v·h + ½·g·h²
   *   v' = v + g·h
   * 常重力自由落体因此是解析精确的，能量不会因积分格式而虚假增长。
   */
  function integrate(state, params) {
    var ball = state.ball;
    var gravity = params.gravity;
    var substeps = estimateSubsteps(ball, gravity, FIXED_STEP);
    var h = FIXED_STEP / substeps;

    for (var i = 0; i < substeps; i += 1) {
      var previous = { x: ball.x, y: ball.y, vx: ball.vx, vy: ball.vy };
      ball.x += ball.vx * h;
      ball.y += ball.vy * h + 0.5 * gravity * h * h;
      ball.vy += gravity * h;
      resolveContacts(state, params, previous, h);
    }
  }

  /**
   * 推进恰好一个固定步（1/240 s）。
   */
  function step(state, params) {
    if (!state || !state.ball || !state.world) {
      throw new TypeError("step(state, params): state 必须由 makeState() 创建");
    }
    var normalized = normalizeParams(params);
    integrate(state, normalized);
    state.steps += 1;
    // 用步数换算时间，避免逐次累加的浮点漂移，保证不同帧率下时间严格一致。
    state.time = state.steps * FIXED_STEP;
    return state;
  }

  /**
   * 按真实经过时间推进仿真。
   *
   * elapsed 不是固定步长：它先被换算成“应推进的固定步数”，余量记在
   * state.acc 中。因此 30/60/120 fps 只要总时长相同，实际执行的固定步数
   * 就相同，最终状态也就相同；暂停时调用方不调用 advance 即可。
   *
   * @param {object} state
   * @param {number} elapsed 经过的秒数（>= 0）
   * @param {object} [params] {gravity, restitution, obstacleEnabled, mass}
   */
  function advance(state, elapsed, params) {
    if (!state || !state.ball || !state.world) {
      throw new TypeError("advance(state, elapsed, params): state 必须由 makeState() 创建");
    }
    if (!isFiniteNumber(elapsed) || elapsed <= 0) {
      return state;
    }

    var normalized = normalizeParams(params);
    // 用“固定步”为单位累计，抵消 1/30、1/60、1/120 的二进制浮点尾差。
    state.acc += elapsed / FIXED_STEP;
    var stepCount = Math.floor(state.acc + 1e-9);
    if (stepCount <= 0) {
      return state;
    }
    if (stepCount > MAX_STEPS_PER_ADVANCE) {
      stepCount = MAX_STEPS_PER_ADVANCE;
    }
    state.acc -= stepCount;
    // 把极小的负数余量归零，避免累计方向漂移。
    if (state.acc < 0 && state.acc > -1e-6) {
      state.acc = 0;
    }

    for (var i = 0; i < stepCount; i += 1) {
      integrate(state, normalized);
      state.steps += 1;
    }
    state.time = state.steps * FIXED_STEP;
    return state;
  }

  /**
   * 计算当前机械能（质量默认 1 kg，势能零点取球心最低可到位置）。
   * 重力滑杆变化会改变势能基准，这是“有原因”的能量变化。
   */
  function computeEnergy(state, params) {
    var normalized = normalizeParams(params);
    var ball = state.ball;
    var floorY = state.world.height - ball.radius;
    var height = Math.max(0, floorY - ball.y);
    var mass = normalized.mass;
    var kinetic = 0.5 * mass * (ball.vx * ball.vx + ball.vy * ball.vy);
    var potential = mass * normalized.gravity * height;
    return {
      kinetic: kinetic,
      potential: potential,
      total: kinetic + potential,
      mass: mass
    };
  }

  return {
    FIXED_STEP: FIXED_STEP,
    SPEC: SPEC,
    DEFAULT_PARAMS: DEFAULT_PARAMS,
    makeState: makeState,
    advance: advance,
    step: step,
    computeEnergy: computeEnergy,
    // 便于课堂/测试读取，但不改变物理行为
    _normalizeParams: normalizeParams
  };
});