"use client";

import { useEffect, useState } from "react";
import { VideoLightbox } from "./VideoLightbox";

/**
 * The home article's CMS body (`dangerouslySetInnerHTML`) still contains raw
 * `.videopart` markup — e.g. the "Avail the Best" section's four video
 * thumbnails (`templates/GAH/scss/homenew.scss` / the article's own `text`
 * field). Those are real DOM nodes with no React tree of their own, so there
 * is nowhere to attach an `onClick`. This mounts once and uses a document-level
 * click listener (event delegation) to catch clicks on any `.videopart`
 * inside the article body and open the same `VideoLightbox` used by
 * `HeroBannerCarousel`, reading the element's own (already-resolved, real)
 * `src`/`data-src` attribute — no separate data-fetch needed.
 */
export function CmsVideoLightboxHydrator() {
  const [videoUrl, setVideoUrl] = useState<string | null>(null);
  const [poster, setPoster] = useState<string | undefined>(undefined);

  useEffect(() => {
    const handleClick = (event: MouseEvent) => {
      const target = (event.target as HTMLElement).closest(".videopart");
      if (!target) return;

      const src = target.getAttribute("src") || target.getAttribute("data-src");
      if (!src) return;

      event.preventDefault();
      const img = target.querySelector("img");
      setPoster(img?.getAttribute("data-src") || img?.getAttribute("src") || undefined);
      setVideoUrl(src);
    };

    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
  }, []);

  if (!videoUrl) return null;
  return <VideoLightbox videoUrl={videoUrl} poster={poster} onClose={() => setVideoUrl(null)} />;
}
