--[[
============================================================================
ETB v11.0 - MainFrame.lua (V8 INTEGRATED - COMPREHENSIVE FIX)
============================================================================
Fixes:
1. Pagination triggers item name refresh
2. Hover preview (ModelPreview popup) properly shows on hover
3. Live Preview with slot buttons + remove/hide icons
4. Accurate per-slot collection stats
5. Clear indication of current slot/weapon type being viewed

Preview Separation:
- HOVER PREVIEW: ETB.ModelPreview floating popup (single item, resets)
- LIVE PREVIEW: Right panel for building outfits (stacks items)
============================================================================
]]--

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

-- v12.58.0: preserve existing ETB.MainFrame table.
-- Future submodules (UI/MainFrame/Views.lua, etc.) will load BEFORE this file
-- and register .Views / .ItemGrid / etc. on NS.ETB.MainFrame.
-- A bare `ETB.MainFrame = { ... }` table-literal clobbers those registrations
-- (this is the v12.45.1 / v12.56.1 namespace-clobber bug class).
-- Applying the preservation pattern preemptively avoids the bug entirely.
ETB.MainFrame = ETB.MainFrame or {}
local MF = ETB.MainFrame

MF.frame = MF.frame or nil
MF.items = MF.items or {}
MF.totalItemCount = MF.totalItemCount or 0  -- Total count without loading all items
MF.itemRows = MF.itemRows or {}
MF.currentPage = MF.currentPage or 1
MF.itemsPerPage = MF.itemsPerPage or 19  -- 19 rows x 1 column
MF.categoryMode = MF.categoryMode or "armor"
MF.previewRotation = MF.previewRotation or 0
MF.livePreviewSlots = MF.livePreviewSlots or {}  -- Track what's in each slot
MF.lastPageLoaded = MF.lastPageLoaded or 0  -- Track which page we last loaded

-- =============================================================================
-- CONSTANTS - Carefully measured for proper layout
-- =============================================================================

local FRAME_WIDTH = 1350
local FRAME_HEIGHT = 850
local SIDEBAR_WIDTH = 210
local PREVIEW_WIDTH = 340
local ITEM_ROW_WIDTH = 750
local ITEM_ROW_HEIGHT = 32
local ROWS_PER_COLUMN = 19
local COLUMNS = 1

-- Layout measurements
local FRAME_MARGIN = 15
local TITLE_AREA_HEIGHT = 45
local TOPBAR_HEIGHT = 95
local BOTTOMBAR_HEIGHT = 50

-- Calculated positions
local TOPBAR_Y = -(TITLE_AREA_HEIGHT)
local CONTENT_Y = -(TITLE_AREA_HEIGHT + TOPBAR_HEIGHT + 8)
local BOTTOM_MARGIN = FRAME_MARGIN + BOTTOMBAR_HEIGHT + 8

-- v12.58.0: expose layout constants on MF so submodules can read them.
-- Submodules that construct sub-panels need these to position relative to
-- the sidebar/grid the same way the main file does.
MF.FRAME_MARGIN = FRAME_MARGIN
MF.BOTTOM_MARGIN = BOTTOM_MARGIN

-- NOTE: Armor slots and weapon categories are now selected via dropdowns in the sidebar
-- The actual category definitions are in ETB.CATEGORY_INFO (Core/Init.lua)

-- Live Preview slot layout (left and right of model)
local PREVIEW_SLOTS_LEFT = { "Head", "Shoulder", "Back", "Chest", "Shirt", "Tabard", "Wrist" }
local PREVIEW_SLOTS_RIGHT = { "Hands", "Waist", "Legs", "Feet", "MainHand", "OffHand" }

-- =============================================================================
-- CREATE MAIN FRAME
-- =============================================================================

function MF:Create()
    return NS.ETB.MainFrame.Construction:Create(self)
end


function MF:CreateTopBar(f)
    return NS.ETB.MainFrame.Construction:CreateTopBar(self, f)
