/* global React, window */
const { Brand, Arrow, SiteScrollCtx } = window;
const { motion, AnimatePresence, useScroll } = window.FM || {};

const Mdiv = motion.div || "div";

// Keyboard handler helper — fire fn on Enter or Space
const kp = (fn) => (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); fn(); } };

// Thin sage line that grows with scroll — works with container OR window
function ScrollProgress({ containerRef }) {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const el = containerRef && containerRef.current;
    if (el) {
      const fn = () => { const t = el.scrollHeight - el.clientHeight; setP(t > 0 ? el.scrollTop / t : 0); };
      el.addEventListener('scroll', fn, { passive: true });
      return () => el.removeEventListener('scroll', fn);
    } else {
      const fn = () => { const t = document.documentElement.scrollHeight - window.innerHeight; setP(t > 0 ? window.scrollY / t : 0); };
      window.addEventListener('scroll', fn, { passive: true });
      return () => window.removeEventListener('scroll', fn);
    }
  }, []);
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0,
      height: 2, background: 'var(--sage)',
      transformOrigin: '0%', transform: `scaleX(${p})`,
      zIndex: 100, pointerEvents: 'none',
    }}/>
  );
}

const pageVariants = {
  initial: { opacity: 0, y: 20 },
  animate: { opacity: 1, y: 0, transition: { duration: 0.55, ease: [0.16, 1, 0.3, 1] } },
  exit:    { opacity: 0, y: -10, transition: { duration: 0.28, ease: [0.7, 0, 1, 1] } },
};

function Nav({ active, go }) {
  const [hidden, setHidden] = React.useState(false);
  const lastY = React.useRef(0);
  React.useEffect(() => {
    const fn = () => {
      const y = window.scrollY;
      setHidden(y > lastY.current + 4 && y > 120);
      lastY.current = y;
    };
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);
  return (
    <nav className="nav" aria-label="Navigation principale" style={{ transform: hidden ? 'translateY(-80px)' : 'translateY(0)', transition: 'transform 0.45s cubic-bezier(0.16,1,0.3,1)' }}>
      <div
        onClick={() => go("home")}
        onKeyDown={kp(() => go("home"))}
        role="button"
        tabIndex={0}
        aria-label="Accueil AAKV"
        data-cursor="hover"
        style={{ cursor: "pointer" }}
      >
        <Brand/>
      </div>
      <div className="nav__links">
        {window.PAGES.map((p) => (
          <a
            key={p.id}
            className={`nav__link ${active === p.id ? "is-active" : ""}`}
            onClick={() => go(p.id)}
            onKeyDown={kp(() => go(p.id))}
            tabIndex={0}
            aria-current={active === p.id ? "page" : undefined}
            data-cursor="hover"
          >
            {p.label}
          </a>
        ))}
      </div>
      <a
        className="nav__cta"
        onClick={() => go("contact")}
        onKeyDown={kp(() => go("contact"))}
        tabIndex={0}
        data-cursor="hover"
      >
        Démarrer
      </a>
    </nav>
  );
}

function MNav({ active, go }) {
  const [open, setOpen] = React.useState(false);
  const menuId = "mnav-menu";

  // Fermer sur Escape + focus trap
  React.useEffect(() => {
    if (!open) return;
    const handleKey = (e) => {
      if (e.key === 'Escape') {
        setOpen(false);
        document.querySelector('.mnav__burger') && document.querySelector('.mnav__burger').focus();
      }
    };
    document.addEventListener('keydown', handleKey);
    return () => document.removeEventListener('keydown', handleKey);
  }, [open]);

  return (
    <>
      <nav className="mnav" aria-label="Navigation mobile">
        <div
          onClick={() => { setOpen(false); go("home"); }}
          onKeyDown={kp(() => { setOpen(false); go("home"); })}
          role="button"
          tabIndex={0}
          aria-label="Accueil AAKV"
        >
          <Brand small/>
        </div>
        <button
          className="mnav__burger"
          onClick={() => setOpen(!open)}
          aria-label={open ? "Fermer le menu" : "Ouvrir le menu"}
          aria-expanded={open}
          aria-controls={menuId}
        >
          <span aria-hidden="true"/>
        </button>
      </nav>
      {open ? (
        <div
          id={menuId}
          role="navigation"
          aria-label="Menu principal"
          style={{ position: "absolute", inset: "60px 0 0 0", background: "var(--bg)", zIndex: 28, padding: "32px 22px", display: "flex", flexDirection: "column", gap: 24 }}
        >
          {window.PAGES.map((p) => (
            <a
              key={p.id}
              style={{ fontFamily: "var(--serif)", fontSize: 36, fontWeight: 300, color: active === p.id ? "var(--sage)" : "var(--dark)" }}
              onClick={() => { setOpen(false); go(p.id); }}
              onKeyDown={kp(() => { setOpen(false); go(p.id); })}
              tabIndex={0}
              aria-current={active === p.id ? "page" : undefined}
            >
              {p.label}
            </a>
          ))}
          <div style={{ marginTop: "auto", paddingTop: 24, borderTop: "1px solid var(--line)" }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Bureau</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 18 }}>32 Route de Genval, Ohain</div>
            <div style={{ marginTop: 10 }}>info@aakv.be</div>
          </div>
        </div>
      ) : null}
    </>
  );
}

