-------------------------
-- AiB Call to Arms Tracker
-------------------------
-- Zeigt aktive Call to Arms Belohnungen für Dungeons & Raids

AiB_CallToArms = AiB_CallToArms or {}
local CTA = AiB_CallToArms

-- v2.1.0.0: AiB_CallToArmsConfig ist Alias auf AiB.db.profile.calltoarms (AceDB)
-- Init-Fallback in PLAYER_LOGIN bleibt als Upgrade-Schutz erhalten.
AiB_CallToArmsConfig = AiB_CallToArmsConfig or nil

-- Data Storage
CTA.data = {}
CTA.lock = false
CTA.lastStatus = nil
CTA.lastUpdate = 0

-- Main Frame
local ctaFrame = nil

-------------------------
-- Create Window
-------------------------
function CTA:CreateWindow()
    if ctaFrame then return end
    
    -- Main Window
    ctaFrame = CreateFrame("Frame", "AiB_CallToArmsFrame", UIParent, "BackdropTemplate")
    ctaFrame:SetSize(250, 100) -- Startet klein, wird dynamisch angepasst
    
    -- Load saved position or use default
    local point = "CENTER"
    local posX = 0
    local posY = 0
    
    if AiB_CallToArmsConfig and AiB_CallToArmsConfig.position then
        point = AiB_CallToArmsConfig.position.point or "CENTER"
        posX = AiB_CallToArmsConfig.position.x or 0
        posY = AiB_CallToArmsConfig.position.y or 0
    end
    
    ctaFrame:SetPoint(point, UIParent, point, posX, posY)
    
    ctaFrame:SetFrameStrata("MEDIUM")
    ctaFrame:SetMovable(true)
    ctaFrame:EnableMouse(true)
    ctaFrame:RegisterForDrag("LeftButton")
    ctaFrame:SetClampedToScreen(true)
    
    -- Backdrop
    ctaFrame:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true,
        tileSize = 32,
        edgeSize = 32,
        insets = { left = 8, right = 8, top = 8, bottom = 8 }
    })
    ctaFrame:SetBackdropColor(0, 0, 0, 0.9)
    ctaFrame:SetBackdropBorderColor(1, 0.8, 0, 1)
    
    -- Drag Functionality
    ctaFrame:SetScript("OnDragStart", function(self)
        self:StartMoving()
    end)
    
    ctaFrame:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
        -- Save position with anchor point
        local point, relativeTo, relativePoint, x, y = self:GetPoint(1)
        
        -- Make sure we have valid coordinates
        if x and y and point then
            AiB_CallToArmsConfig.position = {
                point = point,
                x = math.floor(x + 0.5),
                y = math.floor(y + 0.5)
            }
        end
    end)
    
    -- Title
    local title = ctaFrame:CreateFontString(nil, "OVERLAY")
    title:SetFont("Fonts\\FRIZQT__.TTF", 12, "OUTLINE")
    title:SetPoint("TOP", ctaFrame, "TOP", 0, -12)
    title:SetText("|cFFFFAA00Call to Arms|r")
    ctaFrame.title = title
    
    -- Close Button
    local closeBtn = CreateFrame("Button", nil, ctaFrame)
    closeBtn:SetSize(20, 20)
    closeBtn:SetPoint("TOPRIGHT", ctaFrame, "TOPRIGHT", -5, -5)
    closeBtn:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up")
    closeBtn:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down")
    closeBtn:SetHighlightTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight")
    closeBtn:SetScript("OnClick", function()
        AiB_CallToArmsConfig.enabled = false
        CTA:UpdateVisibility()
    end)
    
    -- Content Frame (für scrollbaren Content)
    local content = CreateFrame("Frame", nil, ctaFrame)
    content:SetPoint("TOPLEFT", ctaFrame, "TOPLEFT", 15, -35)
    content:SetPoint("BOTTOMRIGHT", ctaFrame, "BOTTOMRIGHT", -15, 15)
    ctaFrame.content = content
    
    -- Text Display
    local text = content:CreateFontString(nil, "OVERLAY")
    text:SetFont("Fonts\\FRIZQT__.TTF", 11)
    text:SetPoint("TOPLEFT", content, "TOPLEFT", 0, 0)
    text:SetPoint("TOPRIGHT", content, "TOPRIGHT", 0, 0)
    text:SetJustifyH("LEFT")
    text:SetJustifyV("TOP")
    text:SetTextColor(1, 1, 1, 1)
    ctaFrame.text = text
    
    CTA.frame = ctaFrame
    
    -- Initial Update
    CTA:UpdateVisibility()
