import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";

// Capture UTM params immediately at boot — before React mounts
import { captureUtmParams } from "./lib/utm-persistence";
captureUtmParams();

// Detect if this is a funnel route (lightweight check — no heavy imports)
const isFunnelRoute = /^\/(quiz|oferta|f[2-5]\/|vd|venda|ab\/|bio)/.test(window.location.pathname) || window.location.pathname === "/";

// Initialize global error capture — lazy for funnel routes
if (!isFunnelRoute) {
  // Sentry primeiro (captura erros de boot do app). Só ativa em build de
  // produção; em dev fica inerte. Não carregado em rotas de funil pra
  // manter as páginas de anúncio leves.
  import("./lib/sentry").then(({ initSentry }) => initSentry());
  import("./lib/global-error-handler").then(({ initGlobalErrorHandler }) =>
    initGlobalErrorHandler()
  );
} else {
  // Minimal error capture for funnels (no Supabase dependency)
  window.addEventListener("unhandledrejection", (e) => {
    console.warn("[Funnel] Unhandled rejection:", e.reason?.message || e.reason);
  });
}

// Detect iOS mobile (iPhone/iPod touch) and add class for CSS-based tracking override
const isIOSMobile = /iPhone|iPod/.test(navigator.userAgent) && !(window as any).MSStream;
if (isIOSMobile) {
  document.documentElement.classList.add("ios-mobile");
}

// Auto-detect PWA standalone mode at boot and mark as installed
const INSTALLED_KEY = "pwa-installed-confirmed";
const isStandalone =
  window.matchMedia("(display-mode: standalone)").matches ||
  (window.navigator as any).standalone === true;

if (isStandalone && localStorage.getItem(INSTALLED_KEY) !== "true") {
  localStorage.setItem(INSTALLED_KEY, "true");
  import("./lib/track-event").then(({ trackEvent }) => {
    trackEvent("pwa_installed", { method: "standalone_boot" });
  });
}

// Remove splash screen with fade-out once React mounts
const removeSplash = () => {
  const splash = document.getElementById("splash-screen");
  if (splash) {
    splash.style.opacity = "0";
    splash.addEventListener("transitionend", () => splash.remove(), { once: true });
    setTimeout(() => splash.remove(), 600);
  }
  document.body.style.background = "";
  document.documentElement.style.background = "";
};

// For funnel routes, skip error boundary; for app routes, use the full one
function PassThrough({ children }: { children: React.ReactNode }) {
  return <>{children}</>;
}

const RootWrapper: React.ComponentType<{ children: React.ReactNode }> = isFunnelRoute
  ? PassThrough
  : React.lazy(() =>
      import("./components/GlobalErrorBoundary").then((m) => ({
        default: m.GlobalErrorBoundary as unknown as React.ComponentType<{ children: React.ReactNode }>,
      }))
    );
createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <React.Suspense fallback={null}>
      <RootWrapper>
        <App />
      </RootWrapper>
    </React.Suspense>
  </React.StrictMode>
);

// Run after React's first paint
requestAnimationFrame(() => {
  requestAnimationFrame(removeSplash);
});

// Warm Library images during idle time — only for app routes
if (!isFunnelRoute) {
  const idleWarm = () =>
    import("./lib/library-image-warmup").then(({ warmLibraryImages }) =>
      warmLibraryImages()
    );
  if ("requestIdleCallback" in window) {
    (window as any).requestIdleCallback(idleWarm, { timeout: 3000 });
  } else {
    setTimeout(idleWarm, 2000);
  }
}

// Defer UTMify pixel — injected after page load to avoid blocking FCP/main thread
const injectUtmifyPixel = () => {
  (window as any).pixelId = "69b025e449f0cdcba2bcf5cf";
  const s = document.createElement("script");
  s.async = true;
  s.defer = true;
  s.src = "https://cdn.utmify.com.br/scripts/pixel/pixel.js";
  document.head.appendChild(s);
};

// UTMify é tracking de funil de ads — não faz sentido carregar dentro do app
// nativo (usuária já comprou, não está no funil). Pula em Capacitor (localhost).
const isNativeApp =
  window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
if (!isNativeApp) {
  window.addEventListener("load", () => {
    if ("requestIdleCallback" in window) {
      (window as any).requestIdleCallback(injectUtmifyPixel, { timeout: 4000 });
    } else {
      setTimeout(injectUtmifyPixel, 2500);
    }
  });
}
