local addonName, RLMage = ...

-- Version
local GetAddOnMetadata = C_AddOns and C_AddOns.GetAddOnMetadata or GetAddOnMetadata
RLMage.version = GetAddOnMetadata(addonName, "Version") or "1.0"
local COMM_PREFIX = "RLMage"

-- =========================================================================
-- LOCALIZATION
-- =========================================================================
RLMage.L = {}
local L = RLMage.L

-- German (Default)
local deDE = {
    OPTIONS_TITLE = "RL MageSet Optionen",
    TAB_SETTINGS = "Einstellungen",
    TAB_ABOUT = "Über",
    ENABLE_CATEGORIES = "Kategorien aktivieren:",
    CAT_TELEPORTS = "Teleporte",
    CAT_PORTALS = "Portale",
    CAT_FOOD = "Verpflegung",
    CAT_BUFFS = "Buffs",
    VISIBLE_SPELLS = "Einzelne Zauber sichtbar:",
    RESET_ALL = "Alle sichtbar machen",
    MSG_RESET = "Alle Zauber sind nun sichtbar.",
    MSG_HIDDEN = "versteckt. (Reset in Optionen)",
    ABOUT_TITLE = "Über RLMage",
    ABOUT_CREATOR = "Ersteller: Robin Oliver Lucas",
    ABOUT_CONTACT = "Kontakt",
    ABOUT_HOMEPAGE = "Homepage:",
    ABOUT_BUGTRACKER = "Fehler melden:",
    DESC_CATEGORY = "Einstellungen für RLMage und andere RL Addons.",
    OPEN_OPTIONS = "RLMage Optionen",
    ERR_COMBAT = "Kann Menü nicht im Kampf öffnen/schließen.",
    ERR_COMBAT_HIDE = "Kann Zauber nicht im Kampf verstecken.",
    MM_LEFT_CLICK = "Linksklick: Optionen",
    MM_DRAG = "Ziehen: Bewegen",
    VERSION = "Version:",
    NEW_VERSION = "|cffff0000Neue Version verfügbar: %s|r",
    CHECK_VERSION = "Prüfe auf Updates...",
    CAT_COMBAT = "Kampf-Ansagen",
    COMBAT_ANNOUNCE_STEAL = "Spellsteal ansagen",
    COMBAT_ANNOUNCE_INTERRUPT = "Counterspell ansagen",
    COMBAT_ANNOUNCE_SILENCE = "Stille ansagen",
    COMBAT_MSG_STEAL = "[Spellsteal] %s gestohlen von %s",
    COMBAT_MSG_INTERRUPT = "[Counterspell] %s von %s unterbrochen",
    COMBAT_MSG_SILENCE = "[Stille] Betroffen von %s durch %s",
    COMBAT_MSG_INTERRUPTED_BY = "[Unterbrochen] Zauber durch %s unterbrochen"
}

