local addonName, addon = ...

local FALLBACK_FONT = "Fonts\\FRIZQT__.TTF"

local PANEL_WIDTH = 201
local PANEL_HEIGHT = 73

local CONTENT_WIDTH = 201
local CONTENT_HEIGHT = 61

local TOP_HEIGHT = 20
local BUTTON_HEIGHT = 20
local BUTTON_GAP = 2

local MARKER_SIZE = 20
local MARKER_GAP = 1
local MARKER_COUNT = 8

local function GetFont()
    if addon.fontPath and addon.fontPath ~= "" then
        return addon.fontPath
    end

    if CompactUtilityPanelDB
        and CompactUtilityPanelDB.fontPath
        and CompactUtilityPanelDB.fontPath ~= "" then

        addon.fontPath = CompactUtilityPanelDB.fontPath
        return addon.fontPath
    end

    return FALLBACK_FONT
end

local function GetFontSize()
    local size = tonumber(addon.fontSize)

    if not size and CompactUtilityPanelDB then
        size = tonumber(CompactUtilityPanelDB.fontSize)
    end

    if not size or size <= 0 then
        return 14
    end

    return size
end

local function GetFontColor()
    local db = CompactUtilityPanelDB

    if not db or type(db.fontColor) ~= "table" then
        return 1, 1, 1, 1
    end

    return tonumber(db.fontColor.r) or 1,
           tonumber(db.fontColor.g) or 1,
           tonumber(db.fontColor.b) or 1,
           1
end

local function ApplyFont(fontString)
    if not fontString then return end

    local fontPath = GetFont()
    local fontSize = GetFontSize()
    local r, g, b, a = GetFontColor()

    if not fontPath or fontPath == "" then
        fontPath = FALLBACK_FONT
    end

    fontString:SetFont(fontPath, fontSize, "")
    fontString:SetTextColor(r, g, b, a)
end

function addon:ApplyVisualSettings()
    if not self.visual then return end

    if self.InitializeDatabase then
        self:InitializeDatabase()
    end

    local db = CompactUtilityPanelDB
    if not db then return end

    local opacity = tonumber(db.opacity)
    if opacity == nil then opacity = 0.90 end
    opacity = math.max(0, math.min(1, opacity))

    self.visual:SetAlpha(opacity)

    local pc = db.panelColor
    if type(pc) ~= "table" then
        pc = { r = 0.05, g = 0.05, b = 0.05 }
        db.panelColor = pc
    end

    if self.background then
        self.background:SetColorTexture(
            tonumber(pc.r) or 0.05,
            tonumber(pc.g) or 0.05,
            tonumber(pc.b) or 0.05,
            1
        )
    end

    local bc = db.borderColor
    if type(bc) ~= "table" then
        bc = { r = 0.35, g = 0.35, b = 0.35 }
        db.borderColor = bc
    end

    local width = tonumber(db.borderWidth) or 1
    width = math.max(0, math.min(3, width))

    if width <= 0 then
        if self.borderTop then self.borderTop:Hide() end
        if self.borderBottom then self.borderBottom:Hide() end
        if self.borderLeft then self.borderLeft:Hide() end
        if self.borderRight then self.borderRight:Hide() end
        return
    end

    local r = tonumber(bc.r) or 0.35
    local g = tonumber(bc.g) or 0.35
    local b = tonumber(bc.b) or 0.35

    local function SetBorder(texture)
        if not texture then return end
        texture:SetColorTexture(r, g, b, 1)
        texture:Show()
    end

    if self.borderTop then
        self.borderTop:SetHeight(width)
        SetBorder(self.borderTop)
    end

    if self.borderBottom then
        self.borderBottom:SetHeight(width)
        SetBorder(self.borderBottom)
    end

    if self.borderLeft then
        self.borderLeft:SetWidth(width)
        SetBorder(self.borderLeft)
    end

    if self.borderRight then
        self.borderRight:SetWidth(width)
        SetBorder(self.borderRight)
    end
end