function Footer({ go }) {
  return (
    <footer className="foot">
      <div className="foot__grid">
        <div>
          <h3>L'architecture<br/>que vous <em style={{ color: "var(--sage)", fontStyle: "italic" }}>imaginiez</em>.</h3>
          <p style={{ color: "rgba(245,244,240,0.65)", maxWidth: 360, fontSize: 14, lineHeight: 1.6 }}>Bureau d'architecture & énergie en Brabant Wallon et à Bruxelles. Maisons, extensions, rénovations patrimoniales et énergétiques.</p>
          <a className="btn btn--primary" onClick={() => go("contact")} onKeyDown={kp(() => go("contact"))} tabIndex={0} style={{ background: "var(--sage)", color: "var(--bg)", marginTop: 32 }} data-cursor="hover">Démarrer un projet <Arrow/></a>
        </div>
        <div>
          <div className="foot__col-title">Navigation</div>
          <ul>{window.PAGES.map((p) => <li key={p.id}><a onClick={() => go(p.id)} onKeyDown={kp(() => go(p.id))} tabIndex={0}>{p.label}</a></li>)}</ul>
        </div>
        <div>
          <div className="foot__col-title">Bureau</div>
          <ul><li>32 Route de Genval</li><li>1380 Ohain-Lasne</li><li style={{ marginTop: 8 }}><a>info@aakv.be</a></li><li><a>+32 (0)2 633 …</a></li></ul>
        </div>
        <div>
          <div className="foot__col-title">Suivre</div>
          <ul><li><a>Instagram</a></li><li><a>LinkedIn</a></li><li><a>Pinterest</a></li><li style={{ marginTop: 8 }}><a>Newsletter</a></li></ul>
        </div>
      </div>
      <div className="foot__bar">
        <div>© 2026 AAKV — Architecture & Énergie · Ordre des Architectes BE</div>
        <div className="right"><a>Mentions légales</a><a>RGPD</a><a>Cookies</a></div>
      </div>
    </footer>
  );
}

function MFooter({ go }) {
  return (
    <footer className="mfoot">
      <h3>L'architecture que vous <em style={{ color: "var(--sage)", fontStyle: "italic" }}>imaginiez</em>.</h3>
      <a className="btn btn--primary" onClick={() => go("contact")} onKeyDown={kp(() => go("contact"))} tabIndex={0} style={{ background: "var(--sage)", marginBottom: 28 }}>Démarrer un projet <Arrow/></a>
      <div style={{ display: "grid", gap: 8, fontSize: 12 }}>
        <div>32 Route de Genval, 1380 Ohain-Lasne</div>
        <div>info@aakv.be</div>
        <div style={{ display: "flex", gap: 16, marginTop: 8 }}><a>Instagram</a><a>LinkedIn</a><a>Pinterest</a></div>
      </div>
      <div className="mfoot__bar">© 2026 AAKV · Mentions légales · RGPD</div>
    </footer>
  );
}