-- English
local enUS = {
    OPTIONS_TITLE = "RL MageSet Options",
    TAB_SETTINGS = "Settings",
    TAB_ABOUT = "About",
    ENABLE_CATEGORIES = "Enable Categories:",
    CAT_TELEPORTS = "Teleports",
    CAT_PORTALS = "Portals",
    CAT_FOOD = "Food & Water",
    CAT_BUFFS = "Buffs",
    VISIBLE_SPELLS = "Visible Spells:",
    RESET_ALL = "Unhide All",
    MSG_RESET = "All spells are now visible.",
    MSG_HIDDEN = "hidden. (Reset in Options)",
    ABOUT_TITLE = "About RLMage",
    ABOUT_CREATOR = "Creator: Robin Oliver Lucas",
    ABOUT_CONTACT = "Contact",
    ABOUT_HOMEPAGE = "Homepage:",
    ABOUT_BUGTRACKER = "Bug Tracker:",
    DESC_CATEGORY = "Settings for RLMage and other RL Addons.",
    OPEN_OPTIONS = "RLMage Options",
    ERR_COMBAT = "Cannot open/close menu in combat.",
    ERR_COMBAT_HIDE = "Cannot hide spells in combat.",
    MM_LEFT_CLICK = "Left Click: Options",
    MM_DRAG = "Drag: Move",
    VERSION = "Version:",
    NEW_VERSION = "|cffff0000New version available: %s|r",
    CHECK_VERSION = "Checking for updates...",
    CAT_COMBAT = "Combat Announces",
    COMBAT_ANNOUNCE_STEAL = "Announce Spellsteal",
    COMBAT_ANNOUNCE_INTERRUPT = "Announce Counterspell",
    COMBAT_ANNOUNCE_SILENCE = "Announce Silence",
    COMBAT_MSG_STEAL = "[Spellsteal] %s stolen from %s",
    COMBAT_MSG_INTERRUPT = "[Counterspell] %s interrupted from %s",
    COMBAT_MSG_SILENCE = "[Silence] Affected by %s from %s",
    COMBAT_MSG_INTERRUPTED_BY = "[Interrupted] Cast interrupted by %s"
}

local locale = GetLocale()
local activeLocale = (locale == "deDE") and deDE or enUS

-- Copy to L
for k, v in pairs(activeLocale) do
    L[k] = v
end

-- Standard-Einstellungen
local defaults = {
    showTeleports = true,
    showPortals = true,
    showFood = true,
    showBuffs = true,
    hiddenSpells = {},
    announceSpellsteal = true,
    announceCounterspell = true,
    announceSilence = true,
    minimap = {
        hide = false,
        pos = 45, -- Winkel in Grad
        radius = 80, -- Radius vom Minimap Zentrum
    }
}

-- =========================================================================
-- VERSION CHECK
-- =========================================================================

