local addonName, ns = ...

local hookedFrame

local function IsBigChatBoxLoaded()
    if C_AddOns and C_AddOns.IsAddOnLoaded then
        return C_AddOns.IsAddOnLoaded("BigChatBox")
    end

    if IsAddOnLoaded then
        return IsAddOnLoaded("BigChatBox")
    end

    return false
end

local function CandidateFrame()
    if not IsBigChatBoxLoaded() then return nil end

    local candidates = {
        _G.BigChatBoxFrame,
        type(_G.BigChatBox) == "table" and _G.BigChatBox.frame or nil,
        type(_G.BigChatBox) == "table" and _G.BigChatBox.inputFrame or nil,
        type(_G.BCB) == "table" and _G.BCB.frame or nil,
        type(_G.BCB) == "table" and _G.BCB.inputFrame or nil,
    }

    for _, frame in ipairs(candidates) do
        if frame and frame.IsObjectType and frame:IsObjectType("Frame") then
            return frame
        end
    end

    return nil
end

function ns.GetBigChatBoxStatus()
    local frame = CandidateFrame()
    if not frame then
        return false, nil, false
    end

    local version
    if C_AddOns and C_AddOns.GetAddOnMetadata then
        version = C_AddOns.GetAddOnMetadata("BigChatBox", "Version")
    elseif GetAddOnMetadata then
        version = GetAddOnMetadata("BigChatBox", "Version")
    end

    return true, version, frame:IsShown()
end

function ns.GetAdaptiveChatAnchor()
    if not ChatFloaterDB or ChatFloaterDB.bigChatBoxIntegration == false then
        return nil
    end

    if InCombatLockdown and InCombatLockdown() then
        return nil
    end

    local frame = CandidateFrame()
    if frame and frame:IsShown() then
        return frame
    end

    return nil
end

local function Refresh()
    if ns.OnChatBarPositionChanged then
        ns.OnChatBarPositionChanged()
    end

    if ns.RefreshGUI then
        ns.RefreshGUI()
    end
end

local function HookCandidate()
    local frame = CandidateFrame()
    if not frame or frame == hookedFrame then return end

    hookedFrame = frame
    frame:HookScript("OnShow", Refresh)
    frame:HookScript("OnHide", Refresh)
    frame:HookScript("OnSizeChanged", function()
        if ChatFloaterDB and ChatFloaterDB.chatBarAnchorMode == "ANCHOR" then
            Refresh()
        end
    end)
end

local events = CreateFrame("Frame")
events:RegisterEvent("ADDON_LOADED")
events:RegisterEvent("PLAYER_ENTERING_WORLD")
events:RegisterEvent("PLAYER_REGEN_ENABLED")
events:RegisterEvent("PLAYER_REGEN_DISABLED")
events:SetScript("OnEvent", function(_, event, name)
    if event == "ADDON_LOADED" and name ~= addonName and name ~= "BigChatBox" then
        return
    end

    C_Timer.After(0, function()
        HookCandidate()
        Refresh()
    end)
end)
