-- ============================================================
-- FILE: InterfaceMenu.lua
-- PURPOSE: Minimalist floating game-menu button + animated
--   drawer that replaces Blizzard's micro-button menu row.
--   Provides access to 13 game panels (Character, Talents,
--   Professions, Spellbook, Collections, Guild, Journal,
--   Group Finder, Housing, Help, etc.) plus a re-anchored
--   Blizzard queue-status button.
-- HOW IT WORKS:
--   A small dock button opens/closes a horizontal slide-out
--   drawer via an OnUpdate-driven width/alpha animation.
--   Each drawer button maps to a WoW frame toggle (with
--   C_AddOns.LoadAddOn deferred loading where needed).
--   Blizzard MicroMenuContainer is kept visible-but-mouse-
--   disabled via hooksecurefunc to preserve its screen space.
--   QueueStatusButton is repositioned via a SetPoint hook.
-- DEPENDS ON:
--   MidnightUI_Core, MidnightUI_MoverRegistry, MidnightUI_Settings,
--   MidnightUI_StyleOverlay, MidnightUI_AttachOverlaySettings
-- EXPORTS:
--   _G.MidnightInterface (manager frame)
--   _G.MidnightInterfaceDock (dock button)
--   _G.MidnightInterfaceDrawer (drawer container)
--   _G.MidnightUI_InterfaceMenuDock
--   _G.MidnightUI_ApplyInterfaceMenuSettings()
--   _G.MidnightUI_SetInterfaceMenuLocked(locked)
-- OWNED SAVESVARIABLES: none (reads MidnightUISettings.InterfaceMenu)
-- EVENTS REGISTERED: PLAYER_LOGIN, PLAYER_REGEN_ENABLED
-- FRAMES CREATED: dock button, drawer, 13 menu icon buttons
-- GOTCHAS:
--   SecureActionButtonTemplate macro toggles GameMenuFrame —
--   cannot do this in Lua directly.
--   Combat lockdown defers position/settings changes to
--   PLAYER_REGEN_ENABLED.
--   MicroMenuContainer is kept at alpha=0 mouse-disabled (not
--   hidden) so it still occupies space in the layout engine.
--   PlayerSpellsUtil.ToggleClassTalentFrame preferred on newer
--   TWW builds; falls back to ClassTalentFrame LoadAddOn toggle.
-- ============================================================

local addonName, ns = ...


local C = {
    classColor = (_G.MidnightUI_Core and _G.MidnightUI_Core.GetClassColorTable and _G.MidnightUI_Core.GetClassColorTable("player"))
        or C_ClassColor.GetClassColor(select(2, UnitClass("player"))),
}


local MidnightInterface = CreateFrame("Frame", "MidnightInterface", UIParent)
MidnightInterface:RegisterEvent("PLAYER_LOGIN")

local interfaceDockRef = nil

local pendingInterfaceMenuApply = false


-- ============================================================
-- SECTION: Utilities + Settings + Overlay + Dock Creation
-- Clamp/settings helpers, overlay drag creation, settings
-- application (scale, position), lock state toggler, and the
-- full INTERFACE_BUTTONS definition table with per-button
-- toggle callbacks.  CreateInterfaceDock builds the dock
-- button + drawer + slide animation.  The event handler at
-- the bottom handles PLAYER_LOGIN and PLAYER_REGEN_ENABLED.
--
-- READS:  MidnightUISettings.InterfaceMenu.*, InCombatLockdown
-- WRITES: interfaceDockRef, drawer SetWidth/SetAlpha on slide
--
-- FUNCTIONS:
--   ClampNumber(v,min,max,fb) — safe clamped tonumber
--   EnsureInterfaceMenuSettings() — lazy-init settings sub-table
--   CanToggleFrameDirectly / SafeToggleFrameVisibility — safe
--     Blizzard frame toggle wrappers
--   SaveInterfaceMenuPosition(dockFrame) — write position to settings
--   EnsureInterfaceMenuOverlay(dockFrame) — drag overlay for edit mode
--   ApplyInterfaceMenuSettings() — read settings and reposition dock
--   MidnightUI_SetInterfaceMenuLocked(locked) — toggle edit mode
--   INTERFACE_BUTTONS table — 13 icon + action pairs
--   CreateInterfaceDock() — builds dock button, drawer, buttons,
--     UpdateSlide OnUpdate animation, MoverRegistry registration
--   BuildInterfaceMenuOverlaySettings(content) — settings panel
--   EVENT HANDLER: PLAYER_LOGIN → create dock, hook queue button
--     and micro menu; PLAYER_REGEN_ENABLED → flush deferred apply
-- ============================================================
local function ClampNumber(value, minValue, maxValue, fallback)
    local n = tonumber(value)
    if not n then return fallback end
    if n < minValue then return minValue end
    if n > maxValue then return maxValue end
    return n
