1"use client"
2
3/**
4 * HoverVideoPlayer Component
5 *
6 * A React component that plays video on hover/touch with advanced features like:
7 * - Lazy loading and intersection observer support
8 * - Mobile touch support
9 * - Picture-in-Picture
10 * - Custom overlay support
11 * - Thumbnail support
12 * - Playback controls
13 *
14 * @example
15 * ```tsx
16 * <HoverVideoPlayer
17 * videoSrc="/path/to/video.mp4"
18 * thumbnailSrc="/path/to/thumbnail.jpg"
19 * pausedOverlay={<PlayIcon />}
20 * loadingOverlay={<Spinner />}
21 * enableControls
22 * />
23 * ```
24 */
25import React, {
26 createContext,
27 ReactNode,
28 useCallback,
29 useContext,
30 useEffect,
31 useMemo,
32 useRef,
33 useState,
34} from "react"
35import Image from "next/image"
36import { Maximize, Minimize, Pause, Play, Volume2, VolumeX } from "lucide-react"
37import { AnimatePresence, motion } from "motion/react"
38
39import { cn } from "@/lib/utils"
40import { Button } from "@/components/ui/button"
41import { Slider } from "@/components/ui/slider"
42
43// Types
44interface VideoPlayerState {
45 isHovering: boolean
46 isPlaying: boolean
47 isLoading: boolean
48 progress: number
49 muted: boolean
50 volume: number
51 isPiP: boolean
52 isMobile: boolean
53 controlsVisible: boolean
54 showThumbnail: boolean
55 isInView: boolean
56}
57
58interface HoverVideoPlayerProps {
59 videoSrc: string
60 thumbnailSrc?: string
61 hoverOverlay?: React.ReactNode
62 pausedOverlay?: React.ReactNode
63 loadingOverlay?: React.ReactNode
64 playbackStartDelay?: number
65 restartOnPaused?: boolean
66 unloadVideoOnPaused?: boolean
67 playbackRangeStart?: number
68 playbackRangeEnd?: number
69 muted?: boolean
70 loop?: boolean
71 preload?: "auto" | "metadata" | "none"
72 className?: string
73 style?: React.CSSProperties
74 onHoverStart?: () => void
75 onHoverEnd?: () => void
76 enableControls?: boolean
77 cropTop?: number
78 cropBottom?: number
79 isVimeo?: boolean
80}
81
82interface HoverVideoPlayerContextType {
83 isPlaying: boolean
84 isHovering: boolean
85 isLoading: boolean
86 progress: number
87 volume: number
88 muted: boolean
89 isPiP: boolean
90 isMobile: boolean
91 controlsVisible: boolean
92 videoRef: React.RefObject<HTMLVideoElement | null>
93 togglePlay: () => void
94 toggleMute: () => void
95 togglePiP: () => void
96 setVolume: (value: number) => void
97 setProgress: (value: number) => void
98 cropTop: number
99 cropBottom: number
100 thumbnailSrc?: string
101}
102
103interface VimeoPlayer {
104 destroy: () => void
105 ready: () => Promise<void>
106 setVolume: (volume: number) => Promise<void>
107 play: () => Promise<void>
108 pause: () => Promise<void>
109 on: (event: string, callback: (...args: any[]) => void) => void
110 off: (event: string, callback: (...args: any[]) => void) => void
111}
112
113interface VimeoConstructor {
114 Player: {
115 new (element: HTMLElement, options: any): VimeoPlayer
116 }
117}
118
119// Context
120const HoverVideoPlayerContext =
121 createContext<HoverVideoPlayerContextType | null>(null)
122
123/**
124 * Custom hook to access HoverVideoPlayer context
125 * @throws {Error} If used outside of HoverVideoPlayerContext
126 */
127const useHoverVideoPlayer = () => {
128 const context = useContext(HoverVideoPlayerContext)
129 if (!context) {
130 throw new Error(
131 "useHoverVideoPlayer must be used within a HoverVideoPlayer"
132 )
133 }
134 return context
135}
136
137// Add this helper function before the HoverVideoPlayer component
138function debounce<T extends (...args: any[]) => any>(
139 func: T,
140 wait: number
141): {
142 (...args: Parameters<T>): void
143 cancel: () => void
144} {
145 let timeoutId: NodeJS.Timeout | null = null
146
147 const debouncedFn = (...args: Parameters<T>) => {
148 if (timeoutId) clearTimeout(timeoutId)
149 timeoutId = setTimeout(() => func(...args), wait)
150 }
151
152 debouncedFn.cancel = () => {
153 if (timeoutId) {
154 clearTimeout(timeoutId)
155 timeoutId = null
156 }
157 }
158
159 return debouncedFn
160}
161
162// Add this helper function
163function isVimeoUrl(url: string): boolean {
164 return url.includes("player.vimeo.com/video/") || url.includes("vimeo.com/")
165}
166
167// Add this helper function
168function loadVimeoSDK(): Promise<VimeoConstructor> {
169 return new Promise((resolve, reject) => {
170 if ((window as any).Vimeo) {
171 resolve((window as any).Vimeo)
172 return
173 }
174
175 const script = document.createElement("script")
176 script.src = "https://player.vimeo.com/api/player.js"
177 script.async = true
178 script.onload = () => resolve((window as any).Vimeo)
179 script.onerror = reject
180 document.body.appendChild(script)
181 })
182}
183
184// Main Component
185const HoverVideoPlayer: React.FC<HoverVideoPlayerProps> = ({
186 videoSrc,
187 thumbnailSrc,
188 hoverOverlay,
189 pausedOverlay,
190 loadingOverlay,
191 playbackStartDelay = 0,
192 restartOnPaused = false,
193 unloadVideoOnPaused = false,
194 playbackRangeStart,
195 playbackRangeEnd,
196 muted: initialMuted = false,
197 loop = true,
198 preload = "metadata",
199 className,
200 style,
201 onHoverStart,
202 onHoverEnd,
203 enableControls = false,
204 cropTop = 0,
205 cropBottom = 0,
206 isVimeo = false,
207}) => {
208 // Refs for DOM elements and timing
209 const containerRef = useRef<HTMLDivElement>(null)
210 const videoRef = useRef<HTMLVideoElement>(null)
211 const playbackTimeoutRef = useRef<NodeJS.Timeout | null>(null)
212 const lastPlayAttemptRef = useRef<number>(0)
213
214 // Consolidated state management
215 const [state, setState] = useState<VideoPlayerState>({
216 isHovering: false,
217 isPlaying: false,
218 isLoading: false,
219 progress: 0,
220 muted: initialMuted,
221 volume: 1,
222 isPiP: false,
223 isMobile: false,
224 controlsVisible: false,
225 showThumbnail: true,
226 isInView: false,
227 })
228
229 // Mobile detection
230 const checkMobile = useMemo(
231 () =>
232 debounce(() => {
233 setState((prev) => ({ ...prev, isMobile: window.innerWidth <= 768 }))
234 }, 200),
235 []
236 )
237
238 // Event Handlers
239 const handleTouchStart = useCallback(() => {
240 if (state.isMobile) {
241 setState((prev) => ({ ...prev, controlsVisible: !prev.controlsVisible }))
242 }
243 }, [state.isMobile])
244
245 const handleHoverStart = useCallback(() => {
246 if (!state.isMobile) {
247 console.log("Hover start")
248 setState((prev) => ({ ...prev, isHovering: true }))
249 onHoverStart?.()
250 }
251 }, [state.isMobile, onHoverStart])
252
253 const handleHoverEnd = useCallback(() => {
254 if (!state.isMobile) {
255 console.log("Hover end")
256 setState((prev) => ({ ...prev, isHovering: false }))
257 onHoverEnd?.()
258 }
259 }, [state.isMobile, onHoverEnd])
260
261 // Video Playback Controls
262 const playVideo = useCallback(() => {
263 if (!videoRef.current || !state.isInView) {
264 console.log("PlayVideo blocked:", {
265 hasVideo: !!videoRef.current,
266 isInView: state.isInView,
267 })
268 return
269 }
270
271 const video = videoRef.current
272 console.log("Attempting to play video:", {
273 readyState: video.readyState,
274 paused: video.paused,
275 currentSrc: video.currentSrc,
276 })
277
278 // Reset loading state when attempting to play
279 setState((prev) => ({ ...prev, isLoading: true }))
280
281 // Ensure video is ready to play
282 const attemptPlay = () => {
283 video
284 .play()
285 .then(() => {
286 console.log("Video play success")
287 setState((prev) => ({
288 ...prev,
289 isLoading: false,
290 isPlaying: true,
291 showThumbnail: false,
292 }))
293 })
294 .catch((error) => {
295 console.log("Video play error:", error.name)
296 if (error.name === "NotAllowedError") {
297 // User interaction required - show thumbnail
298 setState((prev) => ({
299 ...prev,
300 isLoading: false,
301 showThumbnail: true,
302 }))
303 } else if (error.name !== "AbortError") {
304 console.error("HoverVideoPlayer: Playback error:", error)
305 setState((prev) => ({
306 ...prev,
307 isLoading: false,
308 showThumbnail: true,
309 }))
310 }
311 })
312 }
313
314 if (video.readyState >= 3) {
315 console.log("Video ready, attempting immediate play")
316 attemptPlay()
317 } else {
318 console.log("Video not ready, waiting for canplay event")
319 const handleCanPlay = () => {
320 console.log("Canplay event fired")
321 video.removeEventListener("canplay", handleCanPlay)
322 attemptPlay()
323 }
324 video.addEventListener("canplay", handleCanPlay)
325 }
326 }, [state.isInView])
327
328 const pauseVideo = useCallback(() => {
329 if (!videoRef.current) return
330
331 videoRef.current.pause()
332 setState((prev) => ({
333 ...prev,
334 isPlaying: false,
335 showThumbnail: true,
336 }))
337
338 if (restartOnPaused) {
339 videoRef.current.currentTime = playbackRangeStart || 0
340 }
341 }, [restartOnPaused, playbackRangeStart])
342
343 // Effects
344
345 // Mobile detection effect
346 useEffect(() => {
347 checkMobile()
348 window.addEventListener("resize", checkMobile)
349 return () => {
350 window.removeEventListener("resize", checkMobile)
351 checkMobile.cancel()
352 }
353 }, [checkMobile])
354
355 // Intersection Observer effect
356 useEffect(() => {
357 const observer = new IntersectionObserver(
358 (entries) => {
359 entries.forEach((entry) => {
360 const isNowInView = entry.isIntersecting
361 setState((prev) => ({ ...prev, isInView: isNowInView }))
362
363 if (!isNowInView) {
364 pauseVideo()
365 }
366 })
367 },
368 {
369 root: null,
370 rootMargin: "50px",
371 threshold: 0.1,
372 }
373 )
374
375 if (containerRef.current) {
376 observer.observe(containerRef.current)
377 }
378
379 return () => observer.disconnect()
380 }, [pauseVideo])
381
382 // Video event handlers effect
383 useEffect(() => {
384 const video = videoRef.current
385 if (!video || !state.isInView) return
386
387 const handlers = {
388 loadstart: () => {
389 console.log("Video loadstart")
390 setState((prev) => ({ ...prev, isLoading: true }))
391 },
392 loadeddata: () => {
393 console.log("Video loadeddata", {
394 readyState: video.readyState,
395 duration: video.duration,
396 paused: video.paused,
397 isHovering: state.isHovering,
398 controlsVisible: state.controlsVisible,
399 })
400 setState((prev) => ({ ...prev, isLoading: false }))
401 // Only attempt to play if we're hovering or controls are visible
402 if (state.isHovering || state.controlsVisible) {
403 console.log("Video loaded and hover/controls active, attempting play")
404 playVideo()
405 }
406 },
407 canplay: () => {
408 console.log("Video canplay event")
409 },
410 playing: () => {
411 console.log("Video playing")
412 setState((prev) => ({
413 ...prev,
414 isLoading: false,
415 isPlaying: true,
416 showThumbnail: false,
417 }))
418 },
419 pause: () => {
420 console.log("Video paused")
421 setState((prev) => ({
422 ...prev,
423 isPlaying: false,
424 showThumbnail: true,
425 }))
426 },
427 error: (e: Event) => {
428 const videoError = (e.target as HTMLVideoElement).error
429 console.error("Video error:", {
430 code: videoError?.code,
431 message: videoError?.message,
432 currentSrc: video.currentSrc,
433 })
434 setState((prev) => ({
435 ...prev,
436 isLoading: false,
437 showThumbnail: true,
438 }))
439 },
440 }
441
442 // Add event listeners
443 Object.entries(handlers).forEach(([event, handler]) => {
444 video.addEventListener(event, handler)
445 })
446
447 // Set initial source and load the video
448 if (!video.src) {
449 console.log("Setting video source:", videoSrc)
450 video.src = videoSrc
451 video.load()
452 }
453
454 return () => {
455 Object.entries(handlers).forEach(([event, handler]) => {
456 video.removeEventListener(event, handler)
457 })
458 }
459 }, [
460 state.isInView,
461 state.isHovering,
462 state.controlsVisible,
463 playVideo,
464 videoSrc,
465 ])
466
467 // Playback control effect
468 useEffect(() => {
469 console.log("Playback control effect:", {
470 isInView: state.isInView,
471 isMobile: state.isMobile,
472 controlsVisible: state.controlsVisible,
473 isHovering: state.isHovering,
474 })
475
476 if (!state.isInView) {
477 console.log("Not in view, skipping playback")
478 return
479 }
480
481 let playbackTimeout: NodeJS.Timeout | undefined
482
483 if (state.isMobile) {
484 if (state.controlsVisible) {
485 console.log("Mobile controls visible, playing")
486 playVideo()
487 } else {
488 console.log("Mobile controls hidden, pausing")
489 pauseVideo()
490 }
491 } else if (state.isHovering) {
492 console.log(
493 "Hovering, scheduling playback with delay:",
494 playbackStartDelay
495 )
496 playbackTimeout = setTimeout(() => {
497 console.log("Playback delay completed, attempting to play")
498 playVideo()
499 }, playbackStartDelay)
500 } else {
501 console.log("Not hovering, pausing")
502 pauseVideo()
503 }
504
505 return () => {
506 if (playbackTimeout) {
507 console.log("Clearing playback timeout")
508 clearTimeout(playbackTimeout)
509 }
510 }
511 }, [
512 state.isInView,
513 state.isMobile,
514 state.controlsVisible,
515 state.isHovering,
516 playVideo,
517 pauseVideo,
518 playbackStartDelay,
519 ])
520
521 // Volume effect
522 useEffect(() => {
523 const video = videoRef.current
524 if (!video) return
525
526 video.muted = state.muted
527 video.volume = state.volume
528 }, [state.muted, state.volume])
529
530 // Control handlers
531 const togglePlayPause = useCallback(() => {
532 if (state.isPlaying) {
533 pauseVideo()
534 } else {
535 playVideo()
536 }
537 }, [state.isPlaying, pauseVideo, playVideo])
538
539 const toggleMute = useCallback(() => {
540 setState((prev) => ({ ...prev, muted: !prev.muted }))
541 }, [])
542
543 const togglePiP = useCallback(async () => {
544 if (!document.pictureInPictureEnabled) return
545
546 try {
547 if (document.pictureInPictureElement) {
548 await document.exitPictureInPicture()
549 setState((prev) => ({ ...prev, isPiP: false }))
550 } else if (videoRef.current) {
551 await videoRef.current.requestPictureInPicture()
552 setState((prev) => ({ ...prev, isPiP: true }))
553 }
554 } catch (error) {
555 console.error("PiP error:", error)
556 }
557 }, [])
558
559 // Context value
560 const contextValue = useMemo<HoverVideoPlayerContextType>(
561 () => ({
562 isPlaying: state.isPlaying,
563 isHovering: state.isHovering,
564 isLoading: state.isLoading,
565 progress: state.progress,
566 volume: state.volume,
567 muted: state.muted,
568 isPiP: state.isPiP,
569 isMobile: state.isMobile,
570 controlsVisible: state.controlsVisible,
571 videoRef,
572 togglePlay: togglePlayPause,
573 toggleMute,
574 togglePiP,
575 setVolume: (value) => setState((prev) => ({ ...prev, volume: value })),
576 setProgress: (value) =>
577 setState((prev) => ({ ...prev, progress: value })),
578 cropTop,
579 cropBottom,
580 thumbnailSrc,
581 }),
582 [
583 state,
584 togglePlayPause,
585 toggleMute,
586 togglePiP,
587 cropTop,
588 cropBottom,
589 thumbnailSrc,
590 ]
591 )
592
593 // Render
594 return (
595 <HoverVideoPlayerContext.Provider value={contextValue}>
596 <motion.div
597 ref={containerRef}
598 className={cn(
599 "relative overflow-hidden group cursor-pointer",
600 className
601 )}
602 style={{
603 ...style,
604 paddingTop: `${cropTop}%`,
605 paddingBottom: `${cropBottom}%`,
606 }}
607 onHoverStart={handleHoverStart}
608 onHoverEnd={handleHoverEnd}
609 onTouchStart={handleTouchStart}
610 initial={{ opacity: 0 }}
611 animate={{ opacity: 1 }}
612 exit={{ opacity: 0 }}
613 transition={{ duration: 0.3 }}
614 >
615 {/* Video Element */}
616 {state.isInView && (
617 <HoverVideoPlayerVideo
618 src={videoSrc}
619 unloadVideoOnPaused={unloadVideoOnPaused}
620 loop={loop}
621 preload={preload}
622 />
623 )}
624
625 {/* Thumbnail */}
626 {thumbnailSrc && (state.showThumbnail || !state.isInView) && (
627 <HoverVideoPlayerThumbnail src={thumbnailSrc} />
628 )}
629
630 {/* Overlays */}
631 {pausedOverlay && (
632 <HoverVideoPlayerPausedOverlay>
633 {pausedOverlay}
634 </HoverVideoPlayerPausedOverlay>
635 )}
636 {loadingOverlay && (
637 <HoverVideoPlayerLoadingOverlay>
638 {loadingOverlay}
639 </HoverVideoPlayerLoadingOverlay>
640 )}
641 {hoverOverlay && !state.isMobile && (
642 <HoverVideoPlayerHoverOverlay>
643 {hoverOverlay}
644 </HoverVideoPlayerHoverOverlay>
645 )}
646
647 {/* Controls */}
648 {enableControls && (
649 <HoverVideoPlayerControls>
650 <div className="flex items-center space-x-2">
651 <HoverVideoPlayerPlayPauseButton />
652 <HoverVideoPlayerVolumeControl />
653 <HoverVideoPlayerPiPButton />
654 </div>
655 <HoverVideoPlayerProgressBar />
656 </HoverVideoPlayerControls>
657 )}
658 </motion.div>
659 </HoverVideoPlayerContext.Provider>
660 )
661}
662
663/**
664 * Video component that handles the actual video element
665 */
666const HoverVideoPlayerVideo: React.FC<{
667 src: string
668 unloadVideoOnPaused: boolean
669 loop: boolean
670 preload: string
671}> = ({ src, unloadVideoOnPaused, loop, preload }) => {
672 const { videoRef, muted, cropTop, cropBottom, isHovering } =
673 useHoverVideoPlayer()
674 const isVimeoVideo = isVimeoUrl(src)
675 const containerRef = useRef<HTMLDivElement>(null)
676 const playerRef = useRef<VimeoPlayer | null>(null)
677
678 useEffect(() => {
679 if (!isVimeoVideo || !containerRef.current) return
680
681 const videoId = src.split("/").pop() || ""
682 let player: VimeoPlayer | null = null
683
684 loadVimeoSDK()
685 .then((Vimeo) => {
686 if (!containerRef.current) return
687
688 player = new Vimeo.Player(containerRef.current, {
689 id: videoId,
690 autopause: false,
691 muted,
692 loop,
693 responsive: true,
694 controls: false,
695 autoplay: false,
696 volume: 1,
697 })
698
699 playerRef.current = player
700
701 player.ready().then(() => {
702 console.log("Vimeo video loaded")
703 if (isHovering) {
704 player?.play()
705 }
706 })
707
708 // Add hover effect handlers
709 const handlePlay = () => {
710 if (player && isHovering) {
711 player.play().catch((error) => {
712 console.error("Vimeo play error:", error)
713 })
714 }
715 }
716
717 const handlePause = () => {
718 if (player) {
719 player.pause().catch((error) => {
720 console.error("Vimeo pause error:", error)
721 })
722 }
723 }
724
725 // Watch for hover state changes
726 if (isHovering) {
727 handlePlay()
728 } else {
729 handlePause()
730 }
731
732 player.on("play", () => console.log("Vimeo video playing"))
733 player.on("pause", () => console.log("Vimeo video paused"))
734 player.on("error", (err) => {
735 console.error("Vimeo player error:", err)
736 })
737 })
738 .catch((error) => {
739 console.error("Failed to load Vimeo SDK:", error)
740 })
741
742 return () => {
743 if (player) {
744 player.destroy()
745 playerRef.current = null
746 }
747 }
748 }, [isVimeoVideo, src, muted, loop, isHovering])
749
750 if (isVimeoVideo) {
751 return <div ref={containerRef} className="absolute inset-0" />
752 }
753
754 return (
755 <video
756 ref={videoRef}
757 className={cn("absolute inset-0 w-full h-full object-cover")}
758 style={{
759 top: `-${cropTop}%`,
760 bottom: `-${cropBottom}%`,
761 height: `calc(100% + ${cropTop + cropBottom}%)`,
762 }}
763 muted={muted}
764 loop={loop}
765 preload={preload}
766 playsInline
767 crossOrigin="anonymous"
768 aria-label="Video player"
769 role="application"
770 />
771 )
772}
773
774/**
775 * Thumbnail component shown when video is not playing
776 */
777const HoverVideoPlayerThumbnail: React.FC<{ src: string }> = ({ src }) => {
778 const { cropTop, cropBottom, isHovering, isLoading, isPlaying } =
779 useHoverVideoPlayer()
780
781 // Only show thumbnail when not playing and not hovering, or when loading
782 if ((isPlaying || isHovering) && !isLoading) return null
783
784 return (
785 <div
786 className={cn("absolute inset-0 w-full h-full")}
787 style={{
788 top: `-${cropTop}%`,
789 bottom: `-${cropBottom}%`,
790 height: `calc(100% + ${cropTop + cropBottom}%)`,
791 }}
792 >
793 <Image
794 src={src}
795 alt="Video thumbnail"
796 fill
797 sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
798 className="object-cover"
799 priority
800 />
801 </div>
802 )
803}
804
805/**
806 * Controls overlay with play/pause, volume, and progress bar
807 */
808const HoverVideoPlayerControls: React.FC<{ children: React.ReactNode }> = ({
809 children,
810}) => {
811 const { isHovering, isMobile, controlsVisible } = useHoverVideoPlayer()
812
813 const shouldShowControls = isMobile ? controlsVisible : isHovering
814
815 return (
816 <motion.div
817 className="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black to-transparent"
818 initial={{ opacity: 0, y: 20 }}
819 animate={{
820 opacity: shouldShowControls ? 1 : 0,
821 y: shouldShowControls ? 0 : 20,
822 }}
823 transition={{ duration: 0.3 }}
824 >
825 {children}
826 </motion.div>
827 )
828}
829
830/**
831 * Overlay shown when hovering over the video
832 */
833const HoverVideoPlayerHoverOverlay: React.FC<{ children: React.ReactNode }> = ({
834 children,
835}) => {
836 const { isHovering, isLoading } = useHoverVideoPlayer()
837
838 return (
839 <AnimatePresence>
840 {isHovering && !isLoading && (
841 <motion.div
842 className="absolute inset-0 z-30 flex items-center justify-center"
843 initial={{ opacity: 0 }}
844 animate={{ opacity: 1 }}
845 exit={{ opacity: 0 }}
846 transition={{ duration: 0.3 }}
847 >
848 {children}
849 </motion.div>
850 )}
851 </AnimatePresence>
852 )
853}
854
855/**
856 * Overlay shown when video is paused
857 */
858const HoverVideoPlayerPausedOverlay: React.FC<{
859 children: React.ReactNode
860}> = ({ children }) => {
861 const { isPlaying, isLoading, isHovering } = useHoverVideoPlayer()
862
863 return (
864 <AnimatePresence>
865 {!isPlaying && !isLoading && !isHovering && (
866 <motion.div
867 className="absolute inset-0 z-10 flex items-center justify-center bg-black bg-opacity-50"
868 initial={{ opacity: 0 }}
869 animate={{ opacity: 1 }}
870 exit={{ opacity: 0 }}
871 transition={{ duration: 0.3 }}
872 >
873 {children}
874 </motion.div>
875 )}
876 </AnimatePresence>
877 )
878}
879
880/**
881 * Overlay shown while video is loading
882 */
883const HoverVideoPlayerLoadingOverlay: React.FC<{
884 children: React.ReactNode
885}> = ({ children }) => {
886 const { isLoading } = useHoverVideoPlayer()
887
888 return (
889 <AnimatePresence mode="wait">
890 {isLoading && (
891 <motion.div
892 className="absolute inset-0 z-20 flex items-center justify-center bg-black bg-opacity-50"
893 initial={{ opacity: 0 }}
894 animate={{ opacity: 1 }}
895 exit={{ opacity: 0 }}
896 transition={{ duration: 0.3 }}
897 >
898 {children}
899 </motion.div>
900 )}
901 </AnimatePresence>
902 )
903}
904
905/**
906 * Play/Pause button component
907 */
908const HoverVideoPlayerPlayPauseButton: React.FC = () => {
909 const { isPlaying, togglePlay } = useHoverVideoPlayer()
910
911 return (
912 <Button
913 size="icon"
914 variant="ghost"
915 onClick={togglePlay}
916 className="text-white hover:text-primary-foreground"
917 aria-label={isPlaying ? "Pause video" : "Play video"}
918 >
919 {isPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6" />}
920 </Button>
921 )
922}
923
924/**
925 * Volume control component with mute toggle and volume slider
926 */
927const HoverVideoPlayerVolumeControl: React.FC = () => {
928 const { muted, toggleMute, volume, setVolume } = useHoverVideoPlayer()
929
930 return (
931 <div className="flex items-center space-x-2">
932 <Button
933 size="icon"
934 variant="ghost"
935 onClick={toggleMute}
936 className="text-white hover:text-primary-foreground"
937 aria-label={muted ? "Unmute" : "Mute"}
938 >
939 {muted ? (
940 <VolumeX className="h-6 w-6" />
941 ) : (
942 <Volume2 className="h-6 w-6" />
943 )}
944 </Button>
945 <Slider
946 className="w-24"
947 value={[muted ? 0 : volume * 100]}
948 min={0}
949 max={100}
950 step={1}
951 onValueChange={(value) => setVolume(value[0] / 100)}
952 aria-label="Volume"
953 />
954 </div>
955 )
956}
957
958/**
959 * Progress bar component for video timeline
960 */
961const HoverVideoPlayerProgressBar: React.FC = () => {
962 const { progress, setProgress, videoRef } = useHoverVideoPlayer()
963
964 return (
965 <Slider
966 className="mt-2"
967 value={[progress]}
968 min={0}
969 max={100}
970 step={0.1}
971 onValueChange={(value) => {
972 if (videoRef.current) {
973 const newTime = (value[0] / 100) * videoRef.current.duration
974 videoRef.current.currentTime = newTime
975 setProgress(value[0])
976 }
977 }}
978 aria-label="Video progress"
979 />
980 )
981}
982
983/**
984 * Picture-in-Picture toggle button
985 */
986const HoverVideoPlayerPiPButton: React.FC = () => {
987 const { isPiP, togglePiP } = useHoverVideoPlayer()
988
989 return (
990 <Button
991 size="icon"
992 variant="ghost"
993 onClick={togglePiP}
994 className="text-white hover:text-primary-foreground"
995 aria-label={
996 isPiP ? "Exit picture in picture" : "Enter picture in picture"
997 }
998 >
999 {isPiP ? (
1000 <Minimize className="h-6 w-6" />
1001 ) : (
1002 <Maximize className="h-6 w-6" />
1003 )}
1004 </Button>
1005 )
1006}
1007
1008/**
1009 * Wrapper component for maintaining aspect ratio with padding
1010 */
1011const HoverVideoPaddingWrapper: React.FC<{
1012 width: number
1013 height: number
1014 className?: string
1015 children?: ReactNode
1016}> = ({ width, height, className, children }) => {
1017 return (
1018 <div
1019 style={{ "--width": width, "--height": height } as React.CSSProperties}
1020 className={cn(
1021 className,
1022 "relative aspect-[var(--width)/var(--height)] [--radius:theme(borderRadius.xl)]"
1023 )}
1024 >
1025 <div className="absolute -inset-[var(--padding)] rounded-[calc(var(--radius)+var(--padding))] shadow-sm ring-1 ring-black/5 [--padding:theme(spacing.2)]" />
1026 {children}
1027 </div>
1028 )
1029}
1030
1031// Add display names for better debugging
1032HoverVideoPlayerControls.displayName = "HoverVideoPlayerControls"
1033HoverVideoPaddingWrapper.displayName = "HoverVideoPaddingWrapper"
1034HoverVideoPlayerHoverOverlay.displayName = "HoverVideoPlayerHoverOverlay"
1035HoverVideoPlayerPausedOverlay.displayName = "HoverVideoPlayerPausedOverlay"
1036HoverVideoPlayerLoadingOverlay.displayName = "HoverVideoPlayerLoadingOverlay"
1037HoverVideoPlayerPlayPauseButton.displayName = "HoverVideoPlayerPlayPauseButton"
1038HoverVideoPlayerVolumeControl.displayName = "HoverVideoPlayerVolumeControl"
1039HoverVideoPlayerProgressBar.displayName = "HoverVideoPlayerProgressBar"
1040HoverVideoPlayerPiPButton.displayName = "HoverVideoPlayerPiPButton"
1041
1042export {
1043 HoverVideoPlayer,
1044 HoverVideoPlayerControls,
1045 HoverVideoPlayerHoverOverlay,
1046 HoverVideoPlayerPausedOverlay,
1047 HoverVideoPlayerLoadingOverlay,
1048 HoverVideoPlayerPlayPauseButton,
1049 HoverVideoPlayerVolumeControl,
1050 HoverVideoPlayerProgressBar,
1051 HoverVideoPlayerPiPButton,
1052 HoverVideoPaddingWrapper,
1053}
1054
1055export default HoverVideoPlayer
1056