end

-------------------------
-- Check Status
-------------------------
function CTA:CheckStatus()
    -- TEST MODE: Show example data
    if AiB_CallToArmsConfig.testMode then
        CTA.data = {
            [1] = {
                dID = 2516,
                name = "Random Dungeon (TEST)",
                rewardIcon = "Interface\\Icons\\INV_Misc_Bag_10",
                tank = AiB_CallToArmsConfig.roles.tank,
                healer = AiB_CallToArmsConfig.roles.healer,
                damage = AiB_CallToArmsConfig.roles.damage
            },
            [2] = {
                dID = 2993,
                name = "Random Heroic Dungeon (TEST)",
                rewardIcon = "Interface\\Icons\\INV_Misc_Bag_10",
                tank = AiB_CallToArmsConfig.roles.tank,
                healer = false,
                damage = false
            }
        }
        CTA.lastStatus = true
        return true
    end
    
    local data = {}
    local hasRewards = false
    
    -- Get player's available roles
    local canTank, canHealer, canDamage = C_LFGList.GetAvailableRoles()
    
    -- Override with config if user wants to see specific roles
    local showTank = AiB_CallToArmsConfig.roles.tank and canTank
    local showHealer = AiB_CallToArmsConfig.roles.healer and canHealer
    local showDamage = AiB_CallToArmsConfig.roles.damage and canDamage
    
    -- Check Random Dungeons
    for i = 1, GetNumRandomDungeons() do
        local dID, dName = GetLFGRandomDungeonInfo(i)
        
        if dID and dName then
            for j = 1, LFG_ROLE_NUM_SHORTAGE_TYPES do
                local eligible, tank, healer, damage, itemCount = GetLFGRoleShortageRewards(dID, j)
                
                if eligible and itemCount and itemCount > 0 then
                    local rewardName, rewardIcon = GetLFGDungeonShortageRewardInfo(dID, j, 1)
                    
                    -- Check if any of the player's selected roles have rewards
                    local hasTank = tank and showTank
                    local hasHealer = healer and showHealer
                    local hasDamage = damage and showDamage
                    
                    if hasTank or hasHealer or hasDamage then
                        data[dID] = {
                            dID = dID,
                            name = dName,
                            rewardIcon = rewardIcon or "Interface\\Icons\\INV_Misc_Bag_10",
                            tank = hasTank,
                            healer = hasHealer,
                            damage = hasDamage
                        }
                        hasRewards = true
                    end
                end
            end
        end
    end
    
    -- Check Raid Finder
    for i = 1, GetNumRFDungeons() do
        local dID, dName = GetRFDungeonInfo(i)
        
        if dID and dName then
            for j = 1, LFG_ROLE_NUM_SHORTAGE_TYPES do
                local eligible, tank, healer, damage, itemCount = GetLFGRoleShortageRewards(dID, j)
                
                if eligible and itemCount and itemCount > 0 then
                    local rewardName, rewardIcon = GetLFGDungeonShortageRewardInfo(dID, j, 1)
                    
                    local hasTank = tank and showTank
                    local hasHealer = healer and showHealer
                    local hasDamage = damage and showDamage
                    
                    if hasTank or hasHealer or hasDamage then
                        data[dID] = {
                            dID = dID,
                            name = dName,
                            rewardIcon = rewardIcon or "Interface\\Icons\\INV_Misc_Bag_10",
                            tank = hasTank,
                            healer = hasHealer,
                            damage = hasDamage
                        }
                        hasRewards = true
                    end
                end
            end
        end
    end
    
    -- *** SOUND TRIGGER: Spiele Sound wenn neue Rewards gefunden wurden ***
    if hasRewards and CTA.lastStatus == false then
        -- Nur triggern wenn von false -> true (neue Rewards erschienen)
        local soundId = AiB_CallToArmsConfig.soundId or 1
        
        if soundId > 0 then
            -- Sound Liste (muss identisch mit Settings sein!)
            local sounds = {
                [1] = "AUCTION_WINDOW_OPEN",      -- Auktionshaus
                [2] = "READY_CHECK",              -- Ready Check
                [3] = "TELL_MESSAGE",             -- Whisper
                [4] = "RAID_WARNING",             -- Raid Warning
                [5] = "ACHIEVEMENT_MENU_OPEN",    -- Achievement
            }
            
            local soundkit = sounds[soundId]
            if soundkit then
                PlaySound(SOUNDKIT[soundkit], "Master")
            end
        end
    end
    
    CTA.data = data
    CTA.lastStatus = hasRewards
    
    return hasRewards
end

