local addonPrefix = "BuzzerComm"
local defaultChannelName = "BuzzerNet"

-- Libraries
local ChatThrottleLib = _G.ChatThrottleLib

-- Helper: Read values from BuzzerRadioConfig with fallback
local function GetRadioConfig(key, fallback)
    local modelIndex = BuzzerSettings and BuzzerSettings.model or 1
    local model = Buzzer_Models and Buzzer_Models[modelIndex]
    if model and model[key] ~= nil then
        return model[key]
    end
    return fallback
end

-- Simple XOR encryption
local function xorEncrypt(input, key)
    local result = {}
    for i = 1, #input do
        local c = input:byte(i)
        local k = key:byte((i - 1) % #key + 1)
        table.insert(result, string.char(bit.bxor(c, k)))
    end
    return table.concat(result)
end

-- Utility: Get actual channel ID used by WoW
local function GetCustomChannelID(name)
    local channelID, channelName = GetChannelName(name)
    if channelID and channelID > 0 then
        return channelID
    end
    return nil
end

-- Setup on login
local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_LOGIN")
f:SetScript("OnEvent", function()
    C_ChatInfo.RegisterAddonMessagePrefix(addonPrefix)

    BuzzerSettings = BuzzerSettings or {}
    BuzzerSettings.chatChannelName = BuzzerSettings.chatChannelName or defaultChannelName

    -- Delay channel join to avoid taking early channel slots
    C_Timer.After(7, function()
        JoinChannelByName(BuzzerSettings.chatChannelName)
        print(string.format("|cffffcc00Buzzer fully operational."))
    end)

    SLASH_BUZZERMESSAGE1 = "/bm"
    SlashCmdList["BUZZERMESSAGE"] = function(msg)
        SendBuzzerMessage(msg)
    end
end)

-- Send message
function SendBuzzerMessage(msg)
    -- Removed the check that prevented sending messages
    if not msg or msg == "" then return end

    local useGuild = GetRadioConfig("sendOverGuild", false)

    local channelID
    if not useGuild then
        channelID = GetCustomChannelID(BuzzerSettings.chatChannelName or defaultChannelName)
        if not channelID then
            print("Buzzer: Cannot send message — no channel ID found.")
            return
        end
    end

    local maxChannels = GetRadioConfig("maxChannels", 15)
    local freq = tonumber(BuzzerSettings.channel or 1)
    local senderName = BuzzerSettings.customName or UnitName("player")
    local text = msg

    if GetRadioConfig("encryption") and BuzzerSettings.encryptionKey then
        text = xorEncrypt(msg, BuzzerSettings.encryptionKey)
    end

    local payload
    if useGuild then
        payload = string.format("%s:%s", senderName, text)
    else
        payload = string.format("%s:%s:%d", senderName, text, freq)
    end
    
    -- Get the current model name for the emote
    local modelIndex = BuzzerSettings.model or 1
    local modelName = "Buzzer" -- Default name in case something goes wrong
    if Buzzer_Models and Buzzer_Models[modelIndex] and Buzzer_Models[modelIndex].name then
        modelName = Buzzer_Models[modelIndex].name
    end

    -- NEW: Send the emote and say messages
    SendChatMessage("speaks into their " .. modelName, "EMOTE")
    SendChatMessage(msg, "SAY")

    -- Send the addon message to other Buzzer users
    if useGuild then
        C_ChatInfo.SendAddonMessage(addonPrefix, payload, "GUILD")
    else
        C_ChatInfo.SendAddonMessage(addonPrefix, payload, "CHANNEL", channelID)
    end

    if BuzzerSettings.enableSound then
        PlaySoundFile("Interface\\AddOns\\Buzzer\\Media\\send.ogg", BuzzerSettings.soundChannel)
    end
end

-- Receive message
local listener = CreateFrame("Frame")
listener:RegisterEvent("CHAT_MSG_ADDON")
listener:SetScript("OnEvent", function(_, event, prefix, message, channelType, sender)
    if event ~= "CHAT_MSG_ADDON" then return end
    if prefix ~= addonPrefix then return end
    -- Removed the check that prevented receiving messages

    local useGuild = GetRadioConfig("sendOverGuild", false)

    -- Only accept messages over the channel type we are configured to use
    if (channelType == "GUILD" and not useGuild) or (channelType == "CHANNEL" and useGuild) then
        return
    end

    if channelType ~= "CHANNEL" and channelType ~= "GUILD" then return end

    local isGuild = (channelType == "GUILD")
    local name, msg, freq

    if isGuild then
        name, msg = strsplit(":", message or "", 2)
    else
        name, msg, freq = strsplit(":", message or "", 3)
    end

    if not name or not msg or (not freq and not isGuild) then
        print("Buzzer: Received malformed message:", message)
        return
    end

    if not isGuild and tonumber(freq) ~= tonumber(BuzzerSettings.channel) then
        return
    end

    if GetRadioConfig("encryption") and BuzzerSettings.encryptionKey then
        msg = xorEncrypt(msg, BuzzerSettings.encryptionKey)
    end

    if sender and sender:match("^[^-]+") ~= UnitName("player") then
        Buzzer_PlayIncomingEmote(msg) -- The mute check will happen inside this function
    else
        -- Play sound for self-sent messages
        if BuzzerSettings.enableSound then
            PlaySoundFile("Interface\\AddOns\\Buzzer\\Media\\receive.ogg", BuzzerSettings.soundChannel)
        end
        
    end

    if isGuild then
        print(string.format("|cffffff00[Buzzer]|r |cff00ff00%s|r: |cffc080ff%s|r", name, msg))
    else
        print(string.format("|cffffff00[Buzzer - Freq %d]|r |cff00ff00%s|r: |cffc080ff%s|r", freq, name, msg))
    end
    
end)