--Attach to character added

local function characterAdded()
	local character = LocalPlayer.Character
	Died = false
	HRP = character:WaitForChild("HumanoidRootPart")
	Humanoid = character:WaitForChild("Humanoid")
	Humanoid:GetPropertyChangedSignal("Sit"):Connect(function()
		if Humanoid.Sit then
			hidePrompt()
		end
	end)
	Humanoid.Died:Connect(function()
		Died = true
		hidePrompt()
	end)
end

LocalPlayer.CharacterAdded:Connect(characterAdded)
if LocalPlayer.Character then
	characterAdded()
end

local function getClosestSeat()
	if HRP and Humanoid then
		if not Humanoid.Sit and not Died then
			local closest = math.huge
			local closestSeat = nil
			local closestModule = nil

			for _, vehicle in pairs(CollectionService:GetTagged("EndorsedVehicle")) do
				local scripts = vehicle:WaitForChild("Scripts")
				local seatingModule = scripts and require(scripts:WaitForChild("LocalVehicleSeating"))
				local seats = seatingModule.GetSeats()

				for _, seat in pairs(seats) do
					local _, seatVisible = Workspace.CurrentCamera:WorldToViewportPoint(seat.Position)
					if seatVisible then
						local dist = (HRP.Position - seat.Position).magnitude
						if dist < closest and dist < MAX_PROMPT_DISTANCE and not seat:FindFirstChild("SeatWeld") then
							closest = dist
							closestSeat = seat
							closestModule = seatingModule
						end
					end
				end
			end

			return closestSeat, closestModule
		end
	end
end

while script.Parent ~= nil do
	local closestSeat, closestModule = getClosestSeat()
	if closestSeat and (not (Humanoid.Sit or Humanoid.PlatformStand)) then
		if closestSeat ~= AdornedSeat then
			hidePrompt()
			AdornedSeat = closestSeat
			AdornedSeatModule = closestModule
			closestModule.ShowPrompt(closestSeat, script.Parent)
		end
	elseif AdornedSeat then
		hidePrompt()
	end
	wait(SEAT_POLL_INTERVAL)
end
