import './utils/disableConsole'; // Must be first import
import './utils/productionErrorHandler'; // Production error handling
import './polyfills';

// Environment check
if (!import.meta.env.VITE_PUBLIC_POSTHOG_KEY) {
  console.warn('⚠️ PostHog key is missing - analytics will be disabled');
}
if (!import.meta.env.VITE_PRIVY_APP_ID) {
  console.warn('⚠️ Privy app ID is missing - wallet connection may fail');
}
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { PostHogProvider } from 'posthog-js/react';
import posthog from 'posthog-js';

// Error Boundary Component
import { Component, ErrorInfo, ReactNode } from 'react';

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
  error?: Error;
}

class ErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false
  };

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

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Error caught by boundary:', error, errorInfo);
    
    // Send error to PostHog if available
    if (typeof posthog !== 'undefined' && posthog.__loaded) {
      posthog.captureException(error, {
        errorInfo,
        errorBoundary: true,
        componentStack: errorInfo.componentStack
      });
    }
  }

  public render() {
    if (this.state.hasError) {
      return (
        <div style={{ 
          padding: '20px', 
          textAlign: 'center', 
          fontFamily: 'system-ui',
          background: '#f5f5f5',
          minHeight: '100vh',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center'
        }}>
          <h1 style={{ color: '#e74c3c' }}>Something went wrong</h1>
          <p style={{ color: '#666' }}>
            {this.state.error?.message || 'An unexpected error occurred'}
          </p>
          <button 
            onClick={() => window.location.reload()} 
            style={{
              padding: '10px 20px',
              backgroundColor: '#3498db',
              color: 'white',
              border: 'none',
              borderRadius: '5px',
              cursor: 'pointer',
              marginTop: '20px'
            }}
          >
            Reload Page
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

// Global error handlers for PostHog
if (import.meta.env.VITE_PUBLIC_POSTHOG_KEY) {
  // Capture unhandled promise rejections
  window.addEventListener('unhandledrejection', (event) => {
    if (typeof posthog !== 'undefined' && posthog.__loaded) {
      posthog.captureException(event.reason, {
        type: 'unhandledrejection',
        promise: event.promise,
        url: window.location.href
      });
    }
  });

  // Capture global JavaScript errors
  window.addEventListener('error', (event) => {
    if (typeof posthog !== 'undefined' && posthog.__loaded) {
      posthog.captureException(event.error || event.message, {
        type: 'javascript_error',
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
        url: window.location.href
      });
    }
  });

  // Capture console errors
  const originalConsoleError = console.error;
  console.error = (...args) => {
    // Call original console.error first
    originalConsoleError.apply(console, args);
    
    // Send to PostHog if available
    if (typeof posthog !== 'undefined' && posthog.__loaded) {
      const errorMessage = args.map(arg => 
        typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
      ).join(' ');
      
      posthog.captureException(new Error(errorMessage), {
        type: 'console_error',
        args: args,
        url: window.location.href
      });
    }
  };
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ErrorBoundary>
      {import.meta.env.VITE_PUBLIC_POSTHOG_KEY ? (
        <PostHogProvider
          apiKey={import.meta.env.VITE_PUBLIC_POSTHOG_KEY}
          options={{
            api_host: 'https://eu.i.posthog.com',
            debug: import.meta.env.DEV,
            disable_session_recording: false,
            capture_pageview: true,
            capture_pageleave: true,
          }}
        >
          <App />
        </PostHogProvider>
      ) : (
        <App />
      )}
    </ErrorBoundary>
  </StrictMode>
);