'use client';

import React, { useEffect, ReactNode } from 'react';

interface Props {
  children: ReactNode;
}

export function MonitoringProvider({ children }: Props) {
  useEffect(() => {
    if (typeof window !== 'undefined') {
      import('@/lib/web-vitals').then(({ reportWebVitals, logVitals }) => {
        reportWebVitals(logVitals);
      }).catch(() => {});
    }
  }, []);

  useEffect(() => {
    if (typeof window !== 'undefined' && process.env.NODE_ENV === 'production') {
      import('@/lib/telemetry').then(m => m.initTelemetry()).catch(() => {});
    }
  }, []);

  useEffect(() => {
    const handleError = (event: ErrorEvent) => {
      console.error('Global error:', event.error);
    };

    const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
      console.error('Unhandled promise rejection:', event.reason);
    };

    window.addEventListener('error', handleError);
    window.addEventListener('unhandledrejection', handleUnhandledRejection);

    return () => {
      window.removeEventListener('error', handleError);
      window.removeEventListener('unhandledrejection', handleUnhandledRejection);
    };
  }, []);

  return <>{children}</>;
}
