local addonName, RLMage = ...

-- Modern Dark Background (RLTotem/RLRaidDungeonReset style)
function RLMage.AddModernBackground(frame, r, g, b, a)
    if not frame then return end
    r, g, b, a = r or 0.1, g or 0.1, b or 0.12, a or 0.95
    
    local bg = frame:CreateTexture(nil, "BACKGROUND")
    bg:SetAllPoints()
    bg:SetColorTexture(r, g, b, a)
    frame.bg = bg
end

-- Modern Border (RLTotem/RLRaidDungeonReset style)
function RLMage.AddModernBorder(frame, r, g, b, a, offset)
    if not frame then return end
    r, g, b, a = r or 0.3, g or 0.3, b or 0.35, a or 1
    offset = offset or 2
    
    local border = frame:CreateTexture(nil, "BACKGROUND")
    border:SetPoint("TOPLEFT", frame, "TOPLEFT", -offset, offset)
    border:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", offset, -offset)
    border:SetColorTexture(r, g, b, a)
    frame.border = border
end

-- Modern Button Style (combination of bg + border)
function RLMage.AddModernButtonStyle(frame, bgR, bgG, bgB, bgA, borderR, borderG, borderB, borderA)
    if not frame then return end
    
    -- Background
    local bg = frame:CreateTexture(nil, "BACKGROUND")
    bg:SetAllPoints()
    bg:SetColorTexture(bgR or 0, bgG or 0, bgB or 0, bgA or 1)
    frame.bg = bg
    
    -- Border
    local border = frame:CreateTexture(nil, "BACKGROUND")
    border:SetPoint("TOPLEFT", frame, "TOPLEFT", -1, 1)
    border:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 1, -1)
    border:SetColorTexture(borderR or 0.3, borderG or 0.3, borderB or 0.35, borderA or 0.6)
    frame.border = border
end

-- Hilfsfunktion für schmalen Kontrastrahmen (legacy, kept for compatibility)
function RLMage.AddThinBorder(frame)
    if not frame then return end
    
    -- Create a frame to hold the border textures
    -- IMPORTANT: SetFrameLevel to 1 to ensure it's BEHIND the button content interaction
    -- AND explicitly disable mouse
    local border = CreateFrame("Frame", nil, frame)
    border:SetAllPoints(frame)
    border:EnableMouse(false) -- CRITICAL: Ensure this frame never eats clicks
    
    -- 1px thin border using 4 textures
    local pixelSize = 1
    
    local t = border:CreateTexture(nil, "OVERLAY")
    t:SetColorTexture(0.8, 0.6, 0, 1) -- Gold
    t:SetPoint("TOPLEFT", border, "TOPLEFT", -pixelSize, pixelSize)
    t:SetPoint("TOPRIGHT", border, "TOPRIGHT", pixelSize, pixelSize)
    t:SetHeight(pixelSize)
    
    local b = border:CreateTexture(nil, "OVERLAY")
    b:SetColorTexture(0.8, 0.6, 0, 1)
    b:SetPoint("BOTTOMLEFT", border, "BOTTOMLEFT", -pixelSize, -pixelSize)
    b:SetPoint("BOTTOMRIGHT", border, "BOTTOMRIGHT", pixelSize, -pixelSize)
    b:SetHeight(pixelSize)
    
    local l = border:CreateTexture(nil, "OVERLAY")
    l:SetColorTexture(0.8, 0.6, 0, 1)
    l:SetPoint("TOPLEFT", border, "TOPLEFT", -pixelSize, pixelSize)
    l:SetPoint("BOTTOMLEFT", border, "BOTTOMLEFT", -pixelSize, -pixelSize)
    l:SetWidth(pixelSize)
    
    local r = border:CreateTexture(nil, "OVERLAY")
    r:SetColorTexture(0.8, 0.6, 0, 1)
    r:SetPoint("TOPRIGHT", border, "TOPRIGHT", pixelSize, pixelSize)
    r:SetPoint("BOTTOMRIGHT", border, "BOTTOMRIGHT", pixelSize, -pixelSize)
    r:SetWidth(pixelSize)
end

-- Spellbook Cache
RLMage.SpellBookCache = {}

