import { createRoot } from "react-dom/client";
import * as Sentry from "@sentry/react";
import App from "./App.tsx";
import "./index.css";
import "./i18n";

// Global safety net: catch any unhandled kid SESSION_EXPIRED errors and
// bounce to the PIN screen instead of crashing into the error boundary.
if (typeof window !== "undefined") {
  window.addEventListener("unhandledrejection", (ev) => {
    const msg = String((ev.reason as any)?.message || ev.reason || "");
    if (
      msg.includes("SESSION_EXPIRED") ||
      (msg.includes("401") && msg.toLowerCase().includes("kid-"))
    ) {
      ev.preventDefault();
      try { localStorage.removeItem("kid-session-token"); } catch {}
      try { localStorage.removeItem("kid_session_token"); } catch {}
      if (!window.location.pathname.startsWith("/kid-login")) {
        window.location.replace("/kid-login");
      }
    }
  });
}

Sentry.init({
  dsn: import.meta.env.VITE_SENTRY_DSN,
  environment: import.meta.env.MODE,
  enabled:
    !!import.meta.env.VITE_SENTRY_DSN &&
    !import.meta.env.VITE_SENTRY_DSN.includes("placeholder"),
  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration({
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],
  tracesSampleRate: 0.2,
  replaysSessionSampleRate: 0.05,
  replaysOnErrorSampleRate: 1.0,
});

const hardReset = async () => {
  try {
    if ("serviceWorker" in navigator) {
      const regs = await navigator.serviceWorker.getRegistrations();
      await Promise.all(regs.map((r) => r.unregister()));
    }
    if ("caches" in window) {
      const keys = await caches.keys();
      await Promise.all(keys.map((k) => caches.delete(k)));
    }
    try { localStorage.clear(); } catch {}
    try { sessionStorage.clear(); } catch {}
  } finally {
    window.location.replace("/auth");
  }
};

createRoot(document.getElementById("root")!).render(
  <Sentry.ErrorBoundary
    fallback={({ error, resetError }) => {
      const isAr = (navigator.language || "").startsWith("ar");
      const msg =
        error instanceof Error
          ? error.message
          : typeof error === "string"
          ? error
          : "Unknown error";
      return (
        <div className="min-h-screen flex items-center justify-center bg-background p-4" dir={isAr ? "rtl" : "ltr"}>
          <div className="max-w-md w-full text-center space-y-4">
            <h1 className="text-2xl font-semibold text-foreground">
              {isAr ? "حدث خطأ ما" : "Something went wrong"}
            </h1>
            <p className="text-muted-foreground text-sm">
              {isAr
                ? "إذا استمرت المشكلة، اضغط على \"مسح البيانات وإعادة المحاولة\"."
                : "If this keeps happening, tap \"Clear data & retry\"."}
            </p>
            <details className="text-xs text-left bg-muted rounded-lg p-3 break-all">
              <summary className="cursor-pointer text-muted-foreground">
                {isAr ? "تفاصيل تقنية" : "Technical details"}
              </summary>
              <pre className="mt-2 whitespace-pre-wrap">{msg}</pre>
            </details>
            <div className="flex flex-col gap-2">
              <button
                onClick={() => { resetError(); window.location.reload(); }}
                className="px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors"
              >
                {isAr ? "تحديث الصفحة" : "Refresh page"}
              </button>
              <button
                onClick={hardReset}
                className="px-4 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/80 transition-colors"
              >
                {isAr ? "مسح البيانات وإعادة المحاولة" : "Clear data & retry"}
              </button>
            </div>
          </div>
        </div>
      );
    }}
    showDialog={false}
  >
    <App />
  </Sentry.ErrorBoundary>
);

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then((reg) => console.log('SW registered:', reg.scope))
      .catch((err) => console.warn('SW registration failed:', err));
  });
}
