import React, { useContext } from "react";
import { VideoPlayerContext } from "../VideoPlayer";
import { motion } from "framer-motion";

export default function TimeLine() {
	const {
		currentTime,
		duration,
		progressRef,
		setIsDragging,
		videoRef,
		isDragging,
		isHovering,
	} = useContext(VideoPlayerContext);
	const handleProgressClick = (e: React.MouseEvent<HTMLDivElement>) => {
		if (!videoRef.current || !progressRef.current) return;

		const rect = progressRef.current.getBoundingClientRect();
		const percent = (e.clientX - rect.left) / rect.width;
		videoRef.current.currentTime = percent * videoRef.current.duration;
	};
	return (
		<>
			<div
				ref={progressRef}
				className="relative h-1 mb-4 cursor-pointer group"
				onClick={handleProgressClick}
				onMouseDown={(e) => {
					setIsDragging(true);
					handleProgressClick(e);
				}}>
				{/* 背景条 */}
				<div className="absolute w-full h-full bg-gray-500/70 rounded-full" />
				{/* 播放进度 */}
				<motion.div
					className="absolute h-full bg-primary rounded-full"
					style={{
						width: `${(currentTime / duration) * 100}%`,
					}}
					transition={{ type: "tween" }}
				/>
				{/* 进度球 */}
				<motion.div
					className={`z-20 absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-3 h-3 rounded-full bg-primaryHover border-primaryActive border shadow-lg
        ${isHovering || isDragging ? "opacity-100" : "opacity-0 group-hover:opacity-100"}`}
					style={{
						left: `${(currentTime / duration) * 100}%`,
					}}
					transition={{ duration: 0.1 }}
				/>
				{/* 预览进度 */}
				<motion.div
					className="z-10 absolute h-full bg-primary rounded-full opacity-0 group-hover:opacity-100 pointer-events-none"
					style={{
						width: `${(currentTime / duration) * 100}%`,
						transform: "scaleY(2.5)",
						transformOrigin: "center",
					}}
					transition={{ duration: 0.1 }}
				/>
			</div>
		</>
	);
}
