// page-shell.jsx — Shared Nav + Footer + atmosphere for sub-pages
const { useState, useEffect, useRef } = React;

// ── Reveal-on-scroll hook ─────────────────────────────────
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) {el.classList.add('in');io.unobserve(el);}});
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function Reveal({ children, stagger = false, as: As = 'div', className = '', ...props }) {
  const ref = useReveal();
  const cls = (stagger ? 'reveal-stagger' : 'reveal') + (className ? ' ' + className : '');
  return <As ref={ref} className={cls} {...props}>{children}</As>;
}

// ── Cursor Glow ────────────────────────────────────────────
function CursorGlow() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    let x = window.innerWidth / 2,y = window.innerHeight / 2;
    let tx = x,ty = y;
    const onMove = (e) => {tx = e.clientX;ty = e.clientY;};
    window.addEventListener('mousemove', onMove);
    let raf;
    const tick = () => {
      x += (tx - x) * 0.12;y += (ty - y) * 0.12;
      el.style.left = x + 'px';el.style.top = y + 'px';
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => {window.removeEventListener('mousemove', onMove);cancelAnimationFrame(raf);};
  }, []);
  return <div ref={ref} className="cursor-glow" />;
}

// ── Nav (shared, no tweaks) ─────────────────────────────────
function NavShared({ lang, setLang, brand }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const t = window.CONTENT[lang];

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    if (menuOpen) document.body.classList.add('menu-open');else
    document.body.classList.remove('menu-open');
    return () => document.body.classList.remove('menu-open');
  }, [menuOpen]);

  // Always link back to index.html for in-page sections
  const links = [
  ['home', 'index.html#home'],
  ['about', 'index.html#why'],
  ['services', 'Leistungen.html'],
  ['projects', 'Projekte.html'],
  ['cases', 'index.html#cases'],
  ['blog', 'Blog.html'],
  ['contact', 'https://cal.eu/avgrowthstudio']];

  const closeMenu = () => setMenuOpen(false);

  return (
    <>
      <nav className={'nav' + (scrolled ? ' scrolled' : '')}>
        <a href="index.html" className="logo" onClick={closeMenu}>
          <span className="logo-mark">A</span>
          <span>{brand}</span>
        </a>
        <ul>
          {links.map(([k, h]) => {
            const ext = /^https?:\/\//.test(h);
            return <li key={k}><a href={h} {...(ext ? { target: '_blank', rel: 'noopener' } : {})}>{t.nav[k]}</a></li>;
          })}
        </ul>
        <div className="right">
          <div className="lang-toggle">
            <button className={lang === 'de' ? 'active' : ''} onClick={() => setLang('de')}>DE</button>
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <a href="https://cal.eu/avgrowthstudio" target="_blank" rel="noopener" className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 13 }} onClick={closeMenu}>
            <span>{t.nav.cta}</span> <span className="arrow">↗</span>
          </a>
          <button
            className={'menu-btn' + (menuOpen ? ' open' : '')}
            aria-label="Menu" aria-expanded={menuOpen}
            onClick={() => setMenuOpen((o) => !o)}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path className="l1" d="M4 7h16" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
              <path className="l2" d="M4 12h16" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
              <path className="l3" d="M4 17h16" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          </button>
        </div>
      </nav>
      <div className={'mobile-menu' + (menuOpen ? ' open' : '')}>
        {links.map(([k, h]) => {
          const ext = /^https?:\/\//.test(h);
          return <a key={k} href={h} {...(ext ? { target: '_blank', rel: 'noopener' } : {})} onClick={closeMenu}>{t.nav[k]}</a>;
        }
        )}
        <a href="https://cal.eu/avgrowthstudio" target="_blank" rel="noopener" className="mm-cta" onClick={closeMenu}>{t.nav.cta}</a>
        <div className="mm-lang">
          <button className={lang === 'de' ? 'active' : ''} onClick={() => setLang('de')}>DE</button>
          <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
        </div>
      </div>
    </>);

}