function addon:RefreshFonts()
    if CompactUtilityPanelDB then
        if CompactUtilityPanelDB.fontPath and CompactUtilityPanelDB.fontPath ~= "" then
            self.fontPath = CompactUtilityPanelDB.fontPath
        end
        if CompactUtilityPanelDB.fontSize then
            self.fontSize = tonumber(CompactUtilityPanelDB.fontSize)
        end
    end

    local fontPath = GetFont()
    local fontSize = GetFontSize()
    local r, g, b, a = GetFontColor()

    if not fontPath or fontPath == "" then
        fontPath = FALLBACK_FONT
    end

    local function UpdateFrame(frame)
        if not frame then return end
        local regions = { frame:GetRegions() }
        for _, region in ipairs(regions) do
            if region:IsObjectType("FontString") then
                region:SetFont(fontPath, fontSize, "")
                region:SetTextColor(r, g, b, a)
            end
        end

        local children = { frame:GetChildren() }
        for _, child in ipairs(children) do
            UpdateFrame(child)
        end
    end

    if self.content then UpdateFrame(self.content) end
    if self.pullButton and self.pullButton.text then ApplyFont(self.pullButton.text) end
    if self.readyButton and self.readyButton.text then ApplyFont(self.readyButton.text) end

    if self.targetMarkerButtons then
        for _, button in pairs(self.targetMarkerButtons) do
            if button.text then ApplyFont(button.text) end
        end
    end

    if self.worldMarkerButtons then
        for _, button in pairs(self.worldMarkerButtons) do
            if button.text then ApplyFont(button.text) end
        end
    end
