import React, { Suspense } from "react";
import ReactDOM from "react-dom/client";

import { RouterProvider } from "react-router-dom";
import { IntercomProvider } from "react-use-intercom";

import { ThemeProvider } from "styled-components";
import theme from "~/constants/theme";

import GlobalStyle from "~/globalStyle";
import { captureClickIdsFromSearch } from "~/helpers/clickIds";
import { installDomSafetyGuards } from "~/helpers/domSafety";

// Must run before the first React render so every DOM mutation React makes
// is protected from third-party interference (Google Translate, extensions).
installDomSafetyGuards();

captureClickIdsFromSearch();

// Store qa=yes flag in localStorage to persist across navigation
const urlParams = new URLSearchParams(window.location.search);
const qaParam = urlParams.get("qa");
if (qaParam === "yes") {
  localStorage.setItem("disable_captcha_qa", "true");
} else if (qaParam === "no") {
  // Remove the flag if explicitly set to no
  localStorage.removeItem("disable_captcha_qa");
}

// Check both URL param and localStorage
const shouldDisableCaptcha =
  qaParam === "yes" || localStorage.getItem("disable_captcha_qa") === "true";

if (shouldDisableCaptcha) {
  // Remove preconnect/dns-prefetch links
  const hcaptchaLinks = document.querySelectorAll('link[href*="hcaptcha.com"]');
  hcaptchaLinks.forEach((link) => link.remove());

  // Remove any existing hCaptcha iframes and containers
  const removeHCaptchaElements = () => {
    // Remove iframes
    const iframes = document.querySelectorAll(
      'iframe[src*="hcaptcha"], iframe[id*="hcaptcha"]'
    );
    iframes.forEach((iframe) => iframe.remove());

    // Remove hcaptcha containers
    const containers = document.querySelectorAll(
      '[id*="hcaptcha-invisible"], [id*="hcaptcha"]'
    );
    containers.forEach((container) => container.remove());
  };

  // Remove immediately and set up observer for any that get added later
  if (document.body) {
    removeHCaptchaElements();
    const observer = new MutationObserver(removeHCaptchaElements);
    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });
  } else {
    // If body doesn't exist yet, wait for DOMContentLoaded
    document.addEventListener("DOMContentLoaded", () => {
      removeHCaptchaElements();
      const observer = new MutationObserver(removeHCaptchaElements);
      observer.observe(document.body, {
        childList: true,
        subtree: true,
      });
    });
  }
}

import "@fontsource-variable/inter";

// Lazy-load secondary fonts — only loaded when needed by specific pages
const loadSecondaryFonts = () => {
  // @ts-ignore - CSS-only imports, no type declarations needed
  import("@fontsource/ubuntu");
  // @ts-ignore
  import("@fontsource/ubuntu/700.css");
  // @ts-ignore
  import("@fontsource/ubuntu/400.css");
  // @ts-ignore
  import("@fontsource/ubuntu/500.css");
  // @ts-ignore - CSS-only imports, no type declarations needed
  import("@fontsource/nunito");
  // @ts-ignore
  import("@fontsource/nunito/700.css");
  // @ts-ignore
  import("@fontsource/nunito/400.css");
  // @ts-ignore
  import("@fontsource/nunito/500.css");
};

if ("requestIdleCallback" in window) {
  requestIdleCallback(loadSecondaryFonts);
} else {
  setTimeout(loadSecondaryFonts, 1000);
}

import { ToastContainer } from "~/components/toast";

import { routes } from "~/router/routes";

import { lazy } from "react";

// Lazy-load devtools — they add ~70kB to the bundle and are only used in dev.
const ReactQueryDevtools = lazy(() =>
  import("@tanstack/react-query-devtools").then((m) => ({
    default: m.ReactQueryDevtools,
  }))
);

import "~/translations/i18n";

import { analyticsSetup, getCreateRouter } from "./helpers/analytics";
import { initDatadogRum } from "./helpers/datadog";
import { intercomKey } from "./helpers/environment";
import { gtmPushEcommerce } from "./helpers/gtag";
import { logger } from "./helpers/logger";
import { ContextWrapper } from "./contexts";

import SuspenseFallback from "~/components/layout/SuspenseFallback";
import { GoogleTagManager } from "./components/google-tag-manager";
import { setupRedditPixel } from "./helpers/setupRedditPixel";
import { reportWebVitals } from "./helpers/webVitals";

const createRouter = getCreateRouter();
const router = createRouter(routes);

// Fire GA4 page_view on every route change for the Axon Pixel (via GTM).
// Initial load is covered by the first subscribe callback.
gtmPushEcommerce("page_view");
let lastTrackedPath = window.location.pathname + window.location.search;
router.subscribe((state) => {
  if (state.navigation.state !== "idle") return;
  const path = state.location.pathname + state.location.search;
  if (path === lastTrackedPath) return;
  lastTrackedPath = path;
  gtmPushEcommerce("page_view");
});

const isProduction = import.meta.env.PROD;

const initNonCriticalAnalytics = () => {
  try {
    setupRedditPixel();
    analyticsSetup();
    initDatadogRum();
    reportWebVitals();
  } catch (error) {
    logger.error("Non-critical analytics initialization failed", error);
  }
};

const win = window as any;

if (typeof win.requestIdleCallback === "function") {
  win.requestIdleCallback(initNonCriticalAnalytics);
} else {
  window.addEventListener("load", initNonCriticalAnalytics);
}

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <IntercomProvider
      appId={intercomKey}
      autoBoot={false}
      apiBase={
        intercomKey
          ? `https://${intercomKey}.intercom-messenger.com`
          : undefined
      }
    >
      <ContextWrapper>
        <ThemeProvider theme={theme}>
          {isProduction ? <GoogleTagManager /> : null}

          <GlobalStyle />
          <Suspense fallback={<SuspenseFallback />}>
            <RouterProvider router={router} />
          </Suspense>
          <ToastContainer />
          {!isProduction && <ReactQueryDevtools initialIsOpen={false} />}
        </ThemeProvider>
      </ContextWrapper>
    </IntercomProvider>
  </React.StrictMode>
);