function Site({ page, projectId, go, isMobile, direction, prod }) {
  const wrapRef = React.useRef(null);

  React.useEffect(() => {
    if (prod) window.scrollTo(0, 0);
    else if (wrapRef.current) wrapRef.current.scrollTop = 0;
  }, [page, projectId]);

  React.useEffect(() => {
    const t = setTimeout(() => {
      const root = prod ? null : wrapRef.current;
      const els = document.querySelectorAll(".fade-up:not(.is-in)");
      const io = new IntersectionObserver(
        (entries) => entries.forEach((e) => {
          if (e.isIntersecting) {
            const delay = parseInt(e.target.dataset.delay || 0);
            if (delay) e.target.style.transitionDelay = delay + 'ms';
            e.target.classList.add("is-in");
          }
        }),
        { root, threshold: 0.08 }
      );
      els.forEach((el) => io.observe(el));
      return () => io.disconnect();
    }, 60);
    return () => clearTimeout(t);
  }, [page, projectId]);

  let Page = null;
  if (page === "home") Page = (
    direction === "editorial" ? <window.HomeEditorial go={go}/> : (
    <>
      <window.HomeHero go={go}/>
      <window.HomePhilosophy/>
      <window.HomeProjects go={go}/>
      <window.HomeStats/>
      <window.HomeServices go={go}/>
      <window.HomeProcess/>
      <window.HomeContact go={go}/>
    </>
    )
  );
  else if (page === "realisations") Page = <window.PageRealisations go={go}/>;
  else if (page === "project")      Page = <window.PageProject id={projectId} go={go}/>;
  else if (page === "services")     Page = <window.PageServices go={go}/>;
  else if (page === "blog")         Page = <window.PageBlog go={go}/>;
  else if (page === "about")        Page = <window.PageAbout go={go}/>;
  else if (page === "contact")      Page = <window.PageContact go={go}/>;

  const path = page === "project" ? `/realisations/${projectId}/` : (window.PAGES.find((p) => p.id === page)?.path || "/");

  if (prod) {
    return (
      <SiteScrollCtx.Provider value={null}>
        <ScrollProgress containerRef={null} />
        <div className={`site ${direction === "editorial" ? "is-editorial" : ""}`}>
          <Nav active={page} go={go}/>
          <AnimatePresence mode="wait">
            <Mdiv key={page + (projectId || "")} variants={pageVariants} initial="initial" animate="animate" exit="exit">
              {Page}
            </Mdiv>
          </AnimatePresence>
          <Footer go={go}/>
        </div>
      </SiteScrollCtx.Provider>
    );
  }

  if (isMobile) {
    return (
      <div className="frame mobile">
        <div className="mobile__screen">
          <div className="mobile__notch"/>
          <window.StatusBar/>
          <div className="mobile__viewport" ref={wrapRef}>
            <div className="site is-mobile">
              <MNav active={page} go={go}/>
              <AnimatePresence mode="wait">
                <Mdiv key={page + (projectId || "")} variants={pageVariants} initial="initial" animate="animate" exit="exit">
                  {Page}
                </Mdiv>
              </AnimatePresence>
              <MFooter go={go}/>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="frame">
      <div className="frame__chrome">
        <div className="frame__dots"><span/><span/><span/></div>
        <div className="frame__url"><b>aakv.be</b>{path}</div>
      </div>
      <SiteScrollCtx.Provider value={wrapRef}>
        <div className="frame__viewport" ref={wrapRef}>
          <ScrollProgress containerRef={wrapRef} />
          <div className={`site ${direction === "editorial" ? "is-editorial" : ""}`}>
            <Nav active={page} go={go}/>
            <AnimatePresence mode="wait">
              <Mdiv key={page + (projectId || "")} variants={pageVariants} initial="initial" animate="animate" exit="exit">
                {Page}
              </Mdiv>
            </AnimatePresence>
            <Footer go={go}/>
          </div>
        </div>
      </SiteScrollCtx.Provider>
    </div>
  );
}

Object.assign(window, { Nav, MNav, Footer, MFooter, Site });
