-- TOG Tools — LogGraph (reusable LibGraph-2.0 line-chart component)
--
-- Generalised from FastGuildInvite's Statistics tab. Any log can be graphed
-- by handing Render() a "graph spec": a set of named series (each with a
-- colour, a match predicate, and a value function), an entry provider, and
-- an optional sub-filter (e.g. the Gathering chart scopes its per-item
-- series to one expansion). The component buckets the entries by time over
-- the selected period and draws one LibGraph line per visible series, with
-- per-series checkboxes, a period dropdown, an optional sub-filter dropdown,
-- and a totals line.
--
-- Spec contract:
--   spec.key        string   stable key (used for prefs + the graph frame)
--   spec.getEntries function() -> { {ts=<epoch>, ...}, ... }
--   spec.getSeries  function(subValue) -> {
--                       { key, label, color={r,g,b,a}|nil, match(entry)->bool,
--                         value(entry)->number|nil }, ... }
--                   color may be nil to auto-assign from the palette; value
--                   defaults to 1 (counting).
--   spec.subFilter  table|nil {
--                       label      string,
--                       getOptions function() -> { {value=, text=}, ... },
--                       default    function() -> value,
--                   }
--   spec.unit       string   noun for the totals line ("items", "mails", ...)
--
-- Frame lifecycle: one persistent frame set, parked on UIParent when idle and
-- reparented onto the caller's host frame on Render. AceGUI pools the host
-- container frames, so creating fresh children each draw would orphan frames
-- onto recycled widgets — reusing a singleton set avoids that (the RowList
-- approach). Within a single log, period / series / sub-filter changes
-- repopulate the existing graph in place; only switching logs re-specs.

local _, addon = ...
local Graph = LibStub("LibGraph-2.0")

local LogGraph = {}
addon.LogGraph = LogGraph

-- {label, daysBack, points, xAxisLabel}. daysBack 0 = "All time": the window
-- spans from the earliest entry to now, split into `points` buckets.
local PERIODS = {
    { label = "Last 24 hours", days = 1,  points = 24, xlabel = "Hours" },
    { label = "Last 7 days",   days = 7,  points = 7,  xlabel = "Days"  },
    { label = "Last 14 days",  days = 14, points = 14, xlabel = "Days"  },
    { label = "Last 30 days",  days = 30, points = 30, xlabel = "Days"  },
    { label = "All time",      days = 0,  points = 30, xlabel = ""      },
}

-- Distinct colours for auto-assigned (dynamic) series. Series past #PALETTE
-- cycle — but MAX_SERIES caps the count first so the chart stays readable.
local PALETTE = {
    {0.00, 0.80, 1.00, 0.9}, {0.30, 1.00, 0.30, 0.9}, {1.00, 0.85, 0.00, 0.9},
    {1.00, 0.35, 0.35, 0.9}, {0.80, 0.40, 1.00, 0.9}, {1.00, 0.60, 0.20, 0.9},
    {0.40, 0.80, 1.00, 0.9}, {0.60, 1.00, 0.60, 0.9}, {1.00, 0.50, 0.80, 0.9},
    {0.70, 0.70, 0.70, 0.9}, {0.50, 1.00, 0.85, 0.9}, {1.00, 1.00, 0.55, 0.9},
}
local MAX_SERIES = 12

local TOP_ROW_H   = 30   -- height of one control-dropdown row (log / period / filters)
local FILTER_DD_W = 140  -- width budget per filter dropdown (for wrap math)
local BOTTOM_H    = 56   -- x-axis label + (wrapping) totals line, below the graph

-- ---------------------------------------------------------------------------
-- Singleton UI + live state
-- ---------------------------------------------------------------------------
local _ui     -- frame set, created lazily
local _state = { spec = nil, prefs = nil }

local function hexColor(c)
    return string.format("ff%02x%02x%02x",
        math.floor((c[1] or 1) * 255),
        math.floor((c[2] or 1) * 255),
        math.floor((c[3] or 1) * 255))
end

-- Native Blizzard dropdown (same widget the chat combo boxes use). items is a
-- {value,text} list; onSelect(value) fires on pick.
local function makeDropdown(name, parent, width)
    local dd = CreateFrame("Frame", name, parent, "UIDropDownMenuTemplate")
    UIDropDownMenu_SetWidth(dd, width)
    return dd
end

