
-- rChat: Chicchai integration
-- Auto-minimize chat frames
-- Updated for Edit Mode compatibility (WoW 12.0)

local A, L = ...

local UP, DOWN = 1, -1

-- Stored max heights
local maxHeights = {}

-- Check if Chicchai is enabled
local function IsEnabled()
    return L:GetConfig("chicchai", "enabled")
end

-- Get minimum height based on number of lines
local function getMinHeight(self)
    local cfg = rChatDB.chicchai
    local minHeight = 0
    for i = 1, cfg.minimizedLines do
        minHeight = minHeight + math.floor(select(2, self:GetFont()) + 0.5) + (self:GetSpacing() * 0.9)
    end
    return minHeight
end

-- Get the max height for a chat frame
local function getMaxHeight(chatframe)
    local name = chatframe:GetName()
    
    if maxHeights[name] and maxHeights[name] > 50 then
        return maxHeights[name]
    end
    
    if rChatDB.chicchaiHeights and rChatDB.chicchaiHeights[name] then
        return rChatDB.chicchaiHeights[name]
    end
    
    return 120
end

-- Save height for a chat frame
local function saveMaxHeight(chatframe)
    if not chatframe then return end
    local name = chatframe:GetName()
    local height = chatframe:GetHeight()
    
    if height and height > 50 then
        maxHeights[name] = height
        
        if not rChatDB.chicchaiHeights then
            rChatDB.chicchaiHeights = {}
        end
        rChatDB.chicchaiHeights[name] = height
    end
end

-- Animate chat frame
local function Animate(chatframe, dir, waitTime, finishedFunc)
    if not IsEnabled() then return end
    if chatframe.Animate == dir or chatframe.State == dir and not chatframe.Animate then return end

    if chatframe.Animate == -dir then
        chatframe.TimeRunning = rChatDB.chicchai.animTime - chatframe.TimeRunning
    else
        chatframe.TimeRunning = 0
    end
    chatframe.WaitTime = waitTime
    chatframe.Animate = dir
    chatframe.finishedFunc = finishedFunc
end

-- Minimize after wait time
local function MinimizeAfterWait(chatframe)
    -- Don't auto-minimize combat log if option is set
    if rChatDB.chicchai.maximizeCombatLog and chatframe:GetName() == "ChatFrame2" then
        return
    end
    Animate(chatframe, DOWN, rChatDB.chicchai.minimizeTime)
end

-- Chat event handler
local function chatEvent(chatframe, event, ...)
    if not IsEnabled() then return end
    
    local chatevt, _, _, _, _, _, _, number = event, ...
    
    if chatevt == "CHAT_MSG_CHANNEL" then
        if number and (number > 3) then return end
    end
    
    local targetFrame = chatframe
    if chatframe.isDocked and GENERAL_CHAT_DOCK then
        targetFrame = GENERAL_CHAT_DOCK.primary or chatframe
    end
    
    if rChatDB.chicchai.lockInCombat and UnitAffectingCombat("player") then
        return
    end
    
    if targetFrame.wasOver == true then return end
    
    Animate(targetFrame, UP, nil, MinimizeAfterWait)
end

-- Update/animation handler
local function Update(chatframe, elapsed)
    if not IsEnabled() then return end
    
    local targetFrame = chatframe
    if chatframe.isDocked and GENERAL_CHAT_DOCK then
        targetFrame = GENERAL_CHAT_DOCK.primary or chatframe
    end
    
    -- Mouse over handling - works for ALL frames including combat log
    if rChatDB.chicchai.maximizeOnEnter then
        if MouseIsOver(targetFrame) and not targetFrame.wasOver then
            targetFrame.wasOver = true
            Animate(targetFrame, UP, rChatDB.chicchai.waitAfterEnter)
        elseif targetFrame.wasOver and not MouseIsOver(targetFrame) then
            targetFrame.wasOver = nil
            -- Don't minimize combat log if option is set
            if not (rChatDB.chicchai.maximizeCombatLog and targetFrame:GetName() == "ChatFrame2") then
                Animate(targetFrame, DOWN, rChatDB.chicchai.waitAfterLeave)
            end
        end
    end
    
    -- Wait timer
    if targetFrame.WaitTime then
        targetFrame.WaitTime = targetFrame.WaitTime - elapsed
        if targetFrame.WaitTime > 0 then return end
        targetFrame.WaitTime = nil
    end
    
    targetFrame.State = nil
    
    if targetFrame.TimeRunning == nil then return end
    targetFrame.TimeRunning = targetFrame.TimeRunning + elapsed
    local animPercent = min(targetFrame.TimeRunning / rChatDB.chicchai.animTime, 1)
    
    local heightPercent = targetFrame.Animate == DOWN and 1 - animPercent or animPercent
    
    local minHeight = getMinHeight(targetFrame)
    local maxHeight = getMaxHeight(targetFrame)
    targetFrame:SetHeight(minHeight + (maxHeight - minHeight) * heightPercent)
    
    if animPercent >= 1 then
        targetFrame.State = targetFrame.Animate
        targetFrame.Animate = nil
        targetFrame.TimeRunning = nil
        if targetFrame.finishedFunc then 
            targetFrame:finishedFunc() 
        end
    end
