1"use client"
2
3import { useEffect, useState } from "react"
4import { Maximize2, Minimize2, Play } from "lucide-react"
5import { AnimatePresence, motion } from "motion/react"
6
7import { cn } from "@/lib/utils"
8import { Button } from "@/components/ui/button"
9
10interface YouTubePlayerProps {
11 videoId: string
12 title?: string
13 defaultExpanded?: boolean
14 customThumbnail?: string
15
16 // Container & Layout
17 className?: string
18 containerClassName?: string
19 expandedClassName?: string
20
21 // Thumbnail & Media
22 thumbnailClassName?: string
23 thumbnailImageClassName?: string
24
25 // Play Button
26 playButtonClassName?: string
27 playIconClassName?: string
28
29 // Title
30 titleClassName?: string
31
32 // Controls
33 controlsClassName?: string
34 expandButtonClassName?: string
35
36 // Backdrop
37 backdropClassName?: string
38
39 // Player
40 playerClassName?: string
41}
42
43export function YouTubePlayer({
44 videoId,
45 title,
46 defaultExpanded = false,
47 customThumbnail,
48
49 // Styling props
50 className,
51 containerClassName,
52 expandedClassName,
53 thumbnailClassName,
54 thumbnailImageClassName,
55 playButtonClassName,
56 playIconClassName,
57 titleClassName,
58 controlsClassName,
59 expandButtonClassName,
60 backdropClassName,
61 playerClassName,
62}: YouTubePlayerProps) {
63 const [expanded, setExpanded] = useState(defaultExpanded)
64 const [playing, setPlaying] = useState(false)
65 const [isHovered, setIsHovered] = useState(false)
66
67 // Extract video ID from full URL if needed
68 const extractVideoId = (id: string) => {
69 if (id.includes("youtube.com") || id.includes("youtu.be")) {
70 try {
71 const url = new URL(id)
72 if (id.includes("youtube.com")) {
73 return url.searchParams.get("v") || ""
74 } else {
75 return url.pathname.substring(1)
76 }
77 } catch (error) {
78 console.error("Invalid YouTube URL:", error)
79 return id
80 }
81 }
82 return id
83 }
84
85 const actualVideoId = extractVideoId(videoId)
86
87 const handlePlay = () => {
88 setPlaying(true)
89 }
90
91 const toggleExpand = () => {
92 setExpanded(!expanded)
93 }
94
95 // Handle Escape key to minimize when expanded
96 useEffect(() => {
97 const handleKeyDown = (event: KeyboardEvent) => {
98 if (event.key === "Escape" && expanded) {
99 setExpanded(false)
100 }
101 }
102 if (expanded) {
103 document.addEventListener("keydown", handleKeyDown)
104 }
105 return () => {
106 document.removeEventListener("keydown", handleKeyDown)
107 }
108 }, [expanded])
109
110 const getThumbnailUrl = () => {
111 if (customThumbnail) return customThumbnail
112 return actualVideoId
113 ? `https://i.ytimg.com/vi/${actualVideoId}/hqdefault.jpg`
114 : ""
115 }
116
117 return (
118 <>
119 {/* Main container - always in the document flow */}
120 <div
121 className={cn(
122 "relative",
123 expanded ? "invisible" : "visible",
124 className
125 )}
126 >
127 <motion.div
128 layoutId={`youtube-player-${videoId}`}
129 className={cn(
130 "overflow-hidden border bg-card text-card-foreground shadow-lg rounded-xl",
131 containerClassName
132 )}
133 >
134 <motion.div
135 layoutId={`youtube-player-content-${videoId}`}
136 className={cn("relative aspect-video bg-muted", playerClassName)}
137 >
138 {!playing && (
139 <>
140 <motion.div
141 layoutId={`youtube-player-thumbnail-container-${videoId}`}
142 className={cn(
143 "absolute inset-0 bg-gradient-to-br from-muted to-muted/80",
144 thumbnailClassName
145 )}
146 >
147 {getThumbnailUrl() && (
148 <motion.img
149 layoutId={`youtube-player-thumbnail-${videoId}`}
150 src={getThumbnailUrl()}
151 alt={title || "Video thumbnail"}
152 className={cn(
153 "absolute inset-0 h-full w-full object-cover opacity-70",
154 thumbnailImageClassName
155 )}
156 />
157 )}
158 </motion.div>
159
160 <motion.div
161 layoutId={`youtube-player-content-overlay-${videoId}`}
162 className="absolute inset-0 flex flex-col items-center justify-center z-10"
163 >
164 <Button
165 size="lg"
166 variant="secondary"
167 className={cn(
168 "relative h-16 w-16 rounded-full border border-border/20 bg-background/80 backdrop-blur-sm md:h-20 md:w-20 p-0",
169 "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
170 playButtonClassName
171 )}
172 onClick={handlePlay}
173 aria-label="Play video"
174 >
175 <Play
176 className={cn(
177 "h-6 w-6 translate-x-[2px] fill-primary text-primary md:h-8 md:w-8",
178 playIconClassName
179 )}
180 />
181 </Button>
182
183 {title && (
184 <motion.h3
185 layoutId={`youtube-player-title-${videoId}`}
186 className={cn(
187 "mt-4 max-w-xs text-center text-sm font-medium text-secondary/90 md:max-w-md md:text-base",
188 titleClassName
189 )}
190 >
191 {title}
192 </motion.h3>
193 )}
194 </motion.div>
195 </>
196 )}
197
198 {playing && (
199 <iframe
200 src={`https://www.youtube.com/embed/${actualVideoId}?autoplay=1&rel=0&modestbranding=1&iv_load_policy=3&showinfo=0&controls=1`}
201 title={title}
202 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
203 allowFullScreen
204 className="h-full w-full border-0"
205 />
206 )}
207
208 {/* Controls Overlay */}
209 <YouTubePlayerControls
210 videoId={videoId}
211 expanded={expanded}
212 playing={playing}
213 isHovered={isHovered}
214 onToggleExpand={toggleExpand}
215 controlsClassName={controlsClassName}
216 expandButtonClassName={expandButtonClassName}
217 />
218 </motion.div>
219 </motion.div>
220 </div>
221
222 {/* Expanded state - fixed position */}
223 <AnimatePresence>
224 {expanded && (
225 <>
226 <motion.div
227 initial={{ opacity: 0 }}
228 animate={{ opacity: 1 }}
229 exit={{ opacity: 0 }}
230 transition={{ duration: 0.2 }}
231 className={cn(
232 "fixed inset-0 z-40 bg-background/80 backdrop-blur-sm",
233 backdropClassName
234 )}
235 onClick={toggleExpand}
236 aria-label="Close expanded video"
237 />
238
239 <div className="fixed inset-0 z-50 flex items-center justify-center pointer-events-none">
240 <motion.div
241 layoutId={`youtube-player-${videoId}`}
242 className={cn(
243 "overflow-hidden border bg-card text-card-foreground shadow-xl rounded-lg pointer-events-auto",
244 "w-[90vw] max-w-[1200px] max-h-[90vh] aspect-video",
245 expandedClassName
246 )}
247 >
248 <motion.div
249 layoutId={`youtube-player-content-${videoId}`}
250 className={cn(
251 "relative aspect-video bg-muted",
252 playerClassName
253 )}
254 >
255 {!playing && (
256 <>
257 <motion.div
258 layoutId={`youtube-player-thumbnail-container-${videoId}`}
259 className={cn(
260 "absolute inset-0 bg-gradient-to-br from-muted to-muted/80",
261 thumbnailClassName
262 )}
263 >
264 {getThumbnailUrl() && (
265 <motion.img
266 layoutId={`youtube-player-thumbnail-${videoId}`}
267 src={getThumbnailUrl()}
268 alt={title || "Video thumbnail"}
269 className={cn(
270 "absolute inset-0 h-full w-full object-cover opacity-70",
271 thumbnailImageClassName
272 )}
273 />
274 )}
275 </motion.div>
276
277 <motion.div
278 layoutId={`youtube-player-content-overlay-${videoId}`}
279 className="absolute inset-0 flex flex-col items-center justify-center z-10"
280 >
281 <Button
282 size="lg"
283 variant="secondary"
284 className={cn(
285 "relative h-16 w-16 rounded-full border border-border/20 bg-background/80 backdrop-blur-sm md:h-20 md:w-20 p-0",
286 "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
287 playButtonClassName
288 )}
289 onClick={handlePlay}
290 aria-label="Play video"
291 >
292 <Play
293 className={cn(
294 "h-6 w-6 translate-x-[2px] fill-primary text-primary md:h-8 md:w-8",
295 playIconClassName
296 )}
297 />
298 </Button>
299
300 {title && (
301 <motion.h3
302 layoutId={`youtube-player-title-${videoId}`}
303 className={cn(
304 "mt-4 max-w-xs text-center text-sm font-medium text-foreground/90 md:max-w-md md:text-base",
305 titleClassName
306 )}
307 >
308 {title}
309 </motion.h3>
310 )}
311 </motion.div>
312 </>
313 )}
314
315 {playing && (
316 <iframe
317 src={`https://www.youtube.com/embed/${actualVideoId}?autoplay=1&rel=0&modestbranding=1&iv_load_policy=3&showinfo=0&controls=1`}
318 title={title}
319 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
320 allowFullScreen
321 className="h-full w-full border-0"
322 />
323 )}
324
325 {/* Controls Overlay */}
326 <YouTubePlayerControls
327 videoId={videoId}
328 expanded={expanded}
329 playing={playing}
330 isHovered={isHovered}
331 onToggleExpand={toggleExpand}
332 controlsClassName={controlsClassName}
333 expandButtonClassName={expandButtonClassName}
334 />
335 </motion.div>
336 </motion.div>
337 </div>
338 </>
339 )}
340 </AnimatePresence>
341 </>
342 )
343}
344
345// Controls Component
346interface YouTubePlayerControlsProps {
347 videoId: string
348 expanded: boolean
349 playing: boolean
350 isHovered: boolean
351 onToggleExpand: () => void
352 controlsClassName?: string
353 expandButtonClassName?: string
354}
355
356function YouTubePlayerControls({
357 videoId,
358 expanded,
359 playing,
360 isHovered,
361 onToggleExpand,
362 controlsClassName,
363 expandButtonClassName,
364}: YouTubePlayerControlsProps) {
365 const shouldShow = !playing || isHovered || expanded
366
367 return (
368 <AnimatePresence>
369 {shouldShow && (
370 <motion.div
371 layoutId={`youtube-player-controls-${videoId}`}
372 initial={{ opacity: 0 }}
373 animate={{ opacity: 1 }}
374 exit={{ opacity: 0 }}
375 transition={{ duration: 0.2 }}
376 className={cn("absolute right-2 top-2 z-20", controlsClassName)}
377 >
378 <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
379 <Button
380 variant="secondary"
381 size="icon"
382 onClick={onToggleExpand}
383 className={cn(
384 "h-8 w-8 rounded-full bg-background/40 backdrop-blur-sm hover:bg-background/60 focus-visible:ring-ring/50 md:h-9 md:w-9",
385 expandButtonClassName
386 )}
387 aria-label={expanded ? "Minimize video" : "Maximize video"}
388 >
389 <motion.div
390 animate={{ rotate: expanded ? 180 : 0 }}
391 transition={{ type: "spring", stiffness: 300, damping: 20 }}
392 >
393 {expanded ? (
394 <Minimize2 className="h-4 w-4 md:h-5 md:w-5" />
395 ) : (
396 <Maximize2 className="h-4 w-4 md:h-5 md:w-5" />
397 )}
398 </motion.div>
399 </Button>
400 </motion.div>
401 </motion.div>
402 )}
403 </AnimatePresence>
404 )
405}
406
407// Export sub-components for advanced customization
408export { YouTubePlayerControls }
409