-------------------------
-- Update Display
-------------------------
function CTA:UpdateDisplay()
    if not ctaFrame or not ctaFrame.text then return end
    
    local tankIcon = "|TInterface\\LFGFrame\\UI-LFG-ICON-PORTRAITROLES:16:16:0:0:64:64:0:19:22:41|t"
    local healerIcon = "|TInterface\\LFGFrame\\UI-LFG-ICON-PORTRAITROLES:16:16:0:0:64:64:20:39:1:20|t"
    local damageIcon = "|TInterface\\LFGFrame\\UI-LFG-ICON-PORTRAITROLES:16:16:0:0:64:64:20:39:22:41|t"
    
    local text = ""
    local lineCount = 0
    
    for _, v in pairs(CTA.data) do
        local iconText = ""
        
        if v.tank then
            iconText = iconText .. tankIcon .. " "
        end
        if v.healer then
            iconText = iconText .. healerIcon .. " "
        end
        if v.damage then
            iconText = iconText .. damageIcon .. " "
        end
        
        if iconText ~= "" then
            text = text .. string.format("|T%s:16|t %s%s\n", v.rewardIcon, iconText, v.name)
            lineCount = lineCount + 1
        end
    end
    
    if text == "" then
        text = "|cFF888888Keine Call to Arms aktiv|r"
        lineCount = 1
    end
    
    ctaFrame.text:SetText(text)
    
    -- Adjust frame height dynamically
    local newHeight = 50 + (lineCount * 22)
    ctaFrame:SetHeight(math.max(newHeight, 80))
end

-------------------------
-- Update Visibility
-------------------------
function CTA:UpdateVisibility()
    if not ctaFrame then return end
    
    if AiB_CallToArmsConfig.enabled and CTA.lastStatus then
        ctaFrame:Show()
        CTA:UpdateDisplay()
    else
        ctaFrame:Hide()
    end
end

-------------------------
-- Update Check (Throttled)
-------------------------
function CTA:Update()
    local now = GetTime()
    
    -- Throttle updates to every 30 seconds
    if CTA.lock or (now - CTA.lastUpdate) < 30 then
        return
    end
    
    CTA.lock = true
    CTA.lastUpdate = now
    
    RequestLFDPlayerLockInfo()
    
    C_Timer.After(1, function()
        local hasRewards = CTA:CheckStatus()
        CTA:UpdateVisibility()
        
        C_Timer.After(29, function()
            CTA.lock = false
        end)
    end)
end

-------------------------
-- Event Handler
-------------------------
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("PLAYER_LOGIN")
eventFrame:RegisterEvent("LFG_UPDATE_RANDOM_INFO")
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")

eventFrame:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_LOGIN" then
        -- Wait for SavedVariables to load
        C_Timer.After(5, function()
            -- Ensure config exists with saved values
            if not AiB_CallToArmsConfig then
                AiB_CallToArmsConfig = {
                    enabled = true,
                    testMode = false,
                    soundId = 1,  -- *** Standard: Auktionshaus Sound ***
                    roles = {tank = true, healer = true, damage = true},
                    position = {point = "CENTER", x = 0, y = 0}
                }
            end
            
            -- *** Upgrade von soundEnabled zu soundId ***
            if AiB_CallToArmsConfig.soundEnabled ~= nil then
                -- Alte Config: soundEnabled war boolean
                if AiB_CallToArmsConfig.soundEnabled == true then
                    AiB_CallToArmsConfig.soundId = 1  -- Auktionshaus Sound
                else
                    AiB_CallToArmsConfig.soundId = 0  -- Aus
                end
                AiB_CallToArmsConfig.soundEnabled = nil  -- Alte Variable löschen
            end
            
            -- *** Ensure soundId exists (für Upgrades) ***
            if AiB_CallToArmsConfig.soundId == nil then
                AiB_CallToArmsConfig.soundId = 1  -- Standard: Auktionshaus
            end
            
            -- Ensure position table exists with point
            if not AiB_CallToArmsConfig.position then
                AiB_CallToArmsConfig.position = {point = "CENTER", x = 0, y = 0}
            elseif not AiB_CallToArmsConfig.position.point then
                -- Upgrade old config without point
                AiB_CallToArmsConfig.position.point = "CENTER"
            end
            
            CTA:CreateWindow()
            CTA:Update()
        end)
    elseif event == "LFG_UPDATE_RANDOM_INFO" or event == "PLAYER_ENTERING_WORLD" then
        CTA:Update()
    end
end)

-- Periodic update check
C_Timer.NewTicker(60, function()
    CTA:Update()
end)