end

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

    local panel = CreateFrame("Frame", "CompactUtilityPanel", UIParent)
    self.panel = panel

    panel:SetSize(PANEL_WIDTH, PANEL_HEIGHT)
    
    -- WICHTIG FUER ELLESMEREUI:
    panel:SetMovable(true)
    panel:EnableMouse(true)

    -- Geladene Position wiederherstellen
    local db = CompactUtilityPanelDB
    if db and db.point then
        panel:SetPoint(db.point, UIParent, db.relativePoint or db.point, db.xOfs or 0, db.yOfs or 0)
    else
        panel:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
    end

    local visual = CreateFrame("Frame", nil, panel)
    visual:SetAllPoints()
    visual:SetFrameLevel(panel:GetFrameLevel())
    self.visual = visual

    local background = visual:CreateTexture(nil, "BACKGROUND")
    background:SetAllPoints()
    self.background = background

    local borderTop = visual:CreateTexture(nil, "BORDER")
    borderTop:SetPoint("TOPLEFT", visual, "TOPLEFT")
    borderTop:SetPoint("TOPRIGHT", visual, "TOPRIGHT")
    self.borderTop = borderTop

    local borderBottom = visual:CreateTexture(nil, "BORDER")
    borderBottom:SetPoint("BOTTOMLEFT", visual, "BOTTOMLEFT")
    borderBottom:SetPoint("BOTTOMRIGHT", visual, "BOTTOMRIGHT")
    self.borderBottom = borderBottom

    local borderLeft = visual:CreateTexture(nil, "BORDER")
    borderLeft:SetPoint("TOPLEFT", visual, "TOPLEFT")
    borderLeft:SetPoint("BOTTOMLEFT", visual, "BOTTOMLEFT")
    self.borderLeft = borderLeft

    local borderRight = visual:CreateTexture(nil, "BORDER")
    borderRight:SetPoint("TOPRIGHT", visual, "TOPRIGHT")
    borderRight:SetPoint("BOTTOMRIGHT", visual, "BOTTOMRIGHT")
    self.borderRight = borderRight

    local content = CreateFrame("Frame", nil, panel)
    content:SetSize(CONTENT_WIDTH, CONTENT_HEIGHT)
    content:SetPoint("CENTER", panel, "CENTER")
    self.content = content

    local markerRowWidth = (MARKER_COUNT * MARKER_SIZE) + ((MARKER_COUNT - 1) * MARKER_GAP) + MARKER_GAP + MARKER_SIZE

    local topContainer = CreateFrame("Frame", nil, content)
    topContainer:SetSize(markerRowWidth, TOP_HEIGHT)
    topContainer:SetPoint("TOP", content, "TOP")

    local actionButtonWidth = (markerRowWidth - BUTTON_GAP) / 2

    local pullButton = self:CreateButton(topContainer, actionButtonWidth, BUTTON_HEIGHT, false)
    pullButton:SetPoint("LEFT", topContainer, "LEFT")
    self.pullButton = pullButton

    local pullText = pullButton:CreateFontString(nil, "OVERLAY")
    pullButton.text = pullText
    ApplyFont(pullText)
    pullText:SetPoint("CENTER")
    pullText:SetText("PULL")

    pullButton:SetScript("OnClick", function()
        if addon.pullActive then
            addon:StopPull()
        else
            addon:StartPull()
        end
    end)

    local readyButton = self:CreateReadyCheckButton(topContainer)
    readyButton:SetSize(actionButtonWidth, BUTTON_HEIGHT)
    readyButton:SetPoint("LEFT", pullButton, "RIGHT", BUTTON_GAP, 0)
    self.readyButton = readyButton

    local targetContainer = CreateFrame("Frame", nil, content)
    targetContainer:SetSize(markerRowWidth, MARKER_SIZE)
    targetContainer:SetPoint("TOP", topContainer, "BOTTOM", 0, -1)
    self.targetContainer = targetContainer

    for i, markerIndex in ipairs(self.targetMarkers) do
        local button = self:CreateTargetMarkerButton(targetContainer, markerIndex)
        button:SetSize(MARKER_SIZE, MARKER_SIZE)
        button:SetPoint("LEFT", targetContainer, "LEFT", (i - 1) * (MARKER_SIZE + MARKER_GAP), 0)
    end

    local clearTargetButton = self:CreateTargetMarkerClearButton(targetContainer)
    clearTargetButton:SetSize(MARKER_SIZE, MARKER_SIZE)
    clearTargetButton:SetPoint("LEFT", targetContainer, "LEFT", MARKER_COUNT * (MARKER_SIZE + MARKER_GAP), 0)
    self.targetMarkerClearButton = clearTargetButton

    local worldContainer = CreateFrame("Frame", nil, content)
    worldContainer:SetSize(markerRowWidth, MARKER_SIZE)
    worldContainer:SetPoint("TOP", targetContainer, "BOTTOM", 0, -1)
    self.worldContainer = worldContainer

    for i, markerData in ipairs(self.worldMarkers) do
        local button = self:CreateWorldMarkerButton(worldContainer, markerData)
        button:SetSize(MARKER_SIZE, MARKER_SIZE)
        button:SetPoint("LEFT", worldContainer, "LEFT", (i - 1) * (MARKER_SIZE + MARKER_GAP), 0)
    end

    local clearWorldButton = self:CreateWorldMarkerClearButton(worldContainer)
    clearWorldButton:SetSize(MARKER_SIZE, MARKER_SIZE)
    -- KORRIGIERT: worldContainer statt clearWorldButton
    clearWorldButton:SetPoint("LEFT", worldContainer, "LEFT", MARKER_COUNT * (MARKER_SIZE + MARKER_GAP), 0)
    self.worldMarkerClearButton = clearWorldButton

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

    -- WorldMarkers.lua überspringt RAID_TARGET_UPDATE-Arbeit, solange das
    -- Panel unsichtbar ist (spart unnötige Texture-Updates). Beim erneuten
    -- Einblenden hier einmal nachholen, damit die Indikatoren stimmen.
    panel:SetScript("OnShow", function()
        if addon.UpdateWorldMarkerIndicators then
            addon:UpdateWorldMarkerIndicators()
        end
    end)

    -- Hinweis: Die EllesmereUI-Registrierung passiert bewusst NICHT hier,
    -- sondern zentral in Core.lua (addon:RegisterToEllesmereUI), die nach
    -- CreateMainPanel() im PLAYER_LOGIN-Handler aufgerufen wird.

    return panel
end