/* global React */
/* Router + mount. Loads after shell + pages. */
(function () {
  const A = window.MA_PAGES_A;
  const B = window.MA_PAGES_B;
  const { SiteHeader, CallingCard, ContactCTA, AIPreviewCTA, SiteFooter, useRoute, refreshIcons } = window.MA;

  function parse(route) {
    const clean = (route || "/").replace(/^\/+/, "").replace(/\/+$/, ""); // "", "services", "service/slug"
    const [head, ...rest] = clean.split("/");
    return { head: head || "home", rest, clean };
  }

  /* Routes that no longer exist, and where each one goes instead: the Doors &
     Windows and chimney services the owner retired, the one-coat and EIFS
     stucco systems, and the old ROI anchor. firebase.json carries the same
     table as permanent redirects, which is what a visitor arriving from
     outside gets. This copy catches what never reaches the server — an old
     hash address, or a stale link clicked inside the site — with `replace` so
     the retired address does not stay in the browser history. Keep the two in
     step. */
  const RETIRED_ROUTES = {
    "category/doors-windows": "/services",
    "service/window-replacement": "/services",
    "service/stone-window-surrounds": "/services",
    "service/exterior-entry-doors": "/services",
    "service/patio-sliding-doors": "/services",
    "service/chimney-facing": "/services",
    "service/one-coat-stucco": "/category/stucco",
    "service/synthetic-eifs-stucco": "/category/stucco",
    roi: "/learn/does-stone-veneer-add-value",
    // American spelling in the slug; the old address keeps working.
    "learn/choosing-a-stone-colour": "/learn/choosing-a-stone-color",
  };

  function Router() {
    const route = useRoute();
    const { head, rest, clean } = parse(route);
    const isPreviewPage = head === "ai-preview";
    const retired = RETIRED_ROUTES[clean];
    React.useEffect(() => { const t = setTimeout(refreshIcons, 60); return () => clearTimeout(t); });
    React.useEffect(() => { if (retired) window.MA_ROUTER.navigate(retired, { replace: true }); }, [retired]);
    if (retired) return null;

    // The page the banner under the menu links to: nothing but the AI preview
    // form. No closing CTA or calling card under it — a second ask below the
    // form only competes with it — and no banner pointing back at itself.
    if (isPreviewPage) {
      return (
        <div>
          <SiteHeader showPreviewBanner={false} />
          <main><AIPreviewCTA standalone /></main>
          <SiteFooter />
        </div>
      );
    }

    let page;
    switch (head) {
      case "home": page = <A.HomePage />; break;
      case "services": page = <A.ServicesPage />; break;
      case "category": page = <A.CategoryPage slug={rest[0] || "masonry-projects"} />; break;
      case "service": page = <A.ServiceDetailPage slug={rest[0] || "manufactured-stone-veneer"} />; break;
      // The old standalone styles page is gone; send its links to the services
      // overview.
      case "styles": page = <A.ServicesPage />; break;
      case "commercial": page = <B.CommercialPage />; break;
      case "gallery": page = <B.GalleryPage />; break;
      case "learn": page = rest[0] ? <B.ArticlePage slug={rest[0]} /> : <B.LearnPage />; break;
      // The cost guide is hidden with the rest of the articles for now
      // (COST_GUIDE_SHOWN, nav-data.js); its address shows the Articles page.
      case "cost": page = window.MA_DATA.COST_GUIDE_SHOWN ? <B.CostPage /> : <B.LearnPage />; break;
      case "about": page = <B.AboutPage />; break;
      case "contact": page = <B.ContactPage />; break;
      case "privacy": page = <B.PrivacyPage />; break;
      default: page = <A.HomePage />;
    }

    // Most pages close on a call to action, but two pages end in a form of
    // their own — the Commercial & Residential page's "leave your details" block
    // and the contact page itself. Stacking a second form under either one makes
    // both of them weaker, so those pages keep their own ask.
    //
    // Privacy is excluded for a different reason: a page explaining what we do
    // with your details should not be interrupted by a form asking for them.
    const ownsItsCTA = head === "commercial" || head === "contact" || head === "privacy";

    // Only the Exterior Remodel page ends in the AI preview: a rendering of the
    // whole finished elevation is what sells the full package. Every other page
    // closes on the plain estimate band instead.
    const isRemodel = head === "category" && rest[0] === window.MA_DATA.REMODEL_SLUG;

    let cta = null;
    if (isRemodel) cta = <AIPreviewCTA />;
    else if (!ownsItsCTA) cta = <ContactCTA />;

    return (
      <div>
        <SiteHeader />
        <main>{page}</main>
        {cta}
        <CallingCard />
        <SiteFooter />
      </div>
    );
  }

  ReactDOM.createRoot(document.getElementById("root")).render(<Router />);
  setTimeout(refreshIcons, 300);
  window.addEventListener("ma:route", () => setTimeout(refreshIcons, 120));
})();
