local addon, ns = ...

-- ============================================================
--  rOrbs – Minimap Icon (LibDBIcon) + Slash Commands + Debug
-- ============================================================

local L = ns.L

-- ---- LibDBIcon / LibDataBroker ----
local LDB    = LibStub("LibDataBroker-1.1", true)
local DBIcon = LibStub("LibDBIcon-1.0",     true)

-- ====================================================================
--  MINIMAP ICON
-- ====================================================================

local function RegisterMinimapIcon()
    if not LDB or not DBIcon then return end

    local ldbObj = LDB:NewDataObject("rOrbs", {
        type  = "launcher",
        label = "rOrbs",
        icon  = "Interface\\AddOns\\rOrbs\\media\\d2_skull",
        OnClick = function(clickedFrame, button)
            if button == "LeftButton" then
                -- Open / show settings panel
                if ns.GUI and ns.GUI.Open then
                    ns.GUI:Open()
                else
                    print("|cffff6600rOrbs|r: Settings not loaded yet. Try again in a moment.")
                end
            elseif button == "RightButton" then
                -- Toggle frame lock
                rOrbsDB = rOrbsDB or {}
                rOrbsDB.frameLocked = not rOrbsDB.frameLocked
                ns.cfg.framesLocked = rOrbsDB.frameLocked
                if ns.GUI and ns.GUI.ChatMsg then
                    ns.GUI:ChatMsg(rOrbsDB.frameLocked
                        and L["CHAT_FRAMES_LOCKED"]
                        or  L["CHAT_FRAMES_UNLOCKED"])
                end
            end
        end,
        OnTooltipShow = function(tip)
            if not tip or not tip.AddLine then return end
            tip:AddLine("|cff6699FFrOrbs|r")
            tip:AddLine(L["CMD_RORBS"],       1, 1, 1)
            tip:AddLine(L["CMD_RORBS_LOCK"],  0.8, 0.8, 0.8)
            tip:AddLine("|cffffd700Left-click|r to open settings", 0.7, 0.9, 1)
            tip:AddLine("|cffffd700Right-click|r to toggle frame lock", 0.7, 0.9, 1)
        end,
    })

    -- Register timing for positional saving (Blizzard API requirement)
    rOrbsDB       = rOrbsDB or {}
    rOrbsDB.minimap = rOrbsDB.minimap or { hide = false }

    DBIcon:Register("rOrbs", ldbObj, rOrbsDB.minimap)
    ns.MinimapIcon = DBIcon

    -- Sync initial visibility
    if rOrbsDB.minimap.hide then
        DBIcon:Hide("rOrbs")
    else
        DBIcon:Show("rOrbs")
    end
end

-- ====================================================================
--  SLASH COMMANDS
-- ====================================================================

local function HandleSlashCmd(msg)
    msg = msg and msg:lower():gsub("^%s+", ""):gsub("%s+$", "") or ""

    -- Safety: settings.lua may not have loaded if there was a prior error
    if not ns.GUI then
        print("|cffff6600rOrbs|r: GUI not available. Check for addon errors (/console scriptErrors 1).")
        return
    end

    if msg == "" or msg == "config" or msg == "options" or msg == "settings" then
        ns.GUI:Toggle()

    elseif msg == "show" then
        local frames = {
            _G["rOrbsPlayerFrame"],
            _G["rOrbsTargetHealthFrame"],
            _G["rOrbsTargetFrame"],
        }
        for _, f in ipairs(frames) do
            if f then f:Show() end
        end
        ns.GUI:ChatMsg(L["CHAT_FRAMES_SHOWN"])

    elseif msg == "hide" then
        local frames = {
            _G["rOrbsPlayerFrame"],
            _G["rOrbsTargetHealthFrame"],
            _G["rOrbsTargetFrame"],
        }
        for _, f in ipairs(frames) do
            if f then f:Hide() end
        end
        ns.GUI:ChatMsg(L["CHAT_FRAMES_HIDDEN"])

    elseif msg == "lock" then
        rOrbsDB = rOrbsDB or {}
        rOrbsDB.frameLocked = true
        ns.cfg.framesLocked  = true
        ns.GUI:ChatMsg(L["CHAT_FRAMES_LOCKED"])

    elseif msg == "unlock" then
        rOrbsDB = rOrbsDB or {}
        rOrbsDB.frameLocked = false
        ns.cfg.framesLocked  = false
        ns.GUI:ChatMsg(L["CHAT_FRAMES_UNLOCKED"])

    elseif msg == "debug" then
        rOrbsDB = rOrbsDB or {}
        rOrbsDB.debug = not rOrbsDB.debug
        ns.debug = rOrbsDB.debug
        ns.GUI:ChatMsg(ns.debug and L["CHAT_DEBUG_ON"] or L["CHAT_DEBUG_OFF"])

    elseif msg == "reset" then
        rOrbs_DB_CHAR = nil
        rOrbs_DB_GLOB = nil
        rOrbsDB       = nil
        ns.GUI:ChatMsg(L["CHAT_RESET_DONE"])
        ReloadUI()

    else
        ns.GUI:ChatMsg(L["CHAT_HELP"])
        local commands = {
            L["CMD_RORBS"],
            L["CMD_RORBS_SHOW"],
            L["CMD_RORBS_HIDE"],
            L["CMD_RORBS_LOCK"],
            L["CMD_RORBS_UNLOCK"],
            L["CMD_RORBS_RESET"],
            L["CMD_RORBS_DEBUG"],
        }
        for _, c in ipairs(commands) do
            print("  " .. c)
        end
    end
end

-- Register slash commands
SLASH_RORBS1 = "/rorbs"
SLASH_RORBS2 = "/rorb"
SlashCmdList["RORBS"] = HandleSlashCmd

-- ====================================================================
--  INIT
-- ====================================================================

ns.RegisterInit("rOrbs_Minimap", function()
    rOrbsDB = rOrbsDB or {}
    RegisterMinimapIcon()
end)
