/* A picture, full size, without leaving the page. Body's attachment images
 * open here (a new tab took the reader away from the conversation). One
 * Lightbox is mounted at the app root; anything can open it. Click, Escape,
 * or the × closes it. */

import { useEffect, useState } from "react";

type Shown = { src: string; alt: string };
const listeners = new Set<(s: Shown | null) => void>();

export function openLightbox(src: string, alt = "") {
  for (const l of listeners) l({ src, alt });
}

export function Lightbox() {
  const [shown, setShown] = useState<Shown | null>(null);
  useEffect(() => {
    listeners.add(setShown);
    return () => { listeners.delete(setShown); };
  }, []);
  useEffect(() => {
    if (!shown) return;
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setShown(null); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [shown]);
  if (!shown) return null;
  return (
    <div className="cu-lightbox" role="dialog" aria-modal="true" aria-label={shown.alt || "Image"}
         onClick={() => setShown(null)}>
      <button type="button" className="cu-lightbox-close" aria-label="Close"
              onClick={() => setShown(null)}>×</button>
      <img src={shown.src} alt={shown.alt} onClick={(e) => e.stopPropagation()} />
      {shown.alt && <span className="cu-lightbox-caption">{shown.alt}</span>}
    </div>
  );
}
