local addonName, addon = ...

--------------------------------------------------
-- DEFAULTS
--------------------------------------------------

addon.defaults = {
    enabled = true,
    scale = 1.0,
    fontSize = 14,
    font = "Expressway",
    fontPath = "Interface\\AddOns\\compact_utility_panel\\Media\\Fonts\\Expressway.TTF",
    pullCountdown = 10,
    locked = false,
    opacity = 0.90,
    panelColor = {
        r = 0.05,
        g = 0.05,
        b = 0.05,
    },
    borderColor = {
        r = 0.35,
        g = 0.35,
        b = 0.35,
    },
    borderWidth = 1,
    fontColor = {
        r = 1,
        g = 1,
        b = 1,
    },
}

--------------------------------------------------
-- DATABASE INITIALIZATION
--------------------------------------------------

function addon:InitializeDatabase()
    if not CompactUtilityPanelDB then
        CompactUtilityPanelDB = {}
    end

    local db = CompactUtilityPanelDB

    for key, value in pairs(self.defaults) do
        if db[key] == nil then
            if type(value) == "table" then
                db[key] = CopyTable(value)
            else
                db[key] = value
            end
        end
    end

    --------------------------------------------------
    -- FONT / FONT PATH SANITIZATION
    --------------------------------------------------

    if not db.fontPath or db.fontPath == "" then
        db.fontPath = self.defaults.fontPath
    end

    if not db.font or db.font == "" then
        db.font = self.defaults.font
    end

    if not db.fontSize or tonumber(db.fontSize) <= 0 then
        db.fontSize = self.defaults.fontSize
    end

    self.fontPath = db.fontPath
    self.fontSize = tonumber(db.fontSize) or 14

    --------------------------------------------------
    -- PULL COUNTDOWN SANITIZATION
    --------------------------------------------------

    if db.pullCountdown == nil then
        db.pullCountdown = self.defaults.pullCountdown
    end

    db.pullCountdown = math.max(
        1,
        math.min(
            30,
            tonumber(db.pullCountdown) or self.defaults.pullCountdown
        )
    )

    --------------------------------------------------
    -- OPACITY
    --------------------------------------------------

    if db.opacity == nil then
        db.opacity = self.defaults.opacity
    end

    db.opacity = math.max(
        0.00,
        math.min(
            1.00,
            tonumber(db.opacity) or self.defaults.opacity
        )
    )

    --------------------------------------------------
    -- COLORS / BORDER
    --------------------------------------------------

    if type(db.panelColor) ~= "table" then
        db.panelColor = CopyTable(self.defaults.panelColor)
    end

    if type(db.borderColor) ~= "table" then
        db.borderColor = CopyTable(self.defaults.borderColor)
    end

    if type(db.fontColor) ~= "table" then
        db.fontColor = CopyTable(self.defaults.fontColor)
    end

    if not db.borderWidth then
        db.borderWidth = self.defaults.borderWidth
    end
end

--------------------------------------------------
-- FONT PATH HELPER
--------------------------------------------------

function addon:GetFontPath(fontName)
    if self.FONT_LIST then
        for _, fontInfo in ipairs(self.FONT_LIST) do
            if fontInfo.name == fontName then
                return fontInfo.file
            end
        end
    end

    return self.defaults.fontPath
end

function addon:LoadFontSettings()
    local db = CompactUtilityPanelDB

    if not db then
        return
    end

    if db.font then
        local resolvedPath = self:GetFontPath(db.font)

        if resolvedPath then
            db.fontPath = resolvedPath
            self.fontPath = resolvedPath
        end
    end

    if db.fontSize then
        self.fontSize = tonumber(db.fontSize) or 14
    end
end

--------------------------------------------------
-- SETTINGS APPLY
--------------------------------------------------

