local addonName, BFL = ...
local L = BFL.L

local StreamerMode = {}
BFL.StreamerMode = StreamerMode
BFL.Modules["StreamerMode"] = StreamerMode

function StreamerMode:Initialize()
	-- Enable Streamer Mode if DB has it active (defaults handled in Database.lua)
	self:UpdateState()

	-- Find the XML button
	if BetterFriendsFrame and BetterFriendsFrame.StreamerModeButton then
		self.toggleButton = BetterFriendsFrame.StreamerModeButton
	end

	self:UpdateState()

	-- Defensively re-apply header text after any FRIENDLIST_UPDATE.
	-- Blizzard's own BNet handlers reset the header to the real BattleTag
	-- whenever friend data changes (e.g. Note Cleanup Wizard batch operations).
	BFL:RegisterEventCallback("FRIENDLIST_UPDATE", function()
		if not StreamerMode:IsActive() then
			return
		end
		if
			BetterFriendsFrame
			and BetterFriendsFrame.FriendsTabHeader
			and BetterFriendsFrame.FriendsTabHeader.BattlenetFrame
		then
			local header = BetterFriendsFrame.FriendsTabHeader.BattlenetFrame.Tag
			if header and header:GetText() ~= BetterFriendlistDB.streamerModeHeaderText then
				header:SetText(BetterFriendlistDB.streamerModeHeaderText)
			end
		end
	end, 100) -- UI priority: runs after data handlers
end

function StreamerMode:Toggle()
	BetterFriendlistDB.streamerModeActive = not BetterFriendlistDB.streamerModeActive
	self:UpdateState()

	-- Refresh Friends List to update names
	if BFL.ForceRefreshFriendsList then
		BFL:ForceRefreshFriendsList()
	end

	-- Refresh QuickJoin List to update names (Streamer Mode Toggled)
	local QuickJoin = BFL:GetModule("QuickJoin")
	if QuickJoin then
		QuickJoin:Update(true)
	end

	-- Refresh tooltip if mouse is currently hovering over the button
	if self.toggleButton and BFL_Tooltip:GetOwner() == self.toggleButton then
		BFL_Tooltip:SetOwner(self.toggleButton, "ANCHOR_RIGHT")
		BFL_Tooltip:SetText(L.STREAMER_MODE_TITLE or "Streamer Mode", 1, 1, 1)
		local status = BetterFriendlistDB.streamerModeActive and (L.STATUS_ENABLED or "Enabled")
			or (L.STATUS_DISABLED or "Disabled")
		BFL_Tooltip:AddLine(L.STREAMER_MODE_BUTTON_DESC or "Click to toggle privacy mode.", 0.7, 0.7, 0.7, true)
		BFL_Tooltip:AddLine(status, 1, 1, 1)
		BFL_Tooltip:Show()
	end

	-- Print status
	if BetterFriendlistDB.streamerModeActive then
		-- BFL:DebugPrint(L.STREAMER_MODE_TITLE .. ": " .. (L.STATUS_ENABLED or "Enabled"))
	else
		-- BFL:DebugPrint(L.STREAMER_MODE_TITLE .. ": " .. (L.STATUS_DISABLED or "Disabled"))
	end
end

function StreamerMode:IsActive()
	return BetterFriendlistDB and BetterFriendlistDB.streamerModeActive
end

function StreamerMode:UpdateAdjacentButtonAnchors()
	-- Re-anchor HelpButton when StreamerModeButton is hidden/shown
	if not BetterFriendsFrame then
		return
	end

	local helpButton = BetterFriendsFrame.HelpButton
	if helpButton then
		helpButton:ClearAllPoints()
		if BetterFriendlistDB.showStreamerModeButton == false then
			-- StreamerModeButton hidden: anchor HelpButton directly to CloseButton
			if BFL.IsClassic then
				helpButton:SetPoint("RIGHT", BetterFriendsFrame.CloseButton, "LEFT", -4, 0)
			else
				helpButton:SetPoint("TOPRIGHT", BetterFriendsFrame.CloseButton, "TOPLEFT", 1, 1)
			end
		else
			-- StreamerModeButton visible: anchor to StreamerModeButton (default)
			if BFL.IsClassic then
				helpButton:SetPoint("RIGHT", self.toggleButton, "LEFT", -1, 0)
			else
				helpButton:SetPoint("TOPRIGHT", self.toggleButton, "TOPLEFT", 0, 0)
			end
		end
	end
