// heritage/gallery.jsx — Editorial grid + lightbox

function Lightbox({ items, startIdx, onClose, theme }) {
  const [idx, setIdx] = React.useState(startIdx);

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') setIdx((i) => (i + 1) % items.length);
      if (e.key === 'ArrowLeft') setIdx((i) => (i - 1 + items.length) % items.length);
    };
    document.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = ''; document.removeEventListener('keydown', onKey); };
  }, [items.length, onClose]);

  const cur = items[idx];

  return ReactDOM.createPortal(
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 110,
      background: 'rgba(15, 12, 9, 0.95)',
      display: 'flex', flexDirection: 'column',
      animation: 'lFade .25s ease',
    }}>
      <style>{`@keyframes lFade { from { opacity: 0; } to { opacity: 1; } }`}</style>

      {/* top bar */}
      <div onClick={(e) => e.stopPropagation()} style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '24px 40px', color: theme.cream,
      }}>
        <Caps size={11} color={theme.cream} ls={0.24} style={{ fontFamily: theme.sans, opacity: 0.7 }}>
          Plate {String(idx + 1).padStart(2, '0')} of {String(items.length).padStart(2, '0')}
        </Caps>
        <button onClick={onClose} style={{
          background: 'transparent', color: theme.cream, border: `1px solid ${theme.cream}55`,
          width: 36, height: 36, borderRadius: 18, cursor: 'pointer', fontSize: 16, lineHeight: 1,
        }}>×</button>
      </div>

      {/* image */}
      <div onClick={(e) => e.stopPropagation()} style={{
        flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '0 80px', position: 'relative', minHeight: 0, overflow: 'hidden',
      }}>
        <button onClick={() => setIdx((i) => (i - 1 + items.length) % items.length)} style={{
          position: 'absolute', left: 32, top: '50%', transform: 'translateY(-50%)',
          width: 48, height: 48, borderRadius: 24, border: `1px solid ${theme.cream}55`,
          background: 'transparent', color: theme.cream, cursor: 'pointer', fontSize: 20,
        }}>‹</button>
        <img key={cur.key} src={img(cur.key, 2000)}
          style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', animation: 'lFade .35s ease' }}
          alt="" />
        <button onClick={() => setIdx((i) => (i + 1) % items.length)} style={{
          position: 'absolute', right: 32, top: '50%', transform: 'translateY(-50%)',
          width: 48, height: 48, borderRadius: 24, border: `1px solid ${theme.cream}55`,
          background: 'transparent', color: theme.cream, cursor: 'pointer', fontSize: 20,
        }}>›</button>
      </div>

      {/* caption */}
      <div onClick={(e) => e.stopPropagation()} style={{ textAlign: 'center', padding: '24px 40px 32px', color: theme.cream }}>
        <div style={{ fontFamily: theme.serif, fontStyle: 'italic', fontSize: 18, color: theme.cream, opacity: 0.85 }}>
          {cur.caption}
        </div>
      </div>
    </div>,
    document.body,
  );
}

function HeritageGallery({ theme, mobile }) {
  const [filter, setFilter] = React.useState('all');
  const [lb, setLb] = React.useState(null);
  const px = mobile ? 24 : 56;

  const filtered = filter === 'all' ? GALLERY : GALLERY.filter(g => g.category === filter);
  const editorial = filter === 'all';

  React.useEffect(() => { setLb(null); }, [filter]);

  return (
    <section id="estate" style={{ background: theme.cream, padding: `${theme.sp(140)}px ${px}px ${theme.sp(120)}px` }}>
      <div style={{ maxWidth: 1400, margin: '0 auto' }}>
        <div data-reveal style={{
          display: 'flex',
          flexDirection: mobile ? 'column' : 'row',
          justifyContent: 'space-between', alignItems: mobile ? 'flex-start' : 'flex-end',
          marginBottom: mobile ? 32 : 64, gap: mobile ? 24 : 48,
        }}>
          <div>
            <Caps size={10} color={theme.oxblood} ls={0.3} style={{ fontFamily: theme.sans }}>Chapter IV · A walk through</Caps>
            <h2 style={{
              fontFamily: theme.serif, fontSize: 'clamp(36px, 5.5vw, 76px)',
              lineHeight: 1.0, fontWeight: 400, color: theme.ink,
              margin: '20px 0 0', letterSpacing: '-0.02em',
            }}>
              <em style={{ fontStyle: 'italic' }}>Mornings, afternoons,</em><br />
              and what comes after.
            </h2>
          </div>
          <div style={{ display: 'flex', gap: 8, paddingBottom: mobile ? 0 : 16, flexWrap: 'wrap' }}>
            {[
              { k: 'all',     l: 'All' },
              { k: 'rooms',   l: 'Rooms' },
              { k: 'dining',  l: 'Dining' },
              { k: 'estate',  l: 'Estate' },
            ].map((c) => (
              <button key={c.k} onClick={() => setFilter(c.k)}
                style={{
                  padding: '8px 14px', border: `1px solid ${theme.ink}`,
                  background: filter === c.k ? theme.ink : 'transparent',
                  color: filter === c.k ? theme.cream : theme.ink,
                  fontFamily: theme.sans, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
                  cursor: 'pointer', transition: 'background .2s, color .2s',
                }}>
                {c.l}
              </button>
            ))}
          </div>
        </div>

        <div style={{
          display: 'grid',
          gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : (editorial ? 'repeat(12, 1fr)' : 'repeat(3, 1fr)'),
          gridAutoRows: mobile ? '160px' : '260px',
          gap: mobile ? 8 : 16,
        }}>
          {filtered.map((g, i) => (
            <button key={g.key} data-reveal data-reveal-delay={String(Math.min(4, (i % 4) + 1))}
              onClick={() => setLb(i)}
              style={{
                gridColumn: mobile ? undefined : (editorial ? `span ${g.span.col}` : undefined),
                gridRow: mobile ? undefined : (editorial ? `span ${g.span.row}` : undefined),
                position: 'relative', padding: 0, border: 'none', background: theme.ink, cursor: 'pointer', overflow: 'hidden',
              }}
              className="gallery-item">
              <img src={img(g.key, mobile ? 600 : 1200)} loading="lazy"
                style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', transition: 'transform 1.2s cubic-bezier(.2,.7,.2,1), opacity .35s' }}
                alt="" />
              <PhotoKey label={`gallery_${i + 1}`} />
              <div className="gallery-cap" style={{
                position: 'absolute', inset: 0,
                background: `linear-gradient(180deg, transparent 50%, ${theme.ink}cc 100%)`,
                opacity: 0, transition: 'opacity .35s',
                display: 'flex', alignItems: 'flex-end', padding: 20,
              }}>
                <div style={{ fontFamily: theme.serif, fontStyle: 'italic', fontSize: 16, color: theme.cream }}>
                  {g.caption}
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>

      <style>{`
        .gallery-item:hover img { transform: scale(1.06); }
        .gallery-item:hover .gallery-cap { opacity: 1; }
      `}</style>

      {lb !== null && <Lightbox items={filtered} startIdx={lb} onClose={() => setLb(null)} theme={theme} />}
    </section>
  );
}

window.HeritageGallery = HeritageGallery;
