-- SimWishlist_Minimap.lua
-- Minimap button (LibDBIcon for ElvUI button bar) + Blizzard Addon Compartment
-- Falls back to a manual draggable minimap button when libs aren't loaded.

local ADDON_NAME  = "SimWishlist"

-- Custom icon: place a 64x64 .tga (or .blp) in your addon folder as "icon.tga"
-- If the file doesn't exist yet, falls back to a built-in icon.
local ICON_CUSTOM = "Interface\\AddOns\\SimWishlist\\icon.tga"
local ICON_FALLBACK = "Interface\\Icons\\INV_Scroll_11"

-- Pick whichever exists (custom takes priority)
local ICON = ICON_CUSTOM

---------------------------------------------------------------------
-- Safe wrapper – SlashHandler may not exist if main file errored
---------------------------------------------------------------------
local function DoSlash(cmd)
    if SlashHandler then
        SlashHandler(cmd)
    else
        print("|cffff4444SimWishlist:|r Main addon not loaded — try /reload")
    end
end

---------------------------------------------------------------------
-- Blizzard Addon Compartment  (ElvUI > Blizzard Improvements)
-- These must be global functions matching the TOC fields.
---------------------------------------------------------------------
function SimWishlist_Compartment_OnClick(_, _, _, _, button)
    if button == "LeftButton" then
        if IsShiftKeyDown() then
            DoSlash("import")
        else
            DoSlash("")
        end
    elseif button == "RightButton" then
        DoSlash("import")
    end
end

function SimWishlist_Compartment_OnEnter(_, menuButtonFrame)
    GameTooltip:SetOwner(menuButtonFrame, "ANCHOR_LEFT")
    GameTooltip:AddLine("|cffcc88ffSim Wishlist|r")
    GameTooltip:AddLine(" ")
    GameTooltip:AddLine("|cffffffffLeft-click|r  Toggle window", 0.8, 0.8, 0.8)
    GameTooltip:AddLine("|cffffffffRight-click|r  Import data",  0.8, 0.8, 0.8)
    GameTooltip:AddLine("|cffffffffShift-click|r  Import data",  0.8, 0.8, 0.8)
    GameTooltip:Show()
end

function SimWishlist_Compartment_OnLeave()
    GameTooltip:Hide()
end

---------------------------------------------------------------------
-- Path 1: LibDataBroker + LibDBIcon  (ElvUI Minimap Button Bar)
---------------------------------------------------------------------
local function TryLDBIcon()
    if not LibStub then return false end

    local LDB = LibStub:GetLibrary("LibDataBroker-1.1", true)
    if not LDB then return false end

    local LDBIcon = LibStub:GetLibrary("LibDBIcon-1.0", true)
    if not LDBIcon then return false end

    local dataObj = LDB:NewDataObject(ADDON_NAME, {
        type  = "launcher",
        text  = "Sim Wishlist",
        label = "Sim Wishlist",
        icon  = ICON,
        OnClick = function(_, button)
            if button == "LeftButton" then
                if IsShiftKeyDown() then
                    DoSlash("import")
                else
                    DoSlash("")
                end
            elseif button == "RightButton" then
                DoSlash("import")
            end
        end,
        OnTooltipShow = function(tt)
            tt:AddLine("|cffcc88ffSim Wishlist|r")
            tt:AddLine(" ")
            tt:AddLine("|cffffffffLeft-click|r  Toggle window", 0.8, 0.8, 0.8)
            tt:AddLine("|cffffffffRight-click|r  Import data",  0.8, 0.8, 0.8)
            tt:AddLine("|cffffffffShift-click|r  Import data",  0.8, 0.8, 0.8)
        end,
    })

    SimWishlistCharDB = SimWishlistCharDB or {}
    if SimWishlistCharDB.minimap == nil then
        SimWishlistCharDB.minimap = { hide = false }
    end

    LDBIcon:Register(ADDON_NAME, dataObj, SimWishlistCharDB.minimap)
    return true
end

---------------------------------------------------------------------
-- Path 2: Manual minimap button (no lib dependencies)
---------------------------------------------------------------------
local function CreateManualMinimapButton()
    SimWishlistCharDB = SimWishlistCharDB or {}
    SimWishlistCharDB.minimapPos = SimWishlistCharDB.minimapPos or 225

    local btn = CreateFrame("Button", "SimWishlistMinimapButton", Minimap)
    btn:SetSize(32, 32)
    btn:SetFrameStrata("MEDIUM")
    btn:SetFrameLevel(8)
    btn:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
    btn:SetMovable(true)
    btn:RegisterForClicks("AnyUp")
    btn:RegisterForDrag("LeftButton")

    local icon = btn:CreateTexture(nil, "ARTWORK")
    icon:SetTexture(ICON)
    icon:SetSize(20, 20)
    icon:SetPoint("CENTER", 0, 0)
    btn.icon = icon

    local border = btn:CreateTexture(nil, "OVERLAY")
    border:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
    border:SetSize(54, 54)
    border:SetPoint("TOPLEFT", 0, 0)

    local bg = btn:CreateTexture(nil, "BACKGROUND")
    bg:SetTexture("Interface\\Minimap\\UI-Minimap-Background")
    bg:SetSize(24, 24)
    bg:SetPoint("CENTER", 1, 1)

    local function UpdatePosition()
        local angle = math.rad(SimWishlistCharDB.minimapPos or 225)
        local x = math.cos(angle) * 80
        local y = math.sin(angle) * 80
        btn:ClearAllPoints()
        btn:SetPoint("CENTER", Minimap, "CENTER", x, y)
    end

    btn:SetScript("OnDragStart", function(self)
        self:SetScript("OnUpdate", function()
            local mx, my = Minimap:GetCenter()
            local cx, cy = GetCursorPosition()
            local scale   = Minimap:GetEffectiveScale()
            cx, cy = cx / scale, cy / scale
            SimWishlistCharDB.minimapPos = math.deg(math.atan2(cy - my, cx - mx))
            UpdatePosition()
        end)
    end)
    btn:SetScript("OnDragStop", function(self)
        self:SetScript("OnUpdate", nil)
    end)

    btn:SetScript("OnClick", function(_, button)
        if button == "LeftButton" then
            if IsShiftKeyDown() then
                DoSlash("import")
            else
                DoSlash("")
            end
        elseif button == "RightButton" then
            DoSlash("import")
        end
    end)

    btn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:AddLine("|cffcc88ffSim Wishlist|r")
        GameTooltip:AddLine(" ")
        GameTooltip:AddLine("|cffffffffLeft-click|r  Toggle window", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("|cffffffffRight-click|r  Import data",  0.8, 0.8, 0.8)
        GameTooltip:AddLine("|cffffffffShift-click|r  Import data",  0.8, 0.8, 0.8)
        GameTooltip:Show()
    end)
    btn:SetScript("OnLeave", function() GameTooltip:Hide() end)

    UpdatePosition()
    btn:Show()
end

---------------------------------------------------------------------
-- Bootstrap
---------------------------------------------------------------------
local loader = CreateFrame("Frame")
loader:RegisterEvent("PLAYER_LOGIN")
loader:SetScript("OnEvent", function(self)
    self:UnregisterAllEvents()
    C_Timer.After(0.2, function()
        local ok, err = pcall(function()
            if not TryLDBIcon() then
                CreateManualMinimapButton()
            end
        end)
        if not ok then
            print("|cffff4444SimWishlist Minimap ERROR:|r " .. tostring(err))
        end
    end)
end)