local _, ns = ...

------------------------------------------------------------
-- Minimap button via LibDBIcon (works with ElvUI, SexyMap, etc.)
------------------------------------------------------------
local LDB = LibStub("LibDataBroker-1.1")
local DBIcon = LibStub("LibDBIcon-1.0")

local ICON_TEXTURE = "Interface\\AddOns\\YippYappHelper\\icon"

-- Create the data broker object
local dataObject = LDB:NewDataObject("YippYappHelper", {
    type = "launcher",
    text = "YippYapp Helper",
    icon = ICON_TEXTURE,

    OnClick = function(self, button)
        if button == "LeftButton" then
            if ns.ToggleApp then
                ns:ToggleApp()
            elseif ns.ToggleDashboard then
                ns:ToggleDashboard()
            end
        elseif button == "RightButton" then
            if ns.MainFrame then
                if ns.MainFrame:IsShown() then
                    ns.MainFrame:Hide()
                else
                    if ns.RefreshAllSlots then ns:RefreshAllSlots() end
                    if ns.RefreshCrests then ns:RefreshCrests() end
                    if ns.AnchorFrame then ns:AnchorFrame() end
                    ns.MainFrame:Show()
                end
            end
        end
    end,

    OnTooltipShow = function(tooltip)
        tooltip:SetText("|cff00ff00YippYapp Helper|r")
        tooltip:AddLine("Left-click: Open YippYapp", 1, 1, 1)
        tooltip:AddLine("Right-click: Gear Upgrades", 1, 1, 1)
        tooltip:AddLine("Drag to reposition", 0.5, 0.5, 0.5)
    end,
})

-- Register with LibDBIcon on load
local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
initFrame:SetScript("OnEvent", function(self)
    self:UnregisterAllEvents()
    YippYappHelperDB = YippYappHelperDB or {}

    -- Migrate old saved angle to LibDBIcon format
    if YippYappHelperDB.minimapAngle and not YippYappHelperDB.libDBIcon then
        YippYappHelperDB.libDBIcon = {}
    end
    YippYappHelperDB.libDBIcon = YippYappHelperDB.libDBIcon or {}

    -- Migrate old hide setting
    if YippYappHelperDB.hideMinimapButton then
        YippYappHelperDB.libDBIcon.hide = true
        YippYappHelperDB.hideMinimapButton = nil
    end

    DBIcon:Register("YippYappHelper", dataObject, YippYappHelperDB.libDBIcon)

    ns.MinimapButton = DBIcon:GetMinimapButton("YippYappHelper")
end)
