local _, ns = ...

local UI = ns.UI or {}
ns.UI = UI

local closedGarbageCollectionPending = false
local lastClosedGarbageCollection = 0

function UI:RequestClosedGarbageCollection()
    if closedGarbageCollectionPending then
        return
    end

    local now = type(GetTime) == "function" and GetTime() or 0
    if lastClosedGarbageCollection > 0 and now > 0 and (now - lastClosedGarbageCollection) < 2 then
        return
    end

    closedGarbageCollectionPending = true
    local function collectClosedRuntimeGarbage()
        closedGarbageCollectionPending = false
        if self.frame and self.frame:IsShown() then
            return
        end
        lastClosedGarbageCollection = type(GetTime) == "function" and GetTime() or lastClosedGarbageCollection
        if type(collectgarbage) == "function" then
            collectgarbage("collect")
        end
    end

    if C_Timer and type(C_Timer.After) == "function" then
        C_Timer.After(0.25, collectClosedRuntimeGarbage)
    else
        collectClosedRuntimeGarbage()
    end
end

function UI:Refresh()
    if not self.frame or not self.frame:IsShown() then
        return
    end

    self:ApplyDisplaySettings()
    self:RefreshSidebar()
    self:RefreshMainTabs()
    self:RefreshSubTabs()
    self:RefreshContent()
    if self.featuresPanelOpen == true then
        self:RefreshFeaturesPanel()
    end
    if self.RefreshCustomTaskTracker then
        self:RefreshCustomTaskTracker()
    end
end

function UI:Initialize()
    if self.frame then
        return
    end

    self:CreateFrame()
    self:EnsureMinimapButton()
    if self.RefreshCustomTaskTracker then
        self:RefreshCustomTaskTracker()
    end
end

function UI:Toggle()
    if not self.frame then
        self:Initialize()
    end

    if self.frame:IsShown() then
        self.frame:Hide()
    else
        if ns and ns.RefreshCurrentCharacterLiveData then
            ns:RefreshCurrentCharacterLiveData()
        end
        self.frame:Show()
        self.frame:Raise()
        self:Refresh()
    end
end
