import { createRoot } from "react-dom/client";
import { lazy, Suspense } from "react";
import { SkeletonCard, SkeletonRow } from "@/components/ui/skeleton";
import { LanguageProvider } from "@/contexts/LanguageContext";
import { ErrorBoundary } from "@/components/shared/ErrorBoundary";
import { initErrorBuffer } from "@/lib/error-buffer";
import { installAutoSync as installOfflineQueueAutoSync } from "@/lib/offlineQueue";
import { Capacitor } from "@capacitor/core";
// Paint the shared placeholders before loading the application dependency graph.
const App = lazy(() => import("./App.tsx"));
import { handleChunkError } from "@/lib/chunkReload";
import { installVersionCheck } from "@/lib/versionCheck";
import "./index.css";

// Hard-disable native browser leave/reload prompts. Draft protection is handled
// inside the app; native beforeunload prompts have repeatedly caused data loss
// by blocking editor/preview refreshes. This also neutralizes handlers attached
// indirectly by old code paths or dependencies after boot.
(() => {
  if (typeof window === "undefined") return;

  const blockedUnloadEvents = new Set(["beforeunload"]);
  const originalAddEventListener = window.addEventListener.bind(window);
  const originalRemoveEventListener = window.removeEventListener.bind(window);

  window.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {
    if (blockedUnloadEvents.has(type)) return;
    return originalAddEventListener(type, listener, options);
  }) as typeof window.addEventListener;

  window.removeEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {
    if (blockedUnloadEvents.has(type)) return;
    return originalRemoveEventListener(type, listener, options);
  }) as typeof window.removeEventListener;

  Object.defineProperty(window, "onbeforeunload", {
    configurable: true,
    enumerable: true,
    get: () => null,
    set: () => undefined,
  });
})();

initErrorBuffer();
// Wire the unified offline queue to network/visibility events so deferred
// mutations replay automatically once connectivity returns. Safe no-op when
// `navigator` is missing (SSR) or already installed.
installOfflineQueueAutoSync();

// After a publish, an open tab may request a chunk that no longer exists.
// handleChunkError reloads once (never with unsaved editor changes) and
// otherwise shows a "New version available – Reload" banner; it never loops.
window.addEventListener("error", (e) => handleChunkError(e.message || ""));
window.addEventListener("unhandledrejection", (e) => {
  const reason = e.reason;
  handleChunkError(typeof reason === "string" ? reason : reason?.message || "");
});
window.addEventListener("vite:preloadError", (e) => {
  e.preventDefault();
  handleChunkError((e as any).payload?.message || "Failed to fetch dynamically imported module");
});

// Deployment pinning (__dpl cookie) can keep a tab on an old build: poll /version.json
// every 5 min and on focus; only a banner, never a forced reload.
if (import.meta.env.PROD) installVersionCheck(__BUILD_VERSION__);

// Restored-from-bfcache: do not force a reload — editor state must survive.
window.addEventListener("pageshow", () => {});

// Native shell (Capacitor): the packaged app is the Supplier Portal, so a cold
// start on "/" must land on the supplier login instead of the internal ERP
// landing page. Deep links / restored routes are left untouched.
(() => {
  try {
    if (!Capacitor.isNativePlatform()) return;
    const path = window.location.pathname;
    if (path === "/" || path === "/index.html") {
      window.history.replaceState(null, "", "/supplier/login");
    }
  } catch {
    /* non-native web build — nothing to do */
  }
})();

const rootElement = document.getElementById("root");
if (rootElement) createRoot(rootElement).render(
  <LanguageProvider>
    <ErrorBoundary>
      <Suspense fallback={<div className="min-h-screen bg-background p-4 sm:p-6 space-y-4" aria-busy="true" data-startup-skeleton><SkeletonCard /><div className="rounded-lg border bg-card">{Array.from({ length: 6 }, (_, i) => <SkeletonRow key={i} />)}</div></div>}><App /></Suspense>
    </ErrorBoundary>
  </LanguageProvider>
);

// Register service worker for PWA install support.
// IMPORTANT: never register inside the Lovable editor iframe or on preview
// hosts — service workers cache aggressively and break live preview updates.
(() => {
  if (!("serviceWorker" in navigator)) return;

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

  const host = window.location.hostname;
  const isPreviewHost =
    host.includes("id-preview--") ||
    host.includes("lovableproject.com") ||
    host === "localhost" ||
    host === "127.0.0.1";

  if (isInIframe || isPreviewHost) {
    // Proactively unregister any SW that may have been installed previously
    // in this context so stale caches don't shadow new builds.
    navigator.serviceWorker.getRegistrations?.().then((regs) => {
      regs.forEach((r) => r.unregister().catch(() => undefined));
    }).catch(() => undefined);
    return;
  }

  window.addEventListener("load", () => {
    navigator.serviceWorker
      .register("/sw.js", { scope: "/" })
      .catch(() => {
        // Silent — app still works without SW
      });
  });
})();

