/* ── Photos Section + Lightbox ── */

const PHOTO_CATS = ['ALL', 'PROMO', 'LIVE'];

function PhotosSection() {
  const [cat, setCat] = React.useState('ALL');
  const [lightbox, setLightbox] = React.useState(null);

  const filtered = cat === 'ALL' ? PHOTOS : PHOTOS.filter(p => p.cat === cat);

  return (
    <section id="photos" data-screen-label="05 Photos" style={{ padding: '100px 0', background: C.black, borderTop: '1px solid #161616' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 40px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 56 }}>
          <div>
            <SectionHeader num={5} title="PHOTOS" />
          </div>
          <div style={{ display: 'flex', gap: 2, marginBottom: 56 }}>
            {PHOTO_CATS.map(c => (
              <FilterBtn key={c} label={c} active={cat === c} onClick={() => setCat(c)} />
            ))}
          </div>
        </div>

        {/* Editorial mixed grid */}
        <PhotoGrid photos={filtered} onOpen={setLightbox} />
      </div>

      {lightbox !== null && (
        <Lightbox
          photos={filtered}
          index={lightbox}
          onClose={() => setLightbox(null)}
          onNav={setLightbox}
        />
      )}
    </section>
  );
}

function FilterBtn({ label, active, onClick }) {
  const [hov, setHov] = React.useState(false);
  return (
    <button onClick={onClick}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ padding: '9px 22px', background: active ? '#e0e0e0' : hov ? '#111' : 'transparent', border: `1px solid ${active ? '#e0e0e0' : '#2a2a2a'}`, color: active ? '#0a0a0a' : hov ? '#e0e0e0' : C.muted, fontFamily: 'Inter', fontWeight: 700, fontSize: 9, letterSpacing: '2.5px', textTransform: 'uppercase', cursor: 'pointer', transition: 'all 0.25s' }}>
      {label}
    </button>
  );
}

function PhotoGrid({ photos, onOpen }) {
  if (!photos.length) {
    return <div style={{ textAlign: 'center', padding: '60px 0', color: C.muted, fontSize: 12, letterSpacing: '2px', textTransform: 'uppercase' }}>No photos in this category.</div>;
  }

  // Build an editorial layout: alternating row patterns
  // Pattern A: 1 tall (2-row) + 2 square stacked
  // Pattern B: 3 across equal
  // Pattern C: 2 wide
  const rows = [];
  let i = 0;
  let patIdx = 0;
  const patterns = ['A', 'B', 'C', 'B'];

  while (i < photos.length) {
    const pat = patterns[patIdx % patterns.length];
    if (pat === 'A' && i + 2 < photos.length) {
      rows.push({ type: 'A', items: [photos[i], photos[i+1], photos[i+2]] });
      i += 3;
    } else if (pat === 'B' && i + 2 < photos.length) {
      rows.push({ type: 'B', items: [photos[i], photos[i+1], photos[i+2]] });
      i += 3;
    } else if (pat === 'C' && i + 1 < photos.length) {
      rows.push({ type: 'C', items: [photos[i], photos[i+1]] });
      i += 2;
    } else {
      // fallback: dump remaining as B-style or singles
      const remaining = photos.slice(i);
      rows.push({ type: 'B', items: remaining });
      i = photos.length;
    }
    patIdx++;
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      {rows.map((row, ri) => {
        const baseIdx = photos.indexOf(row.items[0]);
        if (row.type === 'A') {
          return (
            <div key={ri} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gridTemplateRows: '260px 260px', gap: 3 }}>
              <PhotoCell photo={row.items[0]} index={baseIdx} onOpen={onOpen} style={{ gridRow: '1 / 3' }} tall />
              <PhotoCell photo={row.items[1]} index={baseIdx + 1} onOpen={onOpen} />
              <PhotoCell photo={row.items[2]} index={baseIdx + 2} onOpen={onOpen} />
            </div>
          );
        }
        if (row.type === 'C') {
          return (
            <div key={ri} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 3, height: 380 }}>
              {row.items.map((p, pi) => <PhotoCell key={pi} photo={p} index={baseIdx + pi} onOpen={onOpen} />)}
            </div>
          );
        }
        // B: 3 equal
        return (
          <div key={ri} style={{ display: 'grid', gridTemplateColumns: `repeat(${row.items.length}, 1fr)`, gap: 3, height: 280 }}>
            {row.items.map((p, pi) => <PhotoCell key={pi} photo={p} index={baseIdx + pi} onOpen={onOpen} />)}
          </div>
        );
      })}
    </div>
  );
}

