import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import "./i18n/config"; // Инициализация i18n
import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient } from "./lib/queryClient";

// Глобальная защита от ошибок загрузки чанков
import { initChunkErrorRecovery } from "./lib/chunkErrorRecovery";

// Инициализируем обработку ошибок чанков
initChunkErrorRecovery();

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

const isPreviewHost = (() => {
  const h = window.location.hostname;
  return (
    h.startsWith("id-preview--") ||
    h.startsWith("preview--") ||
    h.endsWith(".lovableproject.com") ||
    h.endsWith(".lovableproject-dev.com") ||
    h.endsWith(".lovable.app") ||
    h === "localhost" ||
    h === "127.0.0.1"
  );
})();

// В dev/preview/iframe полностью снимаем SW и чистим Cache Storage,
// чтобы старые PWA-кэши и SW не вызывали лишние перезагрузки.
const isDev = import.meta.env.DEV;

if (isDev || isPreviewHost || isInIframe) {
  // Снимаем старые SW регистрации один раз за сессию вкладки,
  // чтобы повторные mount'ы не вызывали лишние unregister/reload циклы.
  try {
    if (!sessionStorage.getItem("__sw_cleanup_done")) {
      sessionStorage.setItem("__sw_cleanup_done", "1");
      navigator.serviceWorker?.getRegistrations().then((registrations) => {
        registrations.forEach((r) => r.unregister());
      });
      // Чистим Cache Storage от старых Workbox/PWA кэшей в dev-окружении.
      if (typeof caches !== "undefined") {
        caches.keys().then((names) => {
          names
            .filter((n) =>
              /(^|-)precache-v\d+-|(^|-)runtime-|html-cache|google-fonts-cache|gstatic-fonts-cache|workbox-/.test(
                n,
              ),
            )
            .forEach((n) => caches.delete(n));
        });
      }

      // Чистим PWA/Workbox cookies (vite-pwa, workbox-*) — только PWA-ключи,
      // не трогая Supabase auth и пользовательские настройки.
      const pwaCookieRe = /^(workbox|vite-pwa|pwa|sw)[-_]/i;
      document.cookie.split(";").forEach((c) => {
        const name = c.split("=")[0]?.trim();
        if (name && pwaCookieRe.test(name)) {
          document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
          document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${window.location.hostname}`;
        }
      });

      // Чистим PWA-ключи в localStorage/sessionStorage (не Supabase / app_*).
      const pwaStorageRe = /^(workbox|vite-pwa|pwa|sw|__pwa)/i;
      try {
        for (let i = localStorage.length - 1; i >= 0; i--) {
          const k = localStorage.key(i);
          if (k && pwaStorageRe.test(k)) localStorage.removeItem(k);
        }
        for (let i = sessionStorage.length - 1; i >= 0; i--) {
          const k = sessionStorage.key(i);
          if (k && k !== "__sw_cleanup_done" && pwaStorageRe.test(k)) {
            sessionStorage.removeItem(k);
          }
        }
      } catch {
        // ignore storage errors (private mode и т.п.)
      }

      // Удаляем IndexedDB базы, созданные Workbox (workbox-expiration и пр.).
      if (typeof indexedDB !== "undefined" && "databases" in indexedDB) {
        (indexedDB as any).databases().then((dbs: Array<{ name?: string }>) => {
          dbs.forEach((db) => {
            if (db.name && /^workbox-|^vite-pwa|^pwa-/i.test(db.name)) {
              indexedDB.deleteDatabase(db.name);
            }
          });
        }).catch(() => {});
      }
    }
  } catch {
    navigator.serviceWorker?.getRegistrations().then((registrations) => {
      registrations.forEach((r) => r.unregister());
    });
  }
}

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </StrictMode>,
);
