/*
  Lightbox — a single global image viewer. Any clickable screenshot on the
  page calls window.openLightbox(src, caption) to open a large view in a modal.
  Mounted once (in app.jsx). Close: click backdrop, the X, or Esc.
*/
const Lightbox = () => {
  const [img, setImg] = React.useState(null); // { src, alt }
  React.useEffect(() => {
    const open = (e) => setImg(e.detail);
    const key = (e) => { if (e.key === 'Escape') setImg(null); };
    window.addEventListener('aa-lightbox', open);
    window.addEventListener('keydown', key);
    return () => { window.removeEventListener('aa-lightbox', open); window.removeEventListener('keydown', key); };
  }, []);
  React.useEffect(() => {
    document.body.style.overflow = img ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [img]);
  if (!img) return null;
  return (
    <div onClick={() => setImg(null)} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(4,5,8,0.86)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 'clamp(16px, 4vh, 48px) clamp(16px, 4vw, 64px)', cursor: 'zoom-out',
      animation: 'lb-fade 160ms ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{ position: 'relative', maxWidth: 1280, width: '100%', cursor: 'default' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, gap: 12 }}>
          <span className="mono-label" style={{ fontSize: 12, color: 'var(--fg-2)', letterSpacing: '0.06em' }}>
            <span style={{ color: 'var(--accent-2)' }}>REAL · GENERATED</span> &nbsp;·&nbsp; {img.alt}
          </span>
          <button onClick={() => setImg(null)} aria-label="Close" style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--fg-2)',
            background: 'var(--bg-2)', border: '1px solid var(--line-3)', borderRadius: 8,
            padding: '6px 12px', cursor: 'pointer',
          }}>
            <I.close size={14} /> Esc
          </button>
        </div>
        <img src={img.src} alt={img.alt} style={{
          width: '100%', maxHeight: '82vh', objectFit: 'contain', display: 'block',
          borderRadius: 12, border: '1px solid var(--line-3)',
          boxShadow: '0 40px 120px rgba(0,0,0,0.6)', background: 'var(--bg-1)',
        }} />
      </div>
    </div>
  );
};

// Any component can pop the viewer without importing anything.
window.openLightbox = (src, alt) => window.dispatchEvent(new CustomEvent('aa-lightbox', { detail: { src, alt } }));
window.Lightbox = Lightbox;
