// site-app.jsx — hash-router for the BorderUX site.

window.__siteMode = true;

// Prevent crashes if cookie-banner.jsx is blocked by ad/content blockers
window.CookieBanner = window.CookieBanner || (() => null);

const ROUTES = {
  "/": "home",
  "/services": "services",
  "/open-source": "open-source",
  "/work": "work",
  "/blog": "blog",
  "/contact": "contact",
  "/about": "about",
  "/jobs": "careers",
  "/legal/privacy": "privacy",
  "/legal/terms-of-use": "terms",
  "/legal/licensing": "licensing",
  "/legal/licenses": "licensing",
  "/legal/cookies": "cookies",
};

// Unified programmatic router navigation
window.__bxNavigate = (href) => {
  if (window.location.hostname.endsWith("github.io")) {
    window.history.pushState(null, "", window.location.pathname + "#" + href);
  } else {
    window.history.pushState(null, "", href);
  }
  window.dispatchEvent(new PopStateEvent("popstate"));
};

function useBrowserRoute() {
  const parse = () => {
    const hash = window.location.hash;
    let path = window.location.pathname || "/";
    
    // Resolve hash router paths
    if (hash && hash.startsWith("#/")) {
      const targetPath = hash.slice(1);
      path = targetPath;
    }

    // Redirect legacy stories or post routes
    if (path === "/stories" || path === "/stories/") {
      window.history.replaceState(null, "", "/blog");
      path = "/blog";
    } else if (path.startsWith("/stories/")) {
      const postSlug = path.slice(9);
      window.history.replaceState(null, "", "/blog/" + postSlug);
      path = "/blog/" + postSlug;
    } else if (path.startsWith("/post/")) {
      const postSlug = path.slice(6);
      window.history.replaceState(null, "", "/blog/" + postSlug);
      path = "/blog/" + postSlug;
    } else if (path.startsWith("/case/")) {
      const caseSlug = path.slice(6);
      const cleanSlug = caseSlug.endsWith("/") ? caseSlug.slice(0, -1) : caseSlug;
      window.history.replaceState(null, "", "/work/" + cleanSlug);
      path = "/work/" + cleanSlug;
    } else if (path === "/privacy" || path === "/privacy/") {
      window.history.replaceState(null, "", "/legal/privacy");
      path = "/legal/privacy";
    } else if (path === "/terms" || path === "/terms/" || path === "/legal/terms" || path === "/legal/terms/") {
      window.history.replaceState(null, "", "/legal/terms-of-use");
      path = "/legal/terms-of-use";
    } else if (path === "/cookies" || path === "/cookies/") {
      window.history.replaceState(null, "", "/legal/cookies");
      path = "/legal/cookies";
    } else if (path === "/licensing" || path === "/licensing/") {
      window.history.replaceState(null, "", "/legal/licensing");
      path = "/legal/licensing";
    } else if (path === "/licenses" || path === "/licenses/") {
      window.history.replaceState(null, "", "/legal/licensing");
      path = "/legal/licensing";
    } else if (path === "/careers" || path === "/careers/") {
      window.history.replaceState(null, "", "/jobs");
      path = "/jobs";
    } else if (path === "/invite" || path === "/invite/") {
      window.history.replaceState(null, "", "/contact");
      path = "/contact";
    } else if (path.startsWith("/job/")) {
      window.history.replaceState(null, "", "/jobs");
      path = "/jobs";
    } else if (
      path === "/love" || path === "/love/" || 
      path === "/animus" || path === "/animus/" || 
      path === "/ethos" || path === "/ethos/"
    ) {
      window.history.replaceState(null, "", "/about");
      path = "/about";
    }

    if (path.startsWith("/work/")) {
      const sub = path.slice(6);
      if (sub && sub !== "/") {
        const rawSlug = sub.endsWith("/") ? sub.slice(0, -1) : sub;
        let slug = rawSlug;
        try { slug = decodeURIComponent(rawSlug); } catch (e) {}
        if (slug === "padi") {
          window.history.replaceState(null, "", "/blog/from-course-catalog-to-adventure-ecosystem");
          path = "/blog/from-course-catalog-to-adventure-ecosystem";
        } else if (slug === "cymbiotika") {
          window.history.replaceState(null, "", "/blog/unifying-cymbiotikas-digital-experience");
          path = "/blog/unifying-cymbiotikas-digital-experience";
        } else {
          window.history.replaceState(null, "", "/work");
          path = "/work";
        }
      }
    }
    if (path.startsWith("/blog/tag/")) {
      const tagSlug = path.slice(10);
      const cleanTag = tagSlug.endsWith("/") ? tagSlug.slice(0, -1) : tagSlug;
      if (cleanTag) {
        let slug = cleanTag;
        try { slug = decodeURIComponent(cleanTag); } catch (e) {}
        return { route: "tag", slug };
      } else {
        window.history.replaceState(null, "", "/blog");
        path = "/blog";
      }
    }
    if (path.startsWith("/author/")) {
      const authorSlug = path.slice(8);
      const cleanAuthor = authorSlug.endsWith("/") ? authorSlug.slice(0, -1) : authorSlug;
      if (cleanAuthor) {
        let slug = cleanAuthor;
        try { slug = decodeURIComponent(cleanAuthor); } catch (e) {}
        return { route: "author", slug };
      } else {
        window.history.replaceState(null, "", "/blog");
        path = "/blog";
      }
    }
    if (path.startsWith("/blog/")) {
      const postSlug = path.slice(6);
      let slug = postSlug;
      try { slug = decodeURIComponent(postSlug); } catch (e) {}
      return { route: "post", slug };
    }
    
    const cleanPath = path.endsWith("/") && path !== "/" ? path.slice(0, -1) : path;
    return { route: ROUTES[cleanPath] || "404", slug: null };
  };
  const [state, setState] = React.useState(parse);
  React.useEffect(() => {
    const onPop = () => {
      const next = parse();
      setState((prev) => {
        if (prev.route !== next.route || prev.slug !== next.slug) {
          window.scrollTo({ top: 0, behavior: "instant" });
        }
        return next;
      });
    };
    window.addEventListener("popstate", onPop);
    
    // Global click listener to intercept local clean links
    const onClick = (e) => {
      const a = e.target.closest("a");
      if (!a) return;
      const href = a.getAttribute("href");
      if (!href) return;
      
      if (
        href.startsWith("/") && 
        !href.startsWith("//") && 
        !a.getAttribute("target") && 
        !e.ctrlKey && 
        !e.metaKey && 
        !e.shiftKey && 
        !e.altKey
      ) {
        e.preventDefault();
        window.__bxNavigate(href);
      }
    };
    window.addEventListener("click", onClick);
    
    return () => {
      window.removeEventListener("popstate", onPop);
      window.removeEventListener("click", onClick);
    };
  }, []);
  return state;
}

