-- Buzzer.lua

local f = CreateFrame("Frame")
Buzzer_ChannelButtons = {}

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

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

-- Slash command

SLASH_BUZZ1 = "/buzz"
SlashCmdList["BUZZ"] = 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 == "show" then
        TOGGLE_BUZZER()

    elseif msg == "help" then
        print("Buzzer commands:")
        print("/buzz - toggles UI")
        print("/buzz options - opens the options panel")
        print("/bm <message> - sends a message")

    else
        print("Buzzer commands:")
        print("/buzz - toggles UI")
        print("/buzz options - opens the options panel")
        print("/bm <message> - sends a message")
    end
end

f:RegisterEvent("PLAYER_LOGIN")
f:SetScript("OnEvent", function(self, event, ...)
    if event == "PLAYER_LOGIN" then
        -- Ensure settings table
        BuzzerSettings = BuzzerSettings or {}

        if not BuzzerSettings.soundChannel then
            BuzzerSettings.soundChannel = "Master"
        end

        -- Apply mute default early
        BuzzerSettings.muted = true

        -- Initialize options UI
        Buzzer_InitializeOptions()

        -- Set channel/model defaults
        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

        -- ✅ Build UI first so mute button exists
        if model then
            model.frame = BuzzerMainFrame
            Buzzer_BuildUI(model)
        else
            print("Buzzer: No valid models found.")
        end

        -- ✅ Now update mute button (it exists now)
        local mute = _G["MuteButton"]
        if mute and mute.UpdateIcon then
            mute:SetButtonState(BuzzerSettings.muted and "PUSHED" or "NORMAL", true)
            mute:UpdateIcon()
        end
    end
end)



-- Dynamic model switcher (no reload needed)
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

    -- Clear previous child frames
    for _, child in ipairs({ BuzzerMainFrame:GetChildren() }) do
        local name = child:GetName()
        if name and _G[name] == child then
            _G[name] = nil -- prevent reuse
        end
        child:Hide()
        child:SetParent(nil)
    end
    

    -- Clear previous texture/fontstring regions
    for _, region in ipairs({ BuzzerMainFrame:GetRegions() }) do
        if region:IsObjectType("Texture") or region:IsObjectType("FontString") then
            region:Hide()
            region:SetParent(nil)
        end
    end

    -- Clear model background if set
    if BuzzerMainFrame.BuzzerBackground then
        BuzzerMainFrame.BuzzerBackground:Hide()
        BuzzerMainFrame.BuzzerBackground:SetParent(nil)
        BuzzerMainFrame.BuzzerBackground = nil
    end

    -- Update current model
    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)

        -- Glow
        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

        -- Label
        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
