-- MinimapIcon.lua - BlackBox Minimap Button

local addonName = "BlackBox"
local BlackBox = _G[addonName]

local LDB = LibStub:GetLibrary("LibDataBroker-1.1", true)
local LDBIcon = LibStub:GetLibrary("LibDBIcon-1.0", true)

if not LDB or not LDBIcon then
    print("[BlackBox] Missing LibDataBroker or LibDBIcon. Minimap icon will not load.")
    return
end

-- Debug print helper
local function DebugPrint(...)
    if BlackBoxDB and BlackBoxDB.settings and BlackBoxDB.settings.debugMode then
        print("[BlackBox Debug]", ...)
    end
end

-- Add a variable to track the settings panel state
local isSettingsOpen = false

-- Modify the OpenAddonSettings function
local function OpenAddonSettings()
    DebugPrint("OpenAddonSettings called")
    if not BlackBox.settingsCategoryID then
        DebugPrint("Settings category ID not set. Cannot open BlackBox settings directly.")
        return
    end

    if isSettingsOpen then
        SettingsPanel:Hide() -- Close the settings panel
        isSettingsOpen = false
    else
        Settings.OpenToCategory(BlackBox.settingsCategoryID)
        isSettingsOpen = true
    end
end

-- Hook into the OnHide event of the SettingsPanel to update isSettingsOpen
if SettingsPanel then
    SettingsPanel:HookScript("OnHide", function()
        if isSettingsOpen then
            isSettingsOpen = false
        end
    end)
end

