// Universal image lightbox — fullscreen overlay used by all three directions.
//
// Usage:
//   window.NJF_LIGHTBOX.open(images, startIndex)
//     images: [{url, caption?} | string]
//   window.NJF_LIGHTBOX.openProject(project, startIndex)
//     builds [cover, ...gallery] for the project's images
//
// Mount <Lightbox /> once at the top of the React tree (handled in site-shell).

function Lightbox() {
  const [state, setState] = React.useState({ open: false, images: [], index: 0 });

  React.useEffect(() => {
    const onOpen = (e) => {
      const { images, index } = e.detail || {};
      if (!Array.isArray(images) || images.length === 0) return;
      setState({ open: true, images, index: Math.max(0, Math.min(index || 0, images.length - 1)) });
    };
    window.addEventListener('njf:lightbox-open', onOpen);
    return () => window.removeEventListener('njf:lightbox-open', onOpen);
  }, []);

  React.useEffect(() => {
    if (!state.open) return;
    const close = () => setState(s => ({ ...s, open: false }));
    const next  = () => setState(s => ({ ...s, index: (s.index + 1) % s.images.length }));
    const prev  = () => setState(s => ({ ...s, index: (s.index - 1 + s.images.length) % s.images.length }));
    const onKey = (e) => {
      if (e.key === 'Escape') close();
      else if (e.key === 'ArrowRight') next();
      else if (e.key === 'ArrowLeft') prev();
    };
    window.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [state.open, state.images.length]);

  if (!state.open) return null;

  const img = state.images[state.index];
  const url = typeof img === 'string' ? img : img.url;
  const cap = typeof img === 'string' ? null : img.caption;
  const many = state.images.length > 1;

  const close = () => setState(s => ({ ...s, open: false }));
  const stop  = (e) => e.stopPropagation();
  const next  = (e) => { e.stopPropagation(); setState(s => ({ ...s, index: (s.index + 1) % s.images.length })); };
  const prev  = (e) => { e.stopPropagation(); setState(s => ({ ...s, index: (s.index - 1 + s.images.length) % s.images.length })); };

  const navBtn = {
    background: 'rgba(255,255,255,0.06)', color: '#fff',
    border: '1px solid rgba(255,255,255,0.18)',
    width: 44, height: 44, borderRadius: '50%', fontSize: 22,
    cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontFamily: 'system-ui, sans-serif',
  };

  return (
    <div onClick={close} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.93)',
      zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '60px 80px 80px', cursor: 'zoom-out',
    }}>
      <div onClick={stop} style={{
        position: 'relative', display: 'flex', flexDirection: 'column',
        alignItems: 'center', gap: 14, maxWidth: '100%', maxHeight: '100%',
      }}>
        <img src={url} alt={cap || ''} style={{
          maxWidth: '100%', maxHeight: 'calc(100vh - 180px)',
          objectFit: 'contain', display: 'block', cursor: 'default',
          boxShadow: '0 30px 80px rgba(0,0,0,0.6)',
        }} />
        {cap && (
          <div style={{ color: '#dcdcdc', fontFamily: 'system-ui, sans-serif',
            fontSize: 13, lineHeight: 1.5, textAlign: 'center', maxWidth: 800 }}>
            {cap}
          </div>
        )}
        {many && (
          <div style={{ color: '#888', fontFamily: 'ui-monospace, monospace', fontSize: 11, letterSpacing: 1 }}>
            {state.index + 1} / {state.images.length}
          </div>
        )}
      </div>

      {many && (
        <>
          <button onClick={prev} aria-label="Previous"
            style={{ ...navBtn, position: 'fixed', left: 20, top: '50%', transform: 'translateY(-50%)' }}>‹</button>
          <button onClick={next} aria-label="Next"
            style={{ ...navBtn, position: 'fixed', right: 20, top: '50%', transform: 'translateY(-50%)' }}>›</button>
        </>
      )}

      <button onClick={(e) => { e.stopPropagation(); close(); }} aria-label="Close"
        style={{ ...navBtn, position: 'fixed', top: 18, right: 18, width: 36, height: 36, fontSize: 18 }}>×</button>

      <div style={{ position: 'fixed', bottom: 16, left: '50%', transform: 'translateX(-50%)',
        color: '#666', fontFamily: 'ui-monospace, monospace', fontSize: 10, letterSpacing: 2 }}>
        ESC TO CLOSE{many ? ' · ← →  TO NAVIGATE' : ''}
      </div>
    </div>
  );
}

window.NJF_LIGHTBOX = {
  open: (images, index = 0) => {
    window.dispatchEvent(new CustomEvent('njf:lightbox-open', { detail: { images, index } }));
  },
  openProject: (project, startIndex = 0) => {
    if (!project) return;
    const images = [];
    if (project.cover_url) images.push({ url: project.cover_url, caption: project.title });
    (project.gallery || []).forEach((g) => {
      if (typeof g === 'string') images.push({ url: g });
      else if (g && g.url) images.push(g);
    });
    if (images.length === 0) return;
    window.dispatchEvent(new CustomEvent('njf:lightbox-open', { detail: { images, index: startIndex } }));
  },
  openSingle: (url, caption) => {
    if (!url) return;
    window.dispatchEvent(new CustomEvent('njf:lightbox-open', { detail: { images: [{ url, caption }], index: 0 } }));
  },
};
