-- TOG Tools — Addon Load tab (UI)
-- Sortable table of all installed addons: memory, status, timing.
-- Column layout, sort, virtual scroll, and resize-driven elastic compaction
-- all come from addon.RowList — see GUI/RowList.lua. The original AceGUI
-- Flow + SetWidth approach wrapped to a new line when the user shrunk the
-- window; RowList rows anchor LEFT/RIGHT to the parent so the auto-width
-- column shrinks elastically and cells truncate instead of wrapping.

local _, addon = ...
local AceGUI = LibStub("AceGUI-3.0")

local BRAND = addon.BrandColor or "ffFF8000"

local Tab = addon.modules["addonload"]
Tab.tabKey      = "addonload"
Tab.label       = "Addon Load"
Tab.WINDOW_SIZE = { width = 700, height = 520, minWidth = 520, minHeight = 380 }

-- ---------------------------------------------------------------------------
-- Cell formatters
-- ---------------------------------------------------------------------------
local function fmtMem(kb)
    if not kb or kb <= 0 then return "—" end
    if kb >= 1024 then return string.format("%.1f MB", kb / 1024) end
    return string.format("%d KB", math.floor(kb + 0.5))
end

local function fmtTime(t)
    if not t then return "—" end
    if t < 0.0005 then return "0.000s" end
    return string.format("%.3fs", t)
end

local function setStatusText(summary)
    local f = addon.MainWindow and addon.MainWindow.frame
    if not f then return end
    local companion = summary.hasCompanion and "|cff44ee44!TOGT active|r" or "|cffff8800!TOGT missing|r"
    f:SetStatusText("v" .. addon.Version .. "  |  " .. companion)
end

-- ---------------------------------------------------------------------------
-- Draw
-- ---------------------------------------------------------------------------
function Tab:Draw(container)
    container:SetLayout("Flow")

    Tab:RefreshMemory()
    local rows, summary = Tab:GetData()
    setStatusText(summary)

    -- ---- Summary bar ----------------------------------------------------
    local loginStr = summary.loginTime
        and string.format("  |cffaaaaaa(login window: %.2fs)|r", summary.loginTime) or ""
    local sumLabel = AceGUI:Create("Label")
    sumLabel:SetFullWidth(true)
    sumLabel:SetText(string.format(
        "|c%s%d addons|r  |cff44ee44%d loaded|r  |cffff5555%d failed|r  |cff888888%d disabled/on-demand|r    Memory: |c%s%s total|r%s",
        BRAND, summary.total, summary.loaded, summary.failed, summary.disabled,
        BRAND, fmtMem(summary.totalMem), loginStr
    ))
    container:AddChild(sumLabel)

    -- ---- Body host -------------------------------------------------------
    -- A SimpleGroup with no layout gives us a raw .content frame at full
    -- width and remaining height. RowList builds its header bar, row pool,
    -- and scrollbar directly into that frame; AceGUI handles the resize
    -- propagation when the main window changes size.
    local body = AceGUI:Create("SimpleGroup")
    body:SetFullWidth(true)
    body:SetFullHeight(true)
    body:SetLayout("List")
    container:AddChild(body)

    local rl = addon.RowList:New(body.content, {
        rowHeight = 16,
        columns = {
            { key = "title",  header = "Addon Name", justify = "LEFT",
              headerTip = "Addon Name",
              headerTipDesc = "Sort alphabetically by addon title.",
              sortKey = "name" },

            { key = "mem",    header = "Memory",     width = 65, justify = "RIGHT",
              headerTip = "Memory",
              headerTipDesc = "Lua memory used by this addon. Sorted heaviest-first by default.",
              sortDescDefault = true,
              format = function(e) return fmtMem(e.mem) end },

            { key = "loadTime", header = "Load Time", width = 60, justify = "RIGHT",
              headerTip = "Load Time",
              headerTipDesc = "Time this addon spent loading (delta from when the previous addon finished). Requires !TOGT companion for full coverage.",
              sortDescDefault = true,
              format = function(e) return fmtTime(e.loadTime) end },

            { key = "status", header = "Status",     width = 85, justify = "LEFT",
              gapBefore = 5,
              headerTip = "Status",
              headerTipDesc = "Load result: Loaded, Disabled, On Demand, or failure reason.",
              sortKey = "statusPrio",
              format = function(e) return "|c" .. e.statusColor .. e.status .. "|r" end },
        },
    })

    rl:SetSort("mem", true)
    rl:SetData(rows)

    -- Detach raw frames when AceGUI recycles the host widget — otherwise
    -- the row pool would bleed into whichever UI inherits the SimpleGroup
    -- next from the global widget pool.
    body:SetCallback("OnRelease", function() rl:Detach() end)
end
