// ============================================
// LESSEN page — filter + schedule
// ============================================

function LessenPage({ navigate }) {
  const { Placeholder, Reveal, SectionHeader, Icon } = window.LM_UI;
  const { DANCE_STYLES, CATEGORIES, DAYS, SCHEDULE, TEAM, LOCATIONS } = window.LM_DATA;
  const { t } = window.LM_CMS;

  const [filter, setFilter] = React.useState('all');
  const [ageFilter, setAgeFilter] = React.useState('all');
  const [view, setView] = React.useState('grid'); // 'grid' or 'schedule'
  const [styleInfo, setStyleInfo] = React.useState(null); // open info-modal voor een stijl

  // ESC sluit de modal + lock scroll
  React.useEffect(() => {
    if (!styleInfo) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setStyleInfo(null); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [styleInfo]);

  const filtered = DANCE_STYLES.filter(s => {
    if (filter !== 'all' && s.category !== filter) return false;
    if (ageFilter === 'kids' && !s.age.includes('3') && !s.age.includes('4') && !s.age.includes('5') && !s.age.includes('6')) return false;
    if (ageFilter === 'teens' && !s.age.includes('10') && !s.age.includes('12') && !s.age.includes('+')) return false;
    return true;
  });

  return (
    <div>
      {/* ===== INTRO ===== */}
      <section className="section" style={{ paddingBottom: 32 }}>
        <div className="container">
          <SectionHeader
            eyebrow={t('lessen.intro.eyebrow', 'Lessenaanbod')}
            title={t('lessen.intro.title', `${DANCE_STYLES.length} ${DANCE_STYLES.length === 1 ? 'stijl' : 'stijlen'} — voor elk niveau.`)}
            subtitle={t('lessen.intro.subtitle', 'Van kleuterdans tot competitie. Filter op categorie of leeftijd om je perfecte les te vinden.')}
          />

          {/* View switcher */}
          <Reveal>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16, marginBottom: 24 }}>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
                <span className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)', marginRight: 8 }}>
                  <Icon.Filter size={12} /> {t('lessen.filter.label', 'Categorie:')}
                </span>
                {CATEGORIES.map(c => (
                  <button
                    key={c.id}
                    className={`chip ${filter === c.id ? 'active' : ''}`}
                    onClick={() => setFilter(c.id)}
                  >
                    {c.label}
                  </button>
                ))}
              </div>

              <div style={{ display: 'flex', gap: 4, background: 'var(--ink-100)', padding: 4, borderRadius: 8 }}>
                <button
                  onClick={() => setView('grid')}
                  className="mono"
                  style={{
                    padding: '8px 14px',
                    fontSize: 11,
                    letterSpacing: '0.12em',
                    textTransform: 'uppercase',
                    border: 'none',
                    background: view === 'grid' ? 'var(--teal-500)' : 'transparent',
                    color: view === 'grid' ? '#fff' : 'var(--ink-500)',
                    borderRadius: 6,
                    fontWeight: 600,
                    boxShadow: view === 'grid' ? 'var(--shadow-sm)' : 'none',
                  }}>{t('lessen.view.styles', 'Stijlen')}</button>
                <button
                  onClick={() => setView('schedule')}
                  className="mono"
                  style={{
                    padding: '8px 14px',
                    fontSize: 11,
                    letterSpacing: '0.12em',
                    textTransform: 'uppercase',
                    border: 'none',
                    background: view === 'schedule' ? 'var(--teal-500)' : 'transparent',
                    color: view === 'schedule' ? '#fff' : 'var(--ink-500)',
                    borderRadius: 6,
                    fontWeight: 600,
                    boxShadow: view === 'schedule' ? 'var(--shadow-sm)' : 'none',
                  }}>{t('lessen.view.schedule', 'Uurrooster')}</button>
              </div>
            </div>
          </Reveal>
        </div>
      </section>

      {/* ===== GRID VIEW ===== */}
      {view === 'grid' && (
        <section style={{ paddingBottom: 96 }}>
          <div className="container">
            <div className="grid grid-3">
              {filtered.map((s, i) => (
                <Reveal key={s.id} delay={(i % 6) * 60}>
                  <article
                    className="card"
                    onClick={() => setStyleInfo(s)}
                    style={{
                      overflow: 'hidden', height: '100%', display: 'flex', flexDirection: 'column',
                      cursor: 'pointer', transition: 'transform .2s, box-shadow .2s',
                    }}
                    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)'; }}
                  >
                    <div style={{ position: 'relative' }}>
                      <Placeholder label={s.id} ratio="16/10" src={s.image || ''} style={{ borderRadius: 0 }} />
                      {s.isNew && (
                        <div style={{
                          position: 'absolute',
                          top: 12, left: 12,
                          background: 'var(--teal-500)',
                          color: 'white',
                          padding: '6px 12px',
                          borderRadius: 4,
                          fontSize: 10,
                          letterSpacing: '0.16em',
                          textTransform: 'uppercase',
                          fontWeight: 700,
                          fontFamily: 'var(--font-display)',
                        }}>★ Nieuw</div>
                      )}
                    </div>
                    <div style={{ padding: 24, flex: 1, display: 'flex', flexDirection: 'column' }}>
                      <div style={{ display: 'flex', gap: 6, marginBottom: 12, flexWrap: 'wrap' }}>
                        <span className="style-tag style-tag-ink">{s.age}</span>
                      </div>
                      <h3 className="display" style={{ fontSize: 22, margin: '0 0 10px', textTransform: 'none', letterSpacing: '-0.01em', lineHeight: 1.15 }}>{s.name}</h3>
                      <p style={{ fontSize: 14, color: 'var(--ink-500)', margin: '0 0 20px', flex: 1, lineHeight: 1.55 }}>{s.description}</p>
                      <div className="mono" style={{ fontSize: 11, color: 'var(--teal-700)', letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600 }}>
                        Meer info <Icon.ArrowRight size={11} />
                      </div>
                    </div>
                  </article>
                </Reveal>
              ))}
            </div>
            {filtered.length === 0 && (
              <div style={{ textAlign: 'center', padding: 80, color: 'var(--ink-500)' }}>
                {t('lessen.empty', 'Geen stijlen gevonden met deze filters.')}
              </div>
            )}
          </div>
        </section>
      )}

      {/* ===== SCHEDULE VIEW ===== */}
      {view === 'schedule' && (
        <section style={{ paddingBottom: 96 }}>
          <div className="container">
            <ScheduleCalendar filter={filter} navigate={navigate} />
          </div>
        </section>
      )}

      {/* ===== CTA ===== */}
      <section className="section section-tinted">
        <div className="container">
          <div className="card" style={{ padding: '56px 48px', textAlign: 'center', background: 'var(--gradient)', color: 'white', border: 'none', position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, background: 'repeating-linear-gradient(-45deg, transparent 0 40px, rgba(63,168,158,.05) 40px 41px)' }}></div>
            <div style={{ position: 'relative' }}>
              <h2 className="display" style={{ fontSize: 'clamp(32px, 4vw, 48px)', margin: '0 0 16px' }}>
                {t('lessen.cta.title1', 'Probeer een')} <span className="grad-text">{t('lessen.cta.title2', 'gratis')}</span> {t('lessen.cta.title3', 'proefles.')}
              </h2>
              <p style={{ fontSize: 16, color: 'rgba(255,255,255,.7)', maxWidth: 520, margin: '0 auto 28px' }}>
                {t('lessen.cta.body', 'Niet zeker welke stijl bij je past? Kom een les meedoen — vrijblijvend en gratis.')}
              </p>
              <button className="btn btn-primary" onClick={() => navigate('contact')}>
                {t('lessen.cta.button', 'Plan proefles')} <Icon.ArrowRight />
              </button>
            </div>
          </div>
        </div>
      </section>

      {/* ===== Style-info modal (klik op een kaart in grid view) ===== */}
      {styleInfo && (
        <DanceStyleModal
          style={styleInfo}
          schedule={SCHEDULE}
          days={DAYS}
          team={TEAM || []}
          locations={LOCATIONS || []}
          onClose={() => setStyleInfo(null)}
          onRegister={() => { if (window.LM_GO_INSCHRIJVEN) window.LM_GO_INSCHRIJVEN(styleInfo.inschrijfUrl); setStyleInfo(null); }}
          onGoToSchedule={() => { setStyleInfo(null); setView('schedule'); }}
        />
      )}
    </div>
  );
}

