local NS = rawget(_G, "MCDVoiceCooldownNS") or {}
_G.MCDVoiceCooldownNS = NS

NS.UI = NS.UI or {}
NS.UI.EditorDrafts = NS.UI.EditorDrafts or {}

local Drafts = NS.UI.EditorDrafts

local EDITOR_DRAFT_FIELDS = {
    "spellId", "objectType", "spellName",
    "baseCD", "fixedCD", "checkTalent", "talentId", "talentName", "talentCD",
    "delayEnabled", "delaySeconds",
    "notifyMode", "ttsText", "ttsRate",
    "builtinSoundPath", "sharedMediaSound", "useSharedMediaSound",
    "customSoundPath", "useCustomSound", "soundSource", "soundPath",
}

function Drafts:NormalizeEntryType(value)
    value = tostring(value or "cooldown")
    if value == "cast" then
        return "cast"
    end
    return "cooldown"
end

function Drafts:Save(state, entryType)
    if not state then
        return
    end
    entryType = self:NormalizeEntryType(entryType or state.entryType)
    state._editorDrafts = state._editorDrafts or {}
    local draft = {}
    for _, key in ipairs(EDITOR_DRAFT_FIELDS) do
        draft[key] = state[key]
    end
    state._editorDrafts[entryType] = draft
end

function Drafts:ApplyBlank(state, entryType)
    if not state then
        return
    end
    local api = NS.API
    local modeSound = "SOUND"
    if api and type(api.GetModes) == "function" then
        local _modeTts
        _modeTts, modeSound = api.GetModes()
    end
    local defaultSound = NS.AceOptions and NS.AceOptions.GetDefaultBuiltinSoundPath and NS.AceOptions:GetDefaultBuiltinSoundPath() or ""

    state.spellId = 0
    state.objectType = nil
    state.spellName = ""
    state.baseCD = 0
    state.fixedCD = true
    state.checkTalent = false
    state.talentId = 0
    state.talentName = ""
    state.talentCD = 0
    state.delayEnabled = false
    state.delaySeconds = 0
    state.notifyMode = modeSound
    state.ttsText = ""
    state.ttsRate = 0
    state.builtinSoundPath = defaultSound
    state.sharedMediaSound = ""
    state.useSharedMediaSound = false
    state.customSoundPath = ""
    state.useCustomSound = false
    state.soundSource = "builtin"
    state.soundPath = defaultSound
    state.entryType = self:NormalizeEntryType(entryType)
end

function Drafts:Restore(state, entryType)
    if not state then
        return
    end
    entryType = self:NormalizeEntryType(entryType)
    local draft = state._editorDrafts and state._editorDrafts[entryType]
    if type(draft) ~= "table" then
        self:ApplyBlank(state, entryType)
        return
    end
    for _, key in ipairs(EDITOR_DRAFT_FIELDS) do
        state[key] = draft[key]
    end
    state.entryType = entryType
    state.fixedCD = true
end
