"use client";

import {
  createContext,
  useContext,
  useRef,
  useMemo,
  type ReactNode,
} from "react";

/* ── Module-level singleton ────────────────────────────────────────────────
   A module variable (not React state) survives StrictMode double-invoke and
   HMR reloads, ensuring exactly one <video> element exists per browser tab.
   The browser never re-initialises the media pipeline when the element is
   moved via appendChild — currentTime, paused, volume, and buffered are all
   preserved automatically without any seek or restart logic.                 */
let _videoSingleton: HTMLVideoElement | null = null;

export function getVideoEl(): HTMLVideoElement | null {
  if (typeof window === "undefined") return null;
  if (!_videoSingleton) {
    const v = document.createElement("video");
    v.playsInline = true;
    v.preload = "metadata";
    Object.assign(v.style, {
      width: "100%",
      height: "100%",
      display: "block",
      objectFit: "contain",
      position: "absolute",
      top: "0",
      left: "0",
    });
    _videoSingleton = v;
  }
  return _videoSingleton;
}

/* ── Context ──────────────────────────────────────────────────────────────── */

interface PersistentPlayerContextValue {
  /**
   * Move the singleton <video> into `container`.
   * Returns a cleanup function that moves it back to the off-screen park div.
   */
  mountVideo: (container: HTMLElement) => () => void;
}

const PersistentPlayerContext = createContext<PersistentPlayerContextValue>({
  mountVideo: () => () => {},
});

export function PersistentPlayerProvider({
  children,
}: {
  children: ReactNode;
}) {
  const parkRef = useRef<HTMLDivElement>(null);

  const value = useMemo<PersistentPlayerContextValue>(
    () => ({
      mountVideo: (container) => {
        const el = getVideoEl();
        if (!el) return () => {};
        container.appendChild(el);
        return () => {
          const park = parkRef.current;
          if (park && el.parentNode !== park) {
            park.appendChild(el);
          }
        };
      },
    }),
    [],
  );

  return (
    <PersistentPlayerContext.Provider value={value}>
      {children}
      {/* Off-screen park: keeps the video element alive between slot mounts.
          position:fixed removes it from layout flow; top/left far off-screen. */}
      <div
        ref={parkRef}
        aria-hidden="true"
        style={{
          position: "fixed",
          top: -10000,
          left: -10000,
          width: 1,
          height: 1,
          overflow: "hidden",
          pointerEvents: "none",
        }}
      />
    </PersistentPlayerContext.Provider>
  );
}

export function usePersistentPlayer(): PersistentPlayerContextValue {
  return useContext(PersistentPlayerContext);
}
