-- =============================================================================
-- ETB v12.62.0 — UI/MainFrame/Lifecycle.lua
-- =============================================================================
-- Final MainFrame submodule. Owns the lifecycle methods that orchestrate the
-- main window's appearance: Show/Hide/Toggle/IsShown plus the periodic
-- updateTicker that loads item names asynchronously and refreshes the
-- memory-usage display.
--
-- This is the smallest remaining cluster (5 methods, ~85 lines) but it's
-- the user-facing entry point: every time the player opens the addon, the
-- code path goes through Lifecycle:Show().
--
-- Public API (all take owner = MainFrame singleton as first arg):
--   Lifecycle:Show(owner)
--   Lifecycle:Hide(owner)
--   Lifecycle:Toggle(owner)
--   Lifecycle:IsShown(owner)
--   Lifecycle:UpdateMemoryDisplay(owner)
--
-- Owner contract — fields read/written:
--   owner.frame                       (created on first Show via Create)
--   owner.items                       (current page's items)
--   owner.updateTicker                (C_Timer ticker handle)
--   owner.memoryUpdateCounter         (sub-counter for less-frequent mem updates)
--
-- Owner methods called (all delegate or live in main file):
--   owner:Create()                              (UI construction; still in main file)
--   owner:UpdateCategoryTabs()                  (Filters cluster)
--   owner:UpdateCollectionButtons()             (Filters cluster)
--   owner:UpdateSlotHighlight(catID)            (LivePreview cluster)
--   owner:UpdateWeaponTypeFilter()              (Filters cluster)
--   owner:UpdateCurrentViewingLabel(name)       (LivePreview cluster)
--   owner:RefreshItems()                        (ItemGrid cluster)
--   owner:UpdatePendingItemsForCurrentPage()    (ItemGrid cluster)
--   owner:UpdateDisplay()                       (ItemGrid cluster)
--
-- Globals/Blizzard:
--   C_Timer.NewTicker
--   ETB.BlizzardData (Initialize, itemCache:Get)
--   ETB.Sets (Initialize)
--   ETB.Filtering, ETB.CATEGORY_INFO, ETB.ModelPreview
--   ETB:GetMemoryUsage, ETB:FormatMemory
-- =============================================================================

local ADDON_NAME, NS = ...
local ETB = NS.ETB

NS.ETB.MainFrame = NS.ETB.MainFrame or ETB.MainFrame or {}
local Lifecycle = {}
NS.ETB.MainFrame.Lifecycle = Lifecycle

function Lifecycle:Show(owner)
    if not owner.frame then owner:Create() end

    if not ETB.BlizzardData.initialized then
        ETB.BlizzardData:Initialize()
    end

    -- Ensure Sets are initialized
    if ETB.Sets and not ETB.Sets.INITIALIZED then
        ETB.Sets:Initialize()
    end

    owner:UpdateCategoryTabs()
    owner:UpdateCollectionButtons()
    owner:UpdateSlotHighlight(ETB.Filtering.filters.category)
    owner:UpdateWeaponTypeFilter()  -- Show/hide weapon type filter based on category

    -- Initial slot label
    local catInfo = ETB.CATEGORY_INFO[ETB.Filtering.filters.category]
    owner:UpdateCurrentViewingLabel(catInfo and catInfo.name or "Head")

    owner.frame:Show()
    owner:RefreshItems()

    -- Periodic update for item info loading AND memory display
    -- Reduced frequency and limited processing per tick to improve performance
    if not owner.updateTicker then
        owner.updateTicker = C_Timer.NewTicker(0.5, function()  -- More frequent for faster name loading
            if owner.frame and owner.frame:IsShown() then
                -- Only update items for current page to reduce work
                local updated = owner:UpdatePendingItemsForCurrentPage()

                if updated then
                    -- Refresh item references from cache
                    if ETB.BlizzardData and ETB.BlizzardData.itemCache then
                        for i, item in ipairs(owner.items) do
                            if item and item.itemID then
                                local cached = ETB.BlizzardData.itemCache:Get(item.itemID)
                                if cached then
                                    owner.items[i] = cached
                                end
                            end
                        end
                    end
                    -- Update all rows to show new names
                    owner:UpdateDisplay()
                end

                -- Update memory display (less frequently)
                if not owner.memoryUpdateCounter then owner.memoryUpdateCounter = 0 end
                owner.memoryUpdateCounter = owner.memoryUpdateCounter + 1
                if owner.memoryUpdateCounter >= 6 then  -- Update memory every 3 seconds (6 * 0.5s)
                    owner:UpdateMemoryDisplay()
                    owner.memoryUpdateCounter = 0
                end
            end
        end)
    end
end

function Lifecycle:UpdateMemoryDisplay(owner)
    if not owner.frame or not owner.frame.memoryText then return end
    local mem = ETB:GetMemoryUsage()
    local formatted = ETB:FormatMemory(mem)
    local color = mem > 50000 and "|cffff6666" or mem > 20000 and "|cffffff00" or "|cff00ff00"
    owner.frame.memoryText:SetText(color .. "Mem: " .. formatted .. "|r")
end

function Lifecycle:Hide(owner)
    if owner.frame then owner.frame:Hide() end
    if owner.updateTicker then
        owner.updateTicker:Cancel()
        owner.updateTicker = nil
    end
    -- Also hide the hover preview popup
    if ETB.ModelPreview then
        ETB.ModelPreview:Hide()
    end
end

function Lifecycle:Toggle(owner)
    if owner.frame and owner.frame:IsShown() then owner:Hide() else owner:Show() end
end

function Lifecycle:IsShown(owner)
    return owner.frame and owner.frame:IsShown()
end
