-- NP_CastbarTest/core.lua
local ADDON, ns = ...

-- =========================================================
--  DB / DEFAULTS  (SavedVariables: PomcaDB)
--  IMPORTANT:
--   - NEVER init DB at file-load time in 12.0, because SavedVariables
--     can be loaded AFTER lua chunks run (depending on load order).
--   - Init ONLY on ADDON_LOADED for THIS addon.
--   - Never replace PomcaDB with a new table reference after load.
-- =========================================================
local DEFAULTS = {
    enabled = true,

    scale = 1.0,
    width = 140,
    height = 12,

    showIcon = true,
    showBorder = true,

    interrupt = { ttl = 0.80 },

    colors = {
        normal      = { r=1.0, g=0.7, b=0.0, a=1.0 },  -- yellow
        important   = { r=1.0, g=0.1, b=0.1, a=1.0 },  -- red
        noKick      = { r=0.0, g=0.0, b=0.0, a=0.90 }, -- black
        interrupted = { r=0.6, g=0.2, b=1.0, a=1.0 },  -- purple
        text        = { r=1.0, g=1.0, b=1.0, a=1.0 },
        bg          = { r=0.0, g=0.0, b=0.0, a=0.60 },
        border      = { r=0.05, g=0.05, b=0.05, a=1.0 },
        shield      = { r=1.0, g=1.0, b=1.0, a=0.18 },
    },

    fonts = { index = 1, size = 10, outline = "OUTLINE" },
    skins = { index = 1 },

    -- =========================================================
    --  POSITION / PREVIEW (used when adjusting the castbar)
    -- =========================================================
    position = {
        attachToBlizz = true,   -- anchor to Blizzard nameplate castbar when available
        point = "CENTER",       -- our point
        relPoint = "CENTER",    -- relative point on the anchor
        x = 0,
        y = 0,

        unlocked = false,       -- allow drag-to-move (preview/target only)
        alwaysShow = false,     -- show a preview bar when no cast is happening
    },
}

local function CopyDefaults(src, dst)
    if type(dst) ~= "table" then return end
    for k, v in pairs(src) do
        if type(v) == "table" then
            if type(dst[k]) ~= "table" then dst[k] = {} end
            CopyDefaults(v, dst[k])
        elseif dst[k] == nil then
            dst[k] = v
        end
    end
end

local function InitDB_AfterSavedVariablesLoaded()
    -- PomcaDB is the SavedVariables table (from .toc)
    if type(PomcaDB) ~= "table" then
        PomcaDB = {}
    end

    -- Optional migration (only if PomcaDB is empty)
    if _G.NPCT_DB and next(PomcaDB) == nil then
        for k, v in pairs(_G.NPCT_DB) do
            if PomcaDB[k] == nil then
                PomcaDB[k] = v
            end
        end
    end

    CopyDefaults(DEFAULTS, PomcaDB)

    ns.DB = PomcaDB
    ns.DEFAULTS = DEFAULTS
end

-- =========================================================
--  SLASH (opens settings frame)
-- =========================================================
SLASH_POMCA1 = "/pomca"
SLASH_POMCA2 = "/npct"
SLASH_POMCA3 = "/npcbt"

SlashCmdList.POMCA = function(msg)
    msg = (msg or ""):lower()

    -- If someone types /pomca very early, before ADDON_LOADED ran:
    if type(ns.DB) ~= "table" then
        print("|cffff3333POMCA: DB not ready yet (try again).|r")
        return
    end

    if msg == "reset" then
        -- Wipe IN PLACE (keep the same table reference so WoW saves it)
        for k in pairs(PomcaDB) do
            PomcaDB[k] = nil
        end
        CopyDefaults(DEFAULTS, PomcaDB)
        ns.DB = PomcaDB

        if ns.Castbar and ns.Castbar.RefreshAllPlates then
            ns.Castbar:RefreshAllPlates()
        end
        print("|cff66ff66POMCA: settings reset.|r")
        return
    end

    -- Open UI
    if ns.Settings and ns.Settings.Toggle then
        ns.Settings:Toggle()
    elseif ns.CASet and ns.CASet.Toggle then
        ns.CASet:Toggle()
    else
        print("|cffff3333POMCA: settings UI not loaded (check caset.lua/settings.lua).|r")
    end
end

-- =========================================================
--  EVENT BOOTSTRAP (THIS fixes saving + double /pomca)
-- =========================================================
local boot = CreateFrame("Frame")
boot:RegisterEvent("ADDON_LOADED")
boot:SetScript("OnEvent", function(_, event, addonName)
    if event ~= "ADDON_LOADED" then return end
    if addonName ~= ADDON then return end

    -- ✅ Init DB ONLY here (after SavedVariables are real)
    InitDB_AfterSavedVariablesLoaded()

    -- Optional: apply styles immediately when login is done-ish
    if ns.Castbar and ns.Castbar.RefreshAllPlates then
        ns.Castbar:RefreshAllPlates()
    end

    -- ✅ Start ticker ONLY after DB exists (prevents nil/default ghost state)
    if not ns._ticker then
        ns._ticker = C_Timer.NewTicker(0.05, function()
            local db = ns.DB
            if not (db and db.enabled) then return end
            if not (C_NamePlate and C_NamePlate.GetNamePlates) then return end
            if not (ns.Castbar and ns.Castbar.UpdatePlate) then return end

            for _, plate in pairs(C_NamePlate.GetNamePlates()) do
                ns.Castbar:UpdatePlate(plate)
            end
        end)
    end
end)