end

function StreamerMode:UpdateState()
	if not self.toggleButton then
		-- Try to find it again (if loaded late)
		if BetterFriendsFrame and BetterFriendsFrame.StreamerModeButton then
			self.toggleButton = BetterFriendsFrame.StreamerModeButton
		else
			return
		end
	end

	-- Check Visibility Setting
	if not BetterFriendlistDB.showStreamerModeButton then
		-- Auto-disable Streamer Mode if button is hidden
		if BetterFriendlistDB.streamerModeActive then
			BetterFriendlistDB.streamerModeActive = false
			-- Restore original header if it was changed
			if
				self.originalHeaderText
				and BetterFriendsFrame
				and BetterFriendsFrame.FriendsTabHeader
				and BetterFriendsFrame.FriendsTabHeader.BattlenetFrame
			then
				local header = BetterFriendsFrame.FriendsTabHeader.BattlenetFrame.Tag
				if header then
					header:SetText(self.originalHeaderText)
				end
			end
			-- Update friends list to remove privacy filtering
			local FriendsList = BFL:GetModule("FriendsList")
			if FriendsList and FriendsList.Update then
				FriendsList:Update()
			end
		end
		self.toggleButton:Hide()
		self:UpdateAdjacentButtonAnchors()
		return
	else
		self.toggleButton:Show()
	end

	self:UpdateAdjacentButtonAnchors()

	if self:IsActive() then
		-- Privacy ON -> Twitch Purple (Active)
		self.toggleButton.Icon:SetTexture("Interface\\AddOns\\BetterFriendlist\\Icons\\twitch")
		self.toggleButton.Icon:SetDesaturated(true) -- Desaturate to remove native icon color (likely gold/orange)
		self.toggleButton.Icon:SetVertexColor(0.64, 0.33, 1.0) -- Twitch Purple
		self.toggleButton.Icon:SetAlpha(1.0)

		-- Update Header Text if parent frame exists
		if
			BetterFriendsFrame
			and BetterFriendsFrame.FriendsTabHeader
			and BetterFriendsFrame.FriendsTabHeader.BattlenetFrame
		then
			local battlenetFrame = BetterFriendsFrame.FriendsTabHeader.BattlenetFrame
			local header = battlenetFrame.Tag
			if header then
				-- Don't store original text if we just set it ourselves previously
				if header:GetText() ~= BetterFriendlistDB.streamerModeHeaderText then
					self.originalHeaderText = header:GetText()
				end
				header:SetText(BetterFriendlistDB.streamerModeHeaderText)
			end
		end
	else
		-- Privacy OFF -> Gray (Inactive)
		self.toggleButton.Icon:SetTexture("Interface\\AddOns\\BetterFriendlist\\Icons\\twitch")
		self.toggleButton.Icon:SetDesaturated(true) -- Force Grayscale
		self.toggleButton.Icon:SetVertexColor(1, 1, 1) -- White vertex + Desaturated = Pure Gray
		self.toggleButton.Icon:SetAlpha(0.7)

		-- Restore Header Text & Color
		if
			BetterFriendsFrame
			and BetterFriendsFrame.FriendsTabHeader
			and BetterFriendsFrame.FriendsTabHeader.BattlenetFrame
		then
			local battlenetFrame = BetterFriendsFrame.FriendsTabHeader.BattlenetFrame
			local header = battlenetFrame.Tag

			if header then
				-- Always restore from BNGetInfo as primary source
				local restored = false
				if BNGetInfo then
					local _, battleTag = BNGetInfo()
					if battleTag then
						header:SetText(battleTag)
						restored = true
					end
				end
				-- Fallback to stored original text if BNGetInfo unavailable
				if
					not restored
					and self.originalHeaderText
					and self.originalHeaderText ~= BetterFriendlistDB.streamerModeHeaderText
				then
					header:SetText(self.originalHeaderText)
				end
			end
		end
	end
end
