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("token", {
    name  = "Token",
    order = 20,
})

local function GetTokenDB()
    AhUI_DB = AhUI_DB or {}
    AhUI_DB.token = AhUI_DB.token or {}
    return AhUI_DB.token
end

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

local function IsValidPrice(p)
    return type(p) == "number" and p > 0
end

local function GetPrice()
    if C_WowTokenPublic and C_WowTokenPublic.GetCurrentMarketPrice then
        return C_WowTokenPublic.GetCurrentMarketPrice()
    end
end

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

    local db = GetTokenDB()

    Tooltip:Clear()

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

    if IsValidPrice(db.current) then
        Tooltip:AddLine(
            string.format(L["TOKEN_PRICE"], FormatGold(db.current)),
            12, 0.9, 0.9, 0.9
        )
    else
        Tooltip:AddLine(L["TOKEN_LOADING"], 12, 0.7, 0.7, 0.7)
    end

    if IsValidPrice(db.previous) and IsValidPrice(db.current) then
        local diff = db.current - db.previous
        local sign = diff > 0 and "+" or ""
        local r, g, b = 1, 1, 1

        if diff > 0 then
            r, g, b = 1, 0.2, 0.2
        elseif diff < 0 then
            r, g, b = 0.2, 1, 0.2
        end

        Tooltip:AddLine(
            string.format(L["TOKEN_DIFF"], sign .. FormatGold(diff)),
            12, r, g, b
        )
    end

    if db.lastUpdate then
        Tooltip:AddLine(" ")
        Tooltip:AddLine(
            string.format(L["TOKEN_UPDATED"], date("%H:%M", db.lastUpdate)),
            11, 0.7, 0.7, 0.7
        )
    end

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

local function RequestMarketPriceWithRetry()
    if not C_WowTokenPublic then return end

    C_WowTokenPublic.UpdateMarketPrice()

    C_Timer.After(1, function()
        for _, element in pairs(IP.elements or {}) do
            if element and element._type == "Token" and element.Update then
                element:Update()
            end
        end
    end)
end

local function Create(uid)
    local parent = (IP.frame and IP.frame.content) or UIParent
    local height = (IP.config 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_token.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)

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

    if IP.EnableDrag then
        IP:EnableDrag(element)
    end
	    function element:Update()
        local price = GetPrice()

        if not IsValidPrice(price) then
            self.text:SetText(L["TOKEN_LOADING"])
            self.text:SetTextColor(0.7, 0.7, 0.7)
        else
            local db = GetTokenDB()

            if IsValidPrice(db.current) and db.current ~= price then
                db.previous = db.current
            end

            db.current = price
            db.lastUpdate = time()

            self.text:SetText(FormatGold(price))
            self.text:SetTextColor(1, 1, 1)
        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()

    function element:ApplyHeight(h)
        local s = math.max(16, h - 2)
        self.icon:SetSize(s, s)
        self.text:SetFont(PT.FONT, math.max(10, h - 8), "")
    end

    return element
end

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

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:RegisterEvent("TOKEN_MARKET_PRICE_UPDATED")

ev:SetScript("OnEvent", function(_, event)
    if event == "PLAYER_LOGIN" or event == "WOW_TOKEN_MARKET_PRICE_UPDATED" then
        RequestMarketPriceWithRetry()
    end
end)

C_Timer.NewTicker(300, function()
    RequestMarketPriceWithRetry()
end)