end


function MF:UpdateSlotHighlight(selectedID)
    return NS.ETB.MainFrame.LivePreview:UpdateSlotHighlight(self, selectedID)
end


function MF:UpdateWeaponTypeHighlight(selectedType)
    return NS.ETB.MainFrame.LivePreview:UpdateWeaponTypeHighlight(self, selectedType)
end


function MF:UpdateCurrentViewingLabel(slotName)
    return NS.ETB.MainFrame.LivePreview:UpdateCurrentViewingLabel(self, slotName)
end


function MF:CreateLeftSidebar(f)
    return NS.ETB.MainFrame.Construction:CreateLeftSidebar(self, f)
end


function MF:CreateTab(parent, text, x, y)
    return NS.ETB.MainFrame.Construction:CreateTab(self, parent, text, x, y)
end


function MF:UpdateCategoryTabs()
    return NS.ETB.MainFrame.Filters:UpdateCategoryTabs(self)
end


function MF:UpdateCollectionButtons(filter)
    return NS.ETB.MainFrame.Filters:UpdateCollectionButtons(self, filter)
end


function MF:UpdateWeaponTypeFilter()
    return NS.ETB.MainFrame.Filters:UpdateWeaponTypeFilter(self)
end


function MF:UpdateWeaponCategoryUI()
    return NS.ETB.MainFrame.Filters:UpdateWeaponCategoryUI(self)
end


function MF:CreateItemGrid(f)
    return NS.ETB.MainFrame.Construction:CreateItemGrid(self, f)
end


function MF:CreateLivePreview(f)
    return NS.ETB.MainFrame.Construction:CreateLivePreview(self, f)
end


function MF:CreateSlotButton(parent, slotName, index)
    return NS.ETB.MainFrame.LivePreview:CreateSlotButton(self, parent, slotName, index)
end


function MF:UpdateSlotButtons()
    return NS.ETB.MainFrame.LivePreview:UpdateSlotButtons(self)
end


function MF:RebuildLivePreview()
    return NS.ETB.MainFrame.LivePreview:RebuildLivePreview(self)
end


function MF:CreateBottomBar(f)
    return NS.ETB.MainFrame.Construction:CreateBottomBar(self, f)
end


function MF:AddToLivePreview(item)
    return NS.ETB.MainFrame.LivePreview:AddToLivePreview(self, item)
end


function MF:GetSlotNameForItem(item)
    return NS.ETB.MainFrame.LivePreview:GetSlotNameForItem(self, item)
end


function MF:ShowSetsView()
    return NS.ETB.MainFrame.Views:ShowSetsView(self)
end


function MF:ShowSetBuilderView()
    return NS.ETB.MainFrame.Views:ShowSetBuilderView(self)
end


function MF:HideSetBuilderView()
    return NS.ETB.MainFrame.Views:HideSetBuilderView(self)
end


function MF:ShowSetBuilderEmbedded()
    return NS.ETB.MainFrame.Views:ShowSetBuilderEmbedded(self)
end


function MF:HideSetBuilderEmbedded()
    return NS.ETB.MainFrame.Views:HideSetBuilderEmbedded(self)
end


function MF:IsSetBuilderEmbeddedShown()
    return NS.ETB.MainFrame.Views:IsSetBuilderEmbeddedShown(self)
end


function MF:HideSetsView()
    return NS.ETB.MainFrame.Views:HideSetsView(self)
end


function MF:RefreshItems(force)
    if force then
        return NS.ETB.MainFrame.ItemGrid:RefreshItems(self)
    end

    self._refreshRequestSerial = (self._refreshRequestSerial or 0) + 1
    local serial = self._refreshRequestSerial
    local function run()
        if serial ~= self._refreshRequestSerial then return end
        return NS.ETB.MainFrame.ItemGrid:RefreshItems(self)
    end

    if ETB.QueueWork then
        ETB:QueueWork("mainFrame.refreshItems", function()
            run()
            return true
        end, { pauseInCombat = false, pauseForStartup = false })
    elseif C_Timer and C_Timer.After then
        C_Timer.After(0.05, run)
    else
        return run()
    end
