/* sound-core.js — 声音树 · 纯函数核心（无 DOM、无定时器、无副作用）
 *
 * 职责：
 *  - computeRMS(samples): 对真实 PCM 样本计算 RMS（真实分析音量）
 *  - classify(rms, thresholds): 按 spec 阈值分级 quiet / soft / loud
 *  - createTree() / updateTree(tree, level, dt): 树的生长状态机（纯函数，返回新对象）
 *
 * 阈值严格来自 spec.json：rmsThresholds = { quietBelow: 0.01, loudAtLeast: 0.1 }
 *   rms <  0.01            -> quiet（安静）
 *   0.01 <= rms < 0.1      -> soft （轻声）
 *   rms >= 0.1             -> loud （响亮）
 */
(function (root, factory) {
  if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else {
    root.SoundCore = factory();
  }
})(typeof self !== "undefined" ? self : this, function () {
  "use strict";

  var QUIET_BELOW = 0.01;
  var LOUD_AT_LEAST = 0.1;

  var LEVELS = { QUIET: "quiet", SOFT: "soft", LOUD: "loud" };

  /* 生长速率（每秒进度增量，0-100），安静时缓慢凋萎 */
  var GROWTH_PER_SECOND = { quiet: -3, soft: 8, loud: 20 };
  var MAX_PROGRESS = 100;

  var STAGES = [
    { min: 0, name: "种子" },
    { min: 15, name: "嫩芽" },
    { min: 40, name: "幼苗" },
    { min: 70, name: "小树" },
    { min: 90, name: "繁茂" },
  ];

  var TOTAL_LEAVES = 24;

  /** 对一段 PCM 样本（Float32Array 或 number[]）计算均方根。空样本返回 0。 */
  function computeRMS(samples) {
    if (!samples || samples.length === 0) return 0;
    var sum = 0;
    for (var i = 0; i < samples.length; i++) {
      sum += samples[i] * samples[i];
    }
    return Math.sqrt(sum / samples.length);
  }

  /** 按 spec 阈值把 RMS 分级。阈值可注入，缺省用 spec 值。 */
  function classify(rms, thresholds) {
    var th = thresholds || { quietBelow: QUIET_BELOW, loudAtLeast: LOUD_AT_LEAST };
    if (rms < th.quietBelow) return LEVELS.QUIET;
    if (rms >= th.loudAtLeast) return LEVELS.LOUD;
    return LEVELS.SOFT;
  }

  /** 新建树状态（纯数据）。 */
  function createTree() {
    return {
      progress: 0,
      stage: STAGES[0].name,
      leaves: 0,
      mood: "asleep", // asleep: 未发声；folded: 安静；gentle: 轻声；bright: 响亮
      lastLevel: null,
      elapsed: 0, // 有声累计秒数（仅用于展示）
    };
  }

  /** 由进度推导阶段与叶子数量。 */
  function deriveTreeFields(tree) {
    var stage = STAGES[0].name;
    for (var i = 0; i < STAGES.length; i++) {
      if (tree.progress >= STAGES[i].min) stage = STAGES[i].name;
    }
    tree.stage = stage;
    tree.leaves = Math.round((tree.progress / MAX_PROGRESS) * TOTAL_LEAVES);
    return tree;
  }

  /**
   * 纯状态更新：根据当前声音级别与时间步长 dt（秒）推进树。
   * - soft/loud：按速率生长；loud 时叶片 "bright"，soft 时 "gentle"
   * - quiet：叶片 "folded"，进度缓慢回落（不低于 0）
   * 不修改传入对象；不可变输入，可重复执行，便于测试。
   */
  function updateTree(tree, level, dt) {
    if (dt < 0) throw new Error("dt must be >= 0");
    var next = {
      progress: tree.progress,
      stage: tree.stage,
      leaves: tree.leaves,
      mood: tree.mood,
      lastLevel: level,
      elapsed: tree.elapsed,
    };
    if (level === LEVELS.QUIET) {
      next.mood = "folded";
      var delta = GROWTH_PER_SECOND.quiet * dt;
      next.progress = Math.max(0, next.progress + delta);
    } else if (level === LEVELS.SOFT) {
      next.mood = "gentle";
      next.progress = Math.min(MAX_PROGRESS, next.progress + GROWTH_PER_SECOND.soft * dt);
      next.elapsed = tree.elapsed + dt;
    } else if (level === LEVELS.LOUD) {
      next.mood = "bright";
      next.progress = Math.min(MAX_PROGRESS, next.progress + GROWTH_PER_SECOND.loud * dt);
      next.elapsed = tree.elapsed + dt;
    } else if (level === null) {
      // 尚未发声（例如暂停中）：保持原状
      next.mood = tree.progress > 0 ? tree.mood : "asleep";
      next.lastLevel = tree.lastLevel;
    } else {
      throw new Error("unknown level: " + level);
    }
    return deriveTreeFields(next);
  }

  return {
    LEVELS: LEVELS,
    QUIET_BELOW: QUIET_BELOW,
    LOUD_AT_LEAST: LOUD_AT_LEAST,
    GROWTH_PER_SECOND: GROWTH_PER_SECOND,
    TOTAL_LEAVES: TOTAL_LEAVES,
    STAGES: STAGES,
    computeRMS: computeRMS,
    classify: classify,
    createTree: createTree,
    updateTree: updateTree,
  };
});
