-- 脚本的位置是 "{命名空间}:{路径}"，那么 require 的格式为 "{命名空间}_{路径}"
-- 注意！require 取得的内容不应该被修改，应仅调用
local default = require("tacz_default_state_machine")
local STATIC_TRACK_LINE = default.STATIC_TRACK_LINE
local GUN_KICK_TRACK_LINE = default.GUN_KICK_TRACK_LINE
local MAIN_TRACK = default.MAIN_TRACK
local main_track_states = default.main_track_states

-- main_track_states.idle 重写，继承原版idle
local idle_state = setmetatable({}, {__index = main_track_states.idle})

-- 充电状态，增加元表继承基础状态，统一this访问规则
local charge_state = setmetatable({
    can_charge = true
}, {__index = main_track_states.idle})

-- 常态检测（延迟扳机）
function idle_state.update(this, context)
    if context:isCharging() then
        if charge_state.can_charge then
            context:trigger(this.INPUT_CHARING)
        end
    else
        charge_state.can_charge = true
    end
end

-- 重写 idle 状态的 transition 函数，跳转charge
function idle_state.transition(this, context, input)
    if input == this.INPUT_CHARING then
        context:runAnimation("charge_in", context:getTrack(STATIC_TRACK_LINE, MAIN_TRACK), false, PLAY_ONCE_HOLD, 0)
        return this.main_track_states.charge
    end
    -- 原版逻辑兜底
    return main_track_states.idle.transition(this, context, input)
end

-- 进入延迟扳机状态更新
function charge_state.update(this, context)
    if not context:isCharging() then
        charge_state.can_charge = true
        context:trigger(this.INPUT_CHARING_EXIT)
    end
end

-- 【核心修复】charge_state.transition 补充默认返回 + 补全this.前缀
function charge_state.transition(this, context, input)
    -- 射击释放
    if input == this.INPUT_SHOOT then
        context:stopAnimation(context:getTrack(STATIC_TRACK_LINE, MAIN_TRACK))
        charge_state.can_charge = false
        return this.main_track_states.idle
    end
    -- 松开充电，退出动画
    if input == this.INPUT_CHARING_EXIT then
        context:runAnimation("charge_out", context:getTrack(STATIC_TRACK_LINE, MAIN_TRACK), false, PLAY_ONCE_STOP, 0.3)
        return this.main_track_states.idle
    end
    -- 关键兜底：任意其他输入返回自身，杜绝nil返回
    return this.main_track_states.charge
end

-- 导出状态机主表，继承默认状态机
local M = setmetatable({
    main_track_states = setmetatable({
        idle = idle_state,
        charge = charge_state
    }, {__index = main_track_states}),
    INPUT_RELOAD_RETREAT = "reload_retreat",
    INPUT_CHARING = "input_charging",
    INPUT_CHARING_EXIT = "input_charging_exit"
}, {__index = default})

-- 初始化
function M:initialize(context)
    default.initialize(self, context)
    -- 初始化充电标记
    self.main_track_states.charge.can_charge = true
end

-- 导出
return M