local function setDropdown(dd, items, current, onSelect)
    local function init()
        for _, it in ipairs(items) do
            local info = UIDropDownMenu_CreateInfo()
            info.text         = it.text
            info.value        = it.value
            info.notCheckable = true
            info.func         = function()
                UIDropDownMenu_SetSelectedValue(dd, it.value)
                UIDropDownMenu_SetText(dd, it.text)
                onSelect(it.value)
            end
            UIDropDownMenu_AddButton(info)
        end
    end
    UIDropDownMenu_Initialize(dd, init)
    -- Resolve the label for the current value (falling back to the first item).
    local label = items[1] and items[1].text or ""
    for _, it in ipairs(items) do
        if it.value == current then label = it.text break end
    end
    UIDropDownMenu_SetSelectedValue(dd, current)
    UIDropDownMenu_SetText(dd, label)
end

local function ensureUI()
    if _ui then return _ui end
    local root = CreateFrame("Frame", "TOGToolsLogGraphRoot", UIParent)
    root:Hide()

    -- Single control row: Log picker, Period, Sub-filter — left to right. The
    -- ~12px of built-in padding on UIDropDownMenu frames is taken up with the
    -- negative offsets so the three sit snug rather than gapped.
    local logDD = makeDropdown("TOGToolsLogGraphLogDD", root, 120)
    logDD:SetPoint("TOPLEFT", root, "TOPLEFT", -12, 4)

    local periodDD = makeDropdown("TOGToolsLogGraphPeriodDD", root, 110)
    periodDD:SetPoint("LEFT", logDD, "RIGHT", -10, 0)

    -- Graph holder; precise anchors are set per-refresh once the series count
    -- (and thus the checkbox-row height) is known.
    local graphHolder = CreateFrame("Frame", nil, root)

    local graph = Graph:CreateGraphLine("TOGToolsLogGraphLine", graphHolder,
        "TOPLEFT", "TOPLEFT", 0, 0, 100, 100)
    graph:SetGridColor({0.5, 0.5, 0.5, 0.3})
    graph:SetAxisDrawing(true, true)
    graph:SetAxisColor({1, 1, 1, 1})
    graph:SetAutoScale(false)
    graph:LockYMin(0)

    -- Time axis: we render our own anchors (oldest at left .. "now" at right)
    -- below the plot instead of LibGraph's bare 1..N numbers — those read
    -- backwards on a past->now axis and collided with the label. Disabled in
    -- refresh via XLabelsEnabled=false.
    local xLeft = root:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    xLeft:SetPoint("TOPLEFT", graphHolder, "BOTTOMLEFT", 4, -3)
    xLeft:SetJustifyH("LEFT")
    local xMid = root:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    xMid:SetPoint("TOP", graphHolder, "BOTTOM", 0, -3)
    xMid:SetJustifyH("CENTER")
    local xRight = root:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    xRight:SetPoint("TOPRIGHT", graphHolder, "BOTTOMRIGHT", -4, -3)
    xRight:SetJustifyH("RIGHT")

    local totals = root:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    totals:SetPoint("TOPLEFT", xLeft, "BOTTOMLEFT", 0, -4)
    totals:SetPoint("RIGHT", root, "RIGHT", -4, 0)
    totals:SetJustifyH("LEFT")

    local empty = root:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    empty:SetPoint("CENTER", graphHolder, "CENTER", 0, 0)
    empty:SetText("")

    -- Transparent mouse layer over the plot. LibGraph has no per-point hover
    -- (the lines are just textures), so we map the cursor's X to a time bucket
    -- ourselves and show a GameTooltip. Scripts are attached in Render (where
    -- the data helpers are in scope); above the graph's frame level so it
    -- receives mouse without the graph needing EnableMouse.
    local hover = CreateFrame("Frame", nil, graphHolder)
    hover:SetAllPoints(graphHolder)
    hover:EnableMouse(true)
    hover:SetFrameLevel(graph:GetFrameLevel() + 5)

    _ui = {
        root = root, logDD = logDD, periodDD = periodDD,
        graphHolder = graphHolder, graph = graph, hover = hover,
        xLeft = xLeft, xMid = xMid, xRight = xRight, totals = totals, empty = empty,
        filterDDs = {},
    }

    graphHolder:HookScript("OnSizeChanged", function(_, w, h)
        if w > 1 and h > 1 then _ui.graph:SetSize(w, h) end
    end)

    return _ui
end

-- Reuse-or-create the i-th filter dropdown (the count varies per log).
local function getFilterDD(i)
    local ui = _ui
    local dd = ui.filterDDs[i]
    if dd then return dd end
    dd = makeDropdown("TOGToolsLogGraphFilterDD" .. i, ui.root, FILTER_DD_W - 20)
    ui.filterDDs[i] = dd
    return dd
end

