/* MCA — App router + tweaks */

const { useState: useStateA, useEffect: useEffectA } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#00A5A1",
  "deep": "#1A3B4D",
  "headingFont": "Montserrat",
  "italicEm": true,
  "darkHero": false
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = useStateA(() => {
    const h = window.location.hash.replace(/^#/, "");
    return h || "/";
  });
  const navigate = (to) => {
    window.location.hash = to;
    setRoute(to);
    window.scrollTo({ top: 0, behavior: "instant" });
  };
  useEffectA(() => {
    const onHash = () => setRoute(window.location.hash.replace(/^#/, "") || "/");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // ---- Light / dark theme (user toggle, persisted) ----
  const [theme, setTheme] = useStateA(() => {
    try { return localStorage.getItem("mca-theme") || "dark"; }
    catch (e) { return "dark"; }
  });
  const toggleTheme = () => setTheme((t) => (t === "dark" ? "light" : "dark"));
  useEffectA(() => {
    const light = theme === "light";
    document.documentElement.classList.toggle("theme-light", light);
    document.body.classList.toggle("theme-light", light);
    try { localStorage.setItem("mca-theme", theme); } catch (e) {}
  }, [theme]);

  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffectA(() => {
    document.documentElement.style.setProperty("--teal", tweaks.accent);
    document.documentElement.style.setProperty("--deep", tweaks.deep);
    document.documentElement.style.setProperty("--font-head",
      `"${tweaks.headingFont}", "Helvetica Neue", Helvetica, Arial, sans-serif`);
  }, [tweaks]);

  useEffectA(() => {
    const isHome = route === "/" || route === "";
    const isBlog = route === "/blog" || route.startsWith("/blog/") || route.startsWith("/article/") || route === "/case-studies" || route.startsWith("/case-studies/");
    const isTeam = route === "/team";
    const dark = theme === "dark";
    document.body.classList.toggle("home-dark", isHome && dark);
    document.body.classList.toggle("blog-dark", isBlog && dark);
    document.body.classList.toggle("team-dark-page", isTeam && dark);
    return () => {
      document.body.classList.remove("home-dark");
      document.body.classList.remove("blog-dark");
      document.body.classList.remove("team-dark-page");
    };
  }, [route, theme]);

  // Robust video playback: browsers (esp. iOS Low Power Mode) often block
  // muted autoplay. Play videos when they scroll into view, and prime every
  // video on the first user interaction so they start the moment they can.
  useEffectA(() => {
    let io;
    const playSafely = (v) => {
      if (!v) return;
      v.muted = true;
      v.setAttribute("muted", "");
      v.playsInline = true;
      const p = v.play();
      if (p && p.catch) p.catch(() => {});
    };
    const collect = () => Array.from(document.querySelectorAll("video"));

    const setup = () => {
      const vids = collect();
      if ("IntersectionObserver" in window) {
        io = new IntersectionObserver((entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) playSafely(e.target);
            else if (!e.target.hasAttribute("data-keep-playing")) {
              try { e.target.pause(); } catch (_) {}
            }
          });
        }, { threshold: 0.2 });
        vids.forEach((v) => io.observe(v));
      } else {
        vids.forEach(playSafely);
      }
    };

    const primeAll = () => collect().forEach(playSafely);
    const onFirst = () => { primeAll(); };
    ["touchstart", "pointerdown", "click", "keydown"].forEach((ev) =>
      window.addEventListener(ev, onFirst, { passive: true })
    );

    const t = setTimeout(setup, 60);
    return () => {
      clearTimeout(t);
      if (io) io.disconnect();
      ["touchstart", "pointerdown", "click", "keydown"].forEach((ev) =>
        window.removeEventListener(ev, onFirst)
      );
    };
  }, [route]);

  let body;
  if (route === "/" || route === "") {
    body = (
      <React.Fragment>
        <Hero navigate={navigate} />
        <Services navigate={navigate} />
        <About />
        <Metrics />
        <CaseStudies navigate={navigate} />
        <Insights navigate={navigate} />
        <Team navigate={navigate} />
        <Testimonials />
        <FAQ omit={[
          "What does MCA do as a Web3 consulting company?",
          "Does MCA work with global Web3 teams?",
          "Why do companies hire a Web3 consulting company like MCA?",
          "How does MCA measure success as a Web3 consulting company?",
          "What makes MCA different from other Web3 consulting companies?",
          "What types of companies work with MCA?",
          "Can MCA help with Web3 PR and media visibility?"
        ]} />
        <FinalCTA navigate={navigate} />
      </React.Fragment>
    );
  } else if (route === "/services/ai-solutions") {
    body = <AISolutionsPage navigate={navigate} />;
  } else if (route === "/services/growth-scale") {
    body = <GrowthScalePage navigate={navigate} />;
  } else if (route.startsWith("/services/")) {
    const slug = route.split("/")[2];
    body = <ServicePage slug={slug} navigate={navigate} />;
  } else if (route === "/contact") {
    body = <ContactPage navigate={navigate} />;
  } else if (route === "/reports" || route === "/insights") {
    body = <InsightsPage navigate={navigate} />;
  } else if (route === "/case-studies") {
    body = <CaseStudiesPage navigate={navigate} />;
  } else if (route.startsWith("/case-studies/")) {
    const slug = route.split("/")[2];
    body = <CaseStudyPage slug={slug} navigate={navigate} />;
  } else if (route === "/blog") {
    body = <BlogPage navigate={navigate} />;
  } else if (route.startsWith("/blog/")) {
    const slug = route.split("/")[2];
    body = <ArticlePage slug={slug} navigate={navigate} />;
  } else if (route.startsWith("/article/")) {
    const slug = route.split("/")[2];
    body = <ArticlePage slug={slug} navigate={navigate} />;
  } else if (route === "/team") {
    body = <TeamPage navigate={navigate} />;
  } else {
    body = (
      <section className="page-hero">
        <div className="page-hero__inner" style={{ textAlign: "center" }}>
          <div className="page-hero__crumb">404</div>
          <h1 className="page-hero__title" style={{ margin: "0 auto" }}>Page not found.</h1>
          <p className="page-hero__sub" style={{ margin: "24px auto 0" }}>The page you're looking for doesn't exist or has moved.</p>
          <div style={{ marginTop: 32 }}><Button variant="primary" onClick={() => navigate("/")} withArrow>Back home</Button></div>
        </div>
      </section>
    );
  }

  return (
    <React.Fragment>
      <Nav route={route} navigate={navigate} theme={theme} onToggleTheme={toggleTheme} />
      <main key={route} className="fade-in">{body}</main>
      <Footer navigate={navigate} />

      <AtlasChat />

      <TweaksPanel>
        <TweakSection label="Brand">
          <TweakColor label="Accent" value={tweaks.accent}
            options={["#00A5A1", "#0E1D26", "#3CB1AE", "#D97757", "#1F8A5B"]}
            onChange={(v) => setTweak("accent", v)} />
          <TweakColor label="Deep brand" value={tweaks.deep}
            options={["#1A3B4D", "#0E1D26", "#000000", "#1F2937"]}
            onChange={(v) => setTweak("deep", v)} />
        </TweakSection>
        <TweakSection label="Typography">
          <TweakSelect label="Heading font" value={tweaks.headingFont}
            options={["Montserrat", "Inter", "Cormorant Garamond", "Space Grotesk"]}
            onChange={(v) => setTweak("headingFont", v)} />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

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