local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local PlayerGui = localPlayer:WaitForChild("PlayerGui")
local MainMenuGui = PlayerGui:WaitForChild("MainMenuGui")
local MainFrame = MainMenuGui:WaitForChild("MainFrame")
local Animation = MainFrame:WaitForChild("Animation")
local Searchbar = Animation:WaitForChild("Searchbar")
local AnimAPI = ReplicatedStorage:WaitForChild("LocalScriptAPI")
local AnimSpeedRemote = AnimAPI.AnimSpeed
local Char = localPlayer.Character or localPlayer.CharacterAdded:Wait()

-- Variable to track the currently playing animation
local currentAnimationButton = nil

-- Function to play the animation
local function playAnimation(animName)
	print("Playing animation: " .. animName)
	AnimAPI.PlayAnimation:InvokeServer(animName, Char)
end

-- Function to stop the animation
local function stopAnimation()
	print("Stopping current animation.")
	AnimAPI.StopAnimationOnHumanoid:FireServer(Char.Humanoid)
end

-- Function to handle button clicks
local function onButtonClick(button)
	local animName = button.Name

	-- Check if the button is the currently playing one
	if currentAnimationButton == button then
		print("Button " .. animName .. " clicked again, stopping animation.")
		stopAnimation()
		currentAnimationButton = nil
	else
		-- Stop the currently playing animation if any
		if currentAnimationButton then
			stopAnimation()
		end

		print("Button " .. animName .. " clicked, starting animation.")
		playAnimation(animName)
		currentAnimationButton = button
	end
end

local All_List = Animation:WaitForChild("All_List")

local categories = {
	{name = "Male", template = ReplicatedStorage:WaitForChild("ButtonTemplates"):WaitForChild("MaleTemplate"), 
		list = Animation:WaitForChild("Men_List")},
	{name = "Female", template = ReplicatedStorage:WaitForChild("ButtonTemplates"):WaitForChild("FemaleTemplate"), 
		list = Animation:WaitForChild("Women_List")},
	{name = "ThreePlus", template = ReplicatedStorage:WaitForChild("ButtonTemplates"):WaitForChild("ThreePlusTemplate"), 
		list = Animation:WaitForChild("Plus_List")},
	{name = "Emote", template = ReplicatedStorage:WaitForChild("ButtonTemplates"):WaitForChild("EmoteTemplate"), 
		list = Animation:WaitForChild("Emote_List")}
}

local function hideAllLists()
	for _, category in categories do
		category.list.Visible = false
	end
	All_List.Visible = false
end

local function showList(list)
	hideAllLists()
	list.Visible = true
end

local function setupButtons(categoryName, animNames)
	local category = nil
	for _, cat in categories do
		if cat.name == categoryName then
			category = cat
			break
		end
	end

	if category then
		for _, animName in pairs(animNames) do
			local button = category.template:Clone()
			button.Name = animName
			button.Text = animName

			if categoryName == "ThreePlus" then
				local gender = button:GetAttribute("Gender")
				if not gender or gender == "" then
					warn("Warning! 3+ animation '" .. animName .. "' has no or empty 'Gender' attribute!")
				else
					if gender == "M" then
						button.TextColor3 = Color3.fromRGB(170, 170, 255)
					elseif gender == "F" then
						button.TextColor3 = Color3.fromRGB(255, 185, 255)
					end
				end
			end

			button.Parent = category.list

			-- Connect the click event to the button
			button.MouseButton1Click:Connect(function()
				onButtonClick(button)
			end)

			local allButton = button:Clone()
			allButton.Parent = All_List

			-- Connect the click event to the allButton
			allButton.MouseButton1Click:Connect(function()
				onButtonClick(allButton)
			end)
		end
	end
end

local getAnimationsFunction = ReplicatedStorage:WaitForChild("RemoteFunctions"):WaitForChild("GetAnimations")
local animationsData = getAnimationsFunction:InvokeServer("animation")

for categoryName, animNames in pairs(animationsData) do
	setupButtons(categoryName, animNames)
end

local TitleLabel = script.Parent:WaitForChild("TitleLabel")
local buttons = {
	["+"] = {TitleLabel:WaitForChild("+"), function() showList(Animation:WaitForChild("Plus_List")) end},
	["ALL"] = {TitleLabel:WaitForChild("ALL"), function() showList(All_List) end},
	["E"] = {TitleLabel:WaitForChild("E"), function() showList(Animation:WaitForChild("Emote_List")) end},
	["M"] = {TitleLabel:WaitForChild("M"), function() showList(Animation:WaitForChild("Men_List")) end},
	["W"] = {TitleLabel:WaitForChild("W"), function() showList(Animation:WaitForChild("Women_List")) end}
}

for _, buttonInfo in buttons do
	local button, callback = unpack(buttonInfo)
	button.MouseButton1Click:Connect(callback)
end

local function filterAnimations(query)
	local lowerQuery = query:lower()
	for _, category in categories do
		for _, button in pairs(category.list:GetChildren()) do
			if button:IsA("GuiButton") then
				button.Visible = button.Name:lower():find(lowerQuery) ~= nil
			end
		end
	end

	for _, button in pairs(All_List:GetChildren()) do
		if button:IsA("GuiButton") then
			button.Visible = button.Name:lower():find(lowerQuery) ~= nil
		end
	end
end

Searchbar:GetPropertyChangedSignal("Text"):Connect(function()
	filterAnimations(Searchbar.Text)
end)


ensue that the animation stops when a button is clicked while the animation is performing, whetever it's the same button or a different one. it doesn't matter if the same button is clicked again in order to stop! it could be any button!