import { StrictMode, Component, ErrorInfo, ReactNode, lazy, Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import './styles/global.css';

// Lazy load heavy providers to reduce initial JS parse/execute time
const ThemeProvider = lazy(() => import('./contexts/ThemeContext').then(m => ({ default: m.ThemeProvider })));
const AuthProvider = lazy(() => import('./contexts/AuthContext').then(m => ({ default: m.AuthProvider })));
const CompanyProvider = lazy(() => import('./contexts/CompanyContext').then(m => ({ default: m.CompanyProvider })));
const App = lazy(() => import('./App.tsx'));

import { setupNavigatorLockHandler } from './utils/setupNavigatorLockHandler';
import { registerServiceWorker } from './utils/serviceWorker';

// Performance mark: App start
if (typeof performance !== 'undefined' && performance.mark) {
  performance.mark('app-start');
}

// Lightweight fallback while heavy components load
const InitialFallback = () => (
  <div style={{
    minHeight: '100vh',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    background: '#f9fafb',
    fontFamily: 'system-ui, -apple-system, sans-serif'
  }}>
    <h1 style={{ fontSize: '24px', fontWeight: 600, color: '#1f2937', marginBottom: '16px' }}>
      Tallybooks
    </h1>
    <div style={{
      width: '40px',
      height: '40px',
      border: '3px solid #e5e7eb',
      borderTopColor: '#3b82f6',
      borderRadius: '50%',
      animation: 'spin 1s linear infinite'
    }} />
    <p style={{ fontSize: '14px', color: '#6b7280', marginTop: '12px' }}>
      Initializing...
    </p>
    <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
  </div>
);

class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean; error: Error | null }> {
  constructor(props: { children: ReactNode }) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("Uncaught error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 20, color: 'red' }}>
          <h1>Something went wrong.</h1>
          <pre>{this.state.error?.toString()}</pre>
        </div>
      );
    }

    return this.props.children;
  }
}

// Mount the app
const rootElement = document.getElementById('root');

if (rootElement) {
  const root = createRoot(rootElement);
  
  // Performance mark: Before render
  if (typeof performance !== 'undefined' && performance.mark) {
    performance.mark('before-render');
  }
  
  // Progressive hydration: Load shell immediately, defer heavy providers
  root.render(
    <StrictMode>
      <ErrorBoundary>
        <Suspense fallback={<InitialFallback />}>
          <AuthProvider>
            <Suspense fallback={<InitialFallback />}>
              <CompanyProvider>
                <Suspense fallback={<InitialFallback />}>
                  <ThemeProvider>
                    <Suspense fallback={<InitialFallback />}>
                      <App />
                    </Suspense>
                  </ThemeProvider>
                </Suspense>
              </CompanyProvider>
            </Suspense>
          </AuthProvider>
        </Suspense>
      </ErrorBoundary>
    </StrictMode>
  );
  
  // Performance mark: After render
  if (typeof performance !== 'undefined' && performance.mark) {
    performance.mark('after-render');
    performance.measure('app-mount', 'app-start', 'after-render');
    
    // Log performance metrics in development
    if (import.meta.env.DEV) {
      setTimeout(() => {
        const measures = performance.getEntriesByName('app-mount');
        if (measures.length > 0) {
          console.log(`⚡ App mounted in ${measures[0].duration.toFixed(2)}ms`);
        }
      }, 100);
    }
  }
  
  // Defer ALL non-critical initialization to reduce TBT & improve LCP
  if ('requestIdleCallback' in window) {
    window.requestIdleCallback(() => {
      // Initialize NavigatorLock
      setupNavigatorLockHandler();
      
      // Register service worker
      if (import.meta.env.PROD) {
        registerServiceWorker();
      }
      
      // Preload ONLY Sales page (most common entry point)
      import('./pages/Sales').catch(() => {});
      
      // Preconnect to Supabase
      const preconnect = document.createElement('link');
      preconnect.rel = 'preconnect';
      preconnect.href = 'https://*.supabase.co';
      document.head.appendChild(preconnect);
    }, { timeout: 2000 });
  }
} else {
  console.error('Root element not found!');
}
