local addonName, RF = ...

-------------------------------------------------------------------------------
-- Minimap Button via LibDBIcon
-------------------------------------------------------------------------------

local function InitMinimapButton()
    local LDB = LibStub and LibStub("LibDataBroker-1.1", true)
    local LDBIcon = LibStub and LibStub("LibDBIcon-1.0", true)

    if not LDB or not LDBIcon then
        return
    end

    local dataObj = LDB:NewDataObject("RosterForge", {
        type = "launcher",
        icon = "Interface\\AddOns\\RosterForge\\Data\\logo",
        label = "RosterForge",

        OnClick = function(self, button)
            if button == "LeftButton" then
                RF:Toggle()
            elseif button == "RightButton" then
                -- Right-click should always land on Settings, never close an
                -- already-open window: RF:Toggle() is a plain show/hide flip,
                -- so calling it unconditionally here would close the window
                -- if it happened to already be open (on any tab).
                if not (RF.mainFrame and RF.mainFrame:IsShown()) then
                    RF:Toggle()
                end
                RF:SwitchTab("Settings")
            end
        end,

        OnTooltipShow = function(tooltip)
            tooltip:AddLine("|cFF3B82F6RosterForge|r")
            tooltip:AddLine("Guild Roster Suite", 0.7, 0.7, 0.7)
            tooltip:AddLine(" ")

            if IsInGuild() then
                local guildName = GetGuildInfo("player")
                if guildName then
                    tooltip:AddLine(guildName, 0.4, 0.8, 1.0)
                end
                local stats = RF:GetRosterStats()
                tooltip:AddLine(format("%d online / %d members", stats.online, stats.total), 0.7, 0.7, 0.7)
            else
                tooltip:AddLine("Not in a guild", 0.5, 0.5, 0.5)
            end

            tooltip:AddLine(" ")
            tooltip:AddLine("|cFFFFFFFFLeft-Click:|r Toggle window", 0.7, 0.7, 0.7)
            tooltip:AddLine("|cFFFFFFFFRight-Click:|r Settings", 0.7, 0.7, 0.7)
        end,
    })

    -- Register with LibDBIcon
    if RF.charDB then
        LDBIcon:Register("RosterForge", dataObj, RF.charDB.minimap)
    end
end

RF:RegisterCallback("ADDON_LOADED", function()
    C_Timer.After(0.5, InitMinimapButton)
end)
