// lightbox.jsx — global lightbox triggered by clicking any [data-lb] element.
const { useEffect: _lbE, useState: _lbS } = React;

function Lightbox() {
  const [item, set] = _lbS(null);

  _lbE(() => {
    const onClick = (e) => {
      const el = e.target.closest("[data-lb]");
      if (!el) return;
      // Ignore clicks on real <a>/buttons inside cards
      if (e.target.closest("a, button")) return;
      e.preventDefault();
      const src = el.getAttribute("data-lb");
      const type = el.getAttribute("data-lb-type") || "image";
      const caption = el.getAttribute("data-lb-caption") || "";
      const ratio = el.getAttribute("data-lb-ratio") || "";
      set({ src, type, caption, ratio });
    };
    const onKey = (e) => { if (e.key === "Escape") set(null); };
    document.addEventListener("click", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("click", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, []);

  _lbE(() => {
    document.body.style.overflow = item ? "hidden" : "";
  }, [item]);

  if (!item) return null;

  const isVideo = item.type === "video";
  const isReel = item.ratio === "9:16";

  return (
    <div className="lb-overlay open" onClick={() => set(null)}>
      <button className="lb-close" onClick={() => set(null)} data-cursor="close">close&nbsp;✕</button>
      <div
        className={`lb-stage ${isReel ? "lb-stage--reel" : ""}`}
        onClick={(e) => e.stopPropagation()}
      >
        {isVideo ? (
          <video src={item.src} autoPlay controls loop playsInline />
        ) : (
          <img src={item.src} alt={item.caption || ""} />
        )}
        {item.caption && <div className="lb-caption">{item.caption}</div>}
      </div>
    </div>
  );
}

window.Lightbox = Lightbox;