-- ---------------------------------------------------------------------------
-- Bucketing
-- ---------------------------------------------------------------------------
-- For each visible series, sum value(entry) into `points` time buckets across
-- the period window. Returns { perSeries = { [i] = {bucketsTable, total} }, maxY }.
local function bucketize(entries, series, period)
    local now = (GetServerTime and GetServerTime()) or time()
    local points = period.points
    local startTs, bucketSec

    if period.days > 0 then
        startTs   = now - period.days * 86400
        bucketSec = (period.days * 86400) / points
    else
        -- All time: span from the earliest entry to now.
        local minTs = now
        for _, e in ipairs(entries) do
            if e.ts and e.ts < minTs then minTs = e.ts end
        end
        startTs   = minTs
        bucketSec = math.max((now - startTs) / points, 1)
    end

    local perSeries = {}
    for i = 1, #series do perSeries[i] = { buckets = {}, total = 0 } end
    for i = 1, #series do
        for b = 1, points do perSeries[i].buckets[b] = 0 end
    end

    for _, e in ipairs(entries) do
        local ts = e.ts
        if ts and ts >= startTs and ts <= now then
            local b = math.floor((ts - startTs) / bucketSec) + 1
            if b < 1 then b = 1 elseif b > points then b = points end
            for i = 1, #series do
                local s = series[i]
                if s.match(e) then
                    local v = s.value and s.value(e) or 1
                    perSeries[i].buckets[b] = perSeries[i].buckets[b] + v
                    perSeries[i].total = perSeries[i].total + v
                end
            end
        end
    end

    local maxY = 0
    for i = 1, #series do
        for b = 1, points do
            if perSeries[i].buckets[b] > maxY then maxY = perSeries[i].buckets[b] end
        end
    end
    return perSeries, maxY, points, startTs, bucketSec
end

-- ---------------------------------------------------------------------------
-- Refresh (repopulate the existing graph from current spec + prefs)
-- ---------------------------------------------------------------------------
-- Time-axis anchor text for a point `ts` relative to `now`: "Nh ago" / "now"
-- on the 24h view, a date on the day / all-time views.
local function axisText(period, ts, now)
    if period.days == 1 then
        local h = math.floor((now - ts) / 3600 + 0.5)
        return h <= 0 and "now" or (h .. "h ago")
    elseif period.days == 0 then
        return date("%m/%d/%y", ts)
    end
    return date("%m/%d", ts)
end

-- Forward declaration so rebuildFilterDropdowns() (below) can reference the
-- refresh closure and vice-versa.
local refresh

