/* ════════════════════════════════════════════════════════════════
   app.jsx — root component: language, hash routing, cookie state, RTL
   ════════════════════════════════════════════════════════════════ */

const {
  Nav, Hero, About, AppSection, HowItWorks, Waitlist, Support, Footer, CookieBanner, LegalView,
} = window;

const LANG_CODES = window.LANGS.map((l) => l.code);

/* Each language has its own crawlable URL: de = "/", others = "/<lang>/".
   This is what makes the Arabic/Turkish/English versions indexable. */
function basePath(lang) { return lang === 'de' ? '/' : '/' + lang + '/'; }

function deriveLangFromPath() {
  const m = (location.pathname || '/').match(/^\/(en|tr|ar)(?:\/|$)/);
  return m ? m[1] : 'de';
}

function getInitialLang() {
  // The prerendered page injects its own language (URL is authoritative).
  if (window.__ZS_LANG__ && LANG_CODES.includes(window.__ZS_LANG__)) return window.__ZS_LANG__;
  const fromPath = deriveLangFromPath();
  if (fromPath !== 'de') return fromPath;
  try {
    const saved = localStorage.getItem('zs_lang');
    if (saved && LANG_CODES.includes(saved)) return saved;
  } catch (e) { /* ignore */ }
  return 'de';
}

function parseHash() {
  const h = (location.hash || '').replace(/^#\/?/, '');
  const seg = h.split('/')[0];
  return window.LEGAL_PAGES.includes(seg) ? seg : null;
}

function App() {
  const [lang, setLangState] = React.useState(getInitialLang);
  const [legal, setLegal] = React.useState(parseHash);
  const [cookieOpen, setCookieOpen] = React.useState(() => localStorage.getItem('zs_cookie') !== 'set');

  const t = window.I18N[lang];

  // apply lang + dir to <html>
  React.useEffect(() => {
    const html = document.documentElement;
    html.setAttribute('lang', lang);
    html.setAttribute('dir', lang === 'ar' ? 'rtl' : 'ltr');
  }, [lang]);

  const setLang = (l) => {
    setLangState(l);
    try { localStorage.setItem('zs_lang', l); } catch (e) { /* ignore */ }
    // Reflect the language in the URL so each version is shareable/indexable,
    // without a full reload (keeps the SPA snappy).
    const target = basePath(l) + (location.hash || '');
    if (window.history && window.history.pushState) window.history.pushState({}, '', target);
    else location.assign(target);
  };

  // sync hash <-> legal route
  React.useEffect(() => {
    const onHash = () => setLegal(parseHash());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // sync language + legal route when navigating browser history (back/forward)
  React.useEffect(() => {
    const onPop = () => { setLangState(deriveLangFromPath()); setLegal(parseHash()); };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const goLegal = (page) => { location.hash = '#/' + page; setLegal(page); window.scrollTo(0, 0); };
  const goHome = () => { if (location.hash) location.hash = ''; setLegal(null); };

  const closeCookie = () => { setCookieOpen(false); localStorage.setItem('zs_cookie', 'set'); };

  // Hero primary CTA ("Kontakt aufnehmen") jumps to the contact section.
  const scrollWait = () => window.scrollToId('contact');

  return (
    <React.Fragment>
      <a href="#main" className="skip-link">{window.SKIP[lang]}</a>
      <Nav t={t} lang={lang} setLang={setLang} onHome={goHome} />

      {legal ? (
        <main id="main">
          <LegalView page={legal} lang={lang} t={t} onBack={goHome} />
        </main>
      ) : (
        <main id="main">
          <Hero t={t} onScrollWait={scrollWait} />
          <About t={t} />
          <AppSection t={t} />
          <HowItWorks t={t} />
          <Waitlist t={t} />
          <Support t={t} />
        </main>
      )}

      <Footer t={t} lang={lang} setLang={setLang} goLegal={goLegal} onHome={goHome} />

      {cookieOpen && <CookieBanner t={t} onClose={closeCookie} goLegal={goLegal} />}
    </React.Fragment>
  );
}

/* Mount over the prerendered markup. We use createRoot (not hydrateRoot) on
   purpose: the static HTML is template-generated, not React-generated, so a
   clean client render avoids hydration-mismatch warnings. */
if (typeof document !== 'undefined') {
  const _rootEl = document.getElementById('root');
  if (_rootEl) ReactDOM.createRoot(_rootEl).render(<App />);
}
