// ============================================
// GALERIJ — album-based: featured + grid of albums → album detail → lightbox
// ============================================

function GalerijPage({ navigate }) {
  const { Placeholder, Reveal, SectionHeader, Icon } = window.LM_UI;
  const { GALLERY, GALLERY_CATEGORIES } = window.LM_DATA;
  const { t } = window.LM_CMS;

  const [activeAlbumId, setActiveAlbumId] = React.useState(null);
  const [category, setCategory] = React.useState('all');
  const [year, setYear] = React.useState('all');

  // Build the set of available years from the data
  const years = ['all', ...Array.from(new Set(GALLERY.map(a => a.year))).sort((a, b) => b - a)];

  // Filtered albums
  const filtered = GALLERY.filter(a => {
    if (category !== 'all' && a.category !== category) return false;
    if (year !== 'all' && a.year !== year) return false;
    return true;
  });

  const featured = GALLERY.filter(a => a.featured);

  const activeAlbum = GALLERY.find(a => a.id === activeAlbumId);

  // Close album detail on Escape
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape' && activeAlbumId) setActiveAlbumId(null);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [activeAlbumId]);

  // If album is opened, render album view
  if (activeAlbum) {
    return <AlbumDetail album={activeAlbum} onBack={() => setActiveAlbumId(null)} />;
  }

  // Total photo count for the active filter
  const totalPhotos = filtered.reduce((sum, a) => sum + a.photos.length, 0);

  return (
    <div>
      {/* ===== INTRO ===== */}
      <section className="section" style={{ paddingBottom: 32 }}>
        <div className="container">
          <SectionHeader
            eyebrow={t('galerij.intro.eyebrow', 'Galerij & optredens')}
            title={<>{t('galerij.intro.title1', 'Onze')} <span className="grad-text">{t('galerij.intro.title2', 'momenten')}</span>{t('galerij.intro.title3', ', per album.')}</>}
            subtitle={t('galerij.intro.subtitle', "Bekijk foto's per evenement: gala's, optredens, competities en backstage. Klik op een album om alle foto's te bekijken.")}
          />
        </div>
      </section>

      {/* ===== FEATURED ===== */}
      {featured.length > 0 && category === 'all' && year === 'all' && (
        <section style={{ paddingBottom: 64 }}>
          <div className="container">
            <Reveal>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 16 }}>
                {t('galerij.featured.label', '★ Recent uitgelicht')}
              </div>
            </Reveal>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.min(featured.length, 2)}, 1fr)`, gap: 24 }} className="featured-grid">
              {featured.slice(0, 2).map((a, i) => (
                <Reveal key={a.id} delay={i * 80}>
                  <AlbumCard album={a} size="lg" onOpen={() => setActiveAlbumId(a.id)} />
                </Reveal>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* ===== FILTERS ===== */}
      <section style={{ paddingBottom: 32 }}>
        <div className="container">
          <Reveal>
            <div className="card" style={{ padding: '20px 24px', display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
                <span className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)', marginRight: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon.Filter size={12} /> {t('galerij.filter.category', 'Categorie')}
                </span>
                {GALLERY_CATEGORIES.map(c => (
                  <button key={c.id} className={`chip ${category === c.id ? 'active' : ''}`} onClick={() => setCategory(c.id)}>
                    {c.label}
                  </button>
                ))}
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)' }}>
                  {t('galerij.filter.year', 'Jaar')}
                </span>
                <div style={{ display: 'flex', gap: 4 }}>
                  {years.map(y => (
                    <button key={y} className={`chip ${year === y ? 'active' : ''}`} onClick={() => setYear(y)}>
                      {y === 'all' ? t('galerij.filter.yearAll', 'Alle') : y}
                    </button>
                  ))}
                </div>
              </div>
            </div>
            <div style={{ marginTop: 16, fontSize: 13, color: 'var(--ink-500)' }}>
              <span className="mono" style={{ letterSpacing: '0.08em' }}>
                {filtered.length} {filtered.length === 1 ? 'album' : 'albums'} · {totalPhotos} foto's
              </span>
            </div>
          </Reveal>
        </div>
      </section>

      {/* ===== ALBUM GRID ===== */}
      <section style={{ paddingBottom: 96 }}>
        <div className="container">
          {filtered.length > 0 ? (
            <div className="grid grid-3">
              {filtered.map((a, i) => (
                <Reveal key={a.id} delay={(i % 3) * 60}>
                  <AlbumCard album={a} onOpen={() => setActiveAlbumId(a.id)} />
                </Reveal>
              ))}
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: 80, color: 'var(--ink-500)' }}>
              <Icon.Calendar size={32} />
              <p style={{ marginTop: 16 }}>{t('galerij.empty', 'Geen albums gevonden met deze filters.')}</p>
            </div>
          )}
        </div>
      </section>

      <section className="section section-tinted">
        <div className="container" style={{ textAlign: 'center', maxWidth: 640 }}>
          <Reveal>
            <h2 className="display" style={{ fontSize: 'clamp(28px, 4vw, 40px)', margin: '0 0 16px', textTransform: 'none', letterSpacing: '-0.01em' }}>
              {t('galerij.cta.title1', 'Wil je ook op het')} <span className="grad-text">{t('galerij.cta.title2', 'podium')}</span> {t('galerij.cta.title3', 'staan?')}
            </h2>
            <p style={{ color: 'var(--ink-500)', marginBottom: 28 }}>
              {t('galerij.cta.body', "Iedere danser bij Dance Studio kan deelnemen aan optredens en het jaarlijkse gala.")}
            </p>
            <button className="btn btn-primary" onClick={() => navigate('lessen')}>
              {t('galerij.cta.button', 'Bekijk de lessen')} <Icon.ArrowRight />
            </button>
          </Reveal>
        </div>
      </section>

      <style>{`
        @media (max-width: 880px) {
          .featured-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

// ===== Album Card (used in grid + featured) =====
function AlbumCard({ album, onOpen, size = 'md' }) {
  const { Placeholder, Icon } = window.LM_UI;
  const isLg = size === 'lg';
  const catMap = {
    gala: 'Jaarlijks Gala', optreden: 'Optreden', competitie: 'Competitie',
    showcase: 'Showcase', backstage: 'Backstage',
  };

  return (
    <article
      onClick={onOpen}
      className="card"
      style={{
        overflow: 'hidden',
        cursor: 'pointer',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        transition: 'transform .25s ease, box-shadow .25s ease',
        padding: 0,
      }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = 'var(--shadow-lg)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'var(--shadow-sm)'; }}
    >
      {/* Cover image (stacked placeholders for visual depth) */}
      <div style={{ position: 'relative', aspectRatio: isLg ? '16/9' : '4/3' }}>
        <Placeholder
          label={`${album.id} · cover`}
          ratio="auto"
          src={(album.photos && album.photos[0] && (album.photos[0].url || (typeof album.photos[0] === 'string' ? '' : ''))) || ''}
          style={{ position: 'absolute', inset: 0, borderRadius: 0, aspectRatio: 'unset' }}
        />
        {/* Photo count badge */}
        <div style={{
          position: 'absolute',
          top: 14, right: 14,
          background: 'rgba(14,26,38,.88)',
          color: 'white',
          padding: '6px 12px',
          borderRadius: 999,
          fontSize: 11,
          fontFamily: 'var(--font-mono)',
          fontWeight: 600,
          letterSpacing: '0.04em',
          backdropFilter: 'blur(6px)',
          display: 'flex',
          alignItems: 'center',
          gap: 6,
        }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="1.5" fill="currentColor"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>
          {album.photos.length} foto's
        </div>
        {/* Featured badge */}
        {album.featured && (
          <div style={{
            position: 'absolute',
            top: 14, left: 14,
            background: 'var(--gradient)',
            color: 'white',
            padding: '5px 11px',
            borderRadius: 4,
            fontSize: 10,
            letterSpacing: '0.16em',
            textTransform: 'uppercase',
            fontWeight: 700,
            fontFamily: 'var(--font-display)',
          }}>★ Featured</div>
        )}
        {/* Category badge — pill is bewust altijd wit (ligt op een foto), dus de
            tekst moet altijd donker zijn; var(--ink-900) was wit op donkere thema's. */}
        <div style={{
          position: 'absolute',
          bottom: 14, left: 14,
          background: 'rgba(255,255,255,.95)',
          color: '#16181D',
          padding: '4px 10px',
          borderRadius: 4,
          fontSize: 10,
          letterSpacing: '0.14em',
          textTransform: 'uppercase',
          fontFamily: 'var(--font-mono)',
          fontWeight: 600,
          backdropFilter: 'blur(4px)',
        }}>{catMap[album.category] || album.category}</div>
      </div>

      {/* Info */}
      <div style={{ padding: isLg ? 28 : 20, flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--blue-600)', marginBottom: 6 }}>
          {album.month} {album.year} · {album.location}
        </div>
        <h3 className="display" style={{ fontSize: isLg ? 26 : 20, margin: '0 0 10px', textTransform: 'none', letterSpacing: '-0.01em', lineHeight: 1.2 }}>
          {album.title}
        </h3>
        <p style={{ fontSize: 13, color: 'var(--ink-500)', margin: '0 0 16px', lineHeight: 1.55, flex: 1 }}>
          {album.description}
        </p>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 6,
          fontSize: 12,
          color: 'var(--ink-900)',
          fontWeight: 700,
          textTransform: 'uppercase',
          letterSpacing: '0.08em',
          fontFamily: 'var(--font-display)',
        }}>
          Bekijk album <Icon.ArrowRight size={12} />
        </div>
      </div>
    </article>
  );
}

// ===== Album Detail (full page replacing list) =====
function AlbumDetail({ album, onBack }) {
  const { Placeholder, Reveal, Icon } = window.LM_UI;
  const [lightboxIdx, setLightboxIdx] = React.useState(null);

  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, []);

  // Lightbox keyboard nav
  React.useEffect(() => {
    if (lightboxIdx === null) return;
    const onKey = (e) => {
      if (e.key === 'Escape') setLightboxIdx(null);
      if (e.key === 'ArrowRight') setLightboxIdx((lightboxIdx + 1) % album.photos.length);
      if (e.key === 'ArrowLeft') setLightboxIdx((lightboxIdx - 1 + album.photos.length) % album.photos.length);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [lightboxIdx, album.photos.length]);

  const catMap = {
    gala: 'Jaarlijks Gala', optreden: 'Optreden', competitie: 'Competitie',
    showcase: 'Showcase', backstage: 'Backstage',
  };

  return (
    <div>
      {/* ===== Album header ===== */}
      <section style={{ paddingTop: 48, paddingBottom: 56 }}>
        <div className="container">
          <button onClick={onBack} className="btn btn-ghost btn-sm" style={{ marginBottom: 32 }}>
            <Icon.ArrowRight size={12} style={{ transform: 'rotate(180deg)' }} /> Alle albums
          </button>

          <Reveal>
            <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 56, alignItems: 'flex-end' }} className="album-header">
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                  <span className="stripe-accent"></span>
                  <span className="eyebrow">{catMap[album.category]} · {album.year}</span>
                </div>
                <h1 className="display" style={{ fontSize: 'clamp(40px, 6vw, 72px)', margin: '0 0 20px' }}>
                  {album.title}
                </h1>
                <p style={{ fontSize: 17, color: 'var(--ink-700)', maxWidth: 560, margin: 0 }}>
                  {album.description}
                </p>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, alignItems: 'flex-end' }}>
                <MetaStat label="Foto's" value={album.photos.length} />
                <MetaStat label="Maand" value={album.month} />
                <MetaStat label="Locatie" value={album.location} small />
              </div>
            </div>
          </Reveal>
        </div>
      </section>

      {/* ===== Photo grid ===== */}
      <section style={{ paddingBottom: 96 }}>
        <div className="container">
          <div className="album-photo-grid">
            {album.photos.map((photo, i) => {
              const label = typeof photo === 'string' ? photo : (photo.label || '');
              const url = typeof photo === 'string' ? '' : (photo.url || '');
              const isLarge = i % 7 === 0;
              return (
                <Reveal key={i} delay={(i % 6) * 50}>
                  <div
                    onClick={() => setLightboxIdx(i)}
                    style={{
                      position: 'relative',
                      borderRadius: 14,
                      overflow: 'hidden',
                      cursor: 'pointer',
                      aspectRatio: isLarge ? '4/3' : '1/1',
                      gridColumn: isLarge ? 'span 2' : 'span 1',
                      transition: 'transform .25s',
                    }}
                    onMouseEnter={(e) => { e.currentTarget.style.transform = 'scale(1.015)'; }}
                    onMouseLeave={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
                  >
                    <Placeholder label={label} ratio="auto" src={url} style={{ position: 'absolute', inset: 0, borderRadius: 14, aspectRatio: 'unset' }} />
                    {/* Hover gradient overlay */}
                    <div style={{
                      position: 'absolute',
                      inset: 0,
                      background: 'linear-gradient(180deg, transparent 60%, rgba(14,26,38,.6) 100%)',
                      opacity: 0,
                      transition: 'opacity .25s',
                      display: 'flex',
                      alignItems: 'flex-end',
                      padding: 16,
                    }}
                      onMouseEnter={(e) => { e.currentTarget.style.opacity = '1'; }}
                      onMouseLeave={(e) => { e.currentTarget.style.opacity = '0'; }}
                    >
                      <span className="mono" style={{ fontSize: 11, color: 'white', letterSpacing: '0.08em' }}>
                        #{String(i + 1).padStart(2, '0')}
                      </span>
                    </div>
                  </div>
                </Reveal>
              );
            })}
          </div>
        </div>
      </section>

      {/* ===== Lightbox ===== */}
      {lightboxIdx !== null && (
        <div
          onClick={() => setLightboxIdx(null)}
          style={{
            position: 'fixed', inset: 0,
            background: 'rgba(14,26,38,.94)',
            backdropFilter: 'blur(10px)',
            zIndex: 999,
            display: 'flex',
            flexDirection: 'column',
            padding: '24px 24px 40px',
          }}
        >
          {/* Top bar */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', color: 'white', marginBottom: 20 }}>
            <div>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--teal-300)' }}>
                {album.title}
              </div>
              <div style={{ fontSize: 13, opacity: 0.6, marginTop: 4 }}>
                {lightboxIdx + 1} / {album.photos.length}
              </div>
            </div>
            <button
              onClick={(e) => { e.stopPropagation(); setLightboxIdx(null); }}
              style={{ background: 'rgba(255,255,255,.1)', border: '1px solid rgba(255,255,255,.2)', color: 'white', width: 44, height: 44, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}
            >
              <Icon.Close />
            </button>
          </div>

          {/* Main image area */}
          <div onClick={(e) => e.stopPropagation()} style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', minHeight: 0 }}>
            <button
              onClick={(e) => { e.stopPropagation(); setLightboxIdx((lightboxIdx - 1 + album.photos.length) % album.photos.length); }}
              style={{ position: 'absolute', left: 0, background: 'rgba(255,255,255,.1)', border: '1px solid rgba(255,255,255,.2)', color: 'white', width: 48, height: 48, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', zIndex: 2 }}
            >
              <Icon.ArrowRight size={20} style={{ transform: 'rotate(180deg)' }} />
            </button>
            <button
              onClick={(e) => { e.stopPropagation(); setLightboxIdx((lightboxIdx + 1) % album.photos.length); }}
              style={{ position: 'absolute', right: 0, background: 'rgba(255,255,255,.1)', border: '1px solid rgba(255,255,255,.2)', color: 'white', width: 48, height: 48, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', zIndex: 2 }}
            >
              <Icon.ArrowRight size={20} />
            </button>

            <div style={{ maxWidth: 'min(1400px, 100%)', maxHeight: '100%', width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: 0 }}>
              {(() => {
                const ph = album.photos[lightboxIdx];
                const lbl = typeof ph === 'string' ? ph : (ph.label || '');
                const url = typeof ph === 'string' ? '' : (ph.url || '');
                return <>
                  {url ? (
                    <img
                      src={url}
                      alt={lbl}
                      style={{
                        maxWidth: '100%',
                        maxHeight: 'calc(100vh - 220px)',
                        width: 'auto',
                        height: 'auto',
                        objectFit: 'contain',
                        borderRadius: 12,
                        display: 'block',
                      }}
                    />
                  ) : (
                    <Placeholder label={lbl} ratio="16/10" style={{ borderRadius: 12, width: '100%' }} />
                  )}
                  <p style={{ textAlign: 'center', color: 'rgba(255,255,255,.7)', marginTop: 16, fontSize: 13 }}>{lbl}</p>
                </>;
              })()}
            </div>
          </div>

          {/* Thumbnails */}
          <div onClick={(e) => e.stopPropagation()} style={{ display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap', marginTop: 20, maxHeight: 80, overflowY: 'hidden' }}>
            {album.photos.map((_, i) => (
              <button
                key={i}
                onClick={(e) => { e.stopPropagation(); setLightboxIdx(i); }}
                style={{
                  width: 56, height: 56,
                  borderRadius: 6,
                  background: '#08080B',
                  border: lightboxIdx === i ? '2px solid var(--teal-500)' : '2px solid transparent',
                  cursor: 'pointer',
                  padding: 0,
                  overflow: 'hidden',
                  opacity: lightboxIdx === i ? 1 : 0.5,
                  transition: 'all .15s',
                  flexShrink: 0,
                }}
              >
                <div style={{
                  width: '100%', height: '100%',
                  background: 'repeating-linear-gradient(135deg, rgba(45,111,165,.2) 0 6px, rgba(45,111,165,.4) 6px 7px)',
                }}></div>
              </button>
            ))}
          </div>

          <div className="mono" style={{ textAlign: 'center', marginTop: 12, fontSize: 10, color: 'rgba(255,255,255,.4)', letterSpacing: '0.16em', textTransform: 'uppercase' }}>
            Esc om te sluiten · ← → om te navigeren
          </div>
        </div>
      )}

      <style>{`
        .album-photo-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 14px;
        }
        @media (max-width: 880px) {
          .album-photo-grid { grid-template-columns: repeat(3, 1fr); }
          .album-header { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
        @media (max-width: 560px) {
          .album-photo-grid { grid-template-columns: repeat(2, 1fr); }
          .album-photo-grid > * > div {
            grid-column: span 1 !important;
          }
        }
      `}</style>
    </div>
  );
}

function MetaStat({ label, value, small }) {
  return (
    <div style={{ borderTop: '1px solid var(--border)', paddingTop: 12 }}>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 6 }}>{label}</div>
      <div className="display" style={{ fontSize: small ? 16 : 28, lineHeight: 1.1, textTransform: 'none', letterSpacing: '-0.01em' }}>{value}</div>
    </div>
  );
}

window.LM_PAGES = window.LM_PAGES || {};
window.LM_PAGES.Galerij = GalerijPage;
