local addonName, L = ...

local ICON_TEXTURE = "Interface\\AddOns\\Lustomizer\\assets\\icon"
local OVERVIEW_LOGO_TEXTURE = "Interface\\AddOns\\Lustomizer\\assets\\overview-logo"
local FALLBACK_ICON_TEXTURE = "Interface\\Icons\\INV_Misc_QuestionMark"

local LibDataBroker = LibStub and LibStub("LibDataBroker-1.1", true)
local LibDBIcon = LibStub and LibStub("LibDBIcon-1.0", true)

L.launcher = L.launcher or {
    object = nil,
    initialized = false,
}

local MINIMAP_MENU_ITEMS = {
    { text = "Overview", handler = "OpenMainSettingsCategory" },
    { text = "Bloodlust Sound/TTS", handler = "OpenTabbedSettingsCategory", tabId = "bl_sound", isEnabled = function() return L:GetDB().enableBloodlustAlerts ~= false end },
    { text = "Bloodlust Image", handler = "OpenTabbedSettingsCategory", tabId = "bl_image", isEnabled = function() return L:GetDB().enableBloodlustAlerts ~= false end },
    { text = "Bloodlust Text", handler = "OpenTabbedSettingsCategory", tabId = "bl_text", isEnabled = function() return L:GetDB().enableBloodlustAlerts ~= false end },
    { text = "PI Settings", handler = "OpenTabbedSettingsCategory", tabId = "pi_settings", isEnabled = function() return L:GetDB().enableExperimentalPI == true end },
    { text = "PI Sound/TTS", handler = "OpenTabbedSettingsCategory", tabId = "pi_sound", isEnabled = function() return L:GetDB().enableExperimentalPI == true end },
    { text = "PI Image", handler = "OpenTabbedSettingsCategory", tabId = "pi_image", isEnabled = function() return L:GetDB().enableExperimentalPI == true end },
    { text = "PI Text", handler = "OpenTabbedSettingsCategory", tabId = "pi_text", isEnabled = function() return L:GetDB().enableExperimentalPI == true end },
}

function L:GetAddonIconTexture()
    return ICON_TEXTURE or FALLBACK_ICON_TEXTURE
end

function L:GetOverviewLogoTexture()
    return OVERVIEW_LOGO_TEXTURE or self:GetAddonIconTexture()
end

local function GetMinimapSettings()
    local db = L:GetDB()
    if type(db) ~= "table" then
        return nil
    end

    if type(db.minimapIcon) ~= "table" then
        db.minimapIcon = {}
    end

    return db.minimapIcon
end

local function RefreshCompartmentState(settings)
    if not LibDBIcon then
        return
    end

    -- Keep the minimap icon and the modern addon compartment in sync from the same
    -- saved-variable toggle so the launcher only has one source of truth.
    if settings.showInCompartment then
        LibDBIcon:AddButtonToCompartment(addonName, L:GetAddonIconTexture())
    else
        LibDBIcon:RemoveButtonFromCompartment(addonName)
    end
end

function L:RefreshLauncherIcon()
    local settings = GetMinimapSettings()
    if not settings or not LibDBIcon or not LibDBIcon:IsRegistered(addonName) then
        return
    end

    LibDBIcon:Refresh(addonName, settings)
    RefreshCompartmentState(settings)
end

function L:SetMinimapIconHidden(hidden)
    local settings = GetMinimapSettings()
    if not settings then
        return
    end

    settings.hide = hidden == true
    self:RefreshLauncherIcon()
end

function L:IsMinimapIconHidden()
    local settings = GetMinimapSettings()
    if not settings then
        return false
    end

    return settings.hide == true
end

function L:ToggleMinimapIcon()
    local settings = GetMinimapSettings()
    if not settings then
        return false
    end

    self:SetMinimapIconHidden(not settings.hide)
    return not settings.hide
end

function L:OpenLauncherContextMenu(ownerRegion)
    if not ownerRegion or not MenuUtil or type(MenuUtil.CreateContextMenu) ~= "function" then
        -- Fall back gracefully on clients/UI states where the context menu helpers
        -- are unavailable instead of leaving right-click without any action.
        self:OpenMainSettingsCategory()
        return
    end

    MenuUtil.CreateContextMenu(ownerRegion, function(_ownerRegion, rootDescription)
        rootDescription:CreateTitle("Lustomizer")

        for _, item in ipairs(MINIMAP_MENU_ITEMS) do
            local isEnabled = true
            if type(item.isEnabled) == "function" then
                isEnabled = item.isEnabled() ~= false
            end

            local button = rootDescription:CreateButton(item.text, function()
                if not isEnabled then
                    return
                end

                -- Route every launcher entry back through the existing settings
                -- openers so the minimap menu never grows its own navigation logic.
                if item.handler == "OpenTabbedSettingsCategory" then
                    self:OpenTabbedSettingsCategory(item.tabId)
                    return
                end

                if type(self[item.handler]) == "function" then
                    self[item.handler](self)
                end
            end)
            button:SetEnabled(isEnabled)
        end
    end)
end

function L:InitializeLauncher()
    if self.launcher.initialized then
        self:RefreshLauncherIcon()
        return
    end

    if not LibDataBroker or not LibDBIcon then
        return
    end

    local settings = GetMinimapSettings()
    if not settings then
        return
    end

    -- The launcher is created lazily after SavedVariables are available so icon
    -- visibility/position come straight from the persisted minimap settings.
    local dataObject = LibDataBroker:NewDataObject(addonName, {
        type = "launcher",
        text = addonName,
        icon = self:GetAddonIconTexture(),
        OnClick = function(frame, button)
            if button == "RightButton" then
                self:OpenLauncherContextMenu(frame)
                return
            end

            self:OpenMainSettingsCategory()
        end,
        OnTooltipShow = function(tooltip)
            tooltip:AddLine("Lustomizer")
            tooltip:AddLine(" ")
            tooltip:AddLine("Left-click: Open settings", 1, 1, 1)
            tooltip:AddLine("Right-click: Open settings menu", 1, 1, 1)
        end,
    })

    self.launcher.object = dataObject
    LibDBIcon:Register(addonName, dataObject, settings, self:GetAddonIconTexture())
    RefreshCompartmentState(settings)
    self.launcher.initialized = true
end