end

-- Initialize Chicchai
function L:InitChicchai()
    if not IsEnabled() then 
        for i = 1, NUM_CHAT_WINDOWS do
            local cf = _G["ChatFrame" .. i]
            if cf then
                cf:SetScript("OnUpdate", nil)
            end
        end
        return 
    end
    
    -- Load saved heights from DB
    if rChatDB.chicchaiHeights then
        for name, height in pairs(rChatDB.chicchaiHeights) do
            maxHeights[name] = height
        end
    end
    
    -- Chat frames to manage - now includes ChatFrame2 (Combat Log)
    local chatFrames = {
        ["ChatFrame1"] = {
            events = {
                "CHAT_MSG_SAY", "CHAT_MSG_EMOTE", "CHAT_MSG_TEXT_EMOTE",
                "CHAT_MSG_PARTY", "CHAT_MSG_PARTY_LEADER",
                "CHAT_MSG_WHISPER",
                "CHAT_MSG_GUILD", "CHAT_MSG_OFFICER",
                "CHAT_MSG_RAID", "CHAT_MSG_RAID_LEADER", "CHAT_MSG_RAID_WARNING",
                "CHAT_MSG_BN_WHISPER",
                "CHAT_MSG_CHANNEL",
            },
            minimize = true
        },
        ["ChatFrame2"] = {
            events = {},
            minimize = false  -- Combat Log: don't auto-minimize, but still respond to mouse
        },
        ["ChatFrame3"] = {
            events = {},
            minimize = true
        }
    }
    
    -- Setup each chat frame
    for frameName, config in pairs(chatFrames) do
        local chatframe = _G[frameName]
        if chatframe then
            for _, event in ipairs(config.events) do
                if not chatframe:IsEventRegistered(event) then
                    chatframe:RegisterEvent(event)
                end
            end
            
            -- Set OnUpdate for mouse-over handling
            chatframe:SetScript("OnUpdate", Update)
            
            -- Only hook events for frames that have them
            if #config.events > 0 then
                chatframe:HookScript("OnEvent", chatEvent)
            end
            
            -- Save initial height and then minimize after delay
            C_Timer.After(1.5, function()
                saveMaxHeight(chatframe)
                
                -- Only minimize if configured to do so
                if config.minimize then
                    if chatframe.isDocked and GENERAL_CHAT_DOCK then
                        Animate(GENERAL_CHAT_DOCK.primary, DOWN)
                    else
                        Animate(chatframe, DOWN)
                    end
                end
            end)
        end
    end
    
    -- Hook into Edit Mode save
    if EditModeManagerFrame then
        hooksecurefunc(EditModeManagerFrame, "SaveLayouts", function()
            C_Timer.After(0.1, function()
                for i = 1, NUM_CHAT_WINDOWS do
                    local cf = _G["ChatFrame" .. i]
                    if cf then
                        saveMaxHeight(cf)
                    end
                end
                print("|cff33ff99rChat:|r Chat heights updated from Edit Mode!")
            end)
        end)
    end
    
    -- Handle tab clicks for Combat Log
    hooksecurefunc("FCF_Tab_OnClick", function(tab)
        if not IsEnabled() then return end
        
        -- When clicking Combat Log tab, maximize it
        if tab:GetName() == "ChatFrame2Tab" then
            local cf = _G["ChatFrame2"]
            if cf then
                Animate(cf, UP)
            end
        end
    end)
end

-- Manual save command
SLASH_RCHATSAVE1 = "/rchatsave"
SlashCmdList["RCHATSAVE"] = function()
    for i = 1, NUM_CHAT_WINDOWS do
        local cf = _G["ChatFrame" .. i]
        if cf then
            saveMaxHeight(cf)
            local name = cf:GetName()
            if maxHeights[name] then
                print("|cff33ff99rChat:|r " .. name .. " = " .. math.floor(maxHeights[name]) .. "px")
            end
        end
    end
end