end

local function EnsureInterfaceMenuSettings()
    if not MidnightUISettings then MidnightUISettings = {} end
    if not MidnightUISettings.InterfaceMenu then MidnightUISettings.InterfaceMenu = {} end
    local s = MidnightUISettings.InterfaceMenu
    if s.enabled == nil then s.enabled = true end
    if s.scale == nil then s.scale = 100 end
    return s
end


local function CanToggleFrameDirectly(frame)
    return type(frame) == "table"
        and type(frame.IsShown) == "function"
        and (type(frame.SetShown) == "function"
            or (type(frame.Show) == "function" and type(frame.Hide) == "function"))
end

local function SafeToggleFrameVisibility(frame)
    if not CanToggleFrameDirectly(frame) then
        return false
    end

    local shown = frame:IsShown() == true
    if type(frame.SetShown) == "function" then
        local ok = pcall(frame.SetShown, frame, not shown)
        if ok then return true end
    end

    if shown and type(frame.Hide) == "function" then
        local ok = pcall(frame.Hide, frame)
        if ok then return true end
    elseif not shown and type(frame.Show) == "function" then
        local ok = pcall(frame.Show, frame)
        if ok then return true end
    end

    return false
end


local function SaveInterfaceMenuPosition(dockFrame)
    local s = EnsureInterfaceMenuSettings()
    local point, _, relativePoint, xOfs, yOfs = dockFrame:GetPoint()
    local scale = dockFrame:GetScale()
    if not scale or scale == 0 then scale = 1.0 end
    s.position = {
        point or "BOTTOMRIGHT",
        relativePoint or "BOTTOMRIGHT",
        (tonumber(xOfs) or 0) / scale,
        (tonumber(yOfs) or 0) / scale,
    }
end


local function EnsureInterfaceMenuOverlay(dockFrame)
    if dockFrame.dragOverlay then return dockFrame.dragOverlay end
    local overlay = CreateFrame("Frame", nil, dockFrame, "BackdropTemplate")
    overlay:SetAllPoints()
    overlay:SetFrameStrata("HIGH")
    overlay:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true,
        tileSize = 16,
        edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 },
    })
    overlay:SetBackdropColor(0.05, 0.08, 0.11, 0.30)
    overlay:SetBackdropBorderColor(0.30, 0.46, 0.58, 0.78)
    if _G.MidnightUI_StyleOverlay then _G.MidnightUI_StyleOverlay(overlay, nil, nil, "world") end

    local label = overlay:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    label:SetPoint("CENTER")
    label:SetText("GAME MENU")
    label:SetTextColor(1, 1, 1)

    overlay:EnableMouse(true)
    overlay:RegisterForDrag("LeftButton")
    overlay:SetScript("OnDragStart", function(self)
        if InCombatLockdown and InCombatLockdown() then return end
        dockFrame:StartMoving()
    end)
    overlay:SetScript("OnDragStop", function(self)
        dockFrame:StopMovingOrSizing()
        SaveInterfaceMenuPosition(dockFrame)
        local MR = _G.MidnightUI_MoverRegistry
        if MR and MR.SavePosition then MR.SavePosition("InterfaceMenu") end
    end)

    if _G.MidnightUI_AttachOverlaySettings then
        _G.MidnightUI_AttachOverlaySettings(overlay, "InterfaceMenu")
    end
    dockFrame.dragOverlay = overlay
    return overlay
end