// ===== Schedule Calendar component =====
function ScheduleCalendar({ filter, navigate }) {
  const { Reveal, Icon } = window.LM_UI;
  const { DANCE_STYLES, DAYS, SCHEDULE, TEAM } = window.LM_DATA;

  const styleMap = Object.fromEntries(DANCE_STYLES.map(s => [s.id, s]));
  const teacherMap = Object.fromEntries((TEAM || []).map(t => [t.id, t]));

  const [active, setActive] = React.useState(null); // klik op een les → toont detail-modal

  React.useEffect(() => {
    if (!active) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setActive(null); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [active]);

  const filteredSchedule = SCHEDULE.filter(s => {
    if (filter === 'all') return true;
    return styleMap[s.styleId]?.category === filter;
  });

  // Group by day
  const byDay = DAYS.map((_, dayIdx) =>
    filteredSchedule.filter(s => s.day === dayIdx).sort((a, b) => a.start.localeCompare(b.start))
  );

  // Hour range
  const HOURS = ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00'];

  const timeToMinutes = (t) => {
    const [h, m] = t.split(':').map(Number);
    return h * 60 + m;
  };

  const dayStart = timeToMinutes('09:00');
  const dayEnd = timeToMinutes('22:00');
  const totalMin = dayEnd - dayStart;

  // Toon vakantieperiodes die binnenkort of nu lopen
  // Backwards-compat: ondersteun zowel {label,from,to} (huidig) als {name,start,end} (oude data)
  const VACATIONS = (window.LM_DATA?.VACATIONS || []).map(v => ({
    label: v.label || v.name || 'Vakantie',
    from: v.from || v.start || '',
    to: v.to || v.end || '',
  }));
  const now = new Date();
  const upcomingVacations = VACATIONS
    .filter(v => v.from && v.to && new Date(v.to) >= now)
    .sort((a, b) => new Date(a.from) - new Date(b.from))
    .slice(0, 5);

  return (
    <Reveal>
      {upcomingVacations.length > 0 && (
        <div style={{
          marginBottom: 16,
          padding: '14px 20px',
          background: 'var(--gradient-soft)',
          border: '1px solid var(--blue-100, #d0e1f0)',
          borderRadius: 12,
          display: 'flex',
          alignItems: 'center',
          gap: 14,
          flexWrap: 'wrap',
        }}>
          <span style={{ fontSize: 22 }}>📅</span>
          <div style={{ flex: 1, minWidth: 200 }}>
            <strong style={{ fontSize: 13, color: 'var(--ink-900)' }}>Geen les tijdens:</strong>
            <div style={{ fontSize: 13, color: 'var(--ink-700)', marginTop: 2 }}>
              {upcomingVacations.map((v, i) => (
                <span key={i}>
                  <strong>{v.label}</strong> — {new Date(v.from).toLocaleDateString('nl-BE', { day: 'numeric', month: 'short' })} t.e.m. {new Date(v.to).toLocaleDateString('nl-BE', { day: 'numeric', month: 'short' })}
                  {i < upcomingVacations.length - 1 && <span style={{ color: 'var(--ink-400)' }}> · </span>}
                </span>
              ))}
            </div>
          </div>
        </div>
      )}

      <div className="card" style={{ overflow: 'hidden' }}>
        <div className="schedule-scroll">
          <div className="schedule-scroll-inner">
            {/* Header */}
            <div style={{
              display: 'grid',
              gridTemplateColumns: '80px repeat(6, 1fr)',
              borderBottom: '1px solid var(--border)',
              background: 'var(--ink-50)',
            }}>
              <div style={{ padding: '16px 12px', fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-500)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>Tijd</div>
              {DAYS.map((day, i) => (
                <div key={i} style={{ padding: '16px 12px', borderLeft: '1px solid var(--border)' }}>
                  <div className="display" style={{ fontSize: 14, lineHeight: 1.2, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{day}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ink-500)', marginTop: 2 }}>{byDay[i].length} {byDay[i].length === 1 ? 'les' : 'lessen'}</div>
                </div>
              ))}
            </div>

            {/* Body */}
            <div style={{ display: 'grid', gridTemplateColumns: '80px repeat(6, 1fr)', minHeight: 780, position: 'relative' }}>
              {/* Hour column */}
              <div style={{ borderRight: '1px solid var(--border)' }}>
                {HOURS.map((h, i) => (
                  <div key={i} style={{
                    height: 60,
                    padding: '6px 10px',
                    fontSize: 10,
                    fontFamily: 'var(--font-mono)',
                    color: 'var(--ink-400)',
                    borderBottom: '1px solid var(--ink-100)',
                    letterSpacing: '0.04em',
                  }}>{h}</div>
                ))}
              </div>

              {/* Day columns */}
              {DAYS.map((_, dayIdx) => (
                <div key={dayIdx} style={{
                  position: 'relative',
                  borderRight: dayIdx === DAYS.length - 1 ? 'none' : '1px solid var(--border)',
                  background: 'repeating-linear-gradient(transparent 0 59px, var(--ink-100) 59px 60px)',
                }}>
                  {byDay[dayIdx].map((cls, i) => {
                    const style = styleMap[cls.styleId];
                    const top = ((timeToMinutes(cls.start) - dayStart) / 60) * 60;
                    const height = ((timeToMinutes(cls.end) - timeToMinutes(cls.start)) / 60) * 60;
                    const colors = {
                      teal: { bg: 'var(--teal-50)', border: 'var(--teal-500)', text: 'var(--teal-700)' },
                      blue: { bg: 'var(--blue-50)', border: 'var(--blue-500)', text: 'var(--blue-700)' },
                      ink:  { bg: 'var(--ink-100)', border: 'var(--ink-900)', text: 'var(--ink-900)' },
                      new:  { bg: 'var(--teal-500)', border: 'var(--teal-500)', text: 'white' },
                    };
                    const c = colors[style.tone] || colors.blue;
                    // Backward-compat: ondersteun zowel teacherIds/defaultTeacherIds (arrays, nieuw) als de oude single-velden
                    const slotIds = Array.isArray(cls.teacherIds) ? cls.teacherIds : (cls.teacherId ? [cls.teacherId] : []);
                    const defaultIds = Array.isArray(style.defaultTeacherIds)
                      ? style.defaultTeacherIds
                      : (style.defaultTeacherId ? [style.defaultTeacherId] : []);
                    // Eerste docent voor rooster-grid weergave (alleen één naam past)
                    const teacherId = slotIds[0] || defaultIds[0] || '';
                    const teacher = teacherId ? teacherMap[teacherId] : null;
                    return (
                      <div
                        key={i}
                        onClick={() => setActive({ cls, dayIdx })}
                        style={{
                          position: 'absolute',
                          top: top + 2,
                          left: 4, right: 4,
                          height: height - 4,
                          background: c.bg,
                          borderLeft: `3px solid ${c.border}`,
                          borderRadius: 6,
                          padding: '6px 8px',
                          fontSize: 11,
                          cursor: 'pointer',
                          overflow: 'hidden',
                          color: c.text,
                          transition: 'transform .15s, box-shadow .15s',
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateX(2px)'; e.currentTarget.style.boxShadow = 'var(--shadow-md)'; e.currentTarget.style.zIndex = 10; }}
                        onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateX(0)'; e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.zIndex = 1; }}
                      >
                        <div style={{ fontWeight: 700, fontSize: 12, lineHeight: 1.2, marginBottom: 2 }}>{style.name}</div>
                        <div className="mono" style={{ fontSize: 10, opacity: 0.7 }}>{cls.start}–{cls.end}</div>
                        {height > 60 && (
                          <div className="mono" style={{ fontSize: 10, opacity: 0.7, marginTop: 2 }}>{cls.studio}{teacher ? ` · ${teacher.name}` : ''}</div>
                        )}
                      </div>
                    );
                  })}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Scroll hint (mobile only) */}
        <div className="schedule-hint mono" style={{
          padding: '10px 20px',
          borderTop: '1px solid var(--border)',
          background: 'var(--ink-50)',
          fontSize: 10,
          letterSpacing: '0.14em',
          textTransform: 'uppercase',
          color: 'var(--ink-500)',
          display: 'none',
          textAlign: 'center',
        }}>← Scroll horizontaal voor alle dagen →</div>

        {/* Legend */}
        <div style={{ padding: '20px 24px', borderTop: '1px solid var(--border)', background: 'var(--ink-50)', display: 'flex', gap: 24, flexWrap: 'wrap', fontSize: 12, color: 'var(--ink-500)' }}>
          <span className="mono" style={{ letterSpacing: '0.12em', textTransform: 'uppercase' }}>Legende:</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 12, background: 'var(--teal-50)', borderLeft: '3px solid var(--teal-500)' }}></span>Kleuters / Jazz</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 12, background: 'var(--blue-50)', borderLeft: '3px solid var(--blue-500)' }}></span>Ballet / Disco</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 12, background: 'var(--ink-100)', borderLeft: '3px solid var(--ink-900)' }}></span>Urban / Showteams</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 12, height: 12, background: 'var(--ink-900)', borderLeft: '3px solid var(--teal-500)' }}></span>G-Dans (nieuw)</span>
        </div>
      </div>

      <style>{`
        @media (max-width: 760px) {
          .schedule-hint { display: block !important; }
        }
      `}</style>

      {active && (() => {
        const style = styleMap[active.cls.styleId];
        // Backward-compat: ondersteun zowel teacherIds/defaultTeacherIds (arrays) als de oude single-velden
        const slotIds = Array.isArray(active.cls.teacherIds)
          ? active.cls.teacherIds
          : (active.cls.teacherId ? [active.cls.teacherId] : []);
        const defaultIds = Array.isArray(style?.defaultTeacherIds)
          ? style.defaultTeacherIds
          : (style?.defaultTeacherId ? [style.defaultTeacherId] : []);
        // Welke docenten tonen we?
        //   - Heeft het lesuur eigen docenten? → alleen die.
        //   - Anders: fall back naar de default-docenten van de stijl.
        const effectiveIds = slotIds.length > 0 ? slotIds : defaultIds;
        const allTeachers = effectiveIds.map(id => teacherMap[id]).filter(Boolean);
        const primaryTeacher = allTeachers[0] || null;
        const extraTeachers = allTeachers.slice(1);
        return (
          <ScheduleClassModal
            cls={active.cls}
            dayLabel={DAYS[active.dayIdx]}
            style={style}
            teacher={primaryTeacher}
            extraTeachers={extraTeachers}
            onClose={() => setActive(null)}
            onRegister={() => { if (window.LM_GO_INSCHRIJVEN) window.LM_GO_INSCHRIJVEN(style.inschrijfUrl); setActive(null); }}
          />
        );
      })()}
    </Reveal>
  );
}

