// gallery.jsx — full-screen gallery lightbox: big image + thumb strip + prev/next

const { useState, useEffect, useRef } = React;

function Lightbox({ project, startIndex = 0, onClose, themeVars }) {
  const [idx, setIdx] = useState(startIndex);
  const [hover, setHover] = useState(false);
  const stripRef = useRef(null);
  const photos = project.photos;

  const prev = () => setIdx(i => (i - 1 + photos.length) % photos.length);
  const next = () => setIdx(i => (i + 1) % photos.length);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowLeft') prev();
      else if (e.key === 'ArrowRight') next();
      else if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  // Scroll thumb into view on index change
  useEffect(() => {
    const el = stripRef.current?.querySelector(`[data-thumb="${idx}"]`);
    if (el && el.scrollIntoView) {
      // Use scrollTo on parent instead to avoid page jump
      const parent = stripRef.current;
      const pRect = parent.getBoundingClientRect();
      const eRect = el.getBoundingClientRect();
      const delta = (eRect.left + eRect.width/2) - (pRect.left + pRect.width/2);
      parent.scrollBy({ left: delta, behavior: 'smooth' });
    }
  }, [idx]);

  const photo = photos[idx];

  // Force dark palette inside the lightbox — overrides any theme
  const darkVars = {
    '--bg': '#0a0a0a',
    '--fg': '#f4f4f4',
    '--dim': '#8a8a8a',
    '--dim-heavy': '#3a3a3a',
    '--border': '#2a2a2a',
    '--border-soft': '#1a1a1a',
  };

  return (
    <div
      role="dialog"
      aria-label={`${project.title} gallery`}
      style={{
        ...darkVars,
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'var(--bg)', color: 'var(--fg)',
        display: 'flex', flexDirection: 'column',
        animation: 'fadeIn 200ms ease',
      }}
    >
      <style>{`
        .yl-lb-mobile-arrows { display: none; }
        @media (max-width: 720px) {
          .yl-lb-arrow { display: none !important; }
          .yl-lb-stage { padding: 0 12px !important; }
          .yl-lb-mobile-arrows {
            display: flex !important;
            justify-content: center;
            gap: 16px;
            padding: 8px 16px 4px;
            flex-shrink: 0;
          }
          .yl-lb-kbd-hints { display: none !important; }
        }
      `}</style>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 20px', flexShrink: 0,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button
            onClick={onClose}
            aria-label="Back to projects"
            title="Back to projects"
            style={{
              display: 'flex', alignItems: 'center', gap: 6,
              background: 'transparent', border: '1px solid var(--border)',
              color: 'var(--fg)', cursor: 'pointer',
              padding: '6px 10px 6px 8px', borderRadius: 3,
              fontFamily: 'var(--font-mono)', fontSize: 10,
              letterSpacing: '0.08em', textTransform: 'uppercase',
              transition: 'background 160ms ease, border-color 160ms ease',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--fg)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; }}
          >
            <ArrowSVG dir="left" /> Back
          </button>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 500 }}>
            {project.title}
          </span>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--dim)', letterSpacing: '0.05em' }}>
            {String(idx + 1).padStart(2, '0')} / {String(photos.length).padStart(2, '0')}
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--dim)' }}>
          <span className="yl-lb-kbd-hints" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <kbd style={kbdStyle}>←</kbd><kbd style={kbdStyle}>→</kbd>
          </span>
          <span className="yl-lb-kbd-hints" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <kbd style={kbdStyle}>Esc</kbd>
          </span>
          <button onClick={onClose} style={closeBtn} aria-label="Close">×</button>
        </div>
      </div>

      {/* Main stage */}
      <div
        className="yl-lb-stage"
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
          position: 'relative', overflow: 'hidden', padding: '0 20px',
        }}
      >
        {/* Prev button */}
        <button onClick={prev} aria-label="Previous" className="yl-lb-arrow yl-lb-arrow-prev" style={{
          ...arrowBtn, left: 24, opacity: hover ? 1 : 0.25,
        }}>
          <ArrowSVG dir="left" />
        </button>

        {/* Hero image */}
        <img
          key={photo.id}
          src={photo.src}
          alt={photo.caption}
          style={{
            maxWidth: '100%', maxHeight: '100%',
            objectFit: 'contain',
            animation: 'imgFade 280ms ease',
          }}
        />

        {/* Next button */}
        <button onClick={next} aria-label="Next" className="yl-lb-arrow yl-lb-arrow-next" style={{
          ...arrowBtn, right: 24, opacity: hover ? 1 : 0.25,
        }}>
          <ArrowSVG dir="right" />
        </button>
      </div>

      {/* Mobile-only arrow row — hidden on desktop */}
      <div className="yl-lb-mobile-arrows">
        <button onClick={prev} aria-label="Previous" style={mobileArrowBtn}>
          <ArrowSVG dir="left" />
        </button>
        <button onClick={next} aria-label="Next" style={mobileArrowBtn}>
          <ArrowSVG dir="right" />
        </button>
      </div>

      {/* Caption */}
      <div style={{
        padding: '10px 20px 4px', display: 'flex', justifyContent: 'space-between',
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.04em',
        color: 'var(--dim)', flexShrink: 0, textTransform: 'uppercase',
      }}>
        <span>{photo.caption}</span>
        <span>{photo.place}</span>
      </div>

      {/* Thumb strip */}
      <div
        ref={stripRef}
        style={{
          display: 'flex', gap: 4, padding: '8px 20px 14px',
          overflowX: 'auto', flexShrink: 0,
          scrollbarWidth: 'thin',
          justifyContent: 'center',
        }}
      >
        {photos.map((p, i) => (
          <button
            key={p.id}
            data-thumb={i}
            onClick={() => setIdx(i)}
            aria-label={`Go to photo ${i+1}`}
            style={{
              position: 'relative', flexShrink: 0, cursor: 'pointer',
              border: 'none', padding: 0, background: 'none',
              width: 56, height: 40, overflow: 'hidden',
              outline: i === idx ? '1.5px solid var(--accent)' : '1px solid var(--border)',
              outlineOffset: i === idx ? 2 : 0,
              opacity: i === idx ? 1 : 0.5,
              transition: 'opacity 160ms ease',
            }}
            onMouseEnter={(e) => { if (i !== idx) e.currentTarget.style.opacity = '0.85'; }}
            onMouseLeave={(e) => { if (i !== idx) e.currentTarget.style.opacity = '0.5'; }}
          >
            <img src={p.src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          </button>
        ))}
      </div>
    </div>
  );
}

const kbdStyle = {
  fontFamily: 'var(--font-mono)', fontSize: 10,
  padding: '2px 6px', border: '1px solid var(--border)',
  borderRadius: 3, color: 'var(--fg)',
};

const closeBtn = {
  fontFamily: 'var(--font-display)', fontSize: 24, lineHeight: 1,
  background: 'transparent', border: 'none', cursor: 'pointer',
  color: 'var(--fg)', padding: '4px 10px',
};

const arrowBtn = {
  position: 'absolute', top: '50%', transform: 'translateY(-50%)',
  width: 48, height: 48, borderRadius: '50%',
  background: 'var(--bg)', border: '1px solid var(--border)',
  cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
  color: 'var(--fg)', transition: 'opacity 200ms ease',
  zIndex: 2,
};

const mobileArrowBtn = {
  width: 44, height: 44, borderRadius: '50%',
  background: 'transparent', border: '1px solid var(--border)',
  cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
  color: 'var(--fg)',
};

function ArrowSVG({ dir }) {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ transform: dir === 'right' ? 'scaleX(-1)' : 'none' }}>
      <path d="M10 2 L4 8 L10 14" stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

window.Lightbox = Lightbox;
