local addonName = ...
local f = CreateFrame("Frame")

local chatFrame = ChatFrame1 -- Default main chat frame
local isChatOpen = false
local isGrouped = false

-- Function to check if the player is in a group
local function UpdateGroupStatus()
    isGrouped = IsInGroup() or IsInRaid()
end

-- Function to hide or show chat
local function UpdateChatVisibility()
    if isChatOpen or InCombatLockdown() or isGrouped then
        chatFrame:Show()
    else
        chatFrame:Hide()
    end
end

-- Events to monitor
f:RegisterEvent("PLAYER_LOGIN") -- On login
f:RegisterEvent("PLAYER_REGEN_DISABLED") -- Enter combat
f:RegisterEvent("PLAYER_REGEN_ENABLED") -- Leave combat
f:RegisterEvent("CHAT_MSG_WHISPER") -- Receive whisper
f:RegisterEvent("GROUP_ROSTER_UPDATE") -- Party/raid change
f:RegisterEvent("GROUP_JOINED") -- Group formed
f:RegisterEvent("GROUP_LEFT") -- Group left

-- Hook into edit box to detect when player is typing
hooksecurefunc(ChatFrame1EditBox, "Show", function()
    isChatOpen = true
    UpdateChatVisibility()
end)

hooksecurefunc(ChatFrame1EditBox, "Hide", function()
    isChatOpen = false
    UpdateChatVisibility()
end)

f:SetScript("OnEvent", function(self, event, ...)
    if event == "PLAYER_LOGIN" then
        UpdateGroupStatus()
        UpdateChatVisibility()
    elseif event == "PLAYER_REGEN_DISABLED" or event == "CHAT_MSG_WHISPER" then
        chatFrame:Show()
    elseif event == "PLAYER_REGEN_ENABLED" then
        UpdateChatVisibility()
    elseif event == "GROUP_ROSTER_UPDATE" or event == "GROUP_JOINED" or event == "GROUP_LEFT" then
        UpdateGroupStatus()
        UpdateChatVisibility()
    end
end)
