-- 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 return end -- Prevent creating multiple menus

    -- 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 = 5
    local buttonHeight = 24
    local menuPadding = 20
    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")

    -- Set the "Crate Down" button's OnClick behavior
    crateDownButton:SetScript("OnClick", function()
        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 smaller menu to a 6-button layout with simplified button labels
    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, 200) -- Adjust size to fit 6 buttons
        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 buttons for each zone
        local buttonHeight = 25
        for i, zone in ipairs(zones) do
            local button = CreateFrame("Button", nil, waitHereMenu, "UIPanelButtonTemplate")
            button:SetSize(30, buttonHeight)
            button:SetPoint("TOP", waitHereMenu, "TOP", 0, -10 - (i - 1) * (buttonHeight + 5))
            button:SetText(zone.abbr) -- Only display the abbreviation on the button
            button:SetScript("OnClick", 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())
    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")

    -- Set the "Spread Out" button's OnClick behavior
    spreadOutButton:SetScript("OnClick", function()
        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")

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

    -- Create the Settings button (now below the TimerFrame button)
    local settingsButton = CreateFrame("Button", nil, BlackBoxMenu)
    settingsButton:SetSize(80, buttonHeight) -- Adjust button size
    settingsButton:SetPoint("TOP", timerButton, "BOTTOM", 0, -8) -- Position below the TimerFrame 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)

