local PT = AhUI
if not PT or not PT.InfoPanel then return end
local IP = PT.InfoPanel
local Tooltip = PT.Tooltip
local L = PT.L

IP:RegisterElementInfo("gold", {
    name  = "Gold",
    order = 20,
})

local function GetGoldDB()
    AhUI_DB = AhUI_DB or {}
    AhUI_DB.gold = AhUI_DB.gold or {}

    local realm = GetNormalizedRealmName()
    AhUI_DB.gold[realm] = AhUI_DB.gold[realm] or {}

    return AhUI_DB.gold[realm]
end

local function FormatGold(amount)
    local g = math.floor((amount or 0) / 10000)
    return BreakUpLargeNumbers(g)
end

local function Colorize(v)
    if v > 0 then
        return "|cff00ff00+" .. FormatGold(v) .. "|r"
    elseif v < 0 then
        return "|cffff4040" .. FormatGold(v) .. "|r"
    else
        return FormatGold(0)
    end
end

local function ShowTooltip(self)
    if not Tooltip then return end

    local db = GetGoldDB()
    local total = 0

    Tooltip:Clear()

    Tooltip:AddLine(L["GOLD_TITLE"], 14, 1, 1, 1)
    Tooltip:AddLine(" ")

    for char, money in pairs(db) do
        if type(char) == "string"
           and type(money) == "number"
           and not char:match("^__") then

            total = total + money
            Tooltip:AddLine(
                string.format("%s — %s", char, FormatGold(money)),
                12, 1, 1, 1
            )
        end
    end

    Tooltip:AddLine(" ")
    Tooltip:AddLine(
        string.format(L["GOLD_TOTAL"], FormatGold(total)),
        12, 0.8, 0.8, 0.8
    )

    if db.__sessionStart then
        local now = db[UnitName("player")] or 0
        local delta = now - db.__sessionStart

        Tooltip:AddLine(" ")
        Tooltip:AddLine(
            string.format(L["GOLD_SESSION"], Colorize(delta)),
            12, 1, 1, 1
        )
    end

    Tooltip:ShowAt(self, "BOTTOMLEFT", "TOPLEFT", 0, 6)
end

local function Create(uid)
    local parent = (IP.frame and IP.frame.content) or UIParent
    local height = (IP.config and IP.config.appearance and IP.config.appearance.height) or 24

    local f = CreateFrame("Button", nil, parent)
    f:SetHeight(height)

    local s = math.max(16, height - 2)

    local icon = f:CreateTexture(nil, "ARTWORK")
    icon:SetTexture("Interface\\AddOns\\AhUI\\media\\icons\\ahui_gold.tga")
    icon:SetSize(s, s)
    icon:SetPoint("LEFT", 2, 0)
    icon:SetVertexColor(1, 1, 1)

    local text = f:CreateFontString(nil, "OVERLAY")
    text:SetPoint("LEFT", icon, "RIGHT", 1, 0)
    text:SetFontObject(PT.fonts.normal)
    text:SetTextColor(1, 1, 1)

    f.icon = icon
    f.text = text

    f:SetScript("OnEnter", ShowTooltip)
    f:SetScript("OnLeave", function()
        if Tooltip then Tooltip:Clear() end
    end)

    f:RegisterForClicks("LeftButtonUp")
    f:SetScript("OnClick", function(_, btn)
        if btn == "LeftButton" then
            ToggleAllBags()
        end
    end)

    local element = {
        _type = "Gold",
        id    = uid,
        frame = f,
        icon  = icon,
        text  = text,
        width = 60,
    }

    if IP.EnableDrag then
        IP:EnableDrag(element)
    end

    function element:Update()
        local money = GetMoney() or 0
        self.text:SetText(FormatGold(money))
        self.text:SetTextColor(1, 1, 1)

        local db = GetGoldDB()
        local name = UnitName("player")
        db[name] = money

        if not db.__sessionStart then
            db.__sessionStart = money
        end

        local textW = self.text:GetUnboundedStringWidth() or 0
        local w = self.icon:GetWidth() + textW + 6

        self.width = w
        self.frame:SetWidth(w)
    end

    element:Update()
    return element
end

IP:RegisterElementType("gold", function(uid)
    return Create(uid)
end)

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:RegisterEvent("PLAYER_MONEY")
ev:SetScript("OnEvent", function()
    for _, element in pairs(IP.elements or {}) do
        if element and element._type == "Gold" and element.Update then
            element:Update()
        end
    end
end)