local function ApplyInterfaceMenuSettings()
    local dockFrame = interfaceDockRef or _G.MidnightUI_InterfaceMenuDock
    if not dockFrame then return end
    local s = EnsureInterfaceMenuSettings()

    if InCombatLockdown and InCombatLockdown() then
        pendingInterfaceMenuApply = true
        MidnightInterface:RegisterEvent("PLAYER_REGEN_ENABLED")
        return
    end

    pendingInterfaceMenuApply = false
    MidnightInterface:UnregisterEvent("PLAYER_REGEN_ENABLED")

    local scalePct = ClampNumber(s.scale, 50, 200, 100)
    dockFrame:SetScale(scalePct / 100)

    if s.position and type(s.position) == "table" and #s.position >= 4 then
        dockFrame:ClearAllPoints()
        local effScale = dockFrame:GetScale()
        if not effScale or effScale == 0 then effScale = 1.0 end
        dockFrame:SetPoint(
            s.position[1],
            UIParent,
            s.position[2],
            (tonumber(s.position[3]) or 0) * effScale,
            (tonumber(s.position[4]) or 0) * effScale
        )
    end

    if s.enabled == false then
        dockFrame:Hide()
    else
        dockFrame:Show()
    end

    if _G.MidnightUI_SetInterfaceMenuLocked and MidnightUISettings and MidnightUISettings.Messenger then
        _G.MidnightUI_SetInterfaceMenuLocked(MidnightUISettings.Messenger.locked ~= false)
    end
end
_G.MidnightUI_ApplyInterfaceMenuSettings = ApplyInterfaceMenuSettings

function _G.MidnightUI_SetInterfaceMenuLocked(locked)
    local dockFrame = interfaceDockRef or _G.MidnightUI_InterfaceMenuDock
    if not dockFrame then return end
    local s = EnsureInterfaceMenuSettings()
    local overlay = EnsureInterfaceMenuOverlay(dockFrame)
    if locked or s.enabled == false then
        overlay:Hide()
    else
        overlay:Show()
    end
end


local INTERFACE_BUTTONS = {
    {
        icon = 132146,
        tooltip = "Character",
        onClick = function() ToggleCharacter("PaperDollFrame") end,
    },
    {
        icon = 4620678,
        tooltip = "Professions",
        onClick = function() ToggleProfessionsBook() end,
    },
    {
        icon = "Interface\\Icons\\INV_Misc_Coin_01",
        tooltip = "Currency",
        onClick = function() ToggleCharacter("TokenFrame") end,
    },
    {
        icon = "Interface\\Icons\\Achievement_Quests_Completed_08",
        tooltip = "Achievements",
        onClick = function() ToggleAchievementFrame() end,
    },
    {
        icon = "Interface\\Icons\\ClassIcon_Warrior",
        tooltip = "Talents",
        onClick = function()
            if PlayerSpellsUtil and PlayerSpellsUtil.ToggleClassTalentFrame then
                PlayerSpellsUtil.ToggleClassTalentFrame()
            else
                if not ClassTalentFrame then C_AddOns.LoadAddOn("Blizzard_ClassTalentUI") end
                if ClassTalentFrame then ToggleFrame(ClassTalentFrame) end
            end
        end,
    },
    {
        icon = "Interface\\Icons\\INV_Misc_Book_07",
        tooltip = "Spellbook & Abilities",
        onClick = function()
            if PlayerSpellsUtil and PlayerSpellsUtil.ToggleSpellBookFrame then
                PlayerSpellsUtil.ToggleSpellBookFrame()
            else
                TogglePlayerSpellsFrame()
            end
        end,
    },
    {
        icon = "Interface\\Icons\\Achievement_GuildPerk_MountUp",
        tooltip = "Warband Collections",
        onClick = function() ToggleCollectionsJournal() end,
    },
    {
        icon = "Interface\\Icons\\Achievement_General_StayClassy",
        tooltip = "Guild & Communities",
        onClick = function() ToggleGuildFrame() end,
    },
    {
        icon = "Interface\\Icons\\INV_Misc_Map_01",
        tooltip = "Adventure Guide",
        onClick = function() ToggleEncounterJournal() end,
    },
    {
        icon = "Interface\\Icons\\INV_Misc_GroupLooking",
        tooltip = "Group Finder",
        onClick = function()
            local s = _G.MidnightUISettings
            local useBlizz = s and s.General and s.General.useBlizzardGroupFinder == true
            if not useBlizz and _G.MidnightUI_GroupFinder_Toggle then
                _G.MidnightUI_GroupFinder_Toggle()
            else
                PVEFrame_ToggleFrame()
            end
        end,
    },
    {
        icon = "DynamicHousing",
        tooltip = "Housing Dashboard",
        onClick = function()
            if not HousingDashboardFrame then
                C_AddOns.LoadAddOn("Blizzard_HousingUI")
            end

            if HousingMicroButton and type(HousingMicroButton.Click) == "function" then
                HousingMicroButton:Click()
                return
            end

            SafeToggleFrameVisibility(HousingDashboardFrame)
        end,
    },
    {
        icon = "Interface\\Icons\\INV_Misc_Book_08",
        tooltip = "Encounter Journal",
        onClick = function() ToggleEncounterJournal() end,
    },
    {
        icon = "Interface\\Icons\\INV_Misc_QuestionMark",
        tooltip = "Help",
        onClick = function() ToggleHelpFrame() end,
    },
}


