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

local SLOTS = {
    { slot = "HeadSlot",           name = INVTYPE_HEAD },
    { slot = "ShoulderSlot",       name = INVTYPE_SHOULDER },
    { slot = "ChestSlot",          name = INVTYPE_CHEST },
    { slot = "WristSlot",          name = INVTYPE_WRIST },
    { slot = "HandsSlot",          name = INVTYPE_HAND },
    { slot = "WaistSlot",          name = INVTYPE_WAIST },
    { slot = "LegsSlot",           name = INVTYPE_LEGS },
    { slot = "FeetSlot",           name = INVTYPE_FEET },
    { slot = "MainHandSlot",       name = INVTYPE_WEAPONMAINHAND },
    { slot = "SecondaryHandSlot",  name = INVTYPE_WEAPONOFFHAND },
}

local function GetDurabilityData()
    local minPerc = 100
    local list = {}

    for _, s in ipairs(SLOTS) do
        local id = GetInventorySlotInfo(s.slot)
        if id then
            local cur, max = GetInventoryItemDurability(id)
            if cur and max and max > 0 then
                local perc = math.floor((cur / max) * 100)
                minPerc = math.min(minPerc, perc)
                table.insert(list, { name = s.name, perc = perc })
            end
        end
    end

    return minPerc, list
end

local function GetColorByPerc(p)
    if p < 40 then
        return 1, 0.2, 0.2
    elseif p < 80 then
        return 1, 0.82, 0
    end
    return 1, 1, 1
end

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

    local minPerc, list = GetDurabilityData()

    Tooltip:Clear()

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

    for _, item in ipairs(list) do
        local r, g, b = GetColorByPerc(item.perc)
        Tooltip:AddLine(
            string.format("%s — %d%%", item.name, item.perc),
            12,
            r, g, b
        )
    end

    Tooltip:AddLine(" ")
    do
        local r, g, b = GetColorByPerc(minPerc)
			Tooltip:AddLine(
				string.format(L["DURABILITY_MIN"], minPerc),
				12,
				r, g, b
			)
    end

    Tooltip:AddLine(" ")
    Tooltip:AddLine(L["DURABILITY_CLICK"], 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_durability.tga")
    icon:SetSize(s, s)
    icon:SetPoint("LEFT", 2, 0)
    icon:SetVertexColor(1, 1, 1)

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

    f.icon  = icon
    f.value = value

    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
            ToggleCharacter("PaperDollFrame")
        end
    end)

    local element = {
        _type = "Durability",
        id    = uid,
        frame = f,
        icon  = icon,
        value = value,
        width = 60,
    }

    if IP.EnableDrag then
        IP:EnableDrag(element)
    end
	    function element:Update()
        local minPerc = GetDurabilityData()
        local r, g, b = GetColorByPerc(minPerc)

        self.value:SetText(minPerc .. "%")
        self.value:SetTextColor(r, g, b)

        local textW = self.value: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("durability", function(uid)
    return Create(uid)
end)

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:RegisterEvent("UPDATE_INVENTORY_DURABILITY")
ev:RegisterEvent("PLAYER_EQUIPMENT_CHANGED")

ev:SetScript("OnEvent", function()
    for _, element in pairs(IP.elements or {}) do
        if element and element._type == "Durability" and element.Update then
            element:Update()
        end
    end
end)
