--[[
	Cerebro - Minimap Button
	Creates a minimap icon for quick access to the main window
]]--

local AddonName, PrivateTable = ...
local Cerebro = LibStub("AceAddon-3.0"):GetAddon(AddonName)

local Minimap = Cerebro:NewModule("Minimap", "AceEvent-3.0")

-- LibDataBroker object
local LDB = nil
local LDBIcon = nil

function Minimap:OnInitialize()
	-- Get library references
	LDB = LibStub("LibDataBroker-1.1", true)
	LDBIcon = LibStub("LibDBIcon-1.0", true)
	
	if not LDB then
		Cerebro:Debug("Minimap: LibDataBroker-1.1 not found")
		return
	end
	
	if not LDBIcon then
		Cerebro:Debug("Minimap: LibDBIcon-1.0 not found")
		return
	end
	
	-- Create the data broker object
	local dataObj = LDB:NewDataObject("Cerebro", {
		type = "launcher",
		icon = "Interface\\AddOns\\" .. (AddonName or "Cerebro") .. "\\Media\\MinimapButton",
		OnClick = function(_, button)
			if button == "LeftButton" then
				self:OnLeftClick()
			elseif button == "RightButton" then
				self:OnRightClick()
			end
		end,
		OnTooltipShow = function(tooltip)
			self:OnTooltipShow(tooltip)
		end,
	})
	
	self.dataObj = dataObj
end

function Minimap:OnEnable()
	if not LDBIcon or not self.dataObj then
		return
	end
	
	-- Register the icon with LibDBIcon using the saved position
	LDBIcon:Register("Cerebro", self.dataObj, Cerebro.db.global.minimap)
	
	Cerebro:Debug("Minimap button registered")
end

function Minimap:OnLeftClick()
	-- Toggle the main Cerebro window
	local UI = Cerebro:GetModule("UI", true)
	if UI then
		UI:Toggle()
	end
end

function Minimap:OnRightClick()
	-- Show a quick status or menu
	Cerebro:Print("Use |cff00ff00/cb|r for commands. Left-click to open main window.")
end

function Minimap:OnTooltipShow(tooltip)
	if not tooltip then return end
	
	tooltip:AddLine("|cff00ccffCerebro|r")
	tooltip:AddLine("EPGP Loot System", 1, 1, 1)
	tooltip:AddLine(" ")
	tooltip:AddLine("|cff00ff00Left-Click|r to open main window", 0.8, 0.8, 0.8)
	tooltip:AddLine("|cff00ff00Right-Click|r for quick help", 0.8, 0.8, 0.8)
	
	-- Show current player PR if available
	local playerName = Cerebro:GetFullPlayerName(UnitName("player"))
	if playerName then
		local Player = Cerebro:GetModule("Player", true)
		if Player and Player.GetPR then
			local pr = Player:GetPR(playerName)
			if pr then
				tooltip:AddLine(" ")
				tooltip:AddLine(string.format("Your PR: |cffffd700%.2f|r", pr), 1, 1, 1)
			end
		end
	end
end

-- Public API for hiding/showing the icon
function Minimap:Hide()
	if LDBIcon then
		LDBIcon:Hide("Cerebro")
		Cerebro.db.global.minimap.hide = true
	end
end

function Minimap:Show()
	if LDBIcon then
		LDBIcon:Show("Cerebro")
		Cerebro.db.global.minimap.hide = false
	end
end

function Minimap:Toggle()
	if Cerebro.db.global.minimap.hide then
		self:Show()
	else
		self:Hide()
	end
end