-- Modify the CreateMenu function to add a second option
local function CreateMenu()
    if BlackBoxMenu then
        BlackBoxMenu:Hide()
        BlackBoxMenu:SetParent(nil)
        BlackBoxMenu = nil
    end


    -- Create the main menu frame with a transparent black backdrop and white rounded borders
    BlackBoxMenu = CreateFrame("Frame", "BlackBoxMenu", UIParent, "BackdropTemplate")
    BlackBoxMenu:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", -- Black background texture
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",         -- White border texture
        tile = true,
        tileSize = 16,
        edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 },
    })
    BlackBoxMenu:SetBackdropColor(0, 0, 0, 0.8) -- Transparent black background
    BlackBoxMenu:SetPoint("CENTER") -- Default position (will be updated dynamically)
    BlackBoxMenu:Hide() -- Start hidden

    -- Adjust the height to accommodate four options
    local visibleOptions = 6
    local buttonHeight = 24
    local menuPadding = 30
    BlackBoxMenu:SetSize(100, (visibleOptions * buttonHeight) + menuPadding + 20)

    -- Create the "Crate Down" button (at the top of the menu)
    local crateDownButton = CreateFrame("Button", nil, BlackBoxMenu)
    crateDownButton:SetSize(80, buttonHeight) -- Adjust button size
    crateDownButton:SetPoint("TOP", BlackBoxMenu, "TOP", 0, -5) -- Position the button at the top
    crateDownButton:SetText("Crate Down")
    crateDownButton:SetNormalFontObject("GameFontNormal")
    crateDownButton:SetHighlightFontObject("GameFontHighlight")
    crateDownButton:GetFontString():SetPoint("CENTER")

    -- Update the "Crate Down" button's OnClick behavior
    crateDownButton:SetScript("OnClick", function()
        if waitHereMenu and waitHereMenu:IsShown() then
            waitHereMenu:Hide() -- Close the "Wait Here" menu
        end
    
        local zoneName = GetZoneText() -- Get the current zone name
        local mapID = C_Map.GetBestMapForUnit("player") -- Get the current map ID
        if mapID then
            local position = C_Map.GetPlayerMapPosition(mapID, "player") -- Get player position
            if position then
                local x, y = position:GetXY()
                x = x * 100 -- Convert to percentage
                y = y * 100 -- Convert to percentage
                local message = string.format("Crate Down: %s (%.2f,%.2f)", zoneName, x, y)
                if IsInRaid() then
                    SendChatMessage(message, "RAID") -- Send to raid chat
                elseif IsInGroup() then
                    SendChatMessage(message, "PARTY") -- Send to party chat
                else
                    print(message) -- Print to chat if not in a group
                end
            else
                print("Unable to retrieve player position.")
            end
        else
            print("Unable to retrieve map ID.")
        end
        BlackBoxMenu:Hide() -- Hide the menu after clicking
    end)

    -- Create the "Wait Here" button (below the "Crate Down" button)
    local waitHereButton = CreateFrame("Button", nil, BlackBoxMenu)
    waitHereButton:SetSize(80, buttonHeight) -- Adjust button size
    waitHereButton:SetPoint("TOP", crateDownButton, "BOTTOM", 0, -8) -- Position below the "Crate Down" button
    waitHereButton:SetText("Wait Here")
    waitHereButton:SetNormalFontObject("GameFontNormal")
    waitHereButton:SetHighlightFontObject("GameFontHighlight")
    waitHereButton:GetFontString():SetPoint("CENTER")
    
    -- Update the CreateWaitHereMenu function to change text color on hover
    local function CreateWaitHereMenu()
        local waitHereMenu = CreateFrame("Frame", "WaitHereMenu", UIParent, "BackdropTemplate")
        waitHereMenu:SetBackdrop({
            bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", -- Black background texture
            edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",         -- White border texture
            tile = true,
            tileSize = 16,
            edgeSize = 16,
            insets = { left = 4, right = 4, top = 4, bottom = 4 },
        })
        waitHereMenu:SetBackdropColor(0, 0, 0, 0.8) -- Transparent black background
        waitHereMenu:SetSize(50, 130) -- Narrower menu
        waitHereMenu:Hide() -- Start hidden
    
        -- Zone data
        local zones = {
            { abbr = "AK", name = "Azj-Kahet", coords = "(64.17,74.72)" },
            { abbr = "SI", name = "Siren Isle", coords = "(39.49,52.34)" },
            { abbr = "ID", name = "Isle of Dorn", coords = "(60.60,66.57)" },
            { abbr = "RD", name = "The Ringing Deeps", coords = "(54.10,64.31)" },
            { abbr = "HF", name = "Hallowfall", coords = "(40.72,34.58)" },
            { abbr = "UN", name = "Undermine", coords = "(37.90,50.56)" },
        }
    
        -- Create clickable text for each zone
        for i, zone in ipairs(zones) do
            local text = waitHereMenu:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
            text:SetPoint("TOP", waitHereMenu, "TOP", 0, -10 - (i - 1) * 20) -- Adjust spacing
            text:SetText(zone.abbr)
            text:SetTextColor(1, 0.84, 0) -- Set default color to gold
    
            -- Add hover effect
            text:SetScript("OnEnter", function()
                text:SetTextColor(1, 1, 1) -- White color on hover
            end)
            text:SetScript("OnLeave", function()
                text:SetTextColor(1, 0.84, 0) -- Revert to gold color
            end)
    
            -- Add a click handler to the text
            text:SetScript("OnMouseDown", function()
                local message = string.format("Wait Here: %s %s", zone.name, zone.coords)
                if IsInRaid() then
                    SendChatMessage(message, "RAID")
                elseif IsInGroup() then
                    SendChatMessage(message, "PARTY")
                else
                    print(message) -- Print to chat if not in a group
                end
                waitHereMenu:Hide()
            end)
        end
    
        return waitHereMenu
    end

    -- Example usage: Attach the menu to the "Wait Here" button
    local waitHereMenu = CreateWaitHereMenu()
    waitHereButton:SetScript("OnClick", function()
        waitHereMenu:ClearAllPoints()
        waitHereMenu:SetPoint("RIGHT", BlackBoxMenu, "LEFT", -10, 0)
        waitHereMenu:SetShown(not waitHereMenu:IsShown())

        -- Close the menu automatically after 5 seconds if it is shown
        if waitHereMenu:IsShown() then
            C_Timer.After(5, function()
                if waitHereMenu:IsShown() then
                    DebugPrint("Auto-closing Wait Here menu after 5 seconds.")
                    waitHereMenu:Hide()
                end
            end)
        end
    end)

    -- Attach an OnUpdate script to check for clicks outside the Wait Here menu
    waitHereMenu:SetScript("OnUpdate", function(self, elapsed)
        if IsMouseButtonDown("LeftButton") then
            local cx, cy = GetCursorPosition()
            local scale = UIParent:GetEffectiveScale()
            cx = cx / scale
            cy = cy / scale
            local left, bottom = self:GetLeft(), self:GetBottom()
            local right, top = self:GetRight(), self:GetTop()
            if cx < left or cx > right or cy < bottom or cy > top then
                DebugPrint("Click outside detected — hiding Wait Here menu.")
                self:Hide()
                self:SetScript("OnUpdate", nil) -- Stop checking after hiding
            end
        end
    end)

    -- Adjust the position of the "Spread Out" button to the middle of the menu
    local spreadOutButton = CreateFrame("Button", nil, BlackBoxMenu)
    spreadOutButton:SetSize(80, buttonHeight) -- Adjust button size
    spreadOutButton:SetPoint("TOP", waitHereButton, "BOTTOM", 0, -8) -- Position below the "Wait Here" button
    spreadOutButton:SetText("Spread Out")
    spreadOutButton:SetNormalFontObject("GameFontNormal")
    spreadOutButton:SetHighlightFontObject("GameFontHighlight")
    spreadOutButton:GetFontString():SetPoint("CENTER")

    -- Update the "Spread Out" button's OnClick behavior
    spreadOutButton:SetScript("OnClick", function()
        if waitHereMenu and waitHereMenu:IsShown() then
            waitHereMenu:Hide() -- Close the "Wait Here" menu
        end
    
        local message = "We're Getting New Timers For New Shards, Pick A Zone And Camp It Please."
        if IsInRaid() then
            SendChatMessage(message, "RAID") -- Send to raid chat
        elseif IsInGroup() then
            SendChatMessage(message, "PARTY") -- Send to party chat
        else
            print(message) -- Print to chat if not in a group
        end
        BlackBoxMenu:Hide() -- Hide the menu after clicking
    end)

    -- Create the TimerFrame button (now below the "Spread Out" button)
    local timerButton = CreateFrame("Button", nil, BlackBoxMenu)
    timerButton:SetSize(80, buttonHeight) -- Adjust button size
    timerButton:SetPoint("TOP", spreadOutButton, "BOTTOM", 0, -8) -- Position below the "Spread Out" button
    timerButton:SetText("Timers")
    timerButton:SetNormalFontObject("GameFontNormal")
    timerButton:SetHighlightFontObject("GameFontHighlight")
    timerButton:GetFontString():SetPoint("CENTER")

    -- Update the "Timers" button's OnClick behavior
    timerButton:SetScript("OnClick", function()
        if waitHereMenu and waitHereMenu:IsShown() then
            waitHereMenu:Hide() -- Close the "Wait Here" menu
        end
    
        if TimerFrame and TimerFrame:IsShown() then
            TimerFrame:Hide()
        else
            TimerFrame:Show()
        end
        BlackBoxMenu:Hide() -- Hide the menu after clicking
    end)

    -- Create the LFG button
    local lfgButton = CreateFrame("Button", nil, BlackBoxMenu)
    lfgButton:SetSize(80, buttonHeight)
    lfgButton:SetPoint("TOP", timerButton, "BOTTOM", 0, -8)
    lfgButton:SetText("LFG")
    lfgButton:SetNormalFontObject("GameFontNormal")
    lfgButton:SetHighlightFontObject("GameFontHighlight")
    lfgButton:GetFontString():SetPoint("CENTER")

    -- Create the LFG submenu frame
    local lfgMenu = CreateFrame("Frame", "LFGSubMenu", UIParent, "BackdropTemplate")
    lfgMenu:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true,
        tileSize = 16,
        edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 },
    })
    lfgMenu:SetBackdropColor(0, 0, 0, 0.8)
    lfgMenu:SetSize(100, 55)
    lfgMenu:Hide()

    -- Update "Start Group" button
    local startGroupButton = lfgMenu:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    startGroupButton:SetPoint("TOP", lfgMenu, "TOP", 0, -10)
    startGroupButton:SetText("Start Group")
    startGroupButton:SetTextColor(1, 0.84, 0) -- Gold color by default

    -- Add hover effect for "Start Group" button
    startGroupButton:SetScript("OnEnter", function()
        startGroupButton:SetTextColor(1, 1, 1) -- White on hover
    end)
    startGroupButton:SetScript("OnLeave", function()
        startGroupButton:SetTextColor(1, 0.84, 0) -- Revert to gold
    end)

    -- Add click behavior for "Start Group" button
    startGroupButton:SetScript("OnMouseDown", function()
        TogglePVPUI()
        C_Timer.After(0.3, function()
            if PVPQueueFrameCategoryButton3 then
                PVPQueueFrameCategoryButton3:Click()
                C_Timer.After(0.3, function()
                    for i = 1, LFGListFrame.CategorySelection:GetNumChildren() do
                        local child = select(i, LFGListFrame.CategorySelection:GetChildren())
                        if child and child:IsShown() and child.GetText and child:GetText() == "Custom" then
                            child:Click()
                            C_Timer.After(0.3, function()
                                if LFGListFrame.CategorySelection.StartGroupButton then
                                    LFGListFrame.CategorySelection.StartGroupButton:Click()
                                end
                            end)
                            break
                        end
                    end
                end)
            end
        end)
        lfgMenu:Hide()
        BlackBoxMenu:Hide()
    end)

    -- Update "Find Group" button
    local findGroupButton = lfgMenu:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    findGroupButton:SetPoint("TOP", startGroupButton, "BOTTOM", 0, -10)
    findGroupButton:SetText("Find Group")
    findGroupButton:SetTextColor(1, 0.84, 0) -- Gold color by default

    -- Add hover effect for "Find Group" button
    findGroupButton:SetScript("OnEnter", function()
        findGroupButton:SetTextColor(1, 1, 1) -- White on hover
    end)
    findGroupButton:SetScript("OnLeave", function()
        findGroupButton:SetTextColor(1, 0.84, 0) -- Revert to gold
    end)

    -- Add click behavior for "Find Group" button
    findGroupButton:SetScript("OnMouseDown", function()
        TogglePVPUI()
        C_Timer.After(0.3, function()
            if PVPQueueFrameCategoryButton3 then
                PVPQueueFrameCategoryButton3:Click()
                C_Timer.After(0.3, function()
                    for i = 1, LFGListFrame.CategorySelection:GetNumChildren() do
                        local child = select(i, LFGListFrame.CategorySelection:GetChildren())
                        if child and child:IsShown() and child.GetText and child:GetText() == "Custom" then
                            child:Click()
                            print("BlackBox: Custom category opened. Please click 'Find Group' manually.")
                            break
                        end
                    end
                end)
            end
        end)
        lfgMenu:Hide()
        BlackBoxMenu:Hide()
    end)

    -- Update the "LFG" button's OnClick behavior
    lfgButton:SetScript("OnClick", function()
        if waitHereMenu and waitHereMenu:IsShown() then
            waitHereMenu:Hide() -- Close the "Wait Here" menu
        end
    
        lfgMenu:ClearAllPoints()
        -- Position the LFG menu to the left of the LFG button
        lfgMenu:SetPoint("TOPRIGHT", lfgButton, "TOPLEFT", -10, 0)
        lfgMenu:SetShown(not lfgMenu:IsShown())

        -- Close the LFG menu automatically after 5 seconds if it is shown
        if lfgMenu:IsShown() then
            C_Timer.After(5, function()
                if lfgMenu:IsShown() then
                    DebugPrint("Auto-closing LFG menu after 5 seconds.")
                    lfgMenu:Hide()
                end
            end)
        end
    end)

    -- Attach an OnUpdate script to check for clicks outside the LFG menu
    lfgMenu:SetScript("OnUpdate", function(self, elapsed)
        if IsMouseButtonDown("LeftButton") then
            local cx, cy = GetCursorPosition()
            local scale = UIParent:GetEffectiveScale()
            cx = cx / scale
            cy = cy / scale
            local left, bottom = self:GetLeft(), self:GetBottom()
            local right, top = self:GetRight(), self:GetTop()
            if cx < left or cx > right or cy < bottom or cy > top then
                DebugPrint("Click outside detected — hiding LFG menu.")
                self:Hide()
                self:SetScript("OnUpdate", nil) -- Stop checking after hiding
            end
        end
    end)

    -- Create the Settings button (now below the LFG button)
    local settingsButton = CreateFrame("Button", nil, BlackBoxMenu)
    settingsButton:SetSize(80, buttonHeight) -- Adjust button size
    settingsButton:SetPoint("TOP", lfgButton, "BOTTOM", 0, -8) -- Position below the LFG button
    settingsButton:SetText("Settings")
    settingsButton:SetNormalFontObject("GameFontNormal")
    settingsButton:SetHighlightFontObject("GameFontHighlight")
    settingsButton:GetFontString():SetPoint("CENTER")

    -- Set the Settings button's OnClick behavior
    settingsButton:SetScript("OnClick", function()
        if AddonSettingsFrame and AddonSettingsFrame:IsShown() then
            AddonSettingsFrame:Hide()
        else
            OpenAddonSettings()
        end
        BlackBoxMenu:Hide() -- Hide the menu after clicking
    end)

    -- Remove the OnLeave script and rely on OnUpdate for better behavior
    BlackBoxMenu:SetScript("OnLeave", nil) -- Disable the OnLeave script

    -- Attach an OnUpdate script to check for clicks outside the menu
    BlackBoxMenu:SetScript("OnUpdate", function(self, elapsed)
        if IsMouseButtonDown("LeftButton") then
            local cx, cy = GetCursorPosition()
            local scale = UIParent:GetEffectiveScale()
            cx = cx / scale
            cy = cy / scale
            local left, bottom = self:GetLeft(), self:GetBottom()
            local right, top = self:GetRight(), self:GetTop()
            if cx < left or cx > right or cy < bottom or cy > top then
                DebugPrint("Click outside detected — hiding BlackBoxMenu.")
                self:Hide()
                self:SetScript("OnUpdate", nil) -- Stop checking after hiding
            end
        end
    end)

    DebugPrint("BlackBoxMenu created successfully.")
