/* app.jsx — Router, Tweaks, Mount */
const { useState: useStateA, useEffect: useEffectA } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "a",
  "motion": true,
  "cursorGlow": true,
  "hashField": true,
  "glow": 1,
  "fontScale": 1
}/*EDITMODE-END*/;

const DIR_LABELS = { 'Editorial': 'a', 'Dark Stage': 'b', 'Kinetic': 'c' };
const DIR_REV = { a: 'Editorial', b: 'Dark Stage', c: 'Kinetic' };

function App() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [page, setPage] = useStateA('home');
  const [pendingAnchor, setPendingAnchor] = useStateA(null);

  // apply theme + motion to <html>
  useEffectA(() => {
    const el = document.documentElement;
    el.setAttribute('data-dir', t.direction);
    el.setAttribute('data-motion', t.motion ? '1' : '0');
    el.setAttribute('data-cursor', t.cursorGlow ? '1' : '0');
    el.style.setProperty('--glow-mult', t.glow);
    el.style.setProperty('--scale-user', t.fontScale);
  }, [t.direction, t.motion, t.cursorGlow, t.glow, t.fontScale]);

  const scrollToAnchor = (id) => {
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 72, behavior: 'smooth' });
  };
  const go = (p) => {
    // "kontakt" ist keine eigene Seite mehr — zur Startseite + zum Formular scrollen
    if (p === 'kontakt') {
      if (page === 'home') { scrollToAnchor('kontakt'); }
      else { setPage('home'); setPendingAnchor('kontakt'); }
      return;
    }
    setPage(p);
    window.scrollTo({ top: 0, behavior: 'auto' });
  };
  useEffectA(() => {
    if (!pendingAnchor) return;
    const id = pendingAnchor; setPendingAnchor(null);
    requestAnimationFrame(() => setTimeout(() => scrollToAnchor(id), 90));
  }, [page, pendingAnchor]);

  // Sicherstellen, dass die page-enter Animation tatsächlich startet.
  // Unter Last kann eine frisch gestartete CSS-Animation in Chromium dauerhaft
  // im "play-pending"-Zustand hängen bleiben (startTime null, currentTime 0) —
  // dann bleibt der 0%-Keyframe (opacity:0) stehen und die Seite wirkt leer.
  // Wir geben ihr nach dem Mount per JS explizit einen Startzeitpunkt.
  useEffectA(() => {
    let raf1, raf2;
    const kick = () => {
      const m = document.querySelector('main.page-enter');
      if (!m) return;
      m.getAnimations().forEach((a) => {
        if (a.playState !== 'finished' && a.startTime == null) {
          try { a.startTime = document.timeline.currentTime; } catch (e) {}
        }
      });
    };
    raf1 = requestAnimationFrame(() => { raf2 = requestAnimationFrame(kick); });
    return () => { cancelAnimationFrame(raf1); cancelAnimationFrame(raf2); };
  }, [page]);

  const { HoloBackground, HashField, Nav, Footer } = window;
  const Pages = {
    home: window.HomePage,
    projekte: window.ProjektePage,
    ueber: window.UeberUnsPage,
    schulungen: window.SchulungenPage,
    blog: window.BlogPage,
    portal: window.KundenportalPage,
    impressum: window.ImpressumPage,
    datenschutz: window.DatenschutzPage,
  };
  const Page = Pages[page] || window.HomePage;

  return (
    <>
      <HoloBackground />
      <HashField show={t.hashField} count={7} />
      <Nav page={page} go={go} />
      <main key={page} className="page-enter">
        <Page go={go} />
      </main>
      <Footer go={go} />

      <window.TweaksPanel>
        <window.TweakSection label="Design-Richtung" />
        <window.TweakRadio label="Stil" value={DIR_REV[t.direction]}
          options={['Editorial', 'Dark Stage', 'Kinetic']}
          onChange={(v) => setTweak('direction', DIR_LABELS[v])} />

        <window.TweakSection label="Bewegung" />
        <window.TweakToggle label="Animationen" value={t.motion}
          onChange={(v) => setTweak('motion', v)} />
        <window.TweakToggle label="Verlauf folgt Cursor" value={t.cursorGlow}
          onChange={(v) => setTweak('cursorGlow', v)} />
        <window.TweakToggle label="Schwebendes #-Feld" value={t.hashField}
          onChange={(v) => setTweak('hashField', v)} />
        <window.TweakSlider label="Verlauf-Intensität" value={t.glow}
          min={0} max={2} step={0.1} onChange={(v) => setTweak('glow', v)} />

        <window.TweakSection label="Typografie" />
        <window.TweakSlider label="Schriftgrösse" value={t.fontScale}
          min={0.85} max={1.3} step={0.05} unit="×" onChange={(v) => setTweak('fontScale', v)} />
      </window.TweaksPanel>

      <window.CookieConsent go={go} />
    </>
  );
}

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