-- TOG Tools — Mailbox Stale Watcher tab (UI)
-- Lists each alt with mail expiring within the configured threshold so the
-- player can hop to the right character and rescue it before auto-deletion.
-- Snapshot-only readout: this tab does not open / reply / delete mail.

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

local BRAND = "|c" .. (addon.BrandColor or "ffFF8000")

local Tab = addon.modules["mailbox"]
Tab.tabKey      = "mailbox"
Tab.configKey   = "mailbox"
Tab.label       = "Mailbox"
Tab.WINDOW_SIZE = { width = 640, height = 480, minWidth = 540, minHeight = 360 }
Tab.help = {
    title = "Mailbox Stale Watcher",
    lines = {
        "Lists every alt with mail close to expiring so a stack of Black Lotus or a hard-earned BoE doesn't get auto-deleted because you forgot to visit the mailbox in time.",
        "Snapshot is captured each time an alt opens a mailbox — no need to log into each alt to refresh.",
        "Shows sender, subject, and time remaining for each expiring mail, plus how recent each alt's snapshot is. Snapshots older than a week are flagged so you know to refresh by visiting the mailbox.",
        "Account-wide: data is shared across every alt on every realm. Threshold (default 2 days, adjustable 1–7) lives in the addon settings panel.",
        "|cffffd700Read-only|r — this tab tells you what's about to expire, but does not open, reply, or delete mail. Handle that in-game like normal.",
    },
}

-- A snapshot older than this is flagged as potentially out-of-date in the UI.
local STALE_DAYS = 7

-- ---------------------------------------------------------------------------
-- Formatters
-- ---------------------------------------------------------------------------
local function fmtAge(seconds)
    if not seconds or seconds < 0 then return "?" end
    if seconds < 3600   then return string.format("%dm ago", math.floor(seconds / 60))   end
    if seconds < 86400  then return string.format("%dh ago", math.floor(seconds / 3600)) end
    return string.format("%dd ago", math.floor(seconds / 86400))
end

local function fmtTimeLeft(seconds)
    if not seconds or seconds <= 0 then return "expired" end
    local d = seconds / 86400
    if d < 1 then return string.format("%.1fh", seconds / 3600) end
    return string.format("%.1fd", d)
end

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

    local db = addon.DB.global.mailbox

    -- ---- Threshold control row -----------------------------------------
    local thresholdSlider = AceGUI:Create("Slider")
    thresholdSlider:SetLabel(BRAND .. "Alert when mail expires within (days)|r")
    thresholdSlider:SetSliderValues(1, 7, 1)
    thresholdSlider:SetValue(db.thresholdDays or 2)
    thresholdSlider:SetRelativeWidth(0.5)
    thresholdSlider:SetCallback("OnValueChanged", function(_, _, val)
        db.thresholdDays = math.floor(val + 0.5)
        self:Refresh(container)
    end)
    container:AddChild(thresholdSlider)

    local hint = AceGUI:Create("Label")
    hint:SetText("|cffaaaaaaSnapshot updates each time you visit a mailbox.|r")
    hint:SetRelativeWidth(0.5)
    container:AddChild(hint)

    -- Spacer
    local sp = AceGUI:Create("Label")
    sp:SetText(" ")
    sp:SetFullWidth(true)
    container:AddChild(sp)

    -- ---- Scroll area for alt list --------------------------------------
    local scroll = AceGUI:Create("ScrollFrame")
    scroll:SetLayout("Flow")
    scroll:SetFullWidth(true)
    scroll:SetFullHeight(true)
    container:AddChild(scroll)

    local summaries = self:GetAltSummaries()
    local now = GetServerTime()

    if #summaries == 0 then
        local empty = AceGUI:Create("Label")
        empty:SetText("|cffaaaaaaNo mailbox snapshots yet. Visit a mailbox on each alt to populate.|r")
        empty:SetFullWidth(true)
        scroll:AddChild(empty)
        return
    end

    for _, sum in ipairs(summaries) do
        local age   = sum.snapshotAt and (now - sum.snapshotAt) or nil
        local stale = age and age > (STALE_DAYS * 86400)

        local headerText
        if sum.expiringCount > 0 then
            headerText = string.format(
                "%s%s|r  |cffffaa55%d expiring|r  |cffaaaaaa(snapshot %s%s)|r",
                BRAND, sum.charKey,
                sum.expiringCount,
                fmtAge(age),
                stale and " - stale" or ""
            )
        else
            headerText = string.format(
                "|cffaaaaaa%s - no expiring mail (snapshot %s%s)|r",
                sum.charKey,
                fmtAge(age),
                stale and " - stale" or ""
            )
        end

        local altGroup = AceGUI:Create("InlineGroup")
        altGroup:SetTitle(headerText)
        altGroup:SetFullWidth(true)
        altGroup:SetLayout("List")
        scroll:AddChild(altGroup)

        if sum.expiringCount > 0 then
            for _, item in ipairs(sum.items) do
                local left = item.expiresAt - now
                local subj = (item.subject ~= "") and item.subject or "(no subject)"
                local row  = AceGUI:Create("Label")
                row:SetText(string.format(
                    "  |cffffcc66%s|r  from %s  |cffaaaaaa(%s left)|r",
                    subj, item.sender, fmtTimeLeft(left)
                ))
                row:SetFullWidth(true)
                altGroup:AddChild(row)
            end
        end
    end
end

function Tab:Refresh(container)
    container:ReleaseChildren()
    self:Draw(container)
end