// ============================================
// DanceStyleModal — info-modal voor een dansstijl (klik op kaart in grid view)
// Visueel identiek aan ScheduleClassModal: foto links, info rechts.
// Toont: naam, beschrijving, alle lesuren, alle docenten, alle locaties.
// ============================================
function DanceStyleModal({ style, schedule = [], days = [], team = [], locations = [], onClose, onRegister, onGoToSchedule }) {
  const { Placeholder, Icon } = window.LM_UI;
  if (!style) return null;

  const teacherMap = Object.fromEntries(team.map(t => [t.id, t]));

  // Verzamel alle lesuren voor deze stijl, gesorteerd op dag + starttijd
  const slots = schedule
    .filter(s => s.styleId === style.id)
    .sort((a, b) => (a.day - b.day) || a.start.localeCompare(b.start));

  // Verzamel alle docenten: default-docenten van de stijl + alle docenten uit de lesuren
  const defaultIds = Array.isArray(style.defaultTeacherIds)
    ? style.defaultTeacherIds
    : (style.defaultTeacherId ? [style.defaultTeacherId] : []);
  const allTeacherIds = new Set(defaultIds);
  slots.forEach(s => {
    const ids = Array.isArray(s.teacherIds) ? s.teacherIds : (s.teacherId ? [s.teacherId] : []);
    ids.forEach(id => allTeacherIds.add(id));
  });
  const allTeachers = Array.from(allTeacherIds).map(id => teacherMap[id]).filter(Boolean);

  // Verzamel unieke locaties op basis van studio-namen
  const studioNames = Array.from(new Set(slots.map(s => (s.studio || '').trim()).filter(Boolean)));
  const usedLocations = studioNames.map(name => {
    const key = name.toLowerCase();
    const found = locations.find(l =>
      (l.name || '').trim().toLowerCase() === key ||
      (l.shortName || '').trim().toLowerCase() === key);
    return found || { name };
  });

  const reg = window.LM_DATA?.REGISTRATIONS || {};
  const closed = style.registrationOpen === false || reg.enabled === false;
  const closedMsg = (reg.closedMessage || '').trim() || 'Inschrijvingen voor deze groep zijn momenteel gesloten.';

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 999,
        background: 'rgba(14,26,38,.6)',
        backdropFilter: 'blur(8px)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 24,
        animation: 'fadeIn .25s ease',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--surface)',
          borderRadius: 20,
          maxWidth: 880,
          width: '100%',
          maxHeight: '92vh',
          overflow: 'hidden',
          display: 'grid',
          gridTemplateColumns: 'minmax(0, 0.9fr) minmax(0, 1.1fr)',
          boxShadow: '0 40px 80px rgba(14,26,38,.4)',
          animation: 'slideUp .35s cubic-bezier(.2,.7,.2,1)',
        }}
        className="cls-modal"
      >
        {/* Visueel */}
        <div style={{ position: 'relative', background: 'var(--ink-100)', minHeight: 360 }}>
          <Placeholder
            label={style.id}
            ratio="auto"
            src={style.image || ''}
            style={{ position: 'absolute', inset: 0, borderRadius: 0, aspectRatio: 'unset' }}
          />
          <div style={{
            position: 'absolute',
            top: 20, left: 20,
            display: 'flex', gap: 6, flexWrap: 'wrap',
          }}>
            {style.isNew && (
              <span className="style-tag" style={{ background: 'var(--teal-500)', color: '#fff' }}>★ NIEUW</span>
            )}
            <span className="style-tag style-tag-ink">{style.age}</span>
            {closed && (
              <span className="style-tag" style={{ background: '#fee2e2', color: '#991b1b' }}>🚪 GESLOTEN</span>
            )}
          </div>
        </div>

        {/* Info */}
        <div style={{
          padding: 36,
          overflowY: 'auto',
          maxHeight: '92vh',
          position: 'relative',
        }}>
          <button onClick={onClose} style={{
            position: 'absolute',
            top: 16, right: 16,
            width: 36, height: 36, borderRadius: '50%',
            background: 'var(--ink-100)',
            border: 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
            color: 'var(--ink-700)',
            transition: 'all .15s',
          }}
            onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--teal-500)'; e.currentTarget.style.color = 'white'; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--ink-100)'; e.currentTarget.style.color = 'var(--ink-700)'; }}
          >
            <Icon.Close />
          </button>

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <span className="stripe-accent"></span>
            <span className="eyebrow">Dansstijl</span>
          </div>
          <h2 className="display" style={{ fontSize: 'clamp(26px, 4vw, 38px)', margin: '0 0 14px', textTransform: 'none', letterSpacing: '-0.015em', lineHeight: 1.15 }}>
            {style.name}
          </h2>
          <p style={{ fontSize: 15, lineHeight: 1.65, color: 'var(--ink-700)', margin: '0 0 24px' }}>
            {style.description}
          </p>

          {/* Lesuren */}
          {slots.length > 0 && (
            <>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 10, fontWeight: 600 }}>
                {slots.length === 1 ? 'Lesuur' : `Lesuren (${slots.length})`}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 24 }}>
                {slots.map((s, i) => {
                  const dayLabel = days[s.day] || `Dag ${s.day}`;
                  return (
                    <div key={i} style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '10px 14px',
                      background: 'var(--ink-50)', borderRadius: 10, fontSize: 13,
                      flexWrap: 'wrap',
                    }}>
                      <div style={{ minWidth: 80, fontWeight: 600, color: 'var(--ink-900)' }}>{dayLabel}</div>
                      <div className="mono" style={{ minWidth: 100, color: 'var(--ink-700)' }}>{s.start}–{s.end}</div>
                      {s.studio && (
                        <div style={{ flex: 1, minWidth: 0, color: 'var(--ink-500)' }}>📍 {s.studio}</div>
                      )}
                    </div>
                  );
                })}
              </div>
            </>
          )}
          {slots.length === 0 && (
            <p style={{ fontSize: 13, color: 'var(--ink-500)', fontStyle: 'italic', marginBottom: 24 }}>
              Geen lesuren gepland voor deze stijl.
            </p>
          )}

          {/* Docenten */}
          {allTeachers.length > 0 && (
            <>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 10, fontWeight: 600 }}>
                {allTeachers.length === 1 ? 'Docent' : `Docenten (${allTeachers.length})`}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 24 }}>
                {allTeachers.map(tch => (
                  <div key={tch.id} style={{
                    display: 'flex', gap: 12, alignItems: 'center',
                    padding: 10, background: 'var(--ink-50)', borderRadius: 10,
                  }}>
                    <div style={{ width: 44, height: 44, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: 'var(--ink-100)' }}>
                      {tch.photo
                        ? <img src={tch.photo.replace(/^(?!\/|https?:\/\/|\/\/|data:)/, '/')} alt={tch.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                        : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-500)', fontFamily: 'var(--font-display)', fontSize: 14 }}>
                            {(tch.name || '?').split(' ').map(p => p[0]).join('').slice(0, 2).toUpperCase()}
                          </div>}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{tch.name}</div>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--ink-500)', letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 2 }}>{tch.role}</div>
                      {tch.specialty && <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 4, fontStyle: 'italic' }}>{tch.specialty}</div>}
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}

          {/* Locaties (uniek) */}
          {usedLocations.length > 0 && (
            <>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 10, fontWeight: 600 }}>
                {usedLocations.length === 1 ? 'Locatie' : `Locaties (${usedLocations.length})`}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 24 }}>
                {usedLocations.map((loc, i) => (
                  <div key={i} style={{
                    display: 'flex', gap: 10, alignItems: 'flex-start',
                    padding: 10, background: 'var(--ink-50)', borderRadius: 10, fontSize: 13,
                  }}>
                    <span style={{ fontSize: 18 }}>📍</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <strong>{loc.name}</strong>
                      {loc.tag && <span className="mono" style={{ fontSize: 10, marginLeft: 6, color: 'var(--ink-500)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>{loc.tag}</span>}
                      {(loc.addressLine1 || loc.addressLine2) && (
                        <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 2 }}>
                          {loc.addressLine1}{loc.addressLine2 && <> · {loc.addressLine2}</>}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}

          {/* CTA */}
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {!closed ? (
              <button className="btn btn-primary" onClick={onRegister}>
                Schrijf je in <Icon.ArrowRight />
              </button>
            ) : (
              <div style={{ padding: 12, background: '#fef9c3', border: '1px solid #fde047', borderRadius: 10, color: '#854d0e', fontSize: 13 }}>
                ⚠ {closedMsg}
              </div>
            )}
            {onGoToSchedule && slots.length > 0 && (
              <button className="btn btn-ghost" onClick={onGoToSchedule}>Bekijk in uurrooster</button>
            )}
            <button className="btn btn-ghost" onClick={onClose}>Sluiten</button>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        @media (max-width: 720px) {
          .cls-modal { grid-template-columns: 1fr !important; max-height: 92vh; }
          .cls-modal > div:first-child { min-height: 220px !important; }
        }
      `}</style>
    </div>
  );
}

// ============================================
// ScheduleClassModal — toont info over een les bij klik in het uurrooster
// ============================================
function ScheduleClassModal({ cls, dayLabel, style, teacher, extraTeachers = [], onClose, onRegister }) {
  const { Placeholder, Icon } = window.LM_UI;
  if (!style) return null;
  const reg = window.LM_DATA?.REGISTRATIONS || {};
  const closed = style.registrationOpen === false || reg.enabled === false;
  const closedMsg = (reg.closedMessage || '').trim() || 'Inschrijvingen voor deze groep zijn momenteel gesloten.';

  // Zoek de locatie op aan de hand van de studio-naam (matcht op name OF shortName, case-insensitive)
  const studioName = (cls.studio || '').trim().toLowerCase();
  const location = studioName
    ? (window.LM_DATA?.LOCATIONS || []).find(l =>
        (l.name || '').trim().toLowerCase() === studioName ||
        (l.shortName || '').trim().toLowerCase() === studioName)
    : null;

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 999,
        background: 'rgba(14,26,38,.6)',
        backdropFilter: 'blur(8px)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 24,
        animation: 'fadeIn .25s ease',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--surface)',
          borderRadius: 20,
          maxWidth: 880,
          width: '100%',
          maxHeight: '92vh',
          overflow: 'hidden',
          display: 'grid',
          gridTemplateColumns: 'minmax(0, 0.9fr) minmax(0, 1.1fr)',
          boxShadow: '0 40px 80px rgba(14,26,38,.4)',
          animation: 'slideUp .35s cubic-bezier(.2,.7,.2,1)',
        }}
        className="cls-modal"
      >
        {/* Visueel */}
        <div style={{ position: 'relative', background: 'var(--ink-100)', minHeight: 360 }}>
          <Placeholder
            label={style.id}
            ratio="auto"
            src={style.image || ''}
            style={{ position: 'absolute', inset: 0, borderRadius: 0, aspectRatio: 'unset' }}
          />
          <div style={{
            position: 'absolute',
            top: 20, left: 20,
            display: 'flex', gap: 6, flexWrap: 'wrap',
          }}>
            {style.isNew && (
              <span className="style-tag" style={{ background: 'var(--teal-500)', color: '#fff' }}>★ NIEUW</span>
            )}
            <span className="style-tag style-tag-ink">{style.age}</span>
          </div>
          <div style={{
            position: 'absolute',
            bottom: 20, left: 20,
            background: 'rgba(14,26,38,.88)',
            color: 'white',
            padding: '10px 14px',
            borderRadius: 8,
            backdropFilter: 'blur(6px)',
          }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', opacity: 0.7 }}>
              {dayLabel}
            </div>
            <div className="display" style={{ fontSize: 20, lineHeight: 1, marginTop: 4 }}>
              {cls.start}–{cls.end}
            </div>
          </div>
        </div>

        {/* Info */}
        <div style={{
          padding: 36,
          overflowY: 'auto',
          maxHeight: '92vh',
          position: 'relative',
        }}>
          <button onClick={onClose} style={{
            position: 'absolute',
            top: 16, right: 16,
            width: 36, height: 36, borderRadius: '50%',
            background: 'var(--ink-100)',
            border: 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
            color: 'var(--ink-700)',
            transition: 'all .15s',
          }}
            onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--teal-500)'; e.currentTarget.style.color = 'white'; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--ink-100)'; e.currentTarget.style.color = 'var(--ink-700)'; }}
          >
            <Icon.Close />
          </button>

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <span className="stripe-accent"></span>
            <span className="eyebrow">{cls.studio || 'Winkel'}</span>
          </div>
          <h2 className="display" style={{ fontSize: 'clamp(26px, 4vw, 38px)', margin: '0 0 14px', textTransform: 'none', letterSpacing: '-0.015em', lineHeight: 1.15 }}>
            {style.name}
          </h2>
          <p style={{ fontSize: 15, lineHeight: 1.65, color: 'var(--ink-700)', margin: '0 0 24px' }}>
            {style.description}
          </p>

          {/* Optionele notitie per lesuur */}
          {cls.note && (
            <div style={{
              background: 'var(--gradient-soft)',
              borderLeft: '3px solid var(--blue-500)',
              padding: '12px 16px',
              borderRadius: 8,
              marginBottom: 24,
              fontSize: 14,
              color: 'var(--ink-700)',
              lineHeight: 1.55,
              whiteSpace: 'pre-wrap',
            }}>
              {cls.note}
            </div>
          )}

          {/* Docent(en) */}
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 10, fontWeight: 600 }}>
            {extraTeachers.length > 0 ? `Docenten (${1 + extraTeachers.length})` : 'Docent'}
          </div>
          {teacher ? (
            <>
              <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start', marginBottom: extraTeachers.length > 0 ? 8 : 24, padding: 14, background: 'var(--ink-50)', borderRadius: 12 }}>
                <div style={{ width: 64, height: 64, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: 'var(--ink-100)' }}>
                  {teacher.photo
                    ? <img src={teacher.photo.replace(/^(?!\/|https?:\/\/|\/\/|data:)/, '/')} alt={teacher.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-500)', fontFamily: 'var(--font-display)', fontSize: 20 }}>
                        {(teacher.name || '?').split(' ').map(p => p[0]).join('').slice(0, 2).toUpperCase()}
                      </div>}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="display" style={{ fontSize: 17, margin: 0, textTransform: 'none', letterSpacing: '-0.005em' }}>
                    {teacher.name}
                  </div>
                  <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)', marginTop: 2 }}>
                    {teacher.role}
                  </div>
                  {teacher.specialty && (
                    <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: 4, fontStyle: 'italic' }}>{teacher.specialty}</div>
                  )}
                  {teacher.bio && (
                    <p style={{ fontSize: 13, color: 'var(--ink-700)', margin: '8px 0 0', lineHeight: 1.55 }}>
                      {teacher.bio.length > 220 ? teacher.bio.slice(0, 220) + '…' : teacher.bio}
                    </p>
                  )}
                </div>
              </div>
              {/* Extra docenten (compacter weergegeven onder de primaire) */}
              {extraTeachers.length > 0 && (
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 24 }}>
                  {extraTeachers.map(t => (
                    <div key={t.id} style={{
                      display: 'flex', gap: 10, alignItems: 'center',
                      padding: '8px 12px', background: 'var(--ink-50)', borderRadius: 10,
                      flex: '1 1 220px', minWidth: 0,
                    }}>
                      <div style={{ width: 36, height: 36, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, background: 'var(--ink-100)' }}>
                        {t.photo
                          ? <img src={t.photo.replace(/^(?!\/|https?:\/\/|\/\/|data:)/, '/')} alt={t.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                          : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-500)', fontFamily: 'var(--font-display)', fontSize: 13 }}>
                              {(t.name || '?').split(' ').map(p => p[0]).join('').slice(0, 2).toUpperCase()}
                            </div>}
                      </div>
                      <div style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>
                        <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}</div>
                        <div className="mono" style={{ fontSize: 9, color: 'var(--ink-500)', letterSpacing: '0.12em', textTransform: 'uppercase', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.role}</div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </>
          ) : (
            <p style={{ fontSize: 13, color: 'var(--ink-500)', fontStyle: 'italic', marginBottom: 24 }}>
              Docent wordt nog meegedeeld.
            </p>
          )}

          {/* Locatie (indien gekend) */}
          {location && (
            <>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 10, fontWeight: 600 }}>
                Locatie
              </div>
              <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start', marginBottom: 24, padding: 14, background: 'var(--ink-50)', borderRadius: 12 }}>
                <div style={{ width: 64, height: 64, borderRadius: 12, overflow: 'hidden', flexShrink: 0, background: 'var(--ink-100)' }}>
                  {location.image
                    ? <img src={location.image.replace(/^(?!\/|https?:\/\/|\/\/|data:)/, '/')} alt={location.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-500)', fontFamily: 'var(--font-display)', fontSize: 20 }}>◎</div>}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="display" style={{ fontSize: 17, margin: 0, textTransform: 'none', letterSpacing: '-0.005em' }}>
                    {location.name}
                  </div>
                  {location.tag && (
                    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)', marginTop: 2 }}>
                      {location.tag}
                    </div>
                  )}
                  {(location.addressLine1 || location.addressLine2) && (
                    <div style={{ fontSize: 13, color: 'var(--ink-700)', marginTop: 6 }}>
                      {location.addressLine1}{location.addressLine2 && <><br />{location.addressLine2}</>}
                    </div>
                  )}
                  {location.description && (
                    <p style={{ fontSize: 13, color: 'var(--ink-500)', margin: '8px 0 0', lineHeight: 1.55 }}>
                      {location.description.length > 180 ? location.description.slice(0, 180) + '…' : location.description}
                    </p>
                  )}
                  {(location.addressLine1 || location.addressLine2) && (
                    <a href={`https://maps.google.com/?q=${encodeURIComponent([location.name, location.addressLine1, location.addressLine2].filter(Boolean).join(', '))}`}
                       target="_blank" rel="noreferrer"
                       style={{ fontSize: 12, color: 'var(--blue-600)', textDecoration: 'underline', display: 'inline-block', marginTop: 8 }}>
                      Bekijk op kaart ↗
                    </a>
                  )}
                </div>
              </div>
            </>
          )}

          {/* CTA */}
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {!closed ? (
              <button className="btn btn-primary" onClick={onRegister}>
                Schrijf je in voor deze les <Icon.ArrowRight />
              </button>
            ) : (
              <div style={{ padding: 12, background: '#fef9c3', border: '1px solid #fde047', borderRadius: 10, color: '#854d0e', fontSize: 13 }}>
                ⚠ {closedMsg}
              </div>
            )}
            <button className="btn btn-ghost" onClick={onClose}>Terug naar rooster</button>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        @media (max-width: 720px) {
          .cls-modal { grid-template-columns: 1fr !important; max-height: 92vh; }
          .cls-modal > div:first-child { min-height: 220px !important; }
        }
      `}</style>
    </div>
  );
}

window.LM_PAGES = window.LM_PAGES || {};
window.LM_PAGES.Lessen = LessenPage;
