import { createRoot } from "react-dom/client";
import * as Sentry from "@sentry/react";
import App from "./App";
import "./index.css";
import "./lib/performance"; // Initialize performance monitoring
import "./lib/security"; // Initialize security measures
import {
  SENTRY_IAB_DENY_URLS,
  SENTRY_IAB_IGNORE_ERRORS,
  shouldDropThirdPartySentryEvent,
} from "./lib/sentryClientFilters";

// Initialize Sentry only in production for error tracking
const isProduction = import.meta.env.PROD;
if (isProduction && import.meta.env.VITE_SENTRY_DSN) {
  Sentry.init({
    dsn: import.meta.env.VITE_SENTRY_DSN,
    environment: "production",
    release: import.meta.env.VITE_SENTRY_RELEASE || undefined,
    tracesSampleRate: 0.2,
    integrations: [
      Sentry.browserTracingIntegration({
        // Engine.IO long-polling holds GET /socket.io/ open for pingInterval
        // (25s, server/websocket.ts). Sentry's Consecutive HTTP detector reads
        // those sequential held-open polls as serialized slow requests.
        shouldCreateSpanForRequest: (url) => !url.includes("/socket.io/"),
      }),
      Sentry.replayIntegration({
        maskAllText: true,
        blockAllMedia: false,
      }),
    ],
    replaysSessionSampleRate: 0.1,
    replaysOnErrorSampleRate: 1.0,
    ignoreErrors: [
      'Object Not Found Matching Id',
      'Non-Error promise rejection captured',
      'ResizeObserver loop',
      'antifingerprint',
      'Failed to fetch dynamically imported module',
      'error loading dynamically imported module',
      'Importing a module script failed',
      'Loading chunk',
      'Loading CSS chunk',
      ...SENTRY_IAB_IGNORE_ERRORS,
    ],
    denyUrls: SENTRY_IAB_DENY_URLS,
    beforeSend(event) {
      if (shouldDropThirdPartySentryEvent(event)) {
        return null;
      }
      const msg = event.message || event.exception?.values?.[0]?.value || '';
      if (msg.includes('Object Not Found Matching Id') || msg.includes('MethodName:update')) {
        return null;
      }
      if (
        msg.includes('Failed to fetch dynamically imported module') ||
        msg.includes('error loading dynamically imported module') ||
        msg.includes('dynamically imported module') ||
        msg.includes('Importing a module script failed') ||
        msg.includes('Loading chunk') ||
        msg.includes('Loading CSS chunk')
      ) {
        return null;
      }
      return event;
    },
  });
}

// Rate-limited reload for stale chunk errors: at most one reload per 30 seconds.
// Using a timestamp avoids the permanent-boolean bug where a previous deployment's
// guard flag would block auto-reload for all future deployments.
function safeChunkReload() {
  const KEY = 'chunk_reload_at';
  const last = parseInt(sessionStorage.getItem(KEY) || '0', 10);
  if (Date.now() - last > 30_000) {
    sessionStorage.setItem(KEY, String(Date.now()));
    window.location.reload();
  }
}

function isStaleChunkError(msg: string) {
  return (
    msg.includes('Failed to fetch dynamically imported module') ||
    msg.includes('error loading dynamically imported module') ||
    msg.includes('dynamically imported module') ||
    msg.includes('Loading chunk') ||
    msg.includes('Loading CSS chunk') ||
    msg.includes('Importing a module script failed')
  );
}

// Vite fires this event when a <link rel="modulepreload"> fails
window.addEventListener('vite:preloadError', () => {
  safeChunkReload();
});

// Global error handlers
window.addEventListener('unhandledrejection', (event) => {
  const reason = event.reason;
  const reasonStr = typeof reason === 'string' ? reason : reason?.message || '';

  if (reasonStr.includes('Object Not Found Matching Id') || reasonStr.includes('MethodName:update')) {
    event.preventDefault();
    return;
  }

  if (isStaleChunkError(reasonStr)) {
    event.preventDefault();
    safeChunkReload();
    return;
  }

  if (
    reasonStr === 'Failed to fetch' ||
    reasonStr.includes('fetch') ||
    reasonStr.includes('NetworkError')
  ) {
    event.preventDefault();
    return;
  }

  event.preventDefault();
});

window.addEventListener('error', (event) => {
  const msg = event.message || event.error?.message || '';

  if (isStaleChunkError(msg)) {
    event.preventDefault();
    safeChunkReload();
    return;
  }
});

createRoot(document.getElementById("root")!).render(<App />);
