-- Buzzer.lua

-- Create a global addon table. This is good practice for organizing code.
Buzzer = {}

Buzzer_ChannelButtons = {}

-- Keybinding registration
BINDING_HEADER_BUZZER = "Buzzer Addon"
_G["BINDING_NAME_TOGGLE_BUZZER"] = "Toggle Buzzer Window"

-- Toggle logic
function TOGGLE_BUZZER()
    if BuzzerMainFrame and BuzzerMainFrame:IsShown() then
        BuzzerMainFrame:Hide()
    elseif BuzzerMainFrame then
        BuzzerMainFrame:Show()
    end
end

-- This frame will handle our initialization logic.
local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_LOGIN")
f:SetScript("OnEvent", function(self, event, ...)
    if event == "PLAYER_LOGIN" then
        print("|cff33ff99Buzzer:|r PLAYER_LOGIN event fired in Buzzer.lua!")

        -- Slash command registration moved here to ensure game is ready
        SLASH_BUZZER1 = "/buzzer"
        SlashCmdList["BUZZER"] = function(msg)
            msg = msg:lower()
            if msg == "options" then
                if not BuzzerOptionsCategory then
                    BuzzerOptionsPanel:Show()
                    Buzzer_InitializeOptions()
                end
                if BuzzerOptionsCategory then
                    if not SettingsPanel:IsShown() then
                        ShowUIPanel(SettingsPanel)
                    end
                    C_Timer.After(0, function()
                        if Settings and Settings.OpenToCategory and BuzzerOptionsCategoryName then
                            C_Timer.After(0, function()
                                Settings.OpenToCategory(BuzzerOptionsCategoryName)
                            end)
                        end
                    end)
                else
                    print("Buzzer: Options could not be loaded.")
                end

            elseif msg == "toggle" then
                TOGGLE_BUZZER()

            elseif msg == "emote" then
                BuzzerSettings.emoteMuted = not BuzzerSettings.emoteMuted
                local mute = _G["MuteButton"]
                if mute and mute.UpdateIcon then
                    mute:UpdateIcon()
                end
                if BuzzerSettings.emoteMuted then
                    if BuzzerSettings.enableSound then
                        PlaySoundFile("Interface\\AddOns\\Buzzer\\Media\\off.ogg", BuzzerSettings.soundChannel)
                    end
                    print("Buzzer emotes muted.")
                else
                    if BuzzerSettings.enableSound then
                        PlaySoundFile("Interface\\AddOns\\Buzzer\\Media\\on.ogg", BuzzerSettings.soundChannel)
                    end
                    print("Buzzer emotes enabled.")
                end

            elseif msg == "help" then
                print("Buzzer commands:")
                print("/buzzer toggle - Toggles the Buzzer window.")
                print("/buzzer options - Opens the options panel.")
                print("/buzzer emote - Toggles incoming message emotes.")
                print("/bm <message> - Sends a message.")

            else
                print("Buzzer commands:")
                print("/buzzer toggle - Toggles the Buzzer window.")
                print("/buzzer options - Opens the options panel.")
                print("/buzzer emote - Toggles incoming message emotes.")
                print("/bm <message> - Sends a message.")
            end
        end

        -- Ensure settings table
        BuzzerSettings = BuzzerSettings or {}
        if not BuzzerSettings.soundChannel then BuzzerSettings.soundChannel = "Master" end
        BuzzerSettings.emoteMuted = BuzzerSettings.emoteMuted or false

        Buzzer_InitializeOptions()

        if BuzzerSettings.channel == nil then BuzzerSettings.channel = 1 end
        if BuzzerSettings.model == nil then BuzzerSettings.model = 1 end

        local index = BuzzerSettings.model
        local model = Buzzer_Models and Buzzer_Models[index]

        if not model then
            print("Buzzer: Unknown model index '" .. tostring(index) .. "'.")
            BuzzerSettings.model = 1
            model = Buzzer_Models[1]
            if model and model.name then
                print("Buzzer: Defaulting to model 1 (" .. model.name .. ").")
            else
                print("Buzzer: Defaulting to model 1.")
            end
        end

        if model then
            model.frame = BuzzerMainFrame
            Buzzer_BuildUI(model)
        else
            print("Buzzer: No valid models found.")
        end

        local mute = _G["MuteButton"]
        if mute and mute.UpdateIcon then
            mute:UpdateIcon()
        end
    end
end)


-- Dynamic model switcher
function Buzzer_SwitchModel(index)
    if not Buzzer_Models or not Buzzer_Models[index] then
        print("Buzzer: Cannot switch to unknown model index " .. tostring(index))
        return
    end

    for _, child in ipairs({ BuzzerMainFrame:GetChildren() }) do
        local name = child:GetName()
        if name and _G[name] == child then _G[name] = nil end
        child:Hide()
        child:SetParent(nil)
    end
    
    for _, region in ipairs({ BuzzerMainFrame:GetRegions() }) do
        if region:IsObjectType("Texture") or region:IsObjectType("FontString") then
            region:Hide()
            region:SetParent(nil)
        end
    end

    if BuzzerMainFrame.BuzzerBackground then
        BuzzerMainFrame.BuzzerBackground:Hide()
        BuzzerMainFrame.BuzzerBackground:SetParent(nil)
        BuzzerMainFrame.BuzzerBackground = nil
    end

    BuzzerSettings.model = index
    local model = Buzzer_Models[index]
    model.frame = BuzzerMainFrame
    Buzzer_BuildUI(model)
end


function Buzzer_UpdateChannelButtons()
    for index, button in pairs(Buzzer_ChannelButtons or {}) do
        local isActive = (BuzzerSettings.channel == index)
        if button.Glow then
            if isActive then
                button.Glow:Show()
                if not button.GlowPulse then
                    button.GlowPulse = button.Glow:CreateAnimationGroup()
                    local fadeOut = button.GlowPulse:CreateAnimation("Alpha")
                    fadeOut:SetFromAlpha(1); fadeOut:SetToAlpha(0.2); fadeOut:SetDuration(0.6); fadeOut:SetOrder(1)
                    local fadeIn = button.GlowPulse:CreateAnimation("Alpha")
                    fadeIn:SetFromAlpha(0.2); fadeIn:SetToAlpha(1); fadeIn:SetDuration(0.6); fadeIn:SetOrder(2)
                    button.GlowPulse:SetLooping("REPEAT")
                end
                button.GlowPulse:Play()
            else
                button.Glow:Hide()
                if button.GlowPulse then button.GlowPulse:Stop() end
            end
        end

        if button.Label then
            if isActive then
                button.Label:SetTextColor(0, 1, 0)
                if not button.LabelPulse then
                    button.LabelPulse = button.Label:CreateAnimationGroup()
                    local fadeOut = button.LabelPulse:CreateAnimation("Alpha")
                    fadeOut:SetFromAlpha(1); fadeOut:SetToAlpha(0.5); fadeOut:SetDuration(0.8); fadeOut:SetOrder(1)
                    local fadeIn = button.LabelPulse:CreateAnimation("Alpha")
                    fadeIn:SetFromAlpha(0.5); fadeIn:SetToAlpha(1); fadeIn:SetDuration(0.8); fadeIn:SetOrder(2)
                    button.LabelPulse:SetLooping("REPEAT")
                end
                button.LabelPulse:Play()
            else
                button.Label:SetTextColor(1, 1, 1)
                if button.LabelPulse then button.LabelPulse:Stop() end
            end
        end
    end
end