function RLMage:CompareVersion(v1, v2)
    if v1 == v2 then return 0 end
    local v1parts = { strsplit(".", v1) }
    local v2parts = { strsplit(".", v2) }
    
    for i = 1, math.max(#v1parts, #v2parts) do
        local p1 = tonumber(v1parts[i]) or 0
        local p2 = tonumber(v2parts[i]) or 0
        if p1 > p2 then return 1 end
        if p1 < p2 then return -1 end
    end
    return 0
end

function RLMage:SendVersionCheck()
    if IsInGuild() then
        C_ChatInfo.SendAddonMessage(COMM_PREFIX, "Q", "GUILD")
    end
    if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
        C_ChatInfo.SendAddonMessage(COMM_PREFIX, "Q", "INSTANCE_CHAT")
    elseif IsInRaid() then
        C_ChatInfo.SendAddonMessage(COMM_PREFIX, "Q", "RAID")
    elseif IsInGroup() then
        C_ChatInfo.SendAddonMessage(COMM_PREFIX, "Q", "PARTY")
    end
end

function RLMage:HandleComm(msg, sender)
    if sender == UnitName("player") then return end
    
    local cmd, payload = strsplit(":", msg, 2)
    
    if cmd == "Q" then
        -- Reply with my version via WHISPER to reduce traffic
        C_ChatInfo.SendAddonMessage(COMM_PREFIX, "V:" .. RLMage.version, "WHISPER", sender)
        
    elseif cmd == "V" and payload then
        local remoteVer = payload
        if RLMage:CompareVersion(remoteVer, RLMage.version) == 1 then
            -- Remote is newer
            if RLMage.newVersion ~= remoteVer then
                RLMage.newVersion = remoteVer
                print("|cffffd700RLMage:|r " .. string.format(RLMage.L.NEW_VERSION, remoteVer))
                
                -- Update About Page if open
                if RLMage.UpdateAboutPage then
                    RLMage.UpdateAboutPage()
                end
            end
        end
    end
end

-- Event Frame
local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:RegisterEvent("SPELLS_CHANGED")
f:RegisterEvent("PLAYER_LOGIN")
f:RegisterEvent("PLAYER_REGEN_ENABLED")
f:RegisterEvent("CHAT_MSG_ADDON")

f:SetScript("OnEvent", function(self, event, ...)
    if event == "CHAT_MSG_ADDON" then
        local prefix, msg, channel, sender = ...
        if prefix == COMM_PREFIX then
            RLMage:HandleComm(msg, sender)
        end
        return
    end

    local arg1 = ...

    if event == "ADDON_LOADED" and arg1 == addonName then
        -- Check Class
        local _, class = UnitClass("player")
        if class ~= "MAGE" then
             f:UnregisterAllEvents()
             f:SetScript("OnEvent", nil)
             return
        end

        -- Init DB
        if not RLMageDB then RLMageDB = {} end
        for k, v in pairs(defaults) do
            if RLMageDB[k] == nil then RLMageDB[k] = v end
        end
        
        -- Create Main UI
        RLMage.CreateMainInterface()
        
        -- Init Minimap Button
        RLMage.UpdateMinimapButton()
        
        -- Initial Scan
        if RLMage.ScanSpellbook then RLMage.ScanSpellbook() end
        
    elseif event == "SPELLS_CHANGED" or event == "PLAYER_LOGIN" or event == "PLAYER_REGEN_ENABLED" then
        if event == "PLAYER_LOGIN" then
            C_ChatInfo.RegisterAddonMessagePrefix(COMM_PREFIX)
            
            -- Delay check slightly to ensure everything is loaded
            C_Timer.After(5, function()
                RLMage:SendVersionCheck()
            end)
        end

        if event == "SPELLS_CHANGED" or event == "PLAYER_LOGIN" then
            if RLMage.ScanSpellbook then RLMage.ScanSpellbook() end
        end
        
        if InCombatLockdown() then return end
        if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
    end
end)

function RLMage.CreateMainInterface()
    -- Hauptbutton
    local mainButton = CreateFrame("Button", "RLMageMainButton", UIParent, "SecureActionButtonTemplate")
    mainButton:SetSize(30, 30)
    mainButton:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
    mainButton:SetMovable(true)
    mainButton:EnableMouse(true)
    mainButton:RegisterForDrag("LeftButton")
    mainButton:SetClampedToScreen(true)
    
    -- Modern Dark Background (RLTotem style)
    RLMage.AddModernButtonStyle(mainButton, 0, 0, 0, 1, 1, 0.82, 0, 0.6)
    
    -- Icon
    mainButton.icon = mainButton:CreateTexture(nil, "ARTWORK")
    mainButton.icon:SetAllPoints()
    mainButton.icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)
    mainButton.icon:SetTexture("Interface\\Icons\\Spell_Arcane_PortalStormWind")
    
    -- Highlight texture
    mainButton.highlight = mainButton:CreateTexture(nil, "ARTWORK")
    mainButton.highlight:SetSize(30, 30)
    mainButton.highlight:SetPoint("CENTER", 0, 0)
    mainButton.highlight:SetTexture("Interface\\Buttons\\ButtonHilight-Square")
    mainButton.highlight:SetBlendMode("ADD")
    mainButton.highlight:Hide()
    
    mainButton:SetScript("OnEnter", function(self)
        self.highlight:Show()
        if self.border then
            self.border:SetColorTexture(1, 0.82, 0, 1)
        end
    end)
    mainButton:SetScript("OnLeave", function(self)
        self.highlight:Hide()
        if self.border then
            self.border:SetColorTexture(1, 0.82, 0, 0.6)
        end
    end)
    
    mainButton:SetScript("OnDragStart", function(self)
        if not InCombatLockdown() then self:StartMoving() end
    end)
    mainButton:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
    end)
    
    mainButton:SetScript("OnClick", function(self, button)
        if InCombatLockdown() then 
             print("|cffff0000RLMage:|r Kann Menü nicht im Kampf öffnen/schließen.")
             return 
        end
        if RLMage.TogglePortalMenu then RLMage.TogglePortalMenu() end
    end)
    
    RLMage.MainButton = mainButton
    
    -- Initialize other modules if loaded
    if RLMage.InitPortals then RLMage.InitPortals() end
    if RLMage.InitFood then RLMage.InitFood() end
    if RLMage.InitBuffs then RLMage.InitBuffs() end
    
    RLMage.UpdateAllBars()
