-- QuizClientScript
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")

-- RemoteEvents
local StartQuizEvent = ReplicatedStorage:WaitForChild("StartQuizEvent")
local AnswerSelectedEvent = ReplicatedStorage:WaitForChild("AnswerSelectedEvent")
local UpdateQuestionEvent = ReplicatedStorage:WaitForChild("UpdateQuestionEvent")

-- Reference to the NPC and its ProximityPrompt
local npc = workspace:WaitForChild("Level 1")
local proximityPrompt = npc:WaitForChild("HumanoidRootPart"):WaitForChild("ProximityPrompt")

-- After your other variables, add:
local playerTable = workspace:WaitForChild("PlayerTable")
local answerPart = playerTable:WaitForChild("Answer")
local answerSurfaceGui = answerPart:WaitForChild("SurfaceGui")
local answerLabel = answerSurfaceGui:WaitForChild("TextLabel")

-- GUI References
local npcDialogueGui = playerGui:WaitForChild("NPCDialogue")
local mainGui = playerGui:WaitForChild("MainGui")
local questionFrame = mainGui:WaitForChild("QuestionFrame")
local questionTextLabel = questionFrame:WaitForChild("Question")

npcDialogueGui.Enabled = false

-- Buttons
local acceptButton = npcDialogueGui.Frame:WaitForChild("Accept")
local declineButton = npcDialogueGui.Frame:WaitForChild("Decline")

local answerButtons = {
	questionFrame:WaitForChild("Answer1"),
	questionFrame:WaitForChild("Answer2"),
	questionFrame:WaitForChild("Answer3"),
	questionFrame:WaitForChild("Answer4"),
}

-- Set up answer button clicks
for _, button in ipairs(answerButtons) do
	button.MouseButton1Click:Connect(function()
		local answerText = button:GetAttribute("AnswerText")
		if answerText then
			print("Button clicked:", answerText)
			-- Update the answerLabel with the selected answer text
			answerLabel.Text = answerText
			-- Send the selected answer text to the server
			AnswerSelectedEvent:FireServer(answerText)
		else
			warn("No AnswerText attribute found for button")
		end

		-- Disable all buttons after click
		for _, btn in ipairs(answerButtons) do
			btn.Active = false
		end
	end)
end

-- Function to create typing effect
local function typeText(textLabel, textToType, typingSpeed, callback)
	textLabel.Text = ""
	for i = 1, #textToType do
		textLabel.Text = string.sub(textToType, 1, i)
		wait(typingSpeed)
	end
	if callback then
		callback()
	end
end

-- Update the displayQuestion function to clear the answer text:
local function displayQuestion(questionData)
	mainGui:FindFirstChild("QuestionFrame").Visible = true
	questionFrame.Visible = true

	-- Clear the answer display
	answerLabel.Text = ""

	-- Hide all buttons first and clear previous attributes
	for _, button in ipairs(answerButtons) do
		button.Visible = false
		button.Active = false
		button:SetAttribute("AnswerText", nil) -- Clear any previous AnswerText attributes
	end

	-- Display question with typing effect
	typeText(questionTextLabel, questionData.question, 0.01, function()
		-- After typing is done, show the answer buttons with numbering
		for i, button in ipairs(answerButtons) do
			if questionData.answers[i] then
				-- Store the original answer text without numbering using SetAttribute
				button:SetAttribute("AnswerText", questionData.answers[i])
				-- Set the button text with numbering for display
				button.Text = questionData.answers[i]
				button.Visible = true
				button.Active = true
			else
				button.Visible = false
				button.Active = false
			end
		end
	end)
end

-- Update the UpdateQuestionEvent handler to clear the answer when showing results:
UpdateQuestionEvent.OnClientEvent:Connect(function(data)
	if data.quizFinished then
		mainGui.Enabled = false
		questionFrame.Visible = false
		answerLabel.Text = "" -- Clear answer when quiz finishes
		return
	end

	if data.result then
		-- Show result with typing effect
		for _, button in ipairs(answerButtons) do
			button.Visible = false
		end
		typeText(questionTextLabel, data.result, 0.05)
		-- Don't clear answer text here so player can see their last answer
	else
		-- Show new question
		displayQuestion(data)
	end
end)

-- Handle ProximityPrompt
proximityPrompt.Triggered:Connect(function()
	npcDialogueGui.Enabled = true
	local textLabel = npcDialogueGui.Frame:WaitForChild("Text")

	-- Hide buttons initially
	acceptButton.Visible = false
	declineButton.Visible = false

	-- Show text with typing effect, then show buttons
	typeText(textLabel, "You think you're smart enough to defeat me?!", 0.05, function()
		acceptButton.Visible = true
		declineButton.Visible = true
	end)
end)

-- Handle Accept button
acceptButton.MouseButton1Click:Connect(function()
	npcDialogueGui.Enabled = false
	StartQuizEvent:FireServer()
end)

-- Handle Decline button
declineButton.MouseButton1Click:Connect(function()
	npcDialogueGui.Enabled = false
end) (the NPC has the ability to answer. it's just the same thing as the player. except that. the player has 5 seconds before the NPC can answer. if the player didn't answer in time. it would answer: "Level 1 Is Correct!") -- QuizServerScript (Place in ServerScriptService)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")

-- RemoteEvents
local StartQuizEvent = ReplicatedStorage:WaitForChild("StartQuizEvent")
local AnswerSelectedEvent = ReplicatedStorage:WaitForChild("AnswerSelectedEvent")
local UpdateQuestionEvent = ReplicatedStorage:WaitForChild("UpdateQuestionEvent")