end

-- Create the DataBroker object for the minimap icon
local dataObject = LDB:NewDataObject(addonName, {
    type = "launcher",
    icon = "Interface\\AddOns\\BlackBox\\conquestIcon.tga",
    
    OnClick = function(self, button)
        DebugPrint("Minimap icon clicked. Button:", button)
        
        if button == "LeftButton" then
            if IsAltKeyDown() then
                DebugPrint("Alt+Left-click detected — opening addon settings.")
                OpenAddonSettings()
            elseif IsControlKeyDown() then
                DebugPrint("Ctrl+Left-click detected — removing all TomTom waypoints.")
                -- Check if TomTom and its configuration are available to auto-confirm removal
                if TomTom and TomTom.db and TomTom.db.profile and 
                   TomTom.db.profile.general and TomTom.db.profile.general.confirmremoveall then
                    DebugPrint("Auto-accepting TomTom remove all confirmation.")
                    StaticPopupDialogs["TOMTOM_REMOVE_ALL_CONFIRM"].OnAccept()
                elseif StaticPopupDialogs and StaticPopupDialogs["TOMTOM_REMOVE_ALL_CONFIRM"] then
                    DebugPrint("Auto-accepting TomTom remove all confirmation (fallback).")
                    StaticPopupDialogs["TOMTOM_REMOVE_ALL_CONFIRM"].OnAccept()
                else
                    DebugPrint("TomTom or its confirmation dialog is not available.")
                end
            else
                DebugPrint("LeftButton clicked — toggling menu...")
                CreateMenu() -- Ensure the menu is created

                -- Position the menu below and to the left of the cursor.
                local x, y = GetCursorPosition()
                local scale = UIParent:GetEffectiveScale()
                BlackBoxMenu:ClearAllPoints()
                -- Anchor the menu's TOPRIGHT to the cursor with a slight offset
                BlackBoxMenu:SetPoint("TOPRIGHT", UIParent, "BOTTOMLEFT", (x / scale) - 10, (y / scale) - 10)

                -- Toggle menu visibility
                if BlackBoxMenu:IsShown() then
                    DebugPrint("Hiding BlackBoxMenu.")
                    BlackBoxMenu:Hide()
                    BlackBoxMenu:SetScript("OnUpdate", nil)
                else
                    DebugPrint("Showing BlackBoxMenu.")
                    BlackBoxMenu:Show()
                    -- Attach an OnUpdate script to check if a click occurred outside the menu.
                    BlackBoxMenu:SetScript("OnUpdate", function(self, elapsed)
                        if IsMouseButtonDown("LeftButton") then
                            local cx, cy = GetCursorPosition()
                            local scale = UIParent:GetEffectiveScale()
                            cx = cx / scale
                            cy = cy / scale
                            local left, bottom = self:GetLeft(), self:GetBottom()
                            local right, top = self:GetRight(), self:GetTop()
                            if cx < left or cx > right or cy < bottom or cy > top then
                                DebugPrint("Click outside detected — hiding BlackBoxMenu.")
                                self:Hide()
                                self:SetScript("OnUpdate", nil)
                            end
                        end
                    end)
                end
            end
        elseif button == "RightButton" then
            DebugPrint("Right-click detected — reloading UI.")
            ReloadUI()
        end
    end,
    
    OnTooltipShow = function(tooltip)
        tooltip:AddLine("|cff00ff00War Supply Crates|r")
        tooltip:AddLine("Alt + Left-click to open and close settings.")
        tooltip:AddLine("|cffffff00Ctrl+Left-click to remove all TomTom waypoints|r")
        tooltip:AddLine("|cffff0000Right-click to reload UI|r")
    end,
})


-- Initialize and register the minimap icon.
local function InitializeMinimapIcon()
    BlackBoxDB = BlackBoxDB or {}
    BlackBoxDB.minimapIcon = BlackBoxDB.minimapIcon or { hide = false, minimapPos = 225 }
    if type(BlackBoxDB.minimapIcon.minimapPos) ~= "number" then
        BlackBoxDB.minimapIcon.minimapPos = 225
    end

    LDBIcon:Register(addonName, dataObject, BlackBoxDB.minimapIcon)
    DebugPrint("Minimap icon registered.")

    local icon = LDBIcon:GetMinimapButton(addonName)
    if icon then
        icon:HookScript("OnDragStop", function(self)
            local mx, my = Minimap:GetCenter()
            local bx, by = self:GetCenter()
            local angle = math.deg(math.atan2(by - my, bx - mx))
            if angle < 0 then angle = angle + 360 end
            BlackBoxDB.minimapIcon.minimapPos = angle
            DebugPrint("Icon moved. New angle:", angle)
        end)
    end
end

local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("ADDON_LOADED")
initFrame:SetScript("OnEvent", function(_, _, loadedAddon)
    if loadedAddon == addonName then
        C_Timer.After(0.5, InitializeMinimapIcon)
    end
end)

