local addon, ns = ...

local LSM = LibStub("LibSharedMedia-3.0")

ns.addonName = addon
ns.mediapath = "Interface\\AddOns\\rOrbs\\media\\"

-- Namespace containers
ns.cfg  = {}
ns.unit = CreateFrame("Frame")
ns.func = CreateFrame("Frame")
ns.player = {}

-- Register additional LSM fonts shipped with the addon
LSM:Register("font", "Enchanted Land", ns.mediapath .. "Enchanted_Land.otf")

rOrbs.defaults = { profile = {} }

rOrbs.defaults.profile.fonts = {
    textFont   = "Enchanted Land",
    numberFont = "Enchanted Land",
}

-- Frame dragging settings
rOrbs.defaults.profile.framesUserplaced = true
rOrbs.defaults.profile.framesLocked     = false

rOrbs.defaults.profile.units = {
    player = {
        show  = true,
        size  = 176,
        scale = 1,
        pos   = { a1 = "BOTTOM", a2 = "BOTTOM", af = "UIParent", x = -16, y = 600 },
        health = { frequentUpdates = true },
        power  = { frequentUpdates = true },
        absorb = { show = true },
    },
    target = {
        show  = true,
        size  = 80,
        scale = 1,
        pos   = { a1 = "BOTTOM", a2 = "BOTTOM", af = "UIParent", x = 264, y = 150 },
    },
    targetHealth = {
        show  = true,
        size  = 160,
        scale = 1,
        pos   = { a1 = "BOTTOM", a2 = "BOTTOM", af = "UIParent", x = 264, y = 2 },
        health = { frequentUpdates = true },
        absorb = { show = true },
    },
    targettarget = {
        show  = true,
        size  = 120,
        scale = 1,
        pos   = { a1 = "BOTTOM", a2 = "BOTTOM", af = "UIParent", x = 420, y = 2 },
        health = { frequentUpdates = true },
        absorb = { show = true },
    },
}

-- GUI defaults stored inside rOrbsDB
rOrbs.defaults.gui = {
    minimap    = { hide = false },
    debug      = false,
    frameLocked = false,
}

ns.defaults = rOrbs.defaults

-- Stubs (filled in after GUI loads)
function rOrbs:AddConfig() end
function rOrbs:TriggerReload() end