function addon:ApplySettings()
    local db = CompactUtilityPanelDB

    if not db then
        return
    end

    if not self.panel then
        return
    end

    if db.enabled then
        self.panel:Show()
    else
        self.panel:Hide()
    end

    if self.content and db.scale then
        self.content:SetScale(tonumber(db.scale) or 1.0)
    end

    if self.ApplyVisualSettings then
        self:ApplyVisualSettings()
    end

    if self.RefreshFonts then
        self:RefreshFonts()
    end
end

--------------------------------------------------
-- POSITIONING
--------------------------------------------------

function addon:ResetPosition()
    if not self.panel then
        return
    end

    self.panel:ClearAllPoints()
    self.panel:SetPoint("CENTER", UIParent, "CENTER", 0, 0)

    if CompactUtilityPanelDB then
        CompactUtilityPanelDB.point = "CENTER"
        CompactUtilityPanelDB.relativePoint = "CENTER"
        CompactUtilityPanelDB.xOfs = 0
        CompactUtilityPanelDB.yOfs = 0
    end
end

--------------------------------------------------
-- ELLESMEREUI INTEGRATION (RegisterUnlockElements-API)
--------------------------------------------------

local ELLESMEREUI_PANEL_KEY = "CompactUtilityPanel"
local ELLESMEREUI_PANEL_LABEL = "Compact Utility Panel"

function addon:RegisterToEllesmereUI()
    if not EllesmereUI or not EllesmereUI.RegisterUnlockElements then
        return
    end

    if not self.panel then
        return
    end

    -- Element-Beschreibung gemäss der in EUI_UnlockMode.lua definierten API:
    -- EllesmereUI:RegisterUnlockElements({ element }, folder). "RegisterMover"
    -- existiert in dieser API nicht -- das war der ursprüngliche Fehler.
    local element = {
        key = ELLESMEREUI_PANEL_KEY,
        label = ELLESMEREUI_PANEL_LABEL,

        getFrame = function()
            return addon.panel
        end,

        getSize = function()
            if not addon.panel then return nil end
            return addon.panel:GetWidth(), addon.panel:GetHeight()
        end,

        -- Wird von EllesmereUI beim Loslassen im Unlock Mode aufgerufen.
        -- Wir schreiben direkt in unsere eigene DB, damit CreateMainPanel()
        -- (UI.lua) beim nächsten Login dieselbe Position wiederherstellt.
        savePosition = function(_, point, relPoint, x, y)
            local db = CompactUtilityPanelDB
            if not db then return end
            db.point = point
            db.relativePoint = relPoint
            db.xOfs = x
            db.yOfs = y
        end,

        loadPosition = function()
            local db = CompactUtilityPanelDB
            if not db or not db.point then return nil end
            return {
                point = db.point,
                relPoint = db.relativePoint,
                x = db.xOfs,
                y = db.yOfs,
            }
        end,

        clearPosition = function()
            local db = CompactUtilityPanelDB
            if not db then return end
            db.point = nil
            db.relativePoint = nil
            db.xOfs = nil
            db.yOfs = nil
        end,
    }

    local ok, err = pcall(function()
        EllesmereUI:RegisterUnlockElements({ element }, addonName)
    end)

    if not ok then
        print("|cffff4444CompactUtilityPanel:|r EllesmereUI-Registrierung fehlgeschlagen: " .. tostring(err))
    end
end

--------------------------------------------------
-- EVENTS
--------------------------------------------------

local frame = CreateFrame("Frame")

frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("PLAYER_LOGIN")

frame:SetScript("OnEvent", function(self, event, arg1)
    if event == "ADDON_LOADED" and arg1 == addonName then
        addon:InitializeDatabase()

        if addon.CreateSettings then
            addon:CreateSettings()
        end
    elseif event == "PLAYER_LOGIN" then
        addon:LoadFontSettings()

        if addon.CreateMainPanel then
            addon:CreateMainPanel()
        end

        addon:ApplySettings()

        -- Registrierung direkt nach dem Panel-Setup ausführen
        addon:RegisterToEllesmereUI()
    end
end)