import "./index.css";
import { applyThemeMode, getThemeMode } from "@/lib/themeMode";
// Apply persisted light/dark mode before first paint
applyThemeMode(getThemeMode());
// Suppress error toasts when the user cancels a destructive confirm prompt
import { toast } from "sonner";
const _origToastError = toast.error;
(toast as any).error = (msg: any, ...rest: any[]) => {
  const text = typeof msg === "string" ? msg : msg?.message || "";
  if (text === "cancelled") return;
  return (_origToastError as any)(msg, ...rest);
};
import {
  getCanonicalInstallUrl,
  initInstallPromptCapture,
  isPreviewInstallHost,
  shouldRedirectToCanonicalInstallHost,
} from "@/lib/pwaInstall";

const PREVIEW_SW_RESET_KEY = "lovable-preview-sw-reset";
const LEGACY_APP_SW_RESET_KEY = "legacy-app-sw-reset";
const PASSWORD_RECOVERY_LOCK_KEY = "password-recovery-route-lock-until";

const isInIframe = (() => {
  try {
    return window.self !== window.top;
  } catch {
    return true;
  }
})();

const hostname = window.location.hostname;
const isPreviewHost = isPreviewInstallHost(hostname);
const shouldRedirectToCanonicalHost = shouldRedirectToCanonicalInstallHost(hostname);

function isAuthLinkRoute() {
  const authPaths = new Set(["/reset-password", "/verify"]);
  if (authPaths.has(window.location.pathname)) return true;

  const search = new URLSearchParams(window.location.search);
  const hashText = window.location.hash.startsWith("#") ? window.location.hash.slice(1) : window.location.hash;
  const hash = new URLSearchParams(hashText);
  return ["access_token", "refresh_token", "code", "token_hash", "error", "error_description"].some(
    (key) => search.has(key) || hash.has(key)
  );
}

function getAuthLinkType() {
  const search = new URLSearchParams(window.location.search);
  const hashText = window.location.hash.startsWith("#") ? window.location.hash.slice(1) : window.location.hash;
  const hash = new URLSearchParams(hashText);
  const explicitType = search.get("type") || hash.get("type");
  if (explicitType) return explicitType;

  const pathLooksLikeRecovery = window.location.pathname === "/reset-password";
  if (pathLooksLikeRecovery && (search.has("token_hash") || search.has("code") || hash.has("access_token"))) {
    return "recovery";
  }
  return null;
}

function normalizeRecoveryLinkRoute() {
  if (getAuthLinkType() !== "recovery") return;
  window.sessionStorage.setItem(PASSWORD_RECOVERY_LOCK_KEY, String(Date.now() + 15 * 60 * 1000));
  if (window.location.pathname === "/reset-password") return;

  window.history.replaceState(
    null,
    "",
    `/reset-password${window.location.search}${window.location.hash}`
  );
}

function disableTransientHostInstallability() {
  document.querySelectorAll('link[rel="manifest"]').forEach((manifestLink) => manifestLink.remove());
}

async function clearPreviewServiceWorkers() {
  if (!("serviceWorker" in navigator)) return false;

  const registrations = await navigator.serviceWorker.getRegistrations();
  const hadRegistrations = registrations.length > 0;
  await Promise.all(registrations.map((registration) => registration.unregister()));

  let hadCaches = false;
  if ("caches" in window) {
    const cacheKeys = await window.caches.keys();
    hadCaches = cacheKeys.length > 0;
    await Promise.all(cacheKeys.map((key) => window.caches.delete(key)));
  }

  return hadRegistrations || hadCaches;
}

async function clearLegacyAppServiceWorker() {
  if (!("serviceWorker" in navigator)) return false;

  const registrations = await navigator.serviceWorker.getRegistrations();
  const legacyRegistrations = registrations.filter((registration) => {
    const scriptUrl = registration.active?.scriptURL || registration.waiting?.scriptURL || registration.installing?.scriptURL || "";
    return scriptUrl.endsWith("/sw.js");
  });

  await Promise.all(legacyRegistrations.map((registration) => registration.unregister()));

  if (legacyRegistrations.length > 0 && "caches" in window) {
    const cacheKeys = await window.caches.keys();
    await Promise.all(cacheKeys.map((key) => window.caches.delete(key)));
  }

  return legacyRegistrations.length > 0;
}

const SPLASH_START = Date.now();
(window as any).__splashStart = SPLASH_START;
const SPLASH_MIN_MS = 1400; // let the logo animation (1.2s) finish gracefully

async function bootstrap() {
  normalizeRecoveryLinkRoute();
  const isProcessingAuthLink = isAuthLinkRoute();

  if (!isProcessingAuthLink && !isInIframe && shouldRedirectToCanonicalHost) {
    window.location.replace(getCanonicalInstallUrl(window.location));
    return;
  }

  if (isPreviewHost || isInIframe) {
    disableTransientHostInstallability();
  }

  initInstallPromptCapture();

  if (isPreviewHost || isInIframe) {
    const cleared = await clearPreviewServiceWorkers();
    const alreadyReloaded = window.sessionStorage.getItem(PREVIEW_SW_RESET_KEY) === "1";

    if (cleared && !alreadyReloaded && !isProcessingAuthLink) {
      window.sessionStorage.setItem(PREVIEW_SW_RESET_KEY, "1");
      window.location.reload();
      return;
    }
  } else {
    window.sessionStorage.removeItem(PREVIEW_SW_RESET_KEY);

    const clearedLegacyWorker = await clearLegacyAppServiceWorker();
    const alreadyReloaded = window.sessionStorage.getItem(LEGACY_APP_SW_RESET_KEY) === "1";

    if (clearedLegacyWorker && !alreadyReloaded && !isProcessingAuthLink) {
      window.sessionStorage.setItem(LEGACY_APP_SW_RESET_KEY, "1");
      window.location.reload();
      return;
    }
  }

  // Init native Capacitor plugins (no-op on web)
  const { initNativeApp } = await import("./hooks/useNativeApp");
  void initNativeApp();

  const [{ createRoot }, { default: App }] = await Promise.all([
    import("react-dom/client"),
    import("./App.tsx"),
  ]);

  const rootElement = document.getElementById("root");
  if (!rootElement) throw new Error("Root element not found");

  createRoot(rootElement).render(<App />);

  // Pages call dismissSplash() when their data is ready.
  // Safety net: if no page dismisses within 6s, force-dismiss so the user
  // never stares at a permanent splash.
  const { dismissSplash } = await import("./lib/splashDismiss");
  if (window.location.pathname === "/" || window.location.pathname === "/index" || window.location.pathname === "/index.html") {
    setTimeout(dismissSplash, 1800);
  } else {
    setTimeout(dismissSplash, 6000);
  }
}

void bootstrap();