-- Teleport parts
local playerTeleporter = Workspace:WaitForChild("PlayerTeleporter")
local npcTeleporter = Workspace:WaitForChild("NPCTeleporter")

-- Pre-existing NPC
local npc = Workspace:WaitForChild("Level 1")

-- Folder containing fake NPCs to clone
local fakeNPCFolder = ReplicatedStorage:WaitForChild("FakeNPC")

-- Questions data
local questions = {
	{
		question = "What is 1 + 1?",
		correctAnswer = "2",
		wrongAnswers = {"1", "3", "4"},
	},
	{
		question = "What is 4 x 8?",
		correctAnswer = "32",
		wrongAnswers = {"36", "28", "40"},
	},
	{
		question = "What is 4 / 2?",
		correctAnswer = "2",
		wrongAnswers = {"4", "1", "3"},
	},
	{
		question = "What is 16 + 43?",
		correctAnswer = "59",
		wrongAnswers = {"60", "61", "58"},
	},
	{
		question = "What is 81 / 9?",
		correctAnswer = "9",
		wrongAnswers = {"8", "7", "10"},
	},
}

-- Tables to keep track of players
local playerQuizData = {}
local playerCooldowns = {}

-- Function to shuffle answers
local function shuffleTable(t)
	local shuffled = {}
	while #t > 0 do
		local rand = math.random(#t)
		table.insert(shuffled, t[rand])
		table.remove(t, rand)
	end
	return shuffled
end

-- Update sendQuestion function
local function sendQuestion(player)
    local data = playerQuizData[player]
    if not data then return end

    local currentIndex = data.currentQuestionIndex
    if currentIndex > #questions then return end

    -- No need to set or check cooldowns

    local questionData = questions[currentIndex]

    local answers = {questionData.correctAnswer}
    for _, wrongAnswer in ipairs(questionData.wrongAnswers) do
        table.insert(answers, wrongAnswer)
    end
    answers = shuffleTable(answers)

    print("Sending question", currentIndex, "to player", player.Name)

    UpdateQuestionEvent:FireClient(player, {
        question = questionData.question,
        answers = answers,
        currentQuestion = currentIndex,
        totalQuestions = #questions
    })
end

-- Update StartQuizEvent handler
StartQuizEvent.OnServerEvent:Connect(function(player)
	if playerQuizData[player] then return end

	local character = player.Character
	if not character then return end

	local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
	if humanoidRootPart then
		humanoidRootPart.CFrame = playerTeleporter.CFrame
	end

	local npcToClone = fakeNPCFolder:FindFirstChild(npc.Name)
	if not npcToClone then
		warn("NPC model not found in FakeNPC folder")
		return
	end

	local clonedNPC = npcToClone:Clone()
	clonedNPC.Parent = Workspace

	if not clonedNPC.PrimaryPart then
		clonedNPC.PrimaryPart = clonedNPC:FindFirstChild("HumanoidRootPart") or clonedNPC:FindFirstChild("UpperTorso")
	end

	if clonedNPC.PrimaryPart then
		clonedNPC:SetPrimaryPartCFrame(npcTeleporter.CFrame)
	end

	local humanoid = character:FindFirstChild("Humanoid")
	if humanoid then
		humanoid.WalkSpeed = 0
		humanoid.JumpPower = 0
	end

	playerQuizData[player] = {
		currentQuestionIndex = 1,
		npc = clonedNPC,
	}

	playerCooldowns[player] = false

	wait(1)
	sendQuestion(player)
end)

AnswerSelectedEvent.OnServerEvent:Connect(function(player, selectedAnswer)
	print("Received answer from player:", player.Name, "Answer:", selectedAnswer)

	local data = playerQuizData[player]
	if not data then 
		print("No quiz data found for player")
		return 
	end

	local currentIndex = data.currentQuestionIndex
	local questionData = questions[currentIndex]

	local isCorrect = selectedAnswer == questionData.correctAnswer
	local resultText = isCorrect and "Correct!" or "Wrong!"

	print("Sending result to player:", resultText)

	-- Send result to client
	UpdateQuestionEvent:FireClient(player, {
		result = resultText
	})

	wait(2)

	-- Reset the cooldown before sending the next question
	playerCooldowns[player] = false

	-- Move to next question
	data.currentQuestionIndex = data.currentQuestionIndex + 1

	if data.currentQuestionIndex > #questions then
		print("Quiz finished for player:", player.Name)

		-- Re-enable player movement
		local character = player.Character
		if character then
			local humanoid = character:FindFirstChild("Humanoid")
			if humanoid then
				humanoid.WalkSpeed = 16
				humanoid.JumpPower = 50
			end
		end

		-- Clean up
		if data.npc and data.npc.Parent then
			data.npc:Destroy()
		end

		playerQuizData[player] = nil
		playerCooldowns[player] = nil

		-- Send quiz finished notification
		UpdateQuestionEvent:FireClient(player, { quizFinished = true })
	else
		-- Send next question
		sendQuestion(player)
	end
end)

-- Remove playerCooldowns cleanup in PlayerRemoving
Players.PlayerRemoving:Connect(function(player)
	local data = playerQuizData[player]
	if data then
		if data.npc and data.npc.Parent then
			data.npc:Destroy()
		end
		playerQuizData[player] = nil
		playerCooldowns[player] = nil
	end
end)