-- Load config after VARIABLES_LOADED
local loader = CreateFrame("Frame")
loader:RegisterEvent("VARIABLES_LOADED")
loader:SetScript("OnEvent", function(self, event)
    self:UnregisterEvent("VARIABLES_LOADED")

    -- ── SavedVariable: rOrbsDB (GUI & position settings) ──────────────
    if not rOrbsDB then
        rOrbsDB = {}
    end
    -- Merge GUI defaults into rOrbsDB without overwriting saved values
    local guiDef = rOrbs.defaults.gui
    if rOrbsDB.minimap == nil    then rOrbsDB.minimap     = { hide = false } end
    if rOrbsDB.debug == nil      then rOrbsDB.debug        = false           end
    rOrbsDB.frameLocked = true  -- overlay always hidden; drag via Shift+Alt

    -- Target orb settings
    if rOrbsDB.targetModelShow   == nil then rOrbsDB.targetModelShow   = true  end
    if rOrbsDB.targetModelAlpha  == nil then rOrbsDB.targetModelAlpha  = 1     end
    if rOrbsDB.targetPortraitShow == nil then rOrbsDB.targetPortraitShow = false end
    if rOrbsDB.targetClassColor  == nil then rOrbsDB.targetClassColor  = true  end
    if rOrbsDB.targetRingShow    == nil then rOrbsDB.targetRingShow    = true  end
    if rOrbsDB.targetOrbEnabled  == nil then rOrbsDB.targetOrbEnabled  = true  end

    -- Target-of-Target orb settings
    if rOrbsDB.totOrbEnabled     == nil then rOrbsDB.totOrbEnabled     = false end
    if rOrbsDB.totModelShow      == nil then rOrbsDB.totModelShow      = false end
    if rOrbsDB.totModelAlpha     == nil then rOrbsDB.totModelAlpha     = 1     end
    if rOrbsDB.totPortraitShow   == nil then rOrbsDB.totPortraitShow   = false end
    if rOrbsDB.totClassColor     == nil then rOrbsDB.totClassColor     = true  end
    if rOrbsDB.totRingShow       == nil then rOrbsDB.totRingShow       = true  end
    if rOrbsDB.totNameShow       == nil then rOrbsDB.totNameShow       = true  end
    if rOrbsDB.totNameFontSize   == nil then rOrbsDB.totNameFontSize   = 18    end
    if rOrbsDB.totNamePos        == nil then rOrbsDB.totNamePos        = "TOP" end
    if rOrbsDB.totNameClassColor == nil then rOrbsDB.totNameClassColor = false end
    if rOrbsDB.totNameOffY       == nil then rOrbsDB.totNameOffY       = -8    end

    -- Health / Power ring + figure visibility
    if rOrbsDB.healthRingShow  == nil then rOrbsDB.healthRingShow  = true end
    if rOrbsDB.powerRingShow   == nil then rOrbsDB.powerRingShow   = true end
    if rOrbsDB.healthAngelShow == nil then rOrbsDB.healthAngelShow = true end
    if rOrbsDB.powerDemonShow  == nil then rOrbsDB.powerDemonShow  = true end

    -- Figure position & scale defaults (from SavedVariables reference)
    if rOrbsDB.angelScale == nil then rOrbsDB.angelScale = 0.95 end
    if rOrbsDB.angelOffX  == nil then rOrbsDB.angelOffX  = 57   end
    if rOrbsDB.angelOffY  == nil then rOrbsDB.angelOffY  = 10   end
    if rOrbsDB.demonScale == nil then rOrbsDB.demonScale = 1.0  end
    if rOrbsDB.demonOffX  == nil then rOrbsDB.demonOffX  = -74  end
    if rOrbsDB.demonOffY  == nil then rOrbsDB.demonOffY  = 4    end

    -- Font defaults
    if rOrbsDB["font_HEALTH"]        == nil then rOrbsDB["font_HEALTH"]        = "Enchanted Land" end
    if rOrbsDB["font_POWER"]         == nil then rOrbsDB["font_POWER"]         = "Enchanted Land" end
    if rOrbsDB["font_TARGET_HEALTH"] == nil then rOrbsDB["font_TARGET_HEALTH"] = "Enchanted Land" end

    -- ToT font defaults
    if rOrbsDB["font_TOT_HEALTH"]         == nil then rOrbsDB["font_TOT_HEALTH"]         = "Enchanted Land" end
    if rOrbsDB["fontSize_TOT_HEALTH"]     == nil then rOrbsDB["fontSize_TOT_HEALTH"]     = 28 end
    if rOrbsDB["textShow_TOT_HEALTH"]     == nil then rOrbsDB["textShow_TOT_HEALTH"]     = true end
    if rOrbsDB["textHover_TOT_HEALTH"]    == nil then rOrbsDB["textHover_TOT_HEALTH"]    = true end
    if rOrbsDB["textAlpha_TOT_HEALTH"]    == nil then rOrbsDB["textAlpha_TOT_HEALTH"]    = 0.8  end
    if rOrbsDB["glossTex_TOT_HEALTH"]     == nil then rOrbsDB["glossTex_TOT_HEALTH"]     = "classic" end

    -- Font size defaults
    if rOrbsDB["fontSize_HEALTH"]        == nil then rOrbsDB["fontSize_HEALTH"]        = 35 end
    if rOrbsDB["fontSize_POWER"]         == nil then rOrbsDB["fontSize_POWER"]         = 35 end
    if rOrbsDB["fontSize_TARGET_HEALTH"] == nil then rOrbsDB["fontSize_TARGET_HEALTH"] = 34 end

    -- Text show/hover/alpha defaults
    if rOrbsDB["textShow_HEALTH"]        == nil then rOrbsDB["textShow_HEALTH"]        = true end
    if rOrbsDB["textShow_POWER"]         == nil then rOrbsDB["textShow_POWER"]         = true end
    if rOrbsDB["textShow_TARGET_HEALTH"] == nil then rOrbsDB["textShow_TARGET_HEALTH"] = true end
    if rOrbsDB["textHover_HEALTH"]       == nil then rOrbsDB["textHover_HEALTH"]       = true end
    if rOrbsDB["textHover_POWER"]        == nil then rOrbsDB["textHover_POWER"]        = true end
    if rOrbsDB["textHover_TARGET_HEALTH"]== nil then rOrbsDB["textHover_TARGET_HEALTH"]= true end
    if rOrbsDB["textAlpha_HEALTH"]       == nil then rOrbsDB["textAlpha_HEALTH"]       = 0.8  end
    if rOrbsDB["textAlpha_POWER"]        == nil then rOrbsDB["textAlpha_POWER"]        = 0.8  end
    if rOrbsDB["textAlpha_TARGET_HEALTH"]== nil then rOrbsDB["textAlpha_TARGET_HEALTH"]= 0.8  end
    if rOrbsDB["textMode_HEALTH"]        == nil then rOrbsDB["textMode_HEALTH"]        = "BOTH" end

    -- Target name text defaults
    if rOrbsDB["targetNameShow"]       == nil then rOrbsDB["targetNameShow"]       = true  end
    if rOrbsDB["targetNameFontSize"]   == nil then rOrbsDB["targetNameFontSize"]   = 22    end
    if rOrbsDB["targetNamePos"]        == nil then rOrbsDB["targetNamePos"]        = "TOP" end
    if rOrbsDB["targetNameClassColor"] == nil then rOrbsDB["targetNameClassColor"] = false end
    if rOrbsDB["targetNameOffY"]       == nil then rOrbsDB["targetNameOffY"]       = -8    end

    -- Cast Ring defaults
    if rOrbsDB.castRingEnabled        == nil then rOrbsDB.castRingEnabled        = true    end
    if rOrbsDB.castRingRingScale      == nil then rOrbsDB.castRingRingScale      = 1.0     end
    if rOrbsDB.castRingUseClassColor  == nil then rOrbsDB.castRingUseClassColor  = false   end
    if rOrbsDB.castRingCastR          == nil then rOrbsDB.castRingCastR          = 1.0     end
    if rOrbsDB.castRingCastG          == nil then rOrbsDB.castRingCastG          = 0.15    end
    if rOrbsDB.castRingCastB          == nil then rOrbsDB.castRingCastB          = 0.05    end
    if rOrbsDB.castRingChanR          == nil then rOrbsDB.castRingChanR          = 0.3     end
    if rOrbsDB.castRingChanG          == nil then rOrbsDB.castRingChanG          = 0.6     end
    if rOrbsDB.castRingChanB          == nil then rOrbsDB.castRingChanB          = 1.0     end
    if rOrbsDB.castRingBgMode         == nil then rOrbsDB.castRingBgMode         = "rose_bright" end
    if rOrbsDB.castRingBgAlpha        == nil then rOrbsDB.castRingBgAlpha        = 0.8     end
    if rOrbsDB.castRingFadeTime       == nil then rOrbsDB.castRingFadeTime       = 0.4     end
    if rOrbsDB.castRingBgR            == nil then rOrbsDB.castRingBgR            = 1.0     end
    if rOrbsDB.castRingBgG            == nil then rOrbsDB.castRingBgG            = 1.0     end
    if rOrbsDB.castRingBgB            == nil then rOrbsDB.castRingBgB            = 1.0     end
    if rOrbsDB.castRingBgClassColor   == nil then rOrbsDB.castRingBgClassColor   = false   end

    -- Player Combat Icon: size & position offset (relative to auto-position)
    if rOrbsDB.playerCombatIconSize  == nil then rOrbsDB.playerCombatIconSize  = 28 end
    if rOrbsDB.playerCombatIconOffX  == nil then rOrbsDB.playerCombatIconOffX  = 0  end
    if rOrbsDB.playerCombatIconOffY  == nil then rOrbsDB.playerCombatIconOffY  = 0  end
    -- Player Resting Icon: size & position offset
    if rOrbsDB.playerRestingIconSize == nil then rOrbsDB.playerRestingIconSize = 28 end
    if rOrbsDB.playerRestingIconOffX == nil then rOrbsDB.playerRestingIconOffX = 0  end
    if rOrbsDB.playerRestingIconOffY == nil then rOrbsDB.playerRestingIconOffY = 0  end
    if rOrbsDB.playerRestingIconColor == nil then rOrbsDB.playerRestingIconColor = { r = 1, g = 1, b = 1 } end
    -- Target Combat Icon: size & position offset
    if rOrbsDB.targetCombatIconSize  == nil then rOrbsDB.targetCombatIconSize  = 28 end
    if rOrbsDB.targetCombatIconOffX  == nil then rOrbsDB.targetCombatIconOffX  = 0  end
    if rOrbsDB.targetCombatIconOffY  == nil then rOrbsDB.targetCombatIconOffY  = 0  end

    -- Orb template defaults
    if rOrbsDB["tmplShow_HEALTH"]        == nil then rOrbsDB["tmplShow_HEALTH"]        = true  end
    if rOrbsDB["tmplShow_POWER"]         == nil then rOrbsDB["tmplShow_POWER"]         = true  end
    if rOrbsDB["tmplShow_TARGET_HEALTH"] == nil then rOrbsDB["tmplShow_TARGET_HEALTH"] = false end
    if rOrbsDB["tmplOpacity_HEALTH"]        == nil then rOrbsDB["tmplOpacity_HEALTH"]        = 1 end
    if rOrbsDB["tmplOpacity_POWER"]         == nil then rOrbsDB["tmplOpacity_POWER"]         = 1 end
    if rOrbsDB["tmplOpacity_TARGET_HEALTH"] == nil then rOrbsDB["tmplOpacity_TARGET_HEALTH"] = 1 end
    if rOrbsDB["tmplScale_HEALTH"]        == nil then rOrbsDB["tmplScale_HEALTH"]        = 1 end
    if rOrbsDB["tmplScale_POWER"]         == nil then rOrbsDB["tmplScale_POWER"]         = 1 end
    if rOrbsDB["tmplScale_TARGET_HEALTH"] == nil then rOrbsDB["tmplScale_TARGET_HEALTH"] = 1 end
    if rOrbsDB["tmplColors_HEALTH"] == nil then rOrbsDB["tmplColors_HEALTH"] = false end
    if rOrbsDB["tmplColors_POWER"]  == nil then rOrbsDB["tmplColors_POWER"]  = true  end
    if rOrbsDB["orbTemplate_HEALTH"]        == nil then rOrbsDB["orbTemplate_HEALTH"]        = "red-portal"          end
    if rOrbsDB["orbTemplate_POWER"]         == nil then rOrbsDB["orbTemplate_POWER"]         = "blue-magic-tornado"  end
    if rOrbsDB["orbTemplate_TARGET_HEALTH"] == nil then rOrbsDB["orbTemplate_TARGET_HEALTH"] = "blue-swirly"         end

    -- Gloss texture selection (new/classic)
    if rOrbsDB["glossTex_HEALTH"]        == nil then rOrbsDB["glossTex_HEALTH"]        = "new"     end
    if rOrbsDB["glossTex_POWER"]         == nil then rOrbsDB["glossTex_POWER"]         = "new"     end
    if rOrbsDB["glossTex_TARGET_HEALTH"] == nil then rOrbsDB["glossTex_TARGET_HEALTH"] = "classic" end

    -- Smooth bar defaults
    if rOrbsDB["smoothBar_HEALTH"] == nil then rOrbsDB["smoothBar_HEALTH"] = true end
    if rOrbsDB["smoothSpeed"]      == nil then rOrbsDB["smoothSpeed"]      = 10   end

    if not rOrbsDB.frameScales    then rOrbsDB.frameScales    = {} end
    if not rOrbsDB.framePositions then rOrbsDB.framePositions = {} end

    -- ── Apply profile defaults → ns.cfg ───────────────────────────────
    ns.cfg = {}
    for k, v in pairs(rOrbs.defaults.profile) do
        ns.cfg[k] = v
    end

    -- Restore frame lock state from SavedVariables
    ns.cfg.framesUserplaced = true
    ns.cfg.framesLocked     = rOrbsDB.frameLocked or false

    -- Apply saved position/size overrides to unit config
    local unitKeys = { "player", "targetHealth", "target", "targettarget" }
    for _, uKey in ipairs(unitKeys) do
        if ns.cfg.units and ns.cfg.units[uKey] then
            local savedX    = rOrbsDB["pos_"  .. uKey .. "_x"]
            local savedY    = rOrbsDB["pos_"  .. uKey .. "_y"]
            local savedSize = rOrbsDB["size_" .. uKey]
            if savedX    then ns.cfg.units[uKey].pos.x = savedX    end
            if savedY    then ns.cfg.units[uKey].pos.y = savedY    end
            if savedSize then ns.cfg.units[uKey].size  = savedSize end
        end
    end

    -- Apply saved font overrides (always set, falling back to "Enchanted Land" default)
    local healthFont = rOrbsDB["font_HEALTH"] or "Enchanted Land"
    local powerFont  = rOrbsDB["font_POWER"]  or "Enchanted Land"
    local targetFont = rOrbsDB["font_TARGET_HEALTH"] or "Enchanted Land"
    if LSM:Fetch("font", healthFont) then
        ns.cfg.fonts.textFont = healthFont
    else
        ns.cfg.fonts.textFont = "Enchanted Land"
    end
    if LSM:Fetch("font", powerFont) then
        ns.cfg.fonts.numberFont = powerFont
    else
        ns.cfg.fonts.numberFont = "Enchanted Land"
    end
    -- targetFont is handled directly in target-health.lua

    -- Debug flag
    ns.debug = rOrbsDB.debug == true

    -- Spawn orbs
    C_Timer.After(0, function()
        ns:Init()
    end)

    -- ── Profile auto-apply on PLAYER_LOGIN ────────────────────────────
    -- PLAYER_LOGIN fires after ADDON_LOADED when UnitName("player") is valid.
    -- At that point we can build the char key and apply the correct profile.
    local profileFrame = CreateFrame("Frame")
    profileFrame:RegisterEvent("PLAYER_LOGIN")
    profileFrame:SetScript("OnEvent", function(self, event)
        self:UnregisterEvent("PLAYER_LOGIN")
        if ns.db and ns.db.applyCharProfile then
            ns.db.applyCharProfile()
        end
    end)
end)