function SiteApp() {
  const { route, slug } = useBrowserRoute();
  let pageComponent = null;
  switch (route) {
    case "services":    pageComponent = <PageServices />; break;
    case "open-source": pageComponent = <PageOpenSource />; break;
    case "work":        pageComponent = <PageWork />; break;
    case "blog":        pageComponent = <PageBlog />; break;
    case "tag":         pageComponent = <PageBlog tag={slug} />; break;
    case "author":      pageComponent = <PageBlog author={slug} />; break;
    case "contact":     pageComponent = <PageContact />; break;
    case "about":       pageComponent = <PageAbout />; break;
    case "careers":     pageComponent = <PageCareers />; break;
    case "post":        pageComponent = <BlogArticlePage slug={slug} />; break;
    case "privacy":     pageComponent = <PagePrivacy />; break;
    case "terms":       pageComponent = <PageTerms />; break;
    case "licensing":   pageComponent = <PageLicensing />; break;
    case "cookies":     pageComponent = <PageCookies />; break;
    case "home":        pageComponent = <Home />; break;
    case "404":
    default:            pageComponent = <Page404 />; break;
  }
  return (
    <>
      {pageComponent}
      <CookieBanner />
    </>
  );
}


// Once /content/*.md has finished loading, overlay the parsed values onto
// the CONTENT / SITE_CONTENT objects exported by shared/ folder + site-pages.jsx.
// We mutate the existing objects (rather than reassigning) so the React
// components keep their stable references through the first render.
function __bxApplyContent() {
  const C = window.__BX_CONTENT || {};
  if (!C) return;
  if (window.CONTENT) {
    const home = C.home || {};
    if (C.services && C.services.services) window.CONTENT.services = C.services.services;
    if (C.work && C.work.industries) {
      window.CONTENT.industries = C.work.industries.map((i) => ({
        name: i.name, note: i.summary || i.body,
      }));
    }
    if (C["open-source"] && C["open-source"].oss) {
      window.CONTENT.oss = C["open-source"].oss.slice(0, 3).map((o) => ({
        name: o.name, desc: o.desc, linkText: o.ctaLabel || o.linkText, linkUrl: o.ctaUrl || o.linkUrl, ctaLabel: o.ctaLabel || o.linkText, ctaUrl: o.ctaUrl || o.linkUrl,
      }));
    }
    if (C.blog && C.blog.posts) {
      window.CONTENT.posts = C.blog.posts.slice(0, 4).map((p) => ({
        date: p.date, kind: p.kind, title: p.title, read: p.read, image: p.image || "",
      }));
    }
    if (home.proof) window.CONTENT.proof = home.proof;
    if (home.nav) window.CONTENT.nav = home.nav;
    if (home.quotes) window.CONTENT.quotes = home.quotes;
    if (home.pillars) window.CONTENT.pillars = home.pillars;
    if (home.techTitle) window.CONTENT.techTitle = home.techTitle;
    if (home.servicesTitle) window.CONTENT.servicesTitle = home.servicesTitle;
  }
  if (window.SITE_CONTENT) {
    if (C.services && C.services.services) window.SITE_CONTENT.services = C.services.services;
    if (C.work && C.work.industries)       window.SITE_CONTENT.industries = C.work.industries;
    if (C["open-source"] && C["open-source"].oss) window.SITE_CONTENT.oss = C["open-source"].oss;
    if (C.blog && C.blog.posts)            window.SITE_CONTENT.posts = C.blog.posts;

    if (C.services) Object.assign(window.SITE_CONTENT.servicesMeta, C.services);
    if (C.work)     Object.assign(window.SITE_CONTENT.workMeta, C.work);
    if (C["open-source"]) Object.assign(window.SITE_CONTENT.ossMeta, C["open-source"]);
    if (C.blog)     Object.assign(window.SITE_CONTENT.postsMeta, C.blog);
    if (C.about)    Object.assign(window.SITE_CONTENT.aboutMeta, C.about);
    if (C.careers)  Object.assign(window.SITE_CONTENT.careersMeta, C.careers);
    if (C.contact)  Object.assign(window.SITE_CONTENT.contactMeta, C.contact);
  }
  if (C.authors && C.authors.authors) {
    const list = C.authors.authors;
    window.AUTHOR_INFO = {};
    list.forEach((a) => {
      window.AUTHOR_INFO[a.slug] = {
        name: a.name,
        bio: a.bio,
        avatar: a.avatar,
      };
    });
  }
}

// Wait for /content/*.md to finish loading (when content-loader.js is
// present) before applying the data and mounting React. Without the loader,
// mount immediately with the baked-in fallbacks.
function __bxMount() {
  __bxApplyContent();
  ReactDOM.createRoot(document.getElementById("root")).render(<SiteApp />);
}
if (window.__bxContentReady && typeof window.__bxContentReady.then === "function") {
  window.__bxContentReady.then(__bxMount, __bxMount);
} else {
  __bxMount();
}
