// ── Scrolling slot: cycles through its own image sequence with a crossfade.
//    Even-indexed images belong to the left slot, odd to the right; slots are
//    staggered so only one crossfades at a time → continuous "scroll" feel
//    while keeping exactly 2 pictures visible per area.
function AtmSlot({ images, intervalMs, offsetMs, onOpen, firstFlatIdx }) {
  const [idx, setIdx] = React.useState(0);

  React.useEffect(() => {
    if (images.length <= 1) return;
    let interval;
    const start = setTimeout(() => {
      interval = setInterval(() => {
        setIdx(i => (i + 1) % images.length);
      }, intervalMs);
    }, offsetMs);
    return () => { clearTimeout(start); if (interval) clearInterval(interval); };
  }, [images.length, intervalMs, offsetMs]);

  const currentImg = images[idx];
  // map local slot index → flat index in allImages (slot strides by 2)
  const flatIdx = firstFlatIdx + idx * 2;

  return (
    <div
      className="atm-img-wrap"
      onClick={() => onOpen(flatIdx)}
      role="button"
      tabIndex={0}
      aria-label={`View: ${currentImg.alt}`}
      onKeyDown={e => e.key === 'Enter' && onOpen(flatIdx)}
    >
      {images.map((img, i) => (
        <img
          key={i}
          src={img.src}
          alt={img.alt}
          className={`atm-img ${i === idx ? 'active' : ''}`}
          loading={i === 0 ? 'eager' : 'lazy'}
          decoding="async"
        />
      ))}
      <div className="atm-img-overlay">
        <div className="atm-img-zoom">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="white" strokeWidth="1.3">
            <circle cx="6" cy="6" r="4"/>
            <line x1="9.5" y1="9.5" x2="13" y2="13"/>
            <line x1="4" y1="6" x2="8" y2="6"/>
            <line x1="6" y1="4" x2="6" y2="8"/>
          </svg>
        </div>
      </div>
      {images.length > 1 && (
        <div className="atm-slot-dots" aria-hidden="true">
          {images.map((_, i) => (
            <span key={i} className={`atm-slot-dot ${i === idx ? 'on' : ''}`} />
          ))}
        </div>
      )}
    </div>
  );
}

