if select(2, ...).IS_LEGACY_CLIENT then return end -- HET-LEGACY-1207: no-op once Legacy1207 is deleted
local addonName, ns = ...
local HET = ns.addon

local ACD = LibStub("AceConfigDialog-3.0")

-------------------------------------------------------------------------------
-- Slash Command
-------------------------------------------------------------------------------
function HET:SetupSlashCommand()
    self:RegisterChatCommand("buzzardauras", "SlashCommand")
    self:RegisterChatCommand("ba", "SlashCommand")
    self:RegisterChatCommand("het", "SlashCommand")
end

function HET:SlashCommand(input)
    input = (input or ""):lower():gsub("^%s+", ""):gsub("%s+$", "")
    -- Combat-error bisection: force-park a subsystem live, no reload.
    -- /het debug slots|groups|sounds  (toggle)   /het debug off (clear)
    local sub = input:match("^debug%s+(%S+)$")
    if sub then
        local d = ns.debugSuppress
        if sub == "off" then
            d.slots, d.groups, d.sounds = false, false, false
        elseif sub == "slots" or sub == "groups" or sub == "sounds" then
            d[sub] = not d[sub]
        else
            self:Print("Usage: /het debug slots|groups|sounds|off")
            return
        end
        self:RefreshTracking()
        self:Print(("suppression — slots:%s groups:%s sounds:%s"):format(
            tostring(d.slots), tostring(d.groups), tostring(d.sounds)))
        return
    end
    self:OpenOptions()
end

function HET:OpenOptions()
    -- Whichever copies of AceGUI / AceConfigDialog ended up winning, make
    -- sure our widget decoration and the :Open hook wrap what is actually
    -- current now — a load-on-demand addon may have replaced either since
    -- we installed them.
    if ns.EnsureUIHooks then ns.EnsureUIHooks() end

    -- Prime the font cache the first time the options panel is opened.
    -- LSM font pickers call FontString:SetFont on each listed font as the
    -- dropdown is built. A font file the client has not loaded yet makes
    -- SetFont fail and the row renders blank; the failed call kicks off the
    -- load, so the second open shows it. Touching every registered font once
    -- here (via a throwaway FontString) forces those loads before any picker
    -- opens, so no rows come up blank. Runs one time, out of combat, and only
    -- if the user actually opens options -- no cost for anyone who never does.
    if not self._fontsPrimed then
        self._fontsPrimed = true
        local LSM = LibStub("LibSharedMedia-3.0", true)
        if LSM then
            local primer = self._fontPrimer
            if not primer then
                primer = UIParent:CreateFontString(nil, "BACKGROUND")
                self._fontPrimer = primer
            end
            for _, path in pairs(LSM:HashTable("font")) do
                primer:SetFont(path, 12, "")
            end
        end
    end

    ACD:Open(addonName)
end

-------------------------------------------------------------------------------
-- Minimap Button (LibDataBroker + LibDBIcon)
-------------------------------------------------------------------------------
function HET:SetupMinimapButton()
    local LDB = LibStub("LibDataBroker-1.1", true)
    local LibDBIcon = LibStub("LibDBIcon-1.0", true)
    if not LDB or not LibDBIcon then return end

    local launcher = LDB:NewDataObject("BuzzardAuras", {
        type  = "launcher",
        label = "Buzzard Auras",
        icon  = "Interface\\AddOns\\BuzzardAuras\\Media\\BuzzardAuras",
        OnClick = function(_, button)
            if button == "LeftButton" then
                local openFrame = ACD.OpenFrames and ACD.OpenFrames[addonName]
                if openFrame and openFrame.frame and openFrame.frame:IsShown() then
                    ACD:Close(addonName)
                else
                    HET:OpenOptions()
                end
            end
        end,
        OnTooltipShow = function(tooltip)
            tooltip:AddLine("|cff11ace9Buzzard Auras|r")
            tooltip:AddLine("Left click to open settings", 0.8, 0.8, 0.8)
        end,
    })

    ns.launcher = launcher
    LibDBIcon:Register("BuzzardAuras", launcher, self.db.global.minimapIcon)
end

-------------------------------------------------------------------------------
-- Addon Compartment (global functions referenced in TOC)
-------------------------------------------------------------------------------
function BuzzardAuras_AddonCompartmentFunc(addonName, menuButton)
    local HET = LibStub("AceAddon-3.0"):GetAddon("BuzzardAuras", true)
    if HET and HET.OpenOptions then HET:OpenOptions() end
end

function BuzzardAuras_AddonCompartmentFuncOnEnter(addonName, menuButton)
    GameTooltip:SetOwner(menuButton, "ANCHOR_LEFT")
    GameTooltip:AddLine("|cff11ace9Buzzard Auras|r", 1, 1, 1, true)
    GameTooltip:AddLine("Click to open the options panel.", 0.8, 0.8, 0.8, true)
    GameTooltip:Show()
end

function BuzzardAuras_AddonCompartmentFuncOnLeave(addonName, menuButton)
    GameTooltip:Hide()
end

-------------------------------------------------------------------------------
-- Blizzard Settings Panel
-------------------------------------------------------------------------------
function HET:SetupBlizzardPanel()
    if not (Settings and Settings.RegisterCanvasLayoutCategory) then return end

    local panel = CreateFrame("Frame")
    panel.name = addonName

    local initialized = false
    panel:SetScript("OnShow", function(self)
        if initialized then return end
        initialized = true

        local title = self:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        title:SetPoint("TOPLEFT", 16, -16)
        title:SetText("|cff11ace9Buzzard Auras|r")

        local desc = self:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
        desc:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -8)
        desc:SetText("Spatial Paradox and Innervate tracker for Healers in Midnight. /het")

        local btn = CreateFrame("Button", nil, self, "UIPanelButtonTemplate")
        btn:SetSize(160, 24)
        btn:SetPoint("TOPLEFT", desc, "BOTTOMLEFT", 0, -16)
        btn:SetText("Open Options")
        btn:SetScript("OnClick", function()
            -- Close Blizzard Settings panel and game menu so the AceConfig
            -- dialog isn't obscured. HideUIPanel is safe; SettingsPanel:Close()
            -- routes through ToggleGameMenu -> SpellStopCasting (protected)
            -- and would trigger ADDON_ACTION_FORBIDDEN.
            if not InCombatLockdown() then
                if SettingsPanel and SettingsPanel:IsShown() then
                    HideUIPanel(SettingsPanel)
                end
                if GameMenuFrame and GameMenuFrame:IsShown() then
                    HideUIPanel(GameMenuFrame)
                end
            end
            HET:OpenOptions()
        end)
    end)

    local category = Settings.RegisterCanvasLayoutCategory(panel, "Buzzard Auras")
    Settings.RegisterAddOnCategory(category)
end

-------------------------------------------------------------------------------
-- Init (called from Core.lua OnInitialize hook)
-------------------------------------------------------------------------------
function HET:SetupUI()
    self:SetupSlashCommand()
    self:SetupMinimapButton()
    self:SetupBlizzardPanel()
end
