local addonName, RLMage = ...

-- =========================================================================
-- UTILS
-- =========================================================================

-- Create a 1px gold border around a frame
function RLMage.AddThinBorder(frame)
    if not frame then return end
    if frame.border then return end -- Avoid duplicates

    local border = CreateFrame("Frame", nil, frame)
    border:SetAllPoints(frame)
    border:EnableMouse(false)
    frame.border = border
    
    local pixelSize = 1
    local color = {0.8, 0.6, 0, 1} -- Gold

    local function CreateLine(point1, relPoint1, x1, y1, point2, relPoint2, x2, y2, width, height)
        local t = border:CreateTexture(nil, "OVERLAY")
        t:SetColorTexture(unpack(color))
        t:SetPoint(point1, border, relPoint1, x1, y1)
        t:SetPoint(point2, border, relPoint2, x2, y2)
        if width then t:SetWidth(width) end
        if height then t:SetHeight(height) end
        return t
    end

    -- Top
    CreateLine("TOPLEFT", "TOPLEFT", -pixelSize, pixelSize, "TOPRIGHT", "TOPRIGHT", pixelSize, pixelSize, nil, pixelSize)
    -- Bottom
    CreateLine("BOTTOMLEFT", "BOTTOMLEFT", -pixelSize, -pixelSize, "BOTTOMRIGHT", "BOTTOMRIGHT", pixelSize, -pixelSize, nil, pixelSize)
    -- Left
    CreateLine("TOPLEFT", "TOPLEFT", -pixelSize, pixelSize, "BOTTOMLEFT", "BOTTOMLEFT", -pixelSize, -pixelSize, pixelSize, nil)
    -- Right
    CreateLine("TOPRIGHT", "TOPRIGHT", pixelSize, pixelSize, "BOTTOMRIGHT", "BOTTOMRIGHT", pixelSize, -pixelSize, pixelSize, nil)
end

function RLMage.SetupSecureButton(btn, name, spellID)
    if not btn then return end
    
    local castName = name
    local _, rank = GetSpellInfo(spellID)
    if rank and rank ~= "" then
        castName = name .. "(" .. rank .. ")"
    end

    local macroText = "/cast " .. castName

    btn:SetAttribute("type", "macro")
    btn:SetAttribute("macrotext", macroText)
    btn:SetAttribute("type1", "macro")
    btn:SetAttribute("macrotext1", macroText)
    btn:SetAttribute("type2", "macro")
    btn:SetAttribute("macrotext2", macroText)
    btn:RegisterForClicks("AnyUp", "AnyDown")
    
    -- Icon handling
    local _, _, iconPath = GetSpellInfo(spellID)
    
    if not btn.icon then
        btn.icon = btn:CreateTexture(nil, "ARTWORK")
        btn.icon:SetSize(20, 20)
        btn.icon:SetPoint("LEFT", btn, "LEFT", 0, 0)
    end
    
    if iconPath then
        btn.icon:SetTexture(iconPath)
    end
    
    -- Text handling
    if not btn.text then
        btn.text = btn:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
        btn.text:SetPoint("LEFT", btn.icon, "RIGHT", 5, 0)
        btn.text:SetPoint("RIGHT", btn, "RIGHT", -5, 0)
        btn.text:SetJustifyH("LEFT")
    end

    local label = name
    if GetLocale and GetLocale() == "deDE" then
        label = label:gsub("Teleportieren:%s*", "TP : ")
    end
    btn.text:SetText(label)

    -- Background (dark)
    if not btn.bg then
        btn.bg = btn:CreateTexture(nil, "BACKGROUND")
        btn.bg:SetAllPoints()
        btn.bg:SetColorTexture(0, 0, 0, 0.8)
    end

    -- Clear Normal/Pushed Textures to prevent stretching
    btn:SetNormalTexture("")
    btn:SetPushedTexture("")
    
    -- Highlight
    btn:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")
    
    RLMage.AddThinBorder(btn)
    
    -- Tooltip
    btn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetSpellByID(spellID)
        GameTooltip:Show()
    end)
    btn:SetScript("OnLeave", function() GameTooltip:Hide() end)
end

-- =========================================================================
-- SPELLBOOK SCANNER
-- =========================================================================
RLMage.SpellBookCache = {}

function RLMage.ScanSpellbook()
    RLMage.SpellBookCache = {}
    
    for tab = 1, GetNumSpellTabs() do
        local _, _, offset, numSpells = GetSpellTabInfo(tab)
        for i = 1, numSpells do
            local index = offset + i
            local spellType, spellID = GetSpellBookItemInfo(index, "spell")
            if spellType == "SPELL" and spellID then
                RLMage.SpellBookCache[spellID] = true
            end
        end
    end
end

function RLMage.GetKnownTeleports()
    local result = {}
    if not RLMage.SpellBookCache then return result end
    for id in pairs(RLMage.SpellBookCache) do
        local name = GetSpellInfo(id)
        if name and (name:find("Teleport", 1, true) or name:find("Teleportieren", 1, true)) then
            if not RLMageDB or not RLMageDB.hiddenSpells or not RLMageDB.hiddenSpells[id] then
                table.insert(result, id)
            end
        end
    end
    table.sort(result, function(a, b)
        local na = GetSpellInfo(a) or ""
        local nb = GetSpellInfo(b) or ""
        return na < nb
    end)
    return result
end

function RLMage.GetKnownPortals()
    local result = {}
    if not RLMage.SpellBookCache then return result end
    for id in pairs(RLMage.SpellBookCache) do
        local name = GetSpellInfo(id)
        if name and name:find("Portal", 1, true) then
            if not RLMageDB or not RLMageDB.hiddenSpells or not RLMageDB.hiddenSpells[id] then
                table.insert(result, id)
            end
        end
    end
    table.sort(result, function(a, b)
        local na = GetSpellInfo(a) or ""
        local nb = GetSpellInfo(b) or ""
        return na < nb
    end)
    return result
end

-- Find best spell (highest rank) from a list of IDs
function RLMage.FindBest(idList)
    if not idList then return nil end
    for _, id in ipairs(idList) do
        if IsSpellKnown(id) then return id end
        if RLMage.SpellBookCache and RLMage.SpellBookCache[id] then return id end
    end
    return nil
end

-- Close all menus
function RLMage.CloseAllMenus()
    if not InCombatLockdown() then
        if RLMagePortalContainer and RLMagePortalContainer:IsShown() then
            RLMagePortalContainer:Hide()
        end
        if RLMageTeleportContainer and RLMageTeleportContainer:IsShown() then
            RLMageTeleportContainer:Hide()
        end
        if RLMageFoodContainer and RLMageFoodContainer:IsShown() then
            RLMageFoodContainer:Hide()
        end
        if RLMageBuffContainer and RLMageBuffContainer:IsShown() then
            RLMageBuffContainer:Hide()
        end
    end
end