local function CreateInterfaceDock()
    if interfaceDockRef then return interfaceDockRef end

    local dockFrame = CreateFrame("Button", "MidnightInterfaceDock", UIParent, "SecureActionButtonTemplate")
    dockFrame:SetSize(46, 46)
    dockFrame:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -40, 95)
    dockFrame:SetFrameStrata("HIGH")
    dockFrame:SetMovable(true)
    dockFrame:EnableMouse(true)
    dockFrame:RegisterForDrag("LeftButton")
    dockFrame:RegisterForClicks("AnyDown")

    dockFrame:SetScript("OnDragStart", function(self)
        if InCombatLockdown and InCombatLockdown() then return end
        self:StartMoving()
    end)
    dockFrame:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
        SaveInterfaceMenuPosition(self)
        local MR = _G.MidnightUI_MoverRegistry
        if MR and MR.SavePosition then MR.SavePosition("InterfaceMenu") end
    end)

    dockFrame:SetAttribute("type1", "macro")
    dockFrame:SetAttribute("macrotext1", "/run if GameMenuFrame then GameMenuFrame:SetShown(not GameMenuFrame:IsShown()) end")

    local bgFrame = CreateFrame("Frame", nil, dockFrame, "BackdropTemplate")
    bgFrame:SetAllPoints()
    bgFrame:SetFrameLevel(dockFrame:GetFrameLevel())
    bgFrame:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 2,
        insets = { left = 2, right = 2, top = 2, bottom = 2 }
    })
    bgFrame:SetBackdropColor(0.06, 0.06, 0.08, 0.95)
    bgFrame:SetBackdropBorderColor(0.18, 0.18, 0.22, 1)
    dockFrame.bgFrame = bgFrame

    local icon = dockFrame:CreateTexture(nil, "OVERLAY")
    icon:SetSize(36, 36)
    icon:SetPoint("CENTER")
    icon:SetTexture("Interface\\Icons\\WoW_Store")
    icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)
    dockFrame.icon = icon

    local highlight = dockFrame:CreateTexture(nil, "HIGHLIGHT")
    highlight:SetPoint("TOPLEFT", 2, -2)
    highlight:SetPoint("BOTTOMRIGHT", -2, 2)
    highlight:SetTexture("Interface\\Buttons\\WHITE8x8")
    highlight:SetVertexColor(1, 1, 1, 0.08)
    highlight:SetBlendMode("ADD")

    local drawer = CreateFrame("Frame", "MidnightInterfaceDrawer", dockFrame, "BackdropTemplate")
    drawer:SetPoint("RIGHT", dockFrame, "LEFT", 6, 0)
    drawer:SetSize(1, 44)
    drawer:SetFrameLevel(math.max(dockFrame:GetFrameLevel(), 50))
    drawer:SetClipsChildren(true)

    drawer:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 1,
    })
    drawer:SetBackdropColor(0.06, 0.06, 0.08, 0.92)
    drawer:SetBackdropBorderColor(0.15, 0.15, 0.18, 1)
    drawer:SetAlpha(0)

    local drawerHighlight = drawer:CreateTexture(nil, "ARTWORK")
    drawerHighlight:SetHeight(1)
    drawerHighlight:SetPoint("TOPLEFT", 1, -1)
    drawerHighlight:SetPoint("TOPRIGHT", -1, -1)
    drawerHighlight:SetTexture("Interface\\Buttons\\WHITE8x8")
    drawerHighlight:SetVertexColor(0.25, 0.25, 0.3, 0.3)

    local drawerAccent = drawer:CreateTexture(nil, "OVERLAY")
    drawerAccent:SetHeight(2)
    drawerAccent:SetPoint("BOTTOMLEFT", 6, 1)
    drawerAccent:SetPoint("BOTTOMRIGHT", -6, 1)
    drawerAccent:SetTexture("Interface\\Buttons\\WHITE8x8")
    drawerAccent:SetVertexColor(C.classColor.r, C.classColor.g, C.classColor.b, 0.6)

    local interfaceBtns = {}
    local btnSize = 32
    local btnSpacing = 38

    for i, btnData in ipairs(INTERFACE_BUTTONS) do
        local b = CreateFrame("Button", nil, drawer)
        b:SetSize(btnSize, btnSize)
        b:SetPoint("RIGHT", drawer, "RIGHT", -8 - ((i-1) * btnSpacing), 0)

        local btnBg = b:CreateTexture(nil, "BACKGROUND")
        btnBg:SetAllPoints()
        btnBg:SetTexture("Interface\\Buttons\\WHITE8x8")
        btnBg:SetVertexColor(0.1, 0.1, 0.12, 0.7)
        b.btnBg = btnBg

        local btnBorder = CreateFrame("Frame", nil, b, "BackdropTemplate")
        btnBorder:SetAllPoints()
        btnBorder:SetBackdrop({edgeFile = "Interface\\Buttons\\WHITE8x8", edgeSize = 1})
        btnBorder:SetBackdropBorderColor(0.2, 0.2, 0.24, 1)
        btnBorder:SetFrameLevel(b:GetFrameLevel() + 1)
        b.btnBorder = btnBorder

        local bIcon = b:CreateTexture(nil, "ARTWORK")
        bIcon:SetPoint("TOPLEFT", 2, -2)
        bIcon:SetPoint("BOTTOMRIGHT", -2, 2)
        bIcon:SetTexCoord(0.08, 0.92, 0.08, 0.92)
        b.bIcon = bIcon

        if btnData.icon == "DynamicHousing" then
            bIcon:SetTexture(4622467)
            b:SetScript("OnShow", function(self)
                local housingBtn = _G["HousingMicroButton"]
                if housingBtn and housingBtn.GetNormalTexture then
                    local normal = housingBtn:GetNormalTexture()
                    if normal then
                        local atlas = normal:GetAtlas()
                        if atlas then
                            self.bIcon:SetAtlas(atlas)
                        else
                            local texture = normal:GetTexture()
                            if texture then
                                self.bIcon:SetTexture(texture)
                            end
                        end
                    end
                end
            end)
        else
            bIcon:SetTexture(btnData.icon)
        end

        local hl = b:CreateTexture(nil, "HIGHLIGHT")
        hl:SetAllPoints()
        hl:SetTexture("Interface\\Buttons\\WHITE8x8")
        hl:SetVertexColor(1, 1, 1, 0.12)
        hl:SetBlendMode("ADD")

        b:SetScript("OnEnter", function(self)
            if btnData.icon == "DynamicHousing" and self:GetScript("OnShow") then
                self:GetScript("OnShow")(self)
            end

            self.btnBorder:SetBackdropBorderColor(C.classColor.r, C.classColor.g, C.classColor.b, 0.7)
            self.btnBg:SetVertexColor(0.12, 0.12, 0.15, 0.85)
            GameTooltip:SetOwner(self, "ANCHOR_TOP")
            GameTooltip:SetText(btnData.tooltip)
            GameTooltip:Show()
        end)
        b:SetScript("OnLeave", function(self)
            self.btnBorder:SetBackdropBorderColor(0.2, 0.2, 0.24, 1)
            self.btnBg:SetVertexColor(0.1, 0.1, 0.12, 0.7)
            GameTooltip:Hide()
        end)

        b:SetScript("OnClick", btnData.onClick)
        table.insert(interfaceBtns, b)
    end

    local drawerWidth = (#INTERFACE_BUTTONS * btnSpacing) + 16

    drawer.targetWidth = 1
    drawer.targetAlpha = 0
    local hoverTimer = 0

    local function UpdateSlide(self, elapsed)
        if self:IsMouseOver() or dockFrame:IsMouseOver() then
            hoverTimer = 0
            self.targetWidth = drawerWidth
            self.targetAlpha = 1
            dockFrame.bgFrame:SetBackdropBorderColor(C.classColor.r * 0.7, C.classColor.g * 0.7, C.classColor.b * 0.7, 1)
        else
            hoverTimer = hoverTimer + elapsed
        end

        if hoverTimer > 0.2 then
            self.targetWidth = 1
            self.targetAlpha = 0
            dockFrame.bgFrame:SetBackdropBorderColor(0.18, 0.18, 0.22, 1)
        end

        local speed = math.min(14 * elapsed, 0.6)

        local curW = self:GetWidth()
        local diffW = self.targetWidth - curW
        if math.abs(diffW) < 0.5 then
            self:SetWidth(self.targetWidth)
        else
            self:SetWidth(curW + (diffW * speed))
        end

        local curA = self:GetAlpha()
        local diffA = self.targetAlpha - curA
        if math.abs(diffA) < 0.01 then
            self:SetAlpha(self.targetAlpha)
            if self.targetAlpha <= 0 and self.targetWidth <= 1 then self:Hide() end
        else
            self:SetAlpha(curA + (diffA * speed))
        end
    end
    drawer:SetScript("OnUpdate", UpdateSlide)

    dockFrame:SetScript("OnEnter", function(self)
        drawer:Show()
        GameTooltip:SetOwner(self, "ANCHOR_TOP")
        GameTooltip:SetText("Game Menu")
        GameTooltip:Show()
    end)

    dockFrame:SetScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)

    interfaceDockRef = dockFrame
    _G.MidnightUI_InterfaceMenuDock = dockFrame
    ApplyInterfaceMenuSettings()
    return dockFrame