end


function MF:LoadPageData(pageNum)
    return NS.ETB.MainFrame.ItemGrid:LoadPageData(self, pageNum)
end


function MF:PreloadFirstPageItemInfo()
    return NS.ETB.MainFrame.ItemGrid:PreloadFirstPageItemInfo(self)
end


function MF:RequestItemInfoAsync()
    return NS.ETB.MainFrame.ItemGrid:RequestItemInfoAsync(self)
end


function MF:ClearAllItemRows()
    return NS.ETB.MainFrame.ItemGrid:ClearAllItemRows(self)
end


function MF:UpdateDisplayWithRefresh()
    return NS.ETB.MainFrame.ItemGrid:UpdateDisplayWithRefresh(self)
end


function MF:UpdateDisplay()
    return NS.ETB.MainFrame.ItemGrid:UpdateDisplay(self)
end


function MF:UpdatePendingItemsForCurrentPage()
    return NS.ETB.MainFrame.ItemGrid:UpdatePendingItemsForCurrentPage(self)
end


function MF:UpdateChangedRows()
    return NS.ETB.MainFrame.ItemGrid:UpdateChangedRows(self)
end


function MF:UpdateStats()
    return NS.ETB.MainFrame.ItemGrid:UpdateStats(self)
end


function MF:Show()
    return NS.ETB.MainFrame.Lifecycle:Show(self)
end


function MF:UpdateMemoryDisplay()
    return NS.ETB.MainFrame.Lifecycle:UpdateMemoryDisplay(self)
end


function MF:Hide()
    return NS.ETB.MainFrame.Lifecycle:Hide(self)
end


function MF:Toggle()
    return NS.ETB.MainFrame.Lifecycle:Toggle(self)
end


function MF:IsShown()
    return NS.ETB.MainFrame.Lifecycle:IsShown(self)
end


function MF:GenerateRandomOutfit()
    return NS.ETB.MainFrame.LivePreview:GenerateRandomOutfit(self)
end

-- Handle profile changes
-- v15.8.1: EventBus:Fire passes the event name as the first callback arg
-- (see EventBus.lua line 116). Correct signature is (event, key, profile).
ETB.EventBus:Register("ETB_PROFILE_CHANGED", function(event, key, profile)
    if MF.frame and MF.frame:IsShown() then
        -- Debug: Show what profile we're switching to
        local classID = profile and profile.classID or "nil"
        local primaryArmor = ETB.BlizzardData and ETB.BlizzardData:GetPlayerPrimaryArmor() or "unknown"
        ETB:Debug("MainFrame", "Profile Switch: Class " .. tostring(classID) .. " → Primary Armor: " .. tostring(primaryArmor))
        
        -- Clear caches so items are re-filtered for new class
        if ETB.BlizzardData then
            ETB.BlizzardData:ClearCache()
        end
        MF._filterSignature = nil
        MF._filteredItems = nil
        MF._overallStats = nil
        MF._overallStatsPending = nil
        -- Refresh items with new class filtering
        MF:RefreshItems()
        -- Update the viewing label using CATEGORY_INFO
        local categoryID = ETB.Filtering.filters.category
        local catInfo = ETB.CATEGORY_INFO and ETB.CATEGORY_INFO[categoryID]
        local slotName = catInfo and catInfo.name or "Head"
        MF:UpdateCurrentViewingLabel(slotName)
        -- Update profile selector display
        if ETB.ProfileSelector then
            ETB.ProfileSelector:Update()
        end
    end
end)

ETB:Debug("MainFrame", "MainFrame.lua loaded (V8 UI - Comprehensive Fix)")