function PhotoCell({ photo, index, onOpen, style = {}, tall }) {
  const [hov, setHov] = React.useState(false);
  return (
    <div onClick={() => onOpen(index)}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ position: 'relative', overflow: 'hidden', cursor: 'pointer', background: '#111', ...style }}>
      <img src={photo.src} alt={photo.venue}
        style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block',
          transform: hov ? 'scale(1.05)' : 'scale(1)', transition: 'transform 0.5s ease',
          animation: 'tb-flicker-img 6s infinite' }}
      />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, transparent 40%, rgba(0,0,0,0.9) 100%)', opacity: hov ? 1 : 0, transition: 'opacity 0.3s', display: 'flex', alignItems: 'flex-end', padding: '16px 18px' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '1px', textTransform: 'uppercase', color: '#e0e0e0' }}>{photo.venue}</div>
          <div style={{ fontSize: 10, color: C.muted, marginTop: 2, letterSpacing: '1px', textTransform: 'uppercase' }}>{photo.date}</div>
        </div>
        <i className="fas fa-expand" style={{ marginLeft: 'auto', color: '#e0e0e0', fontSize: 13 }}/>
      </div>
    </div>
  );
}

function Lightbox({ photos, index, onClose, onNav }) {
  const photo = photos[index];

  React.useEffect(() => {
    const handler = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') onNav(Math.min(index + 1, photos.length - 1));
      if (e.key === 'ArrowLeft') onNav(Math.max(index - 1, 0));
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [index]);

  return (
    <div onClick={onClose}
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.97)', backdropFilter: 'blur(8px)', zIndex: 8000, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', animation: 'fadeIn 0.2s ease' }}>
      <button onClick={onClose} style={{ position: 'absolute', top: 24, right: 28, background: 'none', border: 'none', color: '#666', fontSize: 28, cursor: 'pointer', lineHeight: 1 }}>×</button>

      {/* Counter */}
      <div style={{ position: 'absolute', top: 28, left: 32, fontSize: 10, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase', color: '#444' }}>
        {index + 1} / {photos.length}
      </div>

      {/* Nav arrows */}
      {index > 0 && (
        <button onClick={e => { e.stopPropagation(); onNav(index - 1); }}
          style={{ position: 'absolute', left: 24, background: 'none', border: '1px solid #333', color: '#e0e0e0', width: 44, height: 44, cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'border-color 0.2s' }}>
          <i className="fas fa-chevron-left"/>
        </button>
      )}
      {index < photos.length - 1 && (
        <button onClick={e => { e.stopPropagation(); onNav(index + 1); }}
          style={{ position: 'absolute', right: 24, background: 'none', border: '1px solid #333', color: '#e0e0e0', width: 44, height: 44, cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'border-color 0.2s' }}>
          <i className="fas fa-chevron-right"/>
        </button>
      )}

      <img src={photo.src} alt={photo.venue} onClick={e => e.stopPropagation()}
        style={{ maxWidth: '82vw', maxHeight: '76vh', objectFit: 'contain', border: '1px solid #222', animation: 'tb-flicker-img 4s infinite', boxShadow: '0 8px 60px rgba(0,0,0,0.8)' }}
      />
      <div style={{ marginTop: 22, textAlign: 'center' }}>
        <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase', color: '#e0e0e0' }}>{photo.venue}</div>
        <div style={{ fontSize: 10, color: C.muted, marginTop: 4, letterSpacing: '1px', textTransform: 'uppercase' }}>{photo.date}</div>
      </div>
    </div>
  );
}

Object.assign(window, { PhotosSection });
