-- ============================================================
-- FILE: GroupLootMover.lua
-- MODULE: MidnightUI_GroupLootMover  (_G.MidnightUI_GroupLootMover, local M)
--
-- PURPOSE:
--   Makes the Blizzard group-loot roll window (GroupLootContainer
--   and its GroupLootFrame children) movable via MoverRegistry so
--   players can drag it out of the action-bar area in Movement
--   Mode. Right-click behaviour on the overlay is intentionally
--   suppressed (no per-mover settings panel).
--
-- HOW IT WORKS:
--   1. Creates MidnightUI_GroupLootAnchor, a fixed-size invisible
--      frame roughly the footprint of a single roll window. This
--      anchor is what MoverRegistry drags; GroupLootContainer is
--      re-anchored to it whenever a roll appears.
--   2. Registers the anchor with MoverRegistry under key "GroupLoot".
--      onUnlock shows the anchor (so the drag overlay becomes
--      visible in edit mode); onLock hides it again.
--   3. Hooks GroupLootContainer:Show and START_LOOT_ROLL to
--      ClearAllPoints + SetPoint GroupLootContainer back onto the
--      anchor any time Blizzard re-positions it.
--   4. Removes the right-click handler the overlay picks up from
--      AttachOverlayRightClick, per design request.
--
-- DEPENDS ON:
--   MoverRegistry  — MR.DefineMover, MR.ApplyPosition, MR.GetEntry
--   Blizzard GroupLootContainer / GroupLootFrame_OpenNewFrame
--
-- EXPORTS: _G.MidnightUI_GroupLootMover
-- OWNED SAVEDVARIABLES: none (position lives in MidnightUISettings.movers)
-- EVENTS REGISTERED: START_LOOT_ROLL, PLAYER_ENTERING_WORLD
-- FRAMES CREATED: MidnightUI_GroupLootAnchor
--
-- GOTCHAS:
--   GroupLootContainer is re-anchored by Blizzard on every new
--   roll (inside GroupLootContainer_OpenNewFrame). The hook must
--   run *after* that, so we hook the container:Show method and
--   also listen to START_LOOT_ROLL with a 0-delay C_Timer bounce
--   to land after Blizzard's own handler.
--   Right-click handler is attached inside AttachOverlayRightClick
--   via SetScript("OnMouseUp"). We overwrite it with nil after the
--   overlay is created in the onUnlock callback.
-- ============================================================

local M = _G.MidnightUI_GroupLootMover or {}
_G.MidnightUI_GroupLootMover = M

local CreateFrame = CreateFrame
local UIParent = UIParent
local hooksecurefunc = hooksecurefunc
local C_Timer = C_Timer

local MOVER_KEY = "GroupLoot"
local MOVER_LABEL = "Loot Roll Window"
local DEFAULT_POS = "BOTTOM,UIParent,BOTTOM,0,320"
local ANCHOR_WIDTH = 340
local ANCHOR_HEIGHT = 70
local PREVIEW_DURATION = 20

local anchor = CreateFrame("Frame", "MidnightUI_GroupLootAnchor", UIParent)
anchor:SetSize(ANCHOR_WIDTH, ANCHOR_HEIGHT)
anchor:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, 320)
anchor:Hide()
M.anchor = anchor

local function EnsureGroupLootSettings()
    if not _G.MidnightUISettings then _G.MidnightUISettings = {} end
    if type(_G.MidnightUISettings.GroupLoot) ~= "table" then
        _G.MidnightUISettings.GroupLoot = {}
    end
    local s = _G.MidnightUISettings.GroupLoot
    if type(s.scale) ~= "number" then s.scale = 100 end
    return s
end

local function ApplyGroupLootScale()
    local s = EnsureGroupLootSettings()
    local pct = tonumber(s.scale) or 100
    if pct < 50 then pct = 50 elseif pct > 200 then pct = 200 end
    if anchor and anchor.SetScale then
        pcall(anchor.SetScale, anchor, pct / 100)
    end
    local container = _G.GroupLootContainer
    if container and container.SetScale then
        pcall(container.SetScale, container, pct / 100)
    end
end
_G.MidnightUI_ApplyGroupLootScale = ApplyGroupLootScale
M.ApplyScale = ApplyGroupLootScale

local function ReanchorContainer()
    local container = _G.GroupLootContainer
    if not container or not container.ClearAllPoints then return end
    container:ClearAllPoints()
    container:SetPoint("BOTTOM", anchor, "BOTTOM", 0, 0)
    ApplyGroupLootScale()
end
M.Reanchor = ReanchorContainer

local hooked = false
local function InstallContainerHook()
    if hooked then return end
    local container = _G.GroupLootContainer
    if not container then return end
    hooked = true
    hooksecurefunc(container, "Show", ReanchorContainer)
    hooksecurefunc(container, "SetPoint", function()
        if M._suppressReanchor then return end
        M._suppressReanchor = true
        ReanchorContainer()
        M._suppressReanchor = false
    end)
    ReanchorContainer()
end

local evf = CreateFrame("Frame")
evf:RegisterEvent("PLAYER_ENTERING_WORLD")
evf:RegisterEvent("START_LOOT_ROLL")
evf:SetScript("OnEvent", function(_, event)
    if event == "PLAYER_ENTERING_WORLD" then
        ApplyGroupLootScale()
        C_Timer.After(0.1, InstallContainerHook)
    elseif event == "START_LOOT_ROLL" then
        InstallContainerHook()
        C_Timer.After(0, ReanchorContainer)
    end
end)