function Gallery() {
  const sectionRef = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  const [lightbox, setLightbox] = React.useState(null);
  const [areas, setAreas] = React.useState([]);

  // Load gallery areas from data/gallery.json — edit that file to update photos
  React.useEffect(() => {
    fetch('./data/gallery.json')
      .then(r => r.json())
      .then(setAreas)
      .catch(console.error);
  }, []);

  React.useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setVisible(true); observer.disconnect(); } },
      { threshold: 0.06 }
    );
    if (sectionRef.current) observer.observe(sectionRef.current);
    return () => observer.disconnect();
  }, [areas]);

  // Flat image list for lightbox navigation (all areas, all images)
  const allImages = areas.flatMap(a => a.images);

  // Precompute per-area base offsets into allImages so each slot knows its flat idx
  const areaOffsets = [];
  {
    let acc = 0;
    for (const a of areas) { areaOffsets.push(acc); acc += a.images.length; }
  }

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape')     setLightbox(null);
      if (e.key === 'ArrowRight') setLightbox(i => i !== null ? (i + 1) % allImages.length : null);
      if (e.key === 'ArrowLeft')  setLightbox(i => i !== null ? (i - 1 + allImages.length) % allImages.length : null);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [allImages.length]);

  React.useEffect(() => {
    document.body.style.overflow = lightbox !== null ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [lightbox]);

  return (
    <>
      <style>{`
        /* ── Section ── */
        .atm {
          background: #0A0A0A;
          padding: 100px 0 0;
          overflow: hidden;
        }

        /* ── Header ── */
        .atm-header {
          display: flex;
          align-items: flex-end;
          justify-content: space-between;
          padding: 0 96px 64px;
          gap: 32px;
          opacity: 0; transform: translateY(16px);
          transition: opacity 0.8s cubic-bezier(0.16,1,0.3,1) 0.1s,
                      transform 0.8s cubic-bezier(0.16,1,0.3,1) 0.1s;
        }
        .atm-header.in { opacity: 1; transform: translateY(0); }

        .atm-eyebrow {
          font-family: 'Josefin Sans', sans-serif;
          font-size: 11px; font-weight: 400;
          letter-spacing: 0.35em; text-transform: uppercase;
          color: #E84800;
          display: flex; align-items: center; gap: 12px;
          margin-bottom: 18px;
        }
        .atm-eyebrow-rule { width: 32px; height: 1px; background: #E84800; opacity: 0.6; }

        .atm-title {
          font-family: 'Playfair Display', serif;
          font-size: clamp(32px, 3vw, 50px);
          font-weight: 400; font-style: italic;
          color: #F5F0EA;
          line-height: 1.15; letter-spacing: -0.02em;
        }

        .atm-ig-link {
          font-family: 'Josefin Sans', sans-serif;
          font-size: 10px; font-weight: 400;
          letter-spacing: 0.28em; text-transform: uppercase;
          color: rgba(255,255,255,0.35);
          text-decoration: none;
          display: flex; align-items: center; gap: 12px;
          flex-shrink: 0;
          transition: color 0.25s ease;
        }
        .atm-ig-link:hover { color: rgba(255,255,255,0.8); }
        .atm-ig-link svg { flex-shrink: 0; }

        /* ── Area rows ── */
        .atm-areas {
          border-top: 1px solid rgba(255,255,255,0.06);
        }

        .atm-area {
          display: grid;
          grid-template-columns: 300px 1fr;
          gap: 80px;
          padding: 72px 96px;
          border-bottom: 1px solid rgba(255,255,255,0.06);
          align-items: center;
          opacity: 0; transform: translateY(24px);
          transition: opacity 0.9s cubic-bezier(0.16,1,0.3,1),
                      transform 0.9s cubic-bezier(0.16,1,0.3,1);
        }
        .atm-area.in { opacity: 1; transform: translateY(0); }

        /* ── Area info (left col) ── */
        .atm-area-num {
          font-family: 'Josefin Sans', sans-serif;
          font-size: 10px; font-weight: 400;
          letter-spacing: 0.3em; text-transform: uppercase;
          color: #E84800;
          display: block; margin-bottom: 14px;
        }

        .atm-area-name {
          font-family: 'Playfair Display', serif;
          font-size: clamp(26px, 2.4vw, 40px);
          font-weight: 400; font-style: italic;
          color: #F5F0EA;
          line-height: 1.1; letter-spacing: -0.02em;
          margin: 0 0 16px;
        }

        .atm-area-tba {
          display: inline-block;
          font-family: 'Josefin Sans', sans-serif;
          font-size: 9px; font-weight: 400;
          letter-spacing: 0.28em; text-transform: uppercase;
          color: rgba(255,255,255,0.22);
          border: 1px solid rgba(255,255,255,0.1);
          border-radius: 2px;
          padding: 3px 9px;
          margin-bottom: 16px;
        }

        .atm-area-desc {
          font-family: 'Josefin Sans', sans-serif;
          font-size: 12px; font-weight: 300;
          letter-spacing: 0.06em; line-height: 1.85;
          color: rgba(245,240,234,0.32);
          max-width: 220px;
          display: block;
          margin-top: 4px;
        }

        /* Photo-count hint — opens the lightbox at this area's first image */
        .atm-area-more {
          margin-top: 22px;
          display: inline-flex; align-items: center; gap: 10px;
          padding: 8px 14px;
          background: transparent;
          border: 1px solid rgba(255,255,255,0.12);
          border-radius: 100px;
          font-family: 'Josefin Sans', sans-serif;
          font-size: 10px; font-weight: 400;
          letter-spacing: 0.28em; text-transform: uppercase;
          color: rgba(245,240,234,0.6);
          cursor: pointer;
          transition: border-color 0.25s ease, color 0.25s ease, background 0.25s ease;
        }
        .atm-area-more:hover {
          border-color: rgba(232,72,0,0.6);
          color: #fff;
          background: rgba(232,72,0,0.08);
        }
        .atm-area-more-icon {
          position: relative;
          width: 14px; height: 12px;
          flex-shrink: 0;
        }
        .atm-area-more-icon::before,
        .atm-area-more-icon::after {
          content: '';
          position: absolute;
          border: 1px solid currentColor;
          border-radius: 1px;
        }
        .atm-area-more-icon::before {
          top: 0; left: 3px;
          width: 10px; height: 8px;
          opacity: 0.5;
        }
        .atm-area-more-icon::after {
          bottom: 0; left: 0;
          width: 10px; height: 8px;
          background: #0A0A0A;
        }

        /* ── Image slots (right col) — always exactly 2 slots ── */
        .atm-area-images {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 3px;
        }

        .atm-img-wrap {
          position: relative;
          aspect-ratio: 4 / 3;
          overflow: hidden;
          cursor: zoom-in;
          background: #111;
        }

        /* Stacked images — only the active one is visible; crossfade on rotate */
        .atm-img {
          position: absolute; inset: 0;
          width: 100%; height: 100%;
          object-fit: cover; object-position: center;
          display: block;
          opacity: 0;
          transform: scale(1.03);
          transition: opacity 1.2s cubic-bezier(0.4,0,0.2,1),
                      transform 6s ease-out;
        }
        .atm-img.active {
          opacity: 1;
          transform: scale(1);
        }
        .atm-img-wrap:hover .atm-img.active { transform: scale(1.05); transition: transform 0.7s cubic-bezier(0.16,1,0.3,1); }

        .atm-img-overlay {
          position: absolute; inset: 0;
          background: rgba(0,0,0,0);
          transition: background 0.4s ease;
          z-index: 2;
          display: flex; align-items: center; justify-content: center;
          pointer-events: none;
        }
        .atm-img-wrap:hover .atm-img-overlay { background: rgba(0,0,0,0.28); }

        .atm-img-zoom {
          width: 44px; height: 44px;
          border: 1px solid rgba(255,255,255,0.6);
          border-radius: 50%;
          display: flex; align-items: center; justify-content: center;
          opacity: 0; transform: scale(0.7);
          transition: opacity 0.3s ease,
                      transform 0.3s cubic-bezier(0.34,1.56,0.64,1);
        }
        .atm-img-wrap:hover .atm-img-zoom { opacity: 1; transform: scale(1); }
        .atm-img-wrap:focus-visible { outline: 2px solid rgba(232,72,0,0.5); outline-offset: 2px; }

        /* ── Progress dots along the bottom of each slot ── */
        .atm-slot-dots {
          position: absolute;
          left: 0; right: 0; bottom: 10px;
          display: flex; justify-content: center; gap: 6px;
          z-index: 3;
          pointer-events: none;
          opacity: 0.55;
          transition: opacity 0.3s ease;
        }
        .atm-img-wrap:hover .atm-slot-dots { opacity: 0.95; }
        .atm-slot-dot {
          width: 4px; height: 4px; border-radius: 50%;
          background: rgba(255,255,255,0.3);
          transition: background 0.35s ease, width 0.35s ease;
        }
        .atm-slot-dot.on {
          background: #E84800;
          width: 14px; border-radius: 2px;
        }

        /* ── Lightbox ── */
        .atm-lightbox {
          position: fixed; inset: 0; z-index: 2000;
          background: rgba(5,5,5,0.97);
          display: flex; align-items: center; justify-content: center;
          opacity: 0; pointer-events: none;
          transition: opacity 0.3s ease;
        }
        .atm-lightbox.open { opacity: 1; pointer-events: all; }

        .atm-lb-img {
          max-width: 90vw; max-height: 88vh;
          object-fit: contain;
          border-radius: 2px;
          box-shadow: 0 32px 80px rgba(0,0,0,0.8);
        }

        .atm-lb-close {
          position: absolute; top: 28px; right: 36px;
          background: none; border: none;
          color: rgba(255,255,255,0.5);
          font-family: 'Josefin Sans', sans-serif;
          font-size: 10px; letter-spacing: 0.25em; text-transform: uppercase;
          cursor: pointer; display: flex; align-items: center; gap: 10px;
          transition: color 0.2s ease;
        }
        .atm-lb-close:hover { color: #fff; }

        .atm-lb-nav {
          position: absolute; top: 50%; transform: translateY(-50%);
          background: none; border: 1px solid rgba(255,255,255,0.12);
          color: rgba(255,255,255,0.5);
          width: 48px; height: 48px; border-radius: 50%;
          cursor: pointer; display: flex; align-items: center; justify-content: center;
          transition: border-color 0.2s ease, color 0.2s ease,
                      transform 0.2s cubic-bezier(0.34,1.56,0.64,1);
        }
        .atm-lb-nav:hover { border-color: rgba(255,255,255,0.4); color: #fff; }
        .atm-lb-prev { left: 28px; }
        .atm-lb-prev:hover { transform: translateY(-50%) translateX(-2px); }
        .atm-lb-next { right: 28px; }
        .atm-lb-next:hover { transform: translateY(-50%) translateX(2px); }

        .atm-lb-counter {
          position: absolute; bottom: 28px; left: 50%; transform: translateX(-50%);
          font-family: 'Josefin Sans', sans-serif;
          font-size: 10px; letter-spacing: 0.3em;
          color: rgba(255,255,255,0.28);
        }

        /* ── Instagram footer ── */
        .atm-footer {
          display: flex; align-items: center; justify-content: center;
          gap: 16px;
          padding: 48px 96px;
          border-top: 1px solid rgba(255,255,255,0.05);
          opacity: 0; transform: translateY(12px);
          transition: opacity 0.8s cubic-bezier(0.16,1,0.3,1) 0.6s,
                      transform 0.8s cubic-bezier(0.16,1,0.3,1) 0.6s;
        }
        .atm-footer.in { opacity: 1; transform: translateY(0); }

        .atm-footer-text {
          font-family: 'Josefin Sans', sans-serif;
          font-size: 10px; font-weight: 400;
          letter-spacing: 0.3em; text-transform: uppercase;
          color: rgba(255,255,255,0.28);
        }
        .atm-footer-handle {
          font-family: 'Josefin Sans', sans-serif;
          font-size: 10px; font-weight: 600;
          letter-spacing: 0.2em; text-transform: uppercase;
          color: #E84800; text-decoration: none;
          transition: color 0.22s ease;
        }
        .atm-footer-handle:hover { color: #ff5c1a; }

        /* ── Responsive ── */
        @media (max-width: 1024px) {
          .atm-area { grid-template-columns: 240px 1fr; gap: 48px; }
        }
        @media (max-width: 900px) {
          .atm { padding: 72px 0 0; }
          .atm-header { padding: 0 32px 48px; flex-direction: column; align-items: flex-start; gap: 20px; }
          .atm-area { grid-template-columns: 1fr; gap: 32px; padding: 48px 32px; }
          .atm-area-desc { max-width: 100%; }
          .atm-footer { padding: 36px 32px; }
        }
        @media (max-width: 480px) {
          .atm-area { padding: 40px 24px; }
          .atm-area-images { gap: 2px; }
        }

        /* Respect reduced motion: stop the auto-rotation by leaving slot at 0 */
        @media (prefers-reduced-motion: reduce) {
          .atm-img { transition: opacity 0.3s linear; transform: none !important; }
        }
      `}</style>

      {/* ── Lightbox ── */}
      <div
        className={`atm-lightbox ${lightbox !== null ? 'open' : ''}`}
        onClick={() => setLightbox(null)}
        role="dialog"
        aria-modal="true"
        aria-label="Image lightbox"
      >
        {lightbox !== null && allImages[lightbox] && (
          <img
            src={allImages[lightbox].src}
            alt={allImages[lightbox].alt}
            className="atm-lb-img"
            onClick={e => e.stopPropagation()}
          />
        )}

        <button className="atm-lb-close" onClick={() => setLightbox(null)}>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.5">
            <line x1="1" y1="1" x2="11" y2="11"/><line x1="11" y1="1" x2="1" y2="11"/>
          </svg>
          Close
        </button>

        <button
          className="atm-lb-nav atm-lb-prev"
          onClick={e => { e.stopPropagation(); setLightbox(i => (i - 1 + allImages.length) % allImages.length); }}
          aria-label="Previous image"
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
            <polyline points="10,2 4,8 10,14"/>
          </svg>
        </button>

        <button
          className="atm-lb-nav atm-lb-next"
          onClick={e => { e.stopPropagation(); setLightbox(i => (i + 1) % allImages.length); }}
          aria-label="Next image"
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
            <polyline points="6,2 12,8 6,14"/>
          </svg>
        </button>

        {lightbox !== null && (
          <span className="atm-lb-counter">
            {lightbox + 1} / {allImages.length}
          </span>
        )}
      </div>

      {/* ── Section ── */}
      <section className="atm" ref={sectionRef} id="gallery" aria-label="The Atmosphere">

        {/* Header */}
        <div className={`atm-header ${visible ? 'in' : ''}`}>
          <div>
            <p className="atm-eyebrow">
              <span className="atm-eyebrow-rule" />
              The Atmosphere
            </p>
            <h2 className="atm-title">
              Three worlds, one<br />unforgettable night.
            </h2>
          </div>
          <a
            href="https://www.instagram.com/after5loungebar/"
            className="atm-ig-link"
            target="_blank"
            rel="noopener noreferrer"
            aria-label="Follow After5 on Instagram"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
              <circle cx="12" cy="12" r="4"/>
              <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/>
            </svg>
            @after5loungebar
          </a>
        </div>

        {/* Venue area rows */}
        <div className="atm-areas">
          {areas.map((area, areaIdx) => {
            // Split area's images into two slot-sequences (even indices → left, odd → right).
            // Each slot auto-cycles through its sequence on a stagger so the two slots never
            // crossfade simultaneously.
            const leftImgs  = area.images.filter((_, i) => i % 2 === 0);
            const rightImgs = area.images.filter((_, i) => i % 2 === 1);
            const baseFlat  = areaOffsets[areaIdx] ?? 0;

            // Time the two slots so they alternate: each slot holds for ~5.2s, total cycle ~5.2s,
            // right slot offset by half-cycle so the visible change is always one-at-a-time.
            const INTERVAL = 5200;
            return (
              <div
                key={areaIdx}
                className={`atm-area ${visible ? 'in' : ''}`}
                style={{ transitionDelay: `${0.12 + areaIdx * 0.18}s` }}
              >
                {/* Left: area info */}
                <div className="atm-area-info">
                  <span className="atm-area-num">{area.number}</span>
                  <h3 className="atm-area-name">{area.name}</h3>
                  {area.placeholder && <span className="atm-area-tba">Name TBA</span>}
                  <span className="atm-area-desc">{area.desc}</span>
                  <button
                    type="button"
                    className="atm-area-more"
                    onClick={() => setLightbox(baseFlat)}
                    aria-label={`Browse all ${area.images.length} ${area.name} photos`}
                  >
                    <span className="atm-area-more-icon" aria-hidden="true" />
                    Browse all {area.images.length} photos
                  </button>
                </div>

                {/* Right: two scrolling slots — always exactly 2 images visible */}
                <div className="atm-area-images">
                  <AtmSlot
                    images={leftImgs}
                    intervalMs={INTERVAL}
                    offsetMs={0}
                    onOpen={setLightbox}
                    firstFlatIdx={baseFlat + 0}
                  />
                  <AtmSlot
                    images={rightImgs}
                    intervalMs={INTERVAL}
                    offsetMs={INTERVAL / 2}
                    onOpen={setLightbox}
                    firstFlatIdx={baseFlat + 1}
                  />
                </div>
              </div>
            );
          })}
        </div>

        {/* Instagram footer */}
        <div className={`atm-footer ${visible ? 'in' : ''}`}>
          <span className="atm-footer-text">See more on Instagram</span>
          <span style={{ color: 'rgba(255,255,255,0.12)', fontSize: '8px' }}>·</span>
          <a
            href="https://www.instagram.com/after5loungebar/"
            className="atm-footer-handle"
            target="_blank"
            rel="noopener noreferrer"
          >
            @after5loungebar
          </a>
        </div>

      </section>
    </>
  );
}
