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

function IP:EnableDrag(element)
    if not element or not element.frame then return end
    if not IP.frame or not IP.frame.content then return end

    local f = element.frame
    local panel = IP.frame.content

    if f.__dragEnabled then return end
    f.__dragEnabled = true

    f.__element = element
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")

    local function DragAllowed()
        if not IP:IsLocked() then
            return true
        end
        return IsAltKeyDown()
    end

    local function CalcClampedX(cursorX)
        local scale = UIParent:GetScale()
        cursorX = cursorX / scale

        local left = panel:GetLeft()
        if not left then return 0 end

        local wPanel = panel:GetWidth() or 0
        local wEl = f:GetWidth() or 0
        local maxX = wPanel - wEl
        if maxX < 0 then maxX = 0 end

        local x = cursorX - left - (f.__grabOffsetX or 0)
        if x < 0 then x = 0 end
        if x > maxX then x = maxX end
        return x
    end

    f:SetScript("OnDragStart", function(self)
        if not DragAllowed() then return end
        if not panel:GetLeft() then return end

        local cx = GetCursorPosition()
        local scale = UIParent:GetScale()
        cx = cx / scale

        local elLeft = self:GetLeft() or (panel:GetLeft() or 0)
        self.__grabOffsetX = cx - elLeft

        self.__dragging = true

        self:SetScript("OnUpdate", function(s)
            if not s.__dragging then return end
            local cxx = GetCursorPosition()
            local x = CalcClampedX(cxx)
            s:ClearAllPoints()
            s:SetPoint("LEFT", panel, "LEFT", x, 0)
        end)
    end)

    f:SetScript("OnDragStop", function(self)
        if not self.__dragging then return end
        self.__dragging = false
        self:SetScript("OnUpdate", nil)

        if not DragAllowed() then return end

        local el = self.__element
        if not el or not el.db then return end

        local x = CalcClampedX(GetCursorPosition())

        self:ClearAllPoints()
        self:SetPoint("LEFT", panel, "LEFT", x, 0)

        el.db.x = math.floor(x + 0.5)
    end)
end
