import { useContext } from "react";
import { VideoPlayerContext } from "../VideoPlayer";
import { ChevronUpDownIcon } from "@heroicons/react/24/solid";
import { PlaybackSpeed } from "../type";

export default function Speed() {
	const {
		setIsSpeedOpen,
		isSpeedOpen,
		playbackSpeed,
		setPlaybackSpeed,
		videoRef,
	} = useContext(VideoPlayerContext);
	return (
		<>
			<div className="relative flex items-center">
				<button
					onClick={() => setIsSpeedOpen(!isSpeedOpen)}
					className="text-white hover:text-primaryHover flex items-center">
					<span className="text-xl font-bold mr-1">
						{playbackSpeed === 1.0 ? "倍速" : `${playbackSpeed}x`}
					</span>
					<ChevronUpDownIcon className="w-10 h-10" />
				</button>
				{isSpeedOpen && (
					<div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2">
						<div className="bg-black/80 rounded-lg p-2">
							<div className="flex flex-col gap-1">
								{[0.5, 0.75, 1.0, 1.25, 1.5, 2.0].map(
									(speed) => (
										<button
											key={speed}
											onClick={() => {
												setPlaybackSpeed(
													speed as PlaybackSpeed
												);
												if (videoRef.current) {
													videoRef.current.playbackRate =
														speed;
												}
												setIsSpeedOpen(false);
											}}
											className={`px-2 py-1 text-lg whitespace-nowrap ${
												playbackSpeed === speed
													? "text-primaryHover font-bold"
													: "text-white hover:text-primaryHover"
											}`}>
											{speed}x
										</button>
									)
								)}
							</div>
						</div>
					</div>
				)}
			</div>
		</>
	);
}
