import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './styles/globals.css';
import './styles/components.css';
import './styles/animations.css';
import './styles/themes/light.css';
import './styles/themes/dark.css';

// OpenTelemetry Web SDK initialization
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';
import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
import { metrics } from '@opentelemetry/api';

// Import analytics utilities
import { initializeAnalytics } from './utils/analytics';

// Import configuration
import { isOpenTelemetryEnabled, getOtelTracesEndpoint, getOtelMetricsEndpoint } from './config/runtime';

// Store cleanup function for proper teardown
let analyticsCleanup: (() => void) | null = null;

// Initialize OpenTelemetry
const initOpenTelemetry = () => {
  // Check if OpenTelemetry is enabled in configuration
  if (!isOpenTelemetryEnabled()) {
    console.log('OpenTelemetry disabled by configuration');
    return;
  }

  try {
    // Create resource with service information using non-deprecated attributes
    const resource = resourceFromAttributes({
      [ATTR_SERVICE_NAME]: 'bakery-frontend',
      [ATTR_SERVICE_VERSION]: '1.0.0'
    });

    // Initialize tracer with span processor
    const traceExporter = new OTLPTraceExporter({
      url: getOtelTracesEndpoint() // Using configured endpoint
    });

    const traceProvider = new WebTracerProvider({
      resource: resource,
      // Add span processors as array for current OpenTelemetry SDK version
      spanProcessors: [new BatchSpanProcessor(traceExporter)]
    });

    traceProvider.register();

    // Initialize metrics
    const metricExporter = new OTLPMetricExporter({
      url: getOtelMetricsEndpoint()
    });

    const metricReader = new PeriodicExportingMetricReader({
      exporter: metricExporter,
      exportIntervalMillis: 10000, // 10 seconds
    });

    // Use the MeterProvider constructor with readers array
    const meterProvider = new MeterProvider({
      resource: resource,
      readers: [metricReader]
    });

    // Register the meter provider globally using proper API
    metrics.setGlobalMeterProvider(meterProvider);

    console.log('OpenTelemetry initialized for frontend');
  } catch (error) {
    console.error('Failed to initialize OpenTelemetry:', error);
    // Continue without OpenTelemetry if initialization fails
  }
};

// Initialize OpenTelemetry before rendering the app
initOpenTelemetry();

// Initialize analytics tracking and store cleanup function
analyticsCleanup = initializeAnalytics();

// Cleanup on page unload
window.addEventListener('beforeunload', () => {
  if (analyticsCleanup) {
    analyticsCleanup();
  }
});

// PWA/ServiceWorker functionality removed to avoid conflicts in development

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);