end


local function BuildInterfaceMenuOverlaySettings(content)
    if not _G.MidnightUI_CreateOverlayBuilder then return end
    local s = EnsureInterfaceMenuSettings()
    local b = _G.MidnightUI_CreateOverlayBuilder(content, { startY = -6 })

    b:Header("Game Menu")
    b:Checkbox("Enable Game Menu Button", s.enabled ~= false, function(v)
        s.enabled = (v and true or false)
        ApplyInterfaceMenuSettings()
    end)
    b:Slider("Scale %", 50, 200, 5, ClampNumber(s.scale, 50, 200, 100), function(v)
        s.scale = math.floor(v)
        ApplyInterfaceMenuSettings()
    end)

    return b:Height()
end

if _G.MidnightUI_RegisterOverlaySettings then
    _G.MidnightUI_RegisterOverlaySettings("InterfaceMenu", { title = "Game Menu", build = BuildInterfaceMenuOverlaySettings })
end

do
    local MR = _G.MidnightUI_MoverRegistry
    if MR and MR.DefineMover then
        MR.DefineMover("InterfaceMenu", {
            resolveFrame = function() return _G.MidnightUI_InterfaceMenuDock end,
            defaultPosition = "BOTTOMRIGHT,UIParent,BOTTOMRIGHT,-36.11,96.67",
            category = "world", label = "Game Menu",
            externalOverlay = true,
        })
    end
