// ============================================
// MAIN APP — nav, router, footer (CMS-driven)
// ============================================

const { useState, useEffect, useRef } = React;

// Feature-flags voor publieke pagina's worden geleverd door
//   <script src="/wnm-host-platform/frontend.js">
// dat window.WNM = { hasFeature, getFeatures, refresh, ready } zet.
// Pagina's gebruiken: if (window.WNM && window.WNM.hasFeature('slug')) { ... }

function App() {
  const [ready, setReady] = useState(false);

  useEffect(() => {
    (window.LM_READY || Promise.resolve()).then(() => setReady(true));
  }, []);

  if (!ready) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '80vh', color: 'var(--ink-500)' }}>
        Laden…
      </div>
    );
  }

  return <Site />;
}

function findRouteForBuiltin(builtinName, menu) {
  for (const m of menu) {
    if (m.type === 'builtin' && m.page === builtinName) return m.id;
    for (const c of (m.children || [])) {
      if (c.type === 'builtin' && c.page === builtinName) return c.id;
    }
  }
  return null;
}

function Site() {
  const cms = window.LM_CMS;
  const site = cms.site();
  const t = cms.t;
  const RAW_MENU = (window.LM_DATA?.MENU?.length ? window.LM_DATA.MENU : [
    { id: 'home', label: 'Home', type: 'builtin', page: 'home' },
    { id: 'over', label: 'Over ons', type: 'builtin', page: 'over' },
    { id: 'lessen', label: 'Lessen', type: 'builtin', page: 'lessen' },
    { id: 'galerij', label: 'Galerij', type: 'builtin', page: 'galerij' },
    { id: 'contact', label: 'Contact', type: 'builtin', page: 'contact' },
  ]);
  // Inschrijven loopt via een externe (danssport) website → filter een eventueel
  // 'inschrijven'-menu-item weg uit de navigatie en footer.
  const isInschrijvenItem = (x) => x && x.type === 'builtin' && x.page === 'inschrijven';
  let MENU = RAW_MENU
    .filter(m => !isInschrijvenItem(m))
    .map(m => ({ ...m, children: (m.children || []).filter(c => !isInschrijvenItem(c)) }));
  // Dansshow-module: voeg automatisch een nav-item toe wanneer de licentie 'dansshow'
  // bevat en de beheerder er nog geen eigen menu-item voor maakte.
  const showsEnabled = !window.WNM || window.WNM.hasFeature('dansshow');
  const hasShowsItem = MENU.some(m => (m.type === 'builtin' && m.page === 'shows') || (m.children || []).some(c => c.type === 'builtin' && c.page === 'shows'));
  if (showsEnabled && !hasShowsItem) {
    MENU = [...MENU, { id: 'shows', label: 'Dansshow', type: 'builtin', page: 'shows' }];
  }
  const CUSTOM_PAGES = window.LM_DATA?.CUSTOM_PAGES || [];

  const flatRoutes = [];
  MENU.forEach(m => {
    flatRoutes.push(m);
    (m.children || []).forEach(ch => flatRoutes.push(ch));
  });

  const parseRoute = () => {
    const h = (window.location.hash || '').replace('#/', '').replace('#', '');
    const base = h.split('?')[0]; // strip query string
    if (base === 'payment-return') return 'payment-return';
    if (base === 'algemene-voorwaarden') return 'algemene-voorwaarden';
    if (base === 'privacybeleid') return 'privacybeleid';
    if (base === 'webshop' || base.startsWith('webshop/')) return 'webshop';
    if (base === 'shows' || base.startsWith('shows/')) return 'shows';
    if (base === 'inschrijven') return 'lessen'; // interne inschrijfpagina bestaat niet meer
    const found = flatRoutes.find(r => r.id === base);
    return found ? found.id : (flatRoutes[0]?.id || 'home');
  };

  const [route, setRoute] = useState(parseRoute);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [openDropdown, setOpenDropdown] = useState(null);

  const navigate = (id) => {
    // Voor webshop sub-paths (bv. "webshop/cart") laten we de hash gewoon updaten;
    // de WebshopPage luistert zelf op hashchange en switcht intern.
    setMobileOpen(false);
    setOpenDropdown(null);
    // Er is geen interne inschrijfpagina meer (inschrijven loopt extern via de
    // lessen/groepen). Stuur eventuele oude links naar de Lessen-pagina.
    if (id === 'inschrijven') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      window.location.hash = '#/lessen';
      return;
    }
    window.scrollTo({ top: 0, behavior: 'smooth' });
    window.location.hash = '#/' + id;
  };

  useEffect(() => {
    const onHash = () => setRoute(parseRoute());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const renderPage = () => {
    const pages = window.LM_PAGES || {};

    if (route === 'payment-return') {
      const P = pages.PaymentReturn;
      return P ? <P navigate={navigate} /> : null;
    }
    if (route === 'algemene-voorwaarden') {
      const P = pages.Legal;
      return P ? <P navigate={navigate} docKey="terms" /> : null;
    }
    if (route === 'privacybeleid') {
      const P = pages.Legal;
      return P ? <P navigate={navigate} docKey="privacy" /> : null;
    }
    if (route === 'webshop') {
      const P = pages.Webshop;
      return P ? <P navigate={navigate} /> : null;
    }
    if (route === 'shows') {
      const P = pages.Shows;
      return P ? <P navigate={navigate} /> : null;
    }

    const item = flatRoutes.find(r => r.id === route);
    if (item?.type === 'custom') {
      const cp = CUSTOM_PAGES.find(p => p.slug === item.slug || p.id === item.id);
      const CustomPage = pages.Custom;
      if (CustomPage && cp) return <CustomPage page={cp} navigate={navigate} />;
    }
    if (item?.type === 'builtin') {
      const key = item.page;
      const map = {
        home: pages.Home, over: pages.Over, lessen: pages.Lessen,
        galerij: pages.Galerij, contact: pages.Contact,
        sponsors: pages.Sponsors, webshop: pages.Webshop,
      };
      const P = map[key] || pages.Home;
      return P ? <P navigate={navigate} /> : null;
    }
    return pages.Home ? <pages.Home navigate={navigate} /> : null;
  };

  const activeLabel = route === 'payment-return' ? 'Betaling'
    : route === 'algemene-voorwaarden' ? 'Algemene voorwaarden'
    : route === 'privacybeleid' ? 'Privacybeleid'
    : route === 'shows' ? 'Dansshows'
    : ((flatRoutes.find(r => r.id === route)?.label) || 'Home');

  // Admin in maintenance-bypass? Toon een waarschuwingsbalk.
  const status = window.LM_STATUS || {};
  const showMaintenanceBanner = status.maintenance && status.viewerIsAdmin;

  return (
    <div>
      {showMaintenanceBanner && (
        <div style={{
          position: 'sticky', top: 0, zIndex: 1000,
          background: 'linear-gradient(90deg, #b45309, #d97706)',
          color: 'white',
          padding: '10px 20px',
          textAlign: 'center',
          fontSize: 13,
          fontWeight: 600,
          boxShadow: '0 2px 8px rgba(0,0,0,.15)',
        }}>
          🛠 <strong>Onderhoudsmodus is ACTIEF</strong> — bezoekers zien een 503-pagina. Jij ziet de site omdat je ingelogd bent als admin.
          <a href="/?_lm_preview_maintenance=1" target="_blank" rel="noreferrer"
            style={{ marginLeft: 12, color: 'white', textDecoration: 'underline' }}>
            Bekijk de bezoeker-versie ↗
          </a>
        </div>
      )}

      {/* ===== NAV ===== */}
      <header className="nav">
        <div className="nav-inner" style={{ justifyContent: 'flex-end' }}>
          <nav className="nav-menu">
            {MENU.map(m => {
              const isActive = route === m.id || (m.children || []).some(c => c.id === route);
              const hasChildren = (m.children || []).length > 0;
              if (hasChildren) {
                return (
                  <div key={m.id} style={{ position: 'relative' }} onMouseLeave={() => setOpenDropdown(null)}>
                    <button
                      className={`nav-link ${isActive ? 'active' : ''}`}
                      onMouseEnter={() => setOpenDropdown(m.id)}
                      onClick={() => navigate(m.id)}
                    >
                      {m.label}
                      <span
                        onClick={(e) => { e.stopPropagation(); setOpenDropdown(openDropdown === m.id ? null : m.id); }}
                        style={{ fontSize: 9, marginLeft: 6, opacity: 0.6, cursor: 'pointer', padding: '2px 4px' }}
                        title="Toon submenu"
                      >▼</span>
                    </button>
                    {openDropdown === m.id && (
                      <div style={{
                        position: 'absolute', top: '100%', left: 0,
                        background: 'var(--surface)',
                        border: '1px solid var(--border)',
                        borderRadius: 8,
                        boxShadow: 'var(--shadow-md)',
                        minWidth: 200, padding: 8, zIndex: 100,
                      }}>
                        {(m.children || []).map(ch => (
                          <button
                            key={ch.id}
                            onClick={() => navigate(ch.id)}
                            style={{
                              display: 'block', width: '100%', textAlign: 'left',
                              background: 'none', border: 'none',
                              padding: '10px 14px', borderRadius: 6,
                              fontSize: 14, fontWeight: 500, cursor: 'pointer',
                              color: route === ch.id ? 'var(--ink-900)' : 'var(--ink-700)',
                              fontFamily: 'var(--font-body)',
                            }}
                            onMouseEnter={e => e.currentTarget.style.background = 'var(--ink-50)'}
                            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                          >
                            {ch.label}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                );
              }
              return (
                <button
                  key={m.id}
                  className={`nav-link ${route === m.id ? 'active' : ''}`}
                  onClick={() => navigate(m.id)}
                >{m.label}</button>
              );
            })}
          </nav>

          <button className="nav-mobile-toggle" onClick={() => setMobileOpen(!mobileOpen)} aria-label="Menu">
            {window.LM_UI.Icon.Menu({})}
          </button>
        </div>

        {/* Mobile menu */}
        {mobileOpen && (
          <div style={{ background: 'var(--surface)', borderTop: '1px solid var(--border)', padding: 16 }}>
            {MENU.map(m => (
              <div key={m.id}>
                <button
                  onClick={() => navigate(m.id)}
                  style={{
                    display: 'block', width: '100%',
                    background: 'none', border: 'none',
                    padding: '14px 16px', textAlign: 'left',
                    fontSize: 16, fontWeight: 600,
                    color: route === m.id ? 'var(--ink-900)' : 'var(--ink-700)',
                    borderRadius: 6, cursor: 'pointer',
                    fontFamily: 'var(--font-body)',
                  }}
                >{m.label}</button>
                {(m.children || []).map(ch => (
                  <button key={ch.id} onClick={() => navigate(ch.id)}
                    style={{
                      display: 'block', width: '100%',
                      background: 'none', border: 'none',
                      padding: '10px 16px 10px 32px', textAlign: 'left',
                      fontSize: 14, color: 'var(--ink-500)',
                      borderRadius: 6, cursor: 'pointer',
                      fontFamily: 'var(--font-body)',
                    }}
                  >↳ {ch.label}</button>
                ))}
              </div>
            ))}
          </div>
        )}
      </header>

      {/* ===== PAGE ===== */}
      <main data-screen-label={activeLabel}>
        {renderPage()}
      </main>

      {/* ===== FOOTER ===== */}
      <footer className="footer">
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) repeat(3, minmax(0, 1fr))', gap: 56, marginBottom: 56 }} className="footer-grid">
            <div>
              {site.logo && (
                <img
                  src={(site.logo || 'assets/logo.jpg').replace(/^(?!\/|https?:\/\/|\/\/|data:)/, '/')}
                  alt={site.name || "Dance Studio"}
                  style={{
                    height: 80,
                    width: 'auto',
                    maxWidth: 200,
                    marginBottom: 20,
                    borderRadius: 8,
                  }}
                />
              )}
              {/* De footer heeft een vaste donkere achtergrond (#08080B, zie styles.css)
                  — dus hier vaste lichte tekstkleuren, géén thema-variabelen (die zijn
                  relatief aan de pagina-achtergrond en vallen hier verkeerd uit). */}
              <p style={{ fontSize: 14, lineHeight: 1.6, color: 'rgba(255,255,255,.62)', maxWidth: 320, margin: 0 }}>
                {site.footerTagline || 'Een professionele dansschool voor alle leeftijden — van kleuterdans tot competitieteams. Move with purpose.'}
              </p>
            </div>

            <div>
              <h4>{t('footer.navigation', 'Navigatie')}</h4>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {MENU.map(m => (
                  <li key={m.id}><a href={`#/${m.id}`} onClick={(e) => { e.preventDefault(); navigate(m.id); }}>{m.label}</a></li>
                ))}
              </ul>
            </div>

            <div>
              <h4>{t('footer.contact', 'Contact')}</h4>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10, fontSize: 14 }}>
                <li>{site.contactEmail || 'demo@dance-suite.example'}</li>
                <li>{site.contactPhone || '+32 (0)4XX XX XX XX'}</li>
                <li>{site.addressLine1 || 'Winkel adres lijn 1'}<br />{site.addressLine2 || 'Postcode + Gemeente'}</li>
              </ul>
            </div>

            <div>
              <h4>{t('footer.social', 'Sociale media')}</h4>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10, fontSize: 14 }}>
                {site.socialInstagram && <li><a href={site.socialInstagram}>Instagram</a></li>}
                {site.socialFacebook && <li><a href={site.socialFacebook}>Facebook</a></li>}
              </ul>
            </div>
          </div>

          <div style={{ borderTop: '1px solid rgba(255,255,255,.08)', paddingTop: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-400)', letterSpacing: '0.1em' }}>
              {site.footerCopyright || "© 2026 DANCE STUDIO · DANCE SCHOOL · ALLE RECHTEN VOORBEHOUDEN"}
            </div>
            <div style={{ display: 'flex', gap: 20, fontSize: 12, color: 'var(--ink-400)', flexWrap: 'wrap' }}>
              <a href="#/privacybeleid" onClick={e => { e.preventDefault(); navigate('privacybeleid'); }}>{t('footer.privacy', 'Privacybeleid')}</a>
              <a href="#/algemene-voorwaarden" onClick={e => { e.preventDefault(); navigate('algemene-voorwaarden'); }}>{t('footer.terms', 'Algemene voorwaarden')}</a>
              <a href="#/algemene-voorwaarden" onClick={e => { e.preventDefault(); navigate('algemene-voorwaarden'); }}>{t('footer.rules', 'Reglement')}</a>
              <a href="#" onClick={e => { e.preventDefault(); try { localStorage.removeItem('lm_consent'); location.reload(); } catch(_){} }}>{t('footer.cookies', 'Cookie-instellingen')}</a>
            </div>
          </div>

          {/* Ontwerp-credit */}
          <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,.06)', textAlign: 'center', fontSize: 11, color: 'rgba(255,255,255,.45)', letterSpacing: '0.06em' }}>
            Website ontworpen door <a href="https://www.wnm-host.com" target="_blank" rel="noopener noreferrer" style={{ color: 'rgba(255,255,255,.82)', textDecoration: 'none', fontWeight: 700 }}>WNM-HOST.COM</a>
          </div>
        </div>

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

      {/* Snelknoppen-balk onderaan — enkel zichtbaar op gsm */}
      <MobileActionBar navigate={navigate} />

      {/* Cookie consent banner (eerste bezoek of na intrekking) */}
      {window.LM_CookieBanner && <window.LM_CookieBanner />}
    </div>
  );
}

// Vaste snelknoppen-balk onderaan het scherm — verschijnt ALLEEN op smartphone (≤640px).
// Geeft met de duim bereikbare 1-tik acties: bellen, inschrijven, contact.
function MobileActionBar({ navigate }) {
  const site = (window.LM_CMS && window.LM_CMS.site && window.LM_CMS.site()) || {};
  const phone = String(site.contactPhone || '').trim();
  const telHref = 'tel:' + phone.replace(/[^\d+]/g, '');
  const btnStyle = {
    flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
    gap: 3, padding: '8px 4px', minHeight: 54, background: 'none', border: 'none', cursor: 'pointer',
    fontFamily: 'inherit', fontSize: 11, fontWeight: 700, color: 'var(--ink-900)', textDecoration: 'none',
  };
  return (
    <>
      <nav className="lm-mobilebar" aria-label="Snelacties" style={{
        position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 80,
        background: 'var(--surface)', borderTop: '1px solid var(--border)',
        boxShadow: '0 -2px 14px rgba(14,26,38,.12)',
        display: 'none', // standaard verborgen; media query toont op gsm
        paddingBottom: 'env(safe-area-inset-bottom)',
      }}>
        {phone && (
          <a href={telHref} style={btnStyle}>
            <span style={{ fontSize: 20, lineHeight: 1 }}>📞</span><span>Bellen</span>
          </a>
        )}
        <button type="button" onClick={() => navigate('lessen')} style={{ ...btnStyle, color: 'var(--blue-600)' }}>
          <span style={{ fontSize: 20, lineHeight: 1 }}>✍</span><span>Inschrijven</span>
        </button>
        <button type="button" onClick={() => navigate('contact')} style={btnStyle}>
          <span style={{ fontSize: 20, lineHeight: 1 }}>✉</span><span>Contact</span>
        </button>
      </nav>
      <style>{`
        @media (max-width: 640px) {
          .lm-mobilebar { display: flex !important; }
          body { padding-bottom: calc(56px + env(safe-area-inset-bottom)); }
        }
      `}</style>
    </>
  );
}

// Error Boundary — vangt een crash in om het even welke component op zodat de hele
// site niet wit wordt. Toont een nette melding + herlaad-knop en meldt de fout door.
class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { hasError: false }; }
  static getDerivedStateFromError() { return { hasError: true }; }
  componentDidCatch(error, info) {
    if (window.LM_REPORT_ERROR) window.LM_REPORT_ERROR(error, info);
    else console.error('App-fout:', error, info);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{ minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: 24 }}>
          <div style={{ maxWidth: 460 }}>
            <h1 className="display" style={{ fontSize: 28, margin: '0 0 12px', textTransform: 'none' }}>Er ging iets mis</h1>
            <p style={{ color: 'var(--ink-500)', margin: '0 0 20px' }}>
              Er trad een onverwachte fout op bij het laden van deze pagina. Probeer ze opnieuw te laden.
            </p>
            <button className="btn btn-primary" onClick={() => window.location.reload()}>Pagina herladen</button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <ErrorBoundary><App /></ErrorBoundary>
);
