-- 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.configKey   = "addonLoad"
Tab.label       = "Addon Load"
Tab.WINDOW_SIZE = { width = 700, height = 520, minWidth = 520, minHeight = 380 }
Tab.help = {
    title = "Addon Load Monitor",
    lines = {
        "One row per installed addon: name, memory used, load time, and status. Helpful for spotting heavy or slow addons, missing dependencies, or addons that failed to load.",
        "|cffffd700Click any column header|r to sort; click again to reverse. Status sorts failures first so problems land at the top.",
        "Status badges: |cffffd700Loaded|r, |cffffd700On Demand|r, |cffffd700Disabled|r, |cffffd700Missing|r, |cffffd700Dep Missing|r, |cffffd700Wrong Version|r, |cffffd700Corrupt TOC|r, |cffffd700Outdated|r.",
        "Summary bar shows total / loaded / failed / disabled, total memory used, and overall loading-screen duration.",
        "Accurate sub-millisecond load times for every addon when the |cffffd700!TOGT|r companion is installed (a tiny no-UI helper that loads first and records the timing).",
    },
}

-- ---------------------------------------------------------------------------
-- 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. This is the stretchy column — the only column that may truncate when the window is narrow; every other column auto-sizes to fit its content.",
              sortKey = "name" },

            { key = "mem",    header = "Memory",     autoFit = true, minWidth = 45, justify = "RIGHT",
              headerTip = "Memory",
              headerTipDesc = "Lua memory used by this addon. Sorted heaviest-first by default. Column auto-sizes to fit the largest listed memory value.",
              sortDescDefault = true,
              format = function(e) return fmtMem(e.mem) end },

            { key = "loadTime", header = "Load Time", autoFit = true, minWidth = 45, justify = "RIGHT",
              headerTip = "Load Time",
              headerTipDesc = "Time this addon spent loading (delta from when the previous addon finished). Requires !TOGT companion for full coverage. Column auto-sizes to fit the largest listed load time.",
              sortDescDefault = true,
              format = function(e) return fmtTime(e.loadTime) end },

            { key = "status", header = "Status",     autoFit = true, minWidth = 55, justify = "LEFT",
              gapBefore = 5,
              headerTip = "Status",
              headerTipDesc = "Load result: Loaded, Disabled, On Demand, or failure reason. Column auto-sizes to the widest listed status string.",
              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