// ── Footer (shared, simplified) ─────────────────────────────
function FooterShared({ lang, brand }) {
  const t = window.CONTENT[lang];
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div>
            <div className="ready" style={{ fontFamily: "Poppins" }}>{t.footer.ready}</div>
            <div className="ready-sub">{t.footer.readySub}</div>
            <form className="email-form" onSubmit={(e) => {
              e.preventDefault();
              window.open('https://cal.eu/avgrowthstudio', '_blank', 'noopener');
            }}>
              <button type="submit" className="coffee-btn">{lang === 'de' ? 'virtueller Kaffee?' : 'coffee break?'} <span className="arrow">↗</span></button>
            </form>
          </div>
          <div className="col">
            <h4>{t.footer.quick}</h4>
            <ul>
              <li><a href="index.html#home">{t.nav.home}</a></li>
              <li><a href="index.html#why">{t.nav.about}</a></li>
              <li><a href="Leistungen.html">{t.nav.services}</a></li>
              <li><a href="Projekte.html">{t.nav.projects}</a></li>
              <li><a href="https://cal.eu/avgrowthstudio" target="_blank" rel="noopener">{t.nav.contact}</a></li>
            </ul>
          </div>
          <div className="col">
            <h4>Rechtliches</h4>
            <ul>
              <li><a href="Impressum.html">Impressum</a></li>
              <li><a href="Datenschutz.html">Datenschutz</a></li>
              <li><a href="Blog.html">Blog</a></li>
              <li><a href="Leistungen.html">Leistungen</a></li>
            </ul>
          </div>
          <div className="col">
            <h4>Social</h4>
            <ul>
              <li><a href="https://www.linkedin.com/in/anna-juckers-320716209" target="_blank" rel="noopener">LinkedIn</a></li>
              <li><a href="https://www.instagram.com/growthstudio.av" target="_blank" rel="noopener">Instagram</a></li>
              <li><a href="#"></a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <div>{t.footer.copy}</div>
          <div className="social">
            <a href="https://www.linkedin.com/in/anna-juckers-320716209" target="_blank" rel="noopener" aria-label="LinkedIn"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M4 4h4v16H4zM6 2a2 2 0 100 4 2 2 0 000-4zM10 8h4v2h.1a4 4 0 017 0V20h-4v-6c0-1-1-2-2-2s-2 1-2 2v6h-4z" /></svg></a>
            <a href="https://www.instagram.com/growthstudio.av" target="_blank" rel="noopener" aria-label="Instagram"><svg width="14" height="14" viewBox="0 0 24 24" fill="none"><rect x="3" y="3" width="18" height="18" rx="5" stroke="currentColor" strokeWidth="1.6" /><circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.6" /><circle cx="17" cy="7" r="1" fill="currentColor" /></svg></a>
          </div>
        </div>
        <div className="big-mark" style={{ fontFamily: "Poppins", fontSize: "100px" }}>{brand.toUpperCase()}</div>
      </div>
    </footer>);

}