end


MidnightInterface:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_LOGIN" then
        CreateInterfaceDock()
        ApplyInterfaceMenuSettings()

        local imEnabled = not (MidnightUISettings and MidnightUISettings.InterfaceMenu and MidnightUISettings.InterfaceMenu.enabled == false)

        if imEnabled and QueueStatusButton then
            QueueStatusButton:SetParent(UIParent)

            local function GetSavedQSBPos()
                if MidnightUISettings and MidnightUISettings.InterfaceMenu
                   and MidnightUISettings.InterfaceMenu.queueStatusPosition then
                    local p = MidnightUISettings.InterfaceMenu.queueStatusPosition
                    if type(p) == "table" and p[1] and p[2] and p[3] and p[4] then
                        return p[1], p[2], p[3], p[4]
                    end
                end
                return "BOTTOMRIGHT", "BOTTOMRIGHT", -40, 147
            end

            local function SaveQSBPos()
                if not MidnightUISettings then MidnightUISettings = {} end
                if not MidnightUISettings.InterfaceMenu then MidnightUISettings.InterfaceMenu = {} end
                local point, _, relativePoint, xOfs, yOfs = QueueStatusButton:GetPoint()
                if point and relativePoint and xOfs and yOfs then
                    MidnightUISettings.InterfaceMenu.queueStatusPosition = { point, relativePoint, xOfs, yOfs }
                end
            end

            QueueStatusButton:SetMovable(true)
            QueueStatusButton:SetClampedToScreen(true)
            QueueStatusButton:RegisterForDrag("LeftButton")
            QueueStatusButton._muiDragging = false

            local function ForceQueueButtonPosition()
                if QueueStatusButton.moving then return end
                if QueueStatusButton._muiDragging then return end
                QueueStatusButton.moving = true

                local point, relativePoint, xOfs, yOfs = GetSavedQSBPos()
                QueueStatusButton:ClearAllPoints()
                QueueStatusButton:SetPoint(point, UIParent, relativePoint, xOfs, yOfs)
                QueueStatusButton:SetFrameLevel(20)

                QueueStatusButton.moving = false
            end

            ForceQueueButtonPosition()

            hooksecurefunc(QueueStatusButton, "SetPoint", ForceQueueButtonPosition)

            C_Timer.After(1, ForceQueueButtonPosition)

            QueueStatusButton:HookScript("OnDragStart", function(self)
                self._muiDragging = true
                self:StartMoving()
            end)
            QueueStatusButton:HookScript("OnDragStop", function(self)
                self:StopMovingOrSizing()
                SaveQSBPos()
                self._muiDragging = false
                ForceQueueButtonPosition()
            end)
        end

        if imEnabled and MicroMenuContainer then
            MicroMenuContainer:SetAlpha(0)
            MicroMenuContainer:SetScale(0.001)
            MicroMenuContainer:EnableMouse(true)
            if MainMenuMicroButton then
                MainMenuMicroButton:EnableMouse(true)
            end
        elseif imEnabled and MicroMenu then
            MicroMenu:SetAlpha(0)
            MicroMenu:SetScale(0.001)
            MicroMenu:EnableMouse(true)
            if MainMenuMicroButton then
                MainMenuMicroButton:EnableMouse(true)
            end
        end

        if imEnabled then
            local function EnsureMicroMenuMouseEnabled()
                if MicroMenuContainer then
                    if not MicroMenuContainer:IsMouseEnabled() then
                        MicroMenuContainer:EnableMouse(true)
                    end
                elseif MicroMenu then
                    if not MicroMenu:IsMouseEnabled() then
                        MicroMenu:EnableMouse(true)
                    end
                end
                if MainMenuMicroButton and not MainMenuMicroButton:IsMouseEnabled() then
                    MainMenuMicroButton:EnableMouse(true)
                end
            end

            EnsureMicroMenuMouseEnabled()
            C_Timer.NewTicker(0.5, EnsureMicroMenuMouseEnabled, 10)

            if MicroMenuContainer and hooksecurefunc then
                hooksecurefunc(MicroMenuContainer, "EnableMouse", function(self, enabled)
                    if enabled == false then
                        self:EnableMouse(true)
                    end
                end)
            elseif MicroMenu and hooksecurefunc then
                hooksecurefunc(MicroMenu, "EnableMouse", function(self, enabled)
                    if enabled == false then
                        self:EnableMouse(true)
                    end
                end)
            end
            if MainMenuMicroButton and hooksecurefunc then
                hooksecurefunc(MainMenuMicroButton, "EnableMouse", function(self, enabled)
                    if enabled == false then
                        self:EnableMouse(true)
                    end
                end)
            end
        end
    elseif event == "PLAYER_REGEN_ENABLED" then
        if pendingInterfaceMenuApply then
            ApplyInterfaceMenuSettings()
        else
            self:UnregisterEvent("PLAYER_REGEN_ENABLED")
        end
    end
end)