end

function RLMage.UpdateAllBars()
    if RLMage.UpdatePortalButtons then RLMage.UpdatePortalButtons() end
    if RLMage.UpdateFoodButtons then RLMage.UpdateFoodButtons() end
    if RLMage.UpdateBuffButtons then RLMage.UpdateBuffButtons() end
    RLMage.UpdateLayout()
end

function RLMage.UpdateLayout()
    if InCombatLockdown() then return end
    -- Manage positions of Food and Buff buttons relative to MainButton
    if not RLMage.MainButton then return end
    
    local lastAnchor = RLMage.MainButton
    
    if RLMage.FoodButton then
        if RLMageDB.showFood then
            RLMage.FoodButton:Show()
            RLMage.FoodButton:ClearAllPoints()
            RLMage.FoodButton:SetPoint("LEFT", lastAnchor, "RIGHT", 5, 0)
            lastAnchor = RLMage.FoodButton
        else
            RLMage.FoodButton:Hide()
        end
    end
    
    if RLMage.BuffButton then
        if RLMageDB.showBuffs then
            RLMage.BuffButton:Show()
            RLMage.BuffButton:ClearAllPoints()
            RLMage.BuffButton:SetPoint("LEFT", lastAnchor, "RIGHT", 5, 0)
        else
            RLMage.BuffButton:Hide()
        end
    end
end

-- =========================================================================
-- MINIMAP BUTTON
-- =========================================================================

local mmBtn = CreateFrame("Button", "RLMageMinimapButton", Minimap)
mmBtn:Hide() -- Hide by default, show only if Mage
mmBtn:SetSize(36, 36)
mmBtn:SetFrameStrata("HIGH")
mmBtn:SetMovable(true)
mmBtn:EnableMouse(true)
mmBtn:SetClampedToScreen(true)
mmBtn:RegisterForClicks("LeftButtonUp", "RightButtonUp")

-- Modern dark background (RLTotem style)
local mmBg = mmBtn:CreateTexture(nil, "BACKGROUND")
mmBg:SetAllPoints()
mmBg:SetColorTexture(0.2, 0.2, 0.25, 0.8)
mmBtn.bg = mmBg

-- Border
local mmBorder = mmBtn:CreateTexture(nil, "OVERLAY")
mmBorder:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
mmBorder:SetSize(54, 54)
mmBorder:SetPoint("TOPLEFT")
mmBtn.border = mmBorder

-- Icon
local icon = mmBtn:CreateTexture(nil, "ARTWORK")
icon:SetSize(22, 22)
icon:SetPoint("CENTER")
icon:SetTexture("Interface\\Icons\\Spell_Arcane_PortalStormWind")
mmBtn.icon = icon

-- Highlight texture
local mmHighlight = mmBtn:CreateTexture(nil, "HIGHLIGHT")
mmHighlight:SetAllPoints()
mmHighlight:SetColorTexture(1, 1, 1, 0.3)
mmBtn:SetHighlightTexture(mmHighlight)

-- Pushed texture
local mmPushed = mmBtn:CreateTexture(nil, "ARTWORK")
mmPushed:SetAllPoints()
mmPushed:SetColorTexture(0.5, 0.5, 0.5, 0.5)
mmPushed:Hide()
mmBtn.pushed = mmPushed

