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

local function GetClassColor(class)
    local c = class and RAID_CLASS_COLORS[class]
    if c then
        return c.r, c.g, c.b
    end
    return 1, 1, 1
end

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

    Tooltip:Clear()

    if not IsInGuild() then
        Tooltip:AddLine(L["GUILD_NO_GUILD"], 13, 1, 0.3, 0.3)
        Tooltip:ShowAt(self, "BOTTOMLEFT", "TOPLEFT", 0, 6)
        return
    end

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

    local total = GetNumGuildMembers()
    for i = 1, total do
        local name, _, _, level, class, _, _, _, online = GetGuildRosterInfo(i)
        if online then
            local r, g, b = GetClassColor(class)
            Tooltip:AddLine(
                string.format("%s (%s)", name or "?", level or "?"),
                12,
                r, g, b
            )
        end
    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_guild.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)

    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" and IsInGuild() then
            ToggleGuildFrame()
        end
    end)

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

    if IP.EnableDrag then
        IP:EnableDrag(element)
    end
    function element:Update()
        if not IsInGuild() then
            self.text:SetText("— / —")
            self.text:SetTextColor(0.7, 0.7, 0.7)
        else
            local online, total = 0, GetNumGuildMembers()
            for i = 1, total do
                local _, _, _, _, _, _, _, _, onlineStatus = GetGuildRosterInfo(i)
                if onlineStatus then
                    online = online + 1
                end
            end

            self.text:SetText(string.format("%d/%d", online, total))
            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()
    return element
end

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

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:RegisterEvent("GUILD_ROSTER_UPDATE")
ev:RegisterEvent("PLAYER_GUILD_UPDATE")

ev:SetScript("OnEvent", function()
    if IsInGuild() and C_GuildInfo and C_GuildInfo.GuildRoster then
        C_GuildInfo.GuildRoster()
    end

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