-- Build/refresh the per-log filter dropdowns with CASCADING options: each
-- dropdown's choices are drawn from the entries that pass the OTHER active
-- filters, so picking Mining trims the Item / Zone / Source lists to mining
-- gathers only (mirrors the RowList column-filter cascade). A current
-- selection that's no longer offered resets to "All".
local function rebuildFilterDropdowns()
    local ui = _ui
    local spec, prefs = _state.spec, _state.prefs
    if not (ui and spec and prefs and spec.filters) then return end
    prefs.filters = prefs.filters or {}
    local raw = spec.getEntries() or {}
    local nf = #spec.filters
    for i = 1, nf do
        local fdef = spec.filters[i]
        -- Scope = entries passing every OTHER active filter.
        local scoped = {}
        for _, e in ipairs(raw) do
            local keep = true
            for _, other in ipairs(spec.filters) do
                if other.key ~= fdef.key then
                    local ov = prefs.filters[other.key]
                    if ov ~= nil and ov ~= "__all" and not other.match(e, ov) then
                        keep = false; break
                    end
                end
            end
            if keep then scoped[#scoped + 1] = e end
        end
        local opts = fdef.getOptions(scoped) or {}
        local cur  = prefs.filters[fdef.key]
        local valid = false
        for _, o in ipairs(opts) do if o.value == cur then valid = true; break end end
        if not valid then cur = "__all"; prefs.filters[fdef.key] = "__all" end
        local dd = getFilterDD(i)
        setDropdown(dd, opts, cur, function(v)
            prefs.filters[fdef.key] = v
            refresh()
        end)
        dd:Show()
    end
    for i = nf + 1, #ui.filterDDs do ui.filterDDs[i]:Hide() end
end

function refresh()
    local ui = _ui
    local spec, prefs = _state.spec, _state.prefs
    if not (ui and spec and prefs) then return end

    -- Rebuild filter dropdowns first: cascades the option lists to the current
    -- selections and resets any now-invalid selection before we filter data.
    rebuildFilterDropdowns()

    local idx = prefs.period or 1
    if idx < 1 or idx > #PERIODS then idx = 1 end
    local period = PERIODS[idx]

    -- ---- Filter entries by the active per-log filter dropdowns -----------
    local rawEntries = spec.getEntries() or {}
    local entries = rawEntries
    if spec.filters and prefs.filters then
        entries = {}
        for _, e in ipairs(rawEntries) do
            local keep = true
            for _, fdef in ipairs(spec.filters) do
                local v = prefs.filters[fdef.key]
                if v ~= nil and v ~= "__all" and not fdef.match(e, v) then
                    keep = false; break
                end
            end
            if keep then entries[#entries + 1] = e end
        end
    end

    -- ---- Series from the filtered set (capped + auto-coloured) -----------
    local series = spec.getSeries(entries) or {}
    if #series > MAX_SERIES then
        for i = #series, MAX_SERIES + 1, -1 do series[i] = nil end
    end
    for i, s in ipairs(series) do
        if not s.color then s.color = PALETTE[((i - 1) % #PALETTE) + 1] end
    end

    -- ---- Position the filter dropdowns (row 2+, wrapping by width) -------
    local width  = math.max(ui.root:GetWidth(), 200)
    local perRow = math.max(1, math.floor(width / FILTER_DD_W))
    local nf     = #(spec.filters or {})
    for i = 1, nf do
        local dd = ui.filterDDs[i]
        if dd then
            local col = (i - 1) % perRow
            local row = math.floor((i - 1) / perRow)
            dd:ClearAllPoints()
            dd:SetPoint("TOPLEFT", ui.root, "TOPLEFT",
                -12 + col * FILTER_DD_W, -(TOP_ROW_H + row * TOP_ROW_H) + 4)
        end
    end
    local filterRows = math.ceil(nf / perRow)

    -- ---- Layout: graph fills below the control rows ---------------------
    local graphTop = TOP_ROW_H + filterRows * TOP_ROW_H + 6
    ui.graphHolder:ClearAllPoints()
    ui.graphHolder:SetPoint("TOPLEFT",     ui.root, "TOPLEFT",     0, -graphTop)
    ui.graphHolder:SetPoint("BOTTOMRIGHT", ui.root, "BOTTOMRIGHT", 0,  BOTTOM_H)

    -- ---- Data -----------------------------------------------------------
    local perSeries, maxY, points, startTs, bucketSec = bucketize(entries, series, period)

    -- Stash everything the hover overlay needs to map a cursor X to a bucket
    -- and render that bucket's per-series values. xMax matches SetXAxis below.
    _state.hover = {
        series = series, perSeries = perSeries, prefs = prefs,
        points = points, startTs = startTs, bucketSec = bucketSec, period = period,
        xMin = 0, xMax = math.max(2, points + 1),
    }
    _ui._hoverBucket = nil

    ui.graph:ResetData()
    local anyData = false
    for i, s in ipairs(series) do
        if perSeries[i].total > 0 then
            local data = {}
            for b = 1, points do data[b] = { b, perSeries[i].buckets[b] } end
            ui.graph:AddDataSeries(data, s.color, false)
            anyData = true
        end
    end

    ui.graph:SetXAxis(0, math.max(2, points + 1))
    ui.graph:SetYAxis(0, maxY + 1)
    ui.graph:SetGridSpacing(1, math.ceil(maxY / 10) + 1)
    ui.graph:SetYLabels(true, false)
    ui.graph.XLabelsEnabled = false   -- we render our own time anchors below

    ui.empty:SetText(anyData and "" or "|cff888888No data in this period.|r")
    local now = (GetServerTime and GetServerTime()) or time()
    ui.xLeft:SetText(axisText(period, startTs, now))
    ui.xMid:SetText(axisText(period, (startTs + now) / 2, now))
    ui.xRight:SetText(axisText(period, now, now))

    -- ---- Totals line (the legend — names each charted series + its total) -
    local parts = {}
    for i, s in ipairs(series) do
        if perSeries[i].total > 0 then
            tinsert(parts, string.format("|c%s%s|r: %d",
                hexColor(s.color), s.label or s.key, perSeries[i].total))
        end
    end
    ui.totals:SetText(table.concat(parts, "   "))
end

-- Human label for a hovered bucket: an hour range for the 24h period, a day
-- for the daily periods, the bucket's start date for "all time".
local function bucketLabel(h, b)
    local startTs = h.startTs + (b - 1) * h.bucketSec
    if h.period.days == 1 then
        return date("%m/%d %H:00", startTs) .. " – " .. date("%H:00", startTs + h.bucketSec)
    end
    return date("%a %m/%d/%y", startTs)
end

-- ---------------------------------------------------------------------------
-- Public: Render / Detach
-- ---------------------------------------------------------------------------
-- Reparent the singleton frame set onto `host`, bind it to `spec`+`prefs`, and
-- draw. Returns a handle with :Detach() to park the frames back on UIParent
-- (call from the host container's OnRelease).
-- `logPicker` (optional) = { options = {{value,text},...}, current = key,
-- onSelect = function(key) } — renders the leftmost dropdown in the control
-- row so the Log / Period / Expansion pickers share one line.
function LogGraph:Render(host, spec, prefs, logPicker)
    local ui = ensureUI()
    _state.spec  = spec
    _state.prefs = prefs

    ui.root:SetParent(host)
    ui.root:ClearAllPoints()
    ui.root:SetAllPoints(host)
    ui.root:Show()

    -- Log picker (leftmost). When absent, hide it and pull the period dropdown
    -- to the left edge so there's no gap.
    if logPicker then
        setDropdown(ui.logDD, logPicker.options, logPicker.current, function(v)
            if logPicker.onSelect then logPicker.onSelect(v) end
        end)
        ui.logDD:Show()
        ui.periodDD:ClearAllPoints()
        ui.periodDD:SetPoint("LEFT", ui.logDD, "RIGHT", -10, 0)
    else
        ui.logDD:Hide()
        ui.periodDD:ClearAllPoints()
        ui.periodDD:SetPoint("TOPLEFT", ui.root, "TOPLEFT", -12, 4)
    end

    -- AceGUI sizes the host frame AFTER this Draw, and the user can resize the
    -- window later. Re-flow on size change so the checkbox column count and the
    -- graph area track the real width/height (SetScript replaces, so repeated
    -- Renders don't stack handlers).
    ui.root:SetScript("OnSizeChanged", function()
        if _state.spec then refresh() end
    end)

    -- Hover tooltip: map the cursor's X across the plot to a time bucket (the
    -- graph plots data X in [xMin,xMax] across its full width — see LibGraph's
    -- pixel = Width*(x-XMin)/(XMax-XMin)) and show that bucket's per-series
    -- values. Rebuilds only when the bucket under the cursor changes.
    ui.hover:SetScript("OnLeave", function()
        GameTooltip:Hide()
        ui._hoverBucket = nil
    end)
    ui.hover:SetScript("OnUpdate", function(frame)
        local h = _state.hover
        local g = ui.graph
        local w = g:GetWidth()
        if not (h and w and w > 0 and frame:IsMouseOver()) then
            if ui._hoverBucket ~= nil then GameTooltip:Hide(); ui._hoverBucket = nil end
            return
        end
        local scale = g:GetEffectiveScale()
        local cx = (GetCursorPosition()) / scale
        local frac = (cx - g:GetLeft()) / w
        if frac < 0 then frac = 0 elseif frac > 1 then frac = 1 end
        local dataX = h.xMin + frac * (h.xMax - h.xMin)
        local b = math.floor(dataX + 0.5)
        if b < 1 then b = 1 elseif b > h.points then b = h.points end
        if b == ui._hoverBucket then return end   -- still in the same bucket
        ui._hoverBucket = b

        GameTooltip:SetOwner(frame, "ANCHOR_CURSOR")
        GameTooltip:ClearLines()
        GameTooltip:AddLine(bucketLabel(h, b))
        local any = false
        for i, s in ipairs(h.series) do
            local v = h.perSeries[i].buckets[b] or 0
            if v > 0 then
                local c = s.color
                GameTooltip:AddDoubleLine(s.label or s.key, tostring(v),
                    c[1], c[2], c[3], 1, 1, 1)
                any = true
            end
        end
        if not any then GameTooltip:AddLine("No data", 0.6, 0.6, 0.6) end
        GameTooltip:Show()
    end)

    -- Period dropdown.
    local periodItems = {}
    for i, p in ipairs(PERIODS) do periodItems[i] = { value = i, text = p.label } end
    setDropdown(ui.periodDD, periodItems, prefs.period or 1, function(v)
        prefs.period = v
        refresh()
    end)

    -- Per-log filter dropdowns are built (with cascading options) and
    -- positioned inside refresh() → rebuildFilterDropdowns(); just kick it off.
    prefs.filters = prefs.filters or {}
    refresh()

    return {
        Detach = function()
            ui.root:Hide()
            ui.root:SetParent(UIParent)
            ui.root:ClearAllPoints()
            _state.spec, _state.prefs = nil, nil
        end,
    }
end
