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("fpsms", {
    name = "FPS / MS",
})

local function GetLatency()
    local _, _, homeMS, worldMS = GetNetStats()
    return worldMS or homeMS or 0
end

local function GetFPS()
    return math.floor(GetFramerate() or 0)
end

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

    Tooltip:Clear()
	Tooltip:AddLine(L["FPSMS_TITLE"], 14, 1, 1, 1)
	Tooltip:AddLine(" ")
	Tooltip:AddLine(L["FPSMS_MS"], 12, 0.9, 0.9, 0.9)
	Tooltip:AddLine(L["FPSMS_FPS"], 12, 0.9, 0.9, 0.9)

    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 text = f:CreateFontString(nil, "OVERLAY")
    text:SetAllPoints()
    text:SetJustifyH("CENTER")
    text:SetJustifyV("MIDDLE")
    text:SetFontObject(PT.fonts.normal)
    text:SetTextColor(1, 1, 1)

    f.text = text

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


    local element = {
        _type = "FPSMS",
        id    = uid,
        frame = f,
        text  = text,
        width = 0, 
    }
if IP.EnableDrag then
    IP:EnableDrag(element)
end
    function element:Update()
        local ms  = GetLatency()
        local fps = GetFPS()

        local green = "|cff00ff00"
        local white = "|cffffffff"

        local str = string.format(
            "MS:%s%d%s  FPS:%s%d%s",
            green, ms, white,
            green, fps, white
        )

        self.text:SetText(str)

        local w = self.text:GetStringWidth() + 8
        self.width = w
        self.frame:SetWidth(w)
    end

    element:Update()
    return element
end

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

local ticker
local function StartTicker()
    if ticker then return end

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

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:SetScript("OnEvent", function()
    StartTicker()
end)