mmBtn:SetScript("OnEnter", function(self)
    self.bg:SetColorTexture(0.3, 0.3, 0.35, 0.9)
    GameTooltip:SetOwner(self, "ANCHOR_LEFT")
    GameTooltip:AddLine("RLMage")
    GameTooltip:AddLine(RLMage.L.MM_LEFT_CLICK, 1, 1, 1)
    GameTooltip:AddLine(RLMage.L.MM_DRAG, 1, 1, 1)
    GameTooltip:Show()
end)

mmBtn:SetScript("OnLeave", function(self)
    self.bg:SetColorTexture(0.2, 0.2, 0.25, 0.8)
    GameTooltip:Hide()
end)

mmBtn:SetScript("OnMouseDown", function(self, button)
    if button == "LeftButton" then
        self.pushed:Show()
        self.icon:SetPoint("CENTER", self, "CENTER", 1, -1)
    end
end)

mmBtn:SetScript("OnMouseUp", function(self, button)
    self.pushed:Hide()
    self.icon:SetPoint("CENTER", self, "CENTER", 0, 0)
end)

function RLMage.UpdateMinimapButton()
    if not RLMageDB or not RLMageDB.minimap then return end
    
    if RLMageDB.minimap.hide then
        mmBtn:Hide()
    else
        mmBtn:Show()
        local angle = math.rad(RLMageDB.minimap.pos or 45)
        local x = math.cos(angle) * 80
        local y = math.sin(angle) * 80
        mmBtn:ClearAllPoints()
        mmBtn:SetPoint("CENTER", Minimap, "CENTER", x, y)
    end
end

mmBtn:RegisterForDrag("LeftButton")
mmBtn:SetScript("OnDragStart", function(self)
    self:LockHighlight()
    self:SetScript("OnUpdate", function(self)
        local x, y = GetCursorPosition()
        local scale = Minimap:GetEffectiveScale()
        local cx, cy = Minimap:GetCenter()
        x, y = x / scale, y / scale
        local dx, dy = x - cx, y - cy
        local angle = math.deg(math.atan2(dy, dx))
        if angle < 0 then angle = angle + 360 end
        RLMageDB.minimap.pos = angle
        RLMage.UpdateMinimapButton()
    end)
end)

mmBtn:SetScript("OnDragStop", function(self)
    self:UnlockHighlight()
    self:SetScript("OnUpdate", nil)
end)

mmBtn:SetScript("OnClick", function(self, button)
    if RLMage.ToggleOptions then RLMage.ToggleOptions() end
end)

SLASH_RLMAGE1 = "/rlmage"
SlashCmdList["RLMAGE"] = function(msg)
    local cmd = msg and msg:lower() or ""
    
    if cmd == "debug" then
        if RLMage.ScanSpellbook then RLMage.ScanSpellbook() end
        print("|cff00ff00RLMage Debug:|r Suche nach 'Essen'/'Food' Zaubern...")
        
        if RLMage.SpellBookCache then
             local found = false
             for id, _ in pairs(RLMage.SpellBookCache) do
                 local name = GetSpellInfo(id)
                 if name and (name:find("Essen") or name:find("Food") or name:find("Conjure")) then
                      print("Gefunden: " .. name .. " (ID: " .. id .. ")")
                      found = true
                 end
             end
             if not found then print("Keine passenden Zauber im Spellbook Cache gefunden.") end
        else
             print("SpellBookCache ist leer.")
        end
        
    elseif cmd == "scan" then
        if RLMage.ScanSpellbook then 
             RLMage.ScanSpellbook() 
             print("|cff00ff00RLMage:|r Zauberbuch gescannt.")
             if RLMage.UpdateAllBars then RLMage.UpdateAllBars() end
        end

    elseif cmd == "test" then
        if RLMage.TestCombatAnnounce then
            RLMage.TestCombatAnnounce()
        end

    elseif cmd == "debug" then
        if RLMage.ToggleCombatDebug then
            RLMage.ToggleCombatDebug()
        end

    else
        if RLMage.ToggleOptions then 
            RLMage.ToggleOptions() 
        else
            print("RLMage Options not loaded.")
        end
    end
end