-- Mock preview: builds a frame that visually resembles a live
-- group-loot roll window (icon, item name, timer bar, Need/Greed/
-- DE/Pass buttons) so the player can verify positioning without
-- needing a real group/dungeon loot event. Auto-hides after
-- PREVIEW_DURATION seconds or when /muilootroll is run again.
local preview
local previewHideTimer

local function BuildPreview()
    if preview then return preview end
    local p = CreateFrame("Frame", "MidnightUI_GroupLootPreview", anchor, "BackdropTemplate")
    p:SetAllPoints(anchor)
    p:SetFrameStrata("DIALOG")
    p:SetFrameLevel(50)
    p: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 },
    })
    p:SetBackdropColor(0, 0, 0, 0.78)
    p:SetBackdropBorderColor(0.45, 0.45, 0.55, 0.95)

    local iconSize = ANCHOR_HEIGHT - 18
    local icon = p:CreateTexture(nil, "ARTWORK")
    icon:SetSize(iconSize, iconSize)
    icon:SetPoint("LEFT", p, "LEFT", 8, 0)
    icon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
    icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)
    p.icon = icon

    local iconBorder = p:CreateTexture(nil, "OVERLAY")
    iconBorder:SetPoint("TOPLEFT", icon, -1, 1)
    iconBorder:SetPoint("BOTTOMRIGHT", icon, 1, -1)
    iconBorder:SetColorTexture(0.85, 0.72, 0.35, 0.9)

    local iconBg = p:CreateTexture(nil, "BACKGROUND")
    iconBg:SetPoint("TOPLEFT", icon, -1, 1)
    iconBg:SetPoint("BOTTOMRIGHT", icon, 1, -1)
    iconBg:SetColorTexture(0, 0, 0, 1)

    local name = p:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    name:SetPoint("TOPLEFT", icon, "TOPRIGHT", 10, -2)
    name:SetText("|cffa335eeTest Legendary Preview|r")
    p.name = name

    local timer = CreateFrame("StatusBar", nil, p)
    timer:SetPoint("TOPLEFT", name, "BOTTOMLEFT", 0, -4)
    timer:SetPoint("RIGHT", p, "RIGHT", -10, 0)
    timer:SetHeight(6)
    timer:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar")
    timer:SetStatusBarColor(0.25, 0.55, 0.95, 1)
    timer:SetMinMaxValues(0, 1)
    timer:SetValue(0.7)
    p.timer = timer

    local buttonStrip = CreateFrame("Frame", nil, p)
    buttonStrip:SetPoint("TOPLEFT", timer, "BOTTOMLEFT", 0, -4)
    buttonStrip:SetPoint("RIGHT", p, "RIGHT", -10, 0)
    buttonStrip:SetHeight(16)

    local function AddButton(parent, label, r, g, b, order)
        local btn = parent:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        btn:SetText(label)
        btn:SetTextColor(r, g, b)
        btn:SetPoint("LEFT", parent, "LEFT", (order - 1) * 62, 0)
        return btn
    end

    AddButton(buttonStrip, "Need",  0.40, 0.85, 0.40, 1)
    AddButton(buttonStrip, "Greed", 0.90, 0.80, 0.25, 2)
    AddButton(buttonStrip, "DE",    0.60, 0.45, 0.85, 3)
    AddButton(buttonStrip, "Pass",  0.90, 0.35, 0.35, 4)

    p:Hide()
    preview = p
    return p
end

local function HidePreview()
    if preview then preview:Hide() end
    if anchor:IsShown() then
        local s = _G.MidnightUISettings
        local unlocked = s and s.Messenger and s.Messenger.locked == false
        if not unlocked then anchor:Hide() end
    end
    if previewHideTimer and previewHideTimer.Cancel then
        pcall(previewHideTimer.Cancel, previewHideTimer)
    end
    previewHideTimer = nil
end
M.HidePreview = HidePreview

local function ShowPreview()
    BuildPreview()
    anchor:Show()
    preview:Show()
    ReanchorContainer()

    if previewHideTimer and previewHideTimer.Cancel then
        pcall(previewHideTimer.Cancel, previewHideTimer)
    end
    previewHideTimer = C_Timer.NewTimer(PREVIEW_DURATION, HidePreview)
end
M.ShowPreview = ShowPreview

SLASH_MUILOOTROLL1 = "/muilootroll"
SLASH_MUILOOTROLL2 = "/muitestroll"
SlashCmdList["MUILOOTROLL"] = function()
    if preview and preview:IsShown() then
        HidePreview()
    else
        ShowPreview()
    end
end

do
    local MR = _G.MidnightUI_MoverRegistry
    if MR and MR.DefineMover then
        MR.DefineMover(MOVER_KEY, {
            resolveFrame = function() return anchor end,
            defaultPosition = DEFAULT_POS,
            category = "world",
            label = MOVER_LABEL,
            onUnlock = function(frame)
                if frame then frame:Show() end
                local entry = MR.GetEntry and MR.GetEntry(MOVER_KEY)
                if entry and entry.dragOverlay then
                    entry.dragOverlay:SetScript("OnMouseUp", nil)
                end
            end,
            onLock = function(frame)
                if frame then frame:Hide() end
            end,
            onPositionChanged = function()
                ReanchorContainer()
            end,
        })
        if MR.ApplyPosition then MR.ApplyPosition(MOVER_KEY) end
    end
end
