-- TOG Tools — Graphs sub-tab (UI)
-- First sub-tab in the Logs strip. A single "Log" picker chooses which log to
-- chart; the reusable addon.LogGraph component (LibGraph-2.0) renders the
-- selected log's series into a raw host frame parented to the body. Switching
-- logs triggers a MainWindow:Refresh() (re-Draw); period / series / expansion
-- changes are handled inside LogGraph without a rebuild.

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

local LogGraphs = addon.logCategories["graphs"]

local function lastLog()
    local lg = addon.DB and addon.DB.global and addon.DB.global.logGraphs
    return lg and lg.lastLog
end
local function setLastLog(key)
    local lg = addon.DB and addon.DB.global and addon.DB.global.logGraphs
    if lg then lg.lastLog = key end
end

function LogGraphs:Draw(container)
    container:SetLayout("Fill")

    local logs = self:GetGraphableLogs()
    if #logs == 0 then
        local note = AceGUI:Create("Label")
        note:SetFullWidth(true)
        note:SetText("|cffffaa55No graphable logs are enabled.|r\n\nEnable Gathering, Mail, or Trade via |cffffd700ESC > Options > AddOns > TOG Tools > Modules|r, then gather some data.")
        container:AddChild(note)
        return
    end

    -- Resolve the selected log: stored last → first available.
    local selected = lastLog()
    local valid = false
    for _, l in ipairs(logs) do if l.key == selected then valid = true break end end
    if not valid then selected = logs[1].key; setLastLog(selected) end

    local spec, options = nil, {}
    for _, l in ipairs(logs) do
        tinsert(options, { value = l.key, text = l.label })
        if l.key == selected then spec = l.spec end
    end

    -- Single full-area host; LogGraph renders the Log / Period / Expansion
    -- pickers in one row at its top, so the sub-tab needs no filter row.
    local body = AceGUI:Create("SimpleGroup")
    body:SetFullWidth(true)
    body:SetFullHeight(true)
    body:SetLayout("Fill")
    container:AddChild(body)

    local handle = addon.LogGraph:Render(body.content, spec, self:GetPrefs(selected), {
        options = options,
        current = selected,
        onSelect = function(key)
            setLastLog(key)
            if addon.MainWindow and addon.MainWindow.Refresh then
                addon.MainWindow:Refresh()
            end
        end,
    })
    body:SetCallback("OnRelease", function()
        if handle and handle.Detach then handle.Detach() end
    end)
end