function RLMage.ScanSpellbook()
    RLMage.SpellBookCache = {}
    local i = 1
    while true do
        local name, rank = GetSpellBookItemName(i, "spell")
        if not name then break end
        
        -- Get ID directly from Info if possible, or Fallback to Link
        local slotType, spellID = GetSpellBookItemInfo(i, "spell")
        
        if slotType == "SPELL" and spellID then
             RLMage.SpellBookCache[spellID] = true
        else
             -- Fallback for some clients
             local link = nil
             if GetSpellLink then 
                 link = GetSpellLink(i, "spell")
             end
             
             if link then
                 local id = link:match("spell:(%d+)")
                 if id then
                     RLMage.SpellBookCache[tonumber(id)] = true
                 end
             end
        end

        i = i + 1
    end
end

-- Funktion um besten bekannten Spell zu finden
function RLMage.FindBest(idList)
    if not RLMageDB then return nil end
    
    for _, id in ipairs(idList) do
        local known = IsSpellKnown(id)
        
        -- Fallback: Check Spellbook Cache if IsSpellKnown fails
        if not known and RLMage.SpellBookCache and RLMage.SpellBookCache[id] then
            known = true
        end
        
        if known and not RLMageDB.hiddenSpells[id] then
            return id
        end
    end
    return nil
end

-- TBC Compatibility Helper for Secure Buttons
function RLMage.SetupSecureButton(btn, name, spellID)
    if not btn or not name then return end
    
    btn:SetNormalTexture(GetSpellTexture(spellID))
    
    -- Register for ALL clicks
    btn:RegisterForClicks("AnyUp")
    
    -- TBC COMPATIBILITY FIX: "AnyDown" Registration
    -- We register for Down events to bypass potential drag-cancellation issues.
    -- We use standard attributes but ensure click registration is aggressive.
    
    btn:RegisterForClicks("AnyUp", "AnyDown")
    
    -- Get Rank to construct exact spell name "Name(Rank X)"
    -- This is required because spell:ID macros are failing and type="spell" without rank is unreliable
    local _, rank = GetSpellInfo(spellID)
    local castName = name
    if rank and rank ~= "" then
        castName = name .. "(" .. rank .. ")"
    end

    btn:SetNormalTexture(GetSpellTexture(spellID))
    
    -- Register for ALL clicks
    btn:RegisterForClicks("AnyUp", "AnyDown")
    
    local macroText = "/cast " .. castName
    
    -- Use macro with explicit Name(Rank)
    btn:SetAttribute("type", "macro")
    btn:SetAttribute("macrotext", macroText)
    
    -- Explicitly set for main mouse buttons
    btn:SetAttribute("type1", "macro")
    btn:SetAttribute("macrotext1", macroText)
    btn:SetAttribute("type2", "macro")
    btn:SetAttribute("macrotext2", macroText)
    
    -- Clear spell attributes
    btn:SetAttribute("spell", nil)
    btn:SetAttribute("spell1", nil)
    btn:SetAttribute("spell2", nil)
    
    -- Ensure Frame Strata is high enough to be on top of everything
    btn:SetFrameStrata("HIGH")
    btn:EnableMouse(true)
    
    -- Debug & Logic: PostClick (Secure - confirms driver execution + Handle Hiding)
    btn:SetScript("PostClick", function(self, button)
       if IsAltKeyDown() and button == "RightButton" then
           if InCombatLockdown() then
               print("|cffff0000RLMage:|r " .. RLMage.L.ERR_COMBAT_HIDE)
               return
           end
           
           if not RLMageDB.hiddenSpells then RLMageDB.hiddenSpells = {} end
           RLMageDB.hiddenSpells[spellID] = true
           print("|cff00ff00RLMage:|r " .. name .. " " .. RLMage.L.MSG_HIDDEN)
           
           if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
       else
           -- Debug output for normal clicks
           -- print("|cff00ff00RLMage:|r CASTING: " .. name)
       end
    end)
    
    -- Remove insecure OnMouseDown to prevent any event consumption issues
    btn:SetScript("OnMouseDown", nil)
    
    -- Clean other scripts
    btn:SetScript("PreClick", nil)

    btn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetSpellByID(spellID)
        GameTooltip:Show()
    end)
    btn:SetScript("OnLeave", function() GameTooltip:Hide() end)
end