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

local IP = PT.InfoPanel
local Tooltip = PT.Tooltip
local Dropdown = PT.Dropdown
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"
    end
    return FormatGold(0)
end

local function ShowGoldEditDropdown(owner)
    if not Dropdown or not owner then return end

    local db = GetGoldDB()
    local items = {
        {
            text = L["GOLD_EDIT_TITLE"],
            header = true,
        },
    }

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

            table.insert(items, {
                text = char,
                amount = FormatGold(money),
                onClick = function()
                    db[char] = nil
                end,
            })
        end
    end

    table.insert(items, {
        text = L["GOLD_REMOVE_ALL"],
        onClick = function()
            for k in pairs(db) do
                if not tostring(k):match("^__") then
                    db[k] = nil
                end
            end
        end,
    })

    Dropdown:Show({
        owner = owner,
        items = items,
    })
end

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

    local db = GetGoldDB()
    local total = 0

    local warbandMoney = 0
    if C_Bank and C_Bank.FetchDepositedMoney and Enum and Enum.BankType and Enum.BankType.Account then
        warbandMoney = C_Bank.FetchDepositedMoney(Enum.BankType.Account) or 0
    end

    local isAltDown = IsAltKeyDown()  -- Проверяем, зажат ли Alt

    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

            local moneyStr
            if isAltDown then
                moneyStr = GetCoinTextureString(money, 12)  -- Полный формат с иконками
            else
                moneyStr = FormatGold(money)  -- Только золото
            end

            Tooltip:AddLine(
                string.format("%s — %s", char, moneyStr),
                12, 1, 1, 1
            )
        end
    end

    Tooltip:AddLine(" ")  -- Пустая строка после списка персонажей

    if warbandMoney > 0 then
        local warbandStr
        if isAltDown then
            warbandStr = GetCoinTextureString(warbandMoney, 12)
        else
            warbandStr = FormatGold(warbandMoney)
        end

        Tooltip:AddLine(string.format(L["GOLD_WARBAND_BANK"], warbandStr), 12, 0.8, 1, 1)
        total = total + warbandMoney
        Tooltip:AddLine(" ")  -- Пустая строка после Warband Bank
    end

    -- Total
    local totalStr
    if isAltDown then
        totalStr = GetCoinTextureString(total, 12)
    else
        totalStr = FormatGold(total)
    end

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

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

        local sessionStr = Colorize(delta)
        if isAltDown and delta ~= 0 then
            sessionStr = (delta > 0 and "|cff00ff00+" or "|cffff4040") .. GetCoinTextureString(math.abs(delta), 12) .. "|r"
        end

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

    Tooltip:AddLine(" ")
    Tooltip:AddLine(L["GOLD_HINT_BAGS"], 11, 0.7, 0.7, 0.7)
    Tooltip:AddLine(L["GOLD_EDIT_HINT"], 11, 0.7, 0.7, 0.7)
    Tooltip:AddLine(L["GOLD_HINT_ALT"], 11, 0.7, 0.7, 0.7)
	
    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)

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

    f.icon = icon
    f.text = text
	
	f.lastAltState = false

	f.UpdateTooltipAlt = function(self)
		local isAlt = IsAltKeyDown()
		if isAlt ~= self.lastAltState then
			self.lastAltState = isAlt
			ShowTooltip(self)
		end
	end
    f:SetScript("OnEnter", function(self)
		self.lastAltState = IsAltKeyDown()
		ShowTooltip(self)
		self:SetScript("OnUpdate", self.UpdateTooltipAlt)
	end)
	
    f:SetScript("OnLeave", function(self)
		self:SetScript("OnUpdate", nil)
		if Tooltip then Tooltip:Clear() end
	end)

    f:RegisterForClicks("AnyUp")
    f:SetScript("OnClick", function(self, btn)
        if btn == "LeftButton" then
            ToggleAllBags()
            return
        end

        if btn == "RightButton" then
            ShowGoldEditDropdown(self)
            return
        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))

        local db = GetGoldDB()
        local name = UnitName("player")
        db[name] = money
        if not db.__sessionStart then
            db.__sessionStart = money
        end

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

        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)
