import React from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import * as Sentry from '@sentry/react';
import { useTranslation } from 'react-i18next';
import App from './App.tsx';
import './index.css';
import './styles/elevation.css';
import { errorService, ErrorCategory, ErrorLevel } from '@/services/errorService';
import { analyticsInit } from '@/lib/analytics';
import './i18n'; // Initialize i18n

// Initialize analytics first
analyticsInit().catch(() => {/* avoid breaking prod if PostHog fails */});

// Initialize Sentry with proper configuration
Sentry.init({
  dsn: import.meta.env.VITE_SENTRY_DSN,
  release: import.meta.env.VITE_APP_VERSION || '1.0.0',
  environment: import.meta.env.MODE,
  integrations: [
    Sentry.browserTracingIntegration({
      // Removed the problematic reactRouterV6Instrumentation
    }),
    Sentry.replayIntegration({
      // Only capture replays on errors to save bandwidth
      maskAllText: true,
      maskAllInputs: true,
      blockAllMedia: true,
    }),
  ],
  // Performance Monitoring
  tracesSampleRate: import.meta.env.MODE === 'production' ? 0.2 : 1.0,
  
  // Session Replay
  replaysSessionSampleRate: 0, // Keep off by default
  replaysOnErrorSampleRate: 1.0, // Capture replay only on error
  
  beforeSend(event) {
    // Security: scrub sensitive data
    if (event.request?.headers) {
      delete event.request.headers;
    }
    
    // Don't send events if DSN is not configured
    if (!import.meta.env.VITE_SENTRY_DSN) {
      return null;
    }
    
    return event;
  },
});

// Handle stale chunk errors after deployments: auto-reload once
window.addEventListener('error', (event) => {
  const msg = event.message || '';
  if (
    (msg.includes('Failed to fetch dynamically imported module') ||
     msg.includes('Loading chunk') ||
     msg.includes('Loading CSS chunk') ||
     (event.filename && event.filename.includes('/assets/') && msg.includes('MIME type')))
    && !sessionStorage.getItem('chunk_reload')
  ) {
    sessionStorage.setItem('chunk_reload', '1');
    window.location.reload();
    return;
  }
});

// Clear the chunk reload flag on successful load
sessionStorage.removeItem('chunk_reload');

// Enhanced global error handling with Sentry correlation
window.addEventListener('error', (event) => {
  const correlationId = `error_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  
  Sentry.withScope((scope) => {
    scope.setTag('errorType', 'globalError');
    scope.setTag('correlationId', correlationId);
    scope.setContext('errorEvent', {
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
    });
    Sentry.captureException(event.error || new Error(event.message));
  });

  errorService.logError(event.error || event.message, ErrorLevel.ERROR, {
    component: 'global',
    category: ErrorCategory.SYSTEM,
    action: 'window_error',
    metadata: {
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
      source: event.filename?.split('/').pop() || 'unknown',
      correlationId
    }
  });
});

window.addEventListener('unhandledrejection', (event) => {
  // Handle stale chunk errors from dynamic imports (React.lazy)
  const reason = String(event.reason || '');
  if (
    (reason.includes('Failed to fetch dynamically imported module') ||
     reason.includes('Loading chunk') ||
     reason.includes('error loading dynamically imported module') ||
     reason.includes('Unable to preload CSS'))
    && !sessionStorage.getItem('chunk_reload')
  ) {
    sessionStorage.setItem('chunk_reload', '1');
    window.location.reload();
    return;
  }

  const correlationId = `rejection_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

  Sentry.withScope((scope) => {
    scope.setTag('errorType', 'unhandledRejection');
    scope.setTag('correlationId', correlationId);
    scope.setContext('rejectionEvent', {
      reason: String(event.reason).substring(0, 500)
    });
    Sentry.captureException(
      event.reason instanceof Error ? event.reason : new Error(String(event.reason))
    );
  });

  errorService.logError(
    event.reason instanceof Error ? event.reason : new Error(String(event.reason)),
    ErrorLevel.ERROR,
    {
      component: 'global',
      category: ErrorCategory.SYSTEM,
      action: 'unhandled_promise_rejection',
      metadata: {
        reason: String(event.reason).substring(0, 500),
        correlationId
      }
    }
  );
});

// Enhanced navigation error tracking
window.addEventListener('beforeunload', () => {
  // Flush any pending Sentry events
  Sentry.flush(2000);
  
  // Log any pending errors before page unload
  errorService.logEvent('Page unload', {
    component: 'global',
    action: 'page_unload',
    metadata: {
      url: window.location.href,
      userAgent: navigator.userAgent.substring(0, 100)
    }
  });
});

const rootElement = document.getElementById("root");
if (!rootElement) {
  const error = new Error('Root element not found');
  Sentry.captureException(error);
  throw error;
}

// DEBUG: Add immediate loading indicator
rootElement.innerHTML = '<div style="display: flex; justify-content: center; align-items: center; height: 100vh; font-family: Arial; font-size: 18px; background: #f0f0f0;">🔄 Loading Ouizami App...</div>';
console.log('Main.tsx is executing - React mounting now');

// Error fallback component that can use translations
const ErrorFallback = ({ error, resetError }: { error: any; resetError: () => void }) => {
  const { t } = useTranslation('common');
  
  return (
    <div className="min-h-screen flex items-center justify-center p-4 bg-background">
      <div className="max-w-md w-full text-center">
        <h2 className="text-xl font-semibold mb-4 text-destructive">
          {t('unexpectedError')}
        </h2>
        <p className="text-muted-foreground mb-4">
          {t('technicalTeamNotified')}
        </p>
        <button
          onClick={resetError}
          className="px-4 py-2 bg-primary text-primary-foreground rounded hover:bg-primary/90"
        >
          {t('retry')}
        </button>
      </div>
    </div>
  );
};

// Wrap app with Sentry Error Boundary
const AppWithErrorBoundary = Sentry.withErrorBoundary(App, {
  fallback: ErrorFallback,
  beforeCapture: (scope) => {
    scope.setTag('errorBoundary', 'root');
    scope.setLevel('fatal');
  },
});

createRoot(rootElement).render(
  <StrictMode>
    <AppWithErrorBoundary />
  </StrictMode>
);
