// ============================================
// HOME page
// ============================================

function HomePage({ navigate }) {
  const { Placeholder, Reveal, Icon } = window.LM_UI;
  const { DANCE_STYLES, TICKER } = window.LM_DATA;
  const { t, img } = window.LM_CMS;
  const site = window.LM_CMS.site();
  // Promo-blok onderaan de home — standaard zichtbaar, uit te zetten via admin
  const showGDans = site.showGDansBanner !== false;
  // Optioneel een uitgelichte stijl: titel/beschrijving/knop komen dan uit die stijl
  const promoStyle = site.promoStyleId ? (DANCE_STYLES || []).find(st => st.id === site.promoStyleId) : null;

  const featured = ['hiphop', 'klassiek-ballet', 'jazzdance', 'g-dans']
    .map(id => DANCE_STYLES.find(s => s.id === id))
    .filter(Boolean);

  // Bereken inschrijvingen-status (globaal + per stijl) voor de badge
  const REG = window.LM_DATA?.REGISTRATIONS || { enabled: true, openLabel: 'Inschrijvingen open', closedLabel: 'Inschrijvingen gesloten', partialLabel: 'Beperkt open' };
  const totalStyles = DANCE_STYLES.length;
  const openStyles = DANCE_STYLES.filter(s => s.registrationOpen !== false).length;
  const regStatus = (REG.enabled === false || openStyles === 0)
    ? 'closed'
    : (openStyles < totalStyles ? 'partial' : 'open');
  const regBadgeLabel = regStatus === 'closed'
    ? (REG.closedLabel || 'Inschrijvingen gesloten')
    : regStatus === 'partial'
      ? (REG.partialLabel || 'Beperkt open')
      : (REG.openLabel || 'Inschrijvingen open');
  const regBadgeColor = regStatus === 'closed' ? '#b91c1c' : regStatus === 'partial' ? '#f59e0b' : 'var(--teal-500)';

  // Hero-subline: dynamisch op basis van werkelijk aantal stijlen + locaties.
  // Admin kan via Teksten nog steeds een aangepaste fallback zetten, maar standaard rekenen we live.
  const locCount = (window.LM_DATA?.LOCATIONS || []).length;
  const dynamicSubline = (() => {
    const stylesPart = totalStyles > 0
      ? `${totalStyles} ${totalStyles === 1 ? 'stijl' : 'stijlen'}`
      : null;
    const studioPart = locCount > 0
      ? `${locCount} ${locCount === 1 ? 'winkel' : 'winkels'}`
      : null;
    const communityPart = '1 community';
    return [stylesPart, studioPart, communityPart].filter(Boolean).join(' · ');
  })();

  return (
    <div>
      {/* ===== HERO (full-bleed video achtergrond) ===== */}
      <section style={{
        position: 'relative',
        overflow: 'hidden',
        minHeight: 'min(88vh, 880px)',
        display: 'flex',
        alignItems: 'flex-end',
        color: 'white',
        background: '#0e1a26',
      }}>
        {/* Full-bleed video achtergrond */}
        {(() => {
          const videoSrc = img('home.hero.video', '');
          if (!videoSrc) {
            return (
              <div style={{
                position: 'absolute', inset: 0, zIndex: 0,
                background: 'linear-gradient(135deg, #0e1a26 0%, #2d6fa5 50%, #3fa89e 100%)',
                backgroundSize: '200% 200%',
                animation: 'lmHeroBg 14s ease infinite',
              }} />
            );
          }
          const videoUrl = videoSrc.replace(/^(?!\/|https?:\/\/|\/\/|data:)/, '/');
          return (
            <video
              src={videoUrl}
              autoPlay muted playsInline
              onTimeUpdate={(e) => {
                const v = e.currentTarget;
                if (v.duration && v.currentTime >= v.duration - 0.3) {
                  v.pause();
                  v.currentTime = Math.max(0, v.duration - 0.3);
                }
              }}
              style={{
                position: 'absolute',
                top: 0, left: 0,
                width: '100%', height: '100%',
                objectFit: 'cover',
                zIndex: 0,
              }}
            />
          );
        })()}

        {/* Verloop alleen onderaan — houdt het midden vrij zodat de video zichtbaar blijft */}
        <div style={{
          position: 'absolute', inset: 0, zIndex: 1,
          background: 'linear-gradient(180deg, rgba(14,26,38,.35) 0%, rgba(14,26,38,0) 30%, rgba(14,26,38,0) 50%, rgba(14,26,38,.85) 100%)',
          pointerEvents: 'none',
        }} />

        {/* Onderaan-links content overlay — tegen de linkerkant, midden vrij voor de video */}
        <div className="lm-hero-content" style={{
          position: 'relative',
          zIndex: 2,
          paddingBottom: 56,
          paddingTop: 80,
          paddingLeft: 48,
          paddingRight: 32,
          width: '100%',
          maxWidth: '100%',
        }}>
          <Reveal>
            <div style={{ maxWidth: 460 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                <span className="stripe-accent"></span>
                <span className="eyebrow" style={{ color: 'var(--teal-300)' }}>{t('home.hero.eyebrow', 'Dance School · Sinds 2008')}</span>
              </div>
              <p style={{
                fontSize: 17,
                lineHeight: 1.55,
                color: 'rgba(255,255,255,.92)',
                margin: '0 0 8px',
                textShadow: '0 2px 12px rgba(0,0,0,.5)',
              }}>
                {t('home.hero.lead', "Dance Studio is een professionele dansschool voor alle leeftijden — van kleuterdans tot competitie­teams.")}
              </p>
              <p className="mono" style={{ fontSize: 13, color: 'rgba(255,255,255,.65)', margin: '0 0 24px', textShadow: '0 2px 8px rgba(0,0,0,.4)' }}>
                {t('home.hero.subline', dynamicSubline)}
              </p>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
                <button className="btn btn-primary" onClick={() => navigate('lessen')}>
                  {t('home.hero.cta1', 'Bekijk lessen')} <Icon.ArrowRight />
                </button>
                {/* Thema-bewust: surface + ink — op donkere templates was de pill
                    voorheen wit mét bijna-witte tekst (onleesbaar). */}
                <div style={{
                  background: 'var(--surface)',
                  color: 'var(--ink-900)',
                  border: '1px solid var(--border)',
                  padding: '8px 14px',
                  borderRadius: 999,
                  boxShadow: 'var(--shadow-md)',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 8,
                  fontSize: 12,
                  fontWeight: 700,
                  backdropFilter: 'blur(8px)',
                }} title={regStatus === 'partial' ? `${openStyles}/${totalStyles} stijlen open` : ''}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: regBadgeColor, animation: regStatus === 'closed' ? 'none' : 'lmHeroPulse 2s ease-in-out infinite' }}></span>
                  {regBadgeLabel}
                </div>
              </div>
            </div>
          </Reveal>
        </div>

        <style>{`
          @keyframes lmHeroBg     { 0%,100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }
          @keyframes lmHeroPulse  { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.4; transform: scale(1.3); } }
          @media (max-width: 720px) {
            .lm-hero-content { padding-left: 20px !important; padding-right: 20px !important; }
          }
        `}</style>
      </section>

      {/* ===== TICKER STRIP ===== */}
      <section style={{
        background: '#08080B',
        color: 'white',
        padding: '20px 0',
        overflow: 'hidden',
        borderTop: '1px solid rgba(255,255,255,.08)',
        borderBottom: '1px solid rgba(255,255,255,.08)',
      }}>
        <div style={{ display: 'flex', gap: 56, whiteSpace: 'nowrap', animation: 'ticker 40s linear infinite' }}>
          {[...Array(3)].map((_, k) => (
            <div key={k} style={{ display: 'flex', gap: 56, alignItems: 'center', flexShrink: 0 }}>
              {(TICKER && TICKER.length ? TICKER : ['Kleuterdans', 'Ballet', 'Jazz', 'Hip-Hop', 'Videodance', 'Showteams', 'Cheer Crew', 'Disco', 'G-Dans', 'Modern Ballet']).filter(s => s && s.trim()).map((s, i) => (
                <React.Fragment key={i}>
                  <span className="display" style={{ fontSize: 32, color: 'white' }}>{s}</span>
                  <span style={{ color: 'var(--teal-500)', fontSize: 20 }}>✦</span>
                </React.Fragment>
              ))}
            </div>
          ))}
        </div>
        <style>{`
          @keyframes ticker {
            from { transform: translateX(0); }
            to { transform: translateX(-33.33%); }
          }
        `}</style>
      </section>

      {/* ===== STATS ===== */}
      <section className="section">
        <div className="container">
          <div className="grid grid-4 stagger reveal" ref={(el) => {
            if (el) {
              const obs = new IntersectionObserver(([e]) => e.isIntersecting && el.classList.add('in'), { threshold: 0.2 });
              obs.observe(el);
            }
          }}>
            {[
              { num: t('home.stats.0.num', '14+'),  label: t('home.stats.0.label', 'Dansstijlen') },
              { num: t('home.stats.1.num', '350+'), label: t('home.stats.1.label', 'Actieve dansers') },
              { num: t('home.stats.2.num', '17'),   label: t('home.stats.2.label', 'Jaar ervaring') },
              { num: t('home.stats.3.num', '20+'),  label: t('home.stats.3.label', 'Optredens per jaar') },
            ].map((s, i) => (
              <div key={i} style={{ padding: '32px 0', borderTop: '1px solid var(--border)' }}>
                <div className="display grad-text" style={{ fontSize: 'clamp(48px, 6vw, 72px)', marginBottom: 8 }}>{s.num}</div>
                <div className="mono" style={{ fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-500)' }}>{s.label}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ===== FEATURED STYLES ===== */}
      <section className="section section-tinted">
        <div className="container">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 24, marginBottom: 56 }}>
            <Reveal>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                <span className="stripe-accent"></span>
                <span className="eyebrow">{t('home.featured.eyebrow', 'Onze stijlen')}</span>
              </div>
              <h2 className="display" style={{ fontSize: 'clamp(36px, 5vw, 64px)', margin: 0 }}>
                {t('home.featured.title1', 'Vind je')} <span className="grad-text">{t('home.featured.title2', 'stijl.')}</span>
              </h2>
            </Reveal>
            <Reveal delay={100}>
              <button className="btn btn-ghost" onClick={() => navigate('lessen')}>
                {t('home.featured.cta', `Alle ${totalStyles} ${totalStyles === 1 ? 'stijl' : 'stijlen'}`)} <Icon.ArrowRight />
              </button>
            </Reveal>
          </div>

          <div className="grid grid-4">
            {featured.map((s, i) => (
              <Reveal key={s.id} delay={i * 80}>
                <article className="card" style={{ overflow: 'hidden', cursor: 'pointer', transition: 'transform .2s, box-shadow .2s', height: '100%' }}
                  onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-6px)'; e.currentTarget.style.boxShadow = 'var(--shadow-lg)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'var(--shadow-sm)'; }}
                  onClick={() => navigate('lessen')}
                >
                  <Placeholder label={s.id} ratio="4/5" src={s.image || ''} style={{ borderRadius: 0 }} />
                  <div style={{ padding: 20 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                      <span className={`style-tag style-tag-${s.tone}`}>{s.isNew ? 'Nieuw' : 'Lessen'}</span>
                      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-500)' }}>{s.age}</span>
                    </div>
                    <h3 className="display" style={{ fontSize: 20, margin: '0 0 8px', textTransform: 'none', letterSpacing: '-0.01em', lineHeight: 1.15 }}>{s.name}</h3>
                    <p style={{ fontSize: 13, color: 'var(--ink-500)', margin: 0, lineHeight: 1.5 }}>{s.description}</p>
                  </div>
                </article>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      {/* ===== APPROACH ===== */}
      <section className="section">
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.2fr)', gap: 80, alignItems: 'center' }} className="hero-grid">
            <Reveal>
              <div style={{ position: 'relative' }}>
                <Placeholder label="winkel interieur" ratio="1/1" src={img('home.approach.studio', '')} style={{ borderRadius: 20 }} />
                <div style={{
                  position: 'absolute',
                  bottom: -24, right: -24,
                  background: 'var(--surface)',
                  // Thema-bewust: was hardcoded wit → onzichtbaar op lichte thema's
                  color: 'var(--ink-900)',
                  padding: 24,
                  border: '1px solid var(--border)',
                  borderRadius: 16,
                  boxShadow: 'var(--shadow-lg)',
                  maxWidth: 240,
                }}>
                  {(() => {
                    // Live gekoppeld aan de Locaties-lijst uit het admin paneel.
                    // Valt terug op de tekstkey (admin > Teksten) als er nog geen locaties ingevoerd zijn.
                    const locCount = (window.LM_DATA?.LOCATIONS || []).length;
                    const fallbackNum = t('home.approach.studio.number', '2');
                    const num = locCount > 0 ? locCount : fallbackNum;
                    const labelText = locCount > 0
                      ? (locCount === 1 ? 'Volledig uitgeruste danswinkel met sprung floor' : `Volledig uitgeruste danswinkels met sprung floor`)
                      : t('home.approach.studio.label', "Volledig uitgeruste danswinkels met sprung floor");
                    return (
                      <>
                        <div className="display" style={{ fontSize: 40, color: 'var(--teal-500)', lineHeight: 1 }}>{num}</div>
                        <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: 4 }}>{labelText}</div>
                      </>
                    );
                  })()}
                </div>
              </div>
            </Reveal>

            <Reveal delay={100}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                <span className="stripe-accent"></span>
                <span className="eyebrow">{t('home.approach.eyebrow', 'Onze aanpak')}</span>
              </div>
              <h2 className="display" style={{ fontSize: 'clamp(36px, 5vw, 56px)', margin: '0 0 24px' }}>
                {t('home.approach.title', 'Techniek, expressie en plezier — in balans.')}
              </h2>
              <p style={{ fontSize: 17, color: 'var(--ink-700)', marginBottom: 32 }}>
                {t('home.approach.body', "Of je nu voor het eerst je dansschoenen aantrekt of competitief wil dansen: bij Dance Studio krijg je gestructureerde, kwalitatieve lessen door gepassioneerde docenten. We werken aan techniek én aan vertrouwen op de dansvloer.")}
              </p>

              <div style={{ display: 'grid', gap: 20 }}>
                {[
                  { title: t('home.approach.benefit1.title', 'Gediplomeerde docenten'), text: t('home.approach.benefit1.text', 'Elke docent heeft een dansachtergrond en pedagogische opleiding.') },
                  { title: t('home.approach.benefit2.title', 'Jaarlijks gala & optredens'), text: t('home.approach.benefit2.text', 'Iedere danser kan op het podium — van kleuters tot teams.') },
                  { title: t('home.approach.benefit3.title', 'Inclusief & toegankelijk'), text: t('home.approach.benefit3.text', 'Met de nieuwe G-Dans dansen we letterlijk met iedereen.') },
                ].map((b, i) => (
                  <div key={i} style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 8,
                      background: 'var(--gradient)',
                      color: 'white',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      <Icon.Check size={18} />
                    </div>
                    <div>
                      <h4 className="display" style={{ fontSize: 16, margin: '4px 0 4px', textTransform: 'none', letterSpacing: '0' }}>{b.title}</h4>
                      <p style={{ fontSize: 14, color: 'var(--ink-500)', margin: 0 }}>{b.text}</p>
                    </div>
                  </div>
                ))}
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      {/* ===== CTA STRIP (G-Dans promo — aan/uit via admin) ===== */}
      {showGDans && (
      <section style={{
        background: 'var(--gradient)',
        // on-accent = automatisch berekende leesbare kleur op het accent (wit of
        // donker) — hardcoded wit was onleesbaar op thema's met licht accent.
        color: 'var(--on-accent)',
        padding: '80px 0',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute',
          inset: 0,
          background: 'repeating-linear-gradient(-45deg, transparent 0 40px, rgba(255,255,255,.08) 40px 41px)',
          pointerEvents: 'none',
        }}></div>
        <div className="container" style={{ position: 'relative' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 56, alignItems: 'center' }} className="hero-grid">
            <Reveal>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                <span className="stripe-accent"></span>
                <span className="eyebrow" style={{ color: 'var(--on-accent)', opacity: .85 }}>{t('home.cta.eyebrow', 'Nieuw dit seizoen')}</span>
              </div>
              {/* Geen grad-text hier: gradient-tekst op dezelfde gradient-achtergrond
                  lost op in de achtergrond. on-accent is altijd leesbaar. */}
              <h2 className="display" style={{ fontSize: 'clamp(40px, 6vw, 72px)', margin: '0 0 20px', color: 'var(--on-accent)' }}>
                <span>{promoStyle ? promoStyle.name : t('home.cta.title1', 'G-Dans')}</span> {t('home.cta.title2', '— iedereen danst mee.')}
              </h2>
              <p style={{ fontSize: 18, color: 'var(--on-accent)', opacity: .8, maxWidth: 560, margin: 0 }}>
                {promoStyle && promoStyle.description ? promoStyle.description : t('home.cta.body', 'Onze nieuwe inclusieve dansles voor personen met een beperking. Een veilige, energieke ruimte waar elk talent gevierd wordt.')}
              </p>
            </Reveal>
            <Reveal delay={100}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'flex-start' }}>
                <button className="btn btn-primary" onClick={() => navigate('lessen')}>
                  {promoStyle ? ('Meer over ' + promoStyle.name) : t('home.cta.button1', 'Meer over G-Dans')} <Icon.ArrowRight />
                </button>
                <button className="btn" style={{ background: 'transparent', color: 'var(--on-accent)', border: '1.5px solid var(--on-accent)', opacity: .9 }}
                  onClick={() => navigate('contact')}
                >
                  {t('home.cta.button2', 'Contacteer ons')}
                </button>
              </div>
            </Reveal>
          </div>
        </div>
      </section>
      )}

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

window.LM_PAGES = window.LM_PAGES || {};
window.LM_PAGES.Home = HomePage;
