
"use client";

import { useState, useRef, useEffect, type ReactNode } from "react";
import { cn } from "@/lib/utils";

interface StickyPlayerWrapperProps {
  children: ReactNode;
  onVideoEnded?: () => void;
}

export function StickyPlayerWrapper({ children, onVideoEnded }: StickyPlayerWrapperProps) {
  const playerRef = useRef<HTMLDivElement>(null);
  const [isMiniPlayer, setIsMiniPlayer] = useState(false);

  useEffect(() => {
    const mainPlayer = playerRef.current;
    if (!mainPlayer) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        // When the main player is not intersecting (i.e., scrolled out of view),
        // activate the mini player. Otherwise, deactivate it.
        setIsMiniPlayer(!entry.isIntersecting);
      },
      {
        // A threshold of 0 means the callback will trigger as soon as the element
        // is even 1px out of view. A threshold of 1 would mean it has to be fully
        // in view. We check for *not* intersecting, so 0 is what we want.
        threshold: 0,
      }
    );

    observer.observe(mainPlayer);

    return () => {
      observer.unobserve(mainPlayer);
    };
  }, []);

  return (
    <>
      {/* Main Player Container (the observer target) */}
      <div ref={playerRef} className="w-full aspect-video">
        {/* Render the actual player only if it's NOT in mini-player mode to avoid duplication */}
        {!isMiniPlayer && children}
      </div>

      {/* Mini Player */}
      <div
        className={cn(
          "fixed bottom-4 right-4 z-50 w-full max-w-sm aspect-video rounded-lg overflow-hidden shadow-2xl transition-all duration-300 ease-in-out",
          "data-[state=visible]:opacity-100 data-[state=visible]:translate-y-0",
          "data-[state=hidden]:opacity-0 data-[state=hidden]:translate-y-10 data-[state=hidden]:pointer-events-none"
        )}
        data-state={isMiniPlayer ? "visible" : "hidden"}
      >
        {/* Render the actual player here when in mini-player mode */}
        {isMiniPlayer && children}
      </div>
    </>
  );
}

    