// ── PageShell ───────────────────────────────────────────────
function PageShell({ children, kicker, title, lead, currentPath = '', heroAlign, heroExtra, heroClass, heroPin, bareHero, topLamp }) {
  const [lang, setLang] = useState(() => {
    try {return localStorage.getItem('av-lang') || 'de';} catch (e) {return 'de';}
  });
  useEffect(() => {
    try {localStorage.setItem('av-lang', lang);} catch (e) {}
    document.documentElement.setAttribute('lang', lang);
  }, [lang]);
  useEffect(() => {
    if (topLamp) document.body.classList.add('has-lamp');else
    document.body.classList.remove('has-lamp');
    return () => document.body.classList.remove('has-lamp');
  }, [topLamp]);

  // Scroll-driven phases for pinned hero
  const heroRef = useRef(null);
  useEffect(() => {
    if (!heroPin) return;
    const el = heroRef.current;
    if (!el) return;
    let raf = 0;
    const clamp = (v) => Math.max(0, Math.min(1, v));
    const update = () => {
      raf = 0;
      const rect = el.getBoundingClientRect();
      const total = el.offsetHeight - window.innerHeight;
      const scrolled = -rect.top;
      const p = clamp(scrolled / Math.max(1, total));
      // Phase windows:
      //   0.00 – 0.15  : hold, gentle float (nothing happens)
      //   0.15 – 0.50  : zoom in — folder grows toward camera, glow intensifies, text dims
      //   0.50 – 0.82  : Mario-Kart spin (rotateY 0 → 1080deg) while held large
      //   0.82 – 0.95  : fade out, content reveals
      const wake = clamp((p - 0.15) / 0.35);
      const spin = clamp((p - 0.50) / 0.32);
      const fade = clamp((p - 0.82) / 0.13);

      // Eased
      const easeOut = (x) => 1 - Math.pow(1 - x, 3);
      const easeInOut = (x) => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2;
      const wakeE = easeOut(wake);
      const spinE = easeInOut(spin);

      el.style.setProperty('--p', String(p));
      el.style.setProperty('--text-opacity', String(1 - wakeE * 0.9 - fade * 0.1));
      el.style.setProperty('--folder-tilt-x', wakeE * -14 - fade * 4 + 'deg');
      el.style.setProperty('--folder-rotate-y', spinE * 1080 + 'deg');
      // Big zoom-in before the spin, then slight scale-down on fade
      el.style.setProperty('--folder-scale', String(1 + wakeE * 0.55 - fade * 0.5));
      el.style.setProperty('--folder-y', wakeE * -20 - fade * 40 + 'px');
      el.style.setProperty('--folder-glow', String(0.4 + wakeE * 0.6 + spinE * 0.3 - fade * 0.7));
      el.style.setProperty('--pin-fade', String(1 - fade));

      // Disable idle float once user starts engaging
      el.classList.toggle('is-engaged', wake > 0.02);
    };
    const onScroll = () => {if (!raf) raf = requestAnimationFrame(update);};
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [heroPin]);

  const brand = 'AV Growthstudio';
  const t = window.CONTENT[lang];

  const heroCls = 'page-hero' + (
  heroAlign === 'center' ? ' page-hero-center' : '') + (
  heroPin ? ' page-hero-pinned' : '') + (
  topLamp ? ' has-top-lamp' : '') + (
  heroClass ? ' ' + heroClass : '');

  const TopLamp = () =>
  <div className="hero-lamp-stage" aria-hidden="true">
      <div className="hero-lamp-cone hero-lamp-cone-l">
        <div className="mask-bottom" />
        <div className="mask-side" />
      </div>
      <div className="hero-lamp-cone hero-lamp-cone-r">
        <div className="mask-side" />
        <div className="mask-bottom" />
      </div>
      <div className="hero-lamp-floor-blur" />
      <div className="hero-lamp-backdrop" />
      <div className="hero-lamp-halo" style={{ padding: "40px" }} />
      <div className="hero-lamp-bulb" />
      <div className="hero-lamp-line" />
      <div className="hero-lamp-ceiling" />
    </div>;


  const heroInner = bareHero ?
  <>{heroExtra}</> :

  <>
      <Reveal>
        <div className="breadcrumbs">
          <a href="index.html">Home</a>
          <span className="sep" style={{ color: "rgb(167, 139, 255)" }}>/</span>
          <span style={{ color: "rgb(167, 139, 255)" }}>{typeof currentPath === 'object' ? currentPath[lang] || currentPath.de : currentPath}</span>
        </div>
      </Reveal>
      {kicker && <Reveal><span className="kicker">{typeof kicker === 'object' ? kicker[lang] || kicker.de : kicker}</span></Reveal>}
      <Reveal as="h1" style={{ lineHeight: 1.2 }}>{typeof title === 'object' ? title[lang] || title.de : title}</Reveal>
      {lead && <Reveal as="p" className="lead">{typeof lead === 'object' ? lead[lang] || lead.de : lead}</Reveal>}
      {heroExtra && <Reveal>{heroExtra}</Reveal>}
    </>;


  return (
    <>
      <div className="atmos" />
      <div className="grain" />
      <CursorGlow />
      <NavShared lang={lang} setLang={setLang} brand={brand} />
      <main>
        <section ref={heroRef} className={heroCls}>
          {topLamp ?
          <>
              <TopLamp />
              <div className="hero-lamp-content">{heroInner}</div>
            </> :

          heroPin ? <div className="page-hero-pin-inner" style={{ padding: "0px 40px 60px" }}>{heroInner}</div> : heroInner
          }
        </section>
        <div className="page-content" style={{ color: "rgb(244, 241, 251)" }}>
          {typeof children === 'function' ? children({ lang, t }) : children}
        </div>
      </main>
      <FooterShared lang={lang} brand={brand} />
    </>);

}

Object.assign(window, { PageShell, Reveal, useReveal, CursorGlow, NavShared, FooterShared });