'use client';

import dynamic from 'next/dynamic';
import { Suspense, useEffect, useState } from 'react';

const DynamicAnalyticsProvider = dynamic(() => import('./AnalyticsProvider'), {
  ssr: false,
});
const DynamicScrollDepthTracker = dynamic(() => import('./ScrollDepthTracker'), {
  ssr: false,
});
const DynamicWebVitalsTracker = dynamic(() => import('./WebVitalsTracker'), {
  ssr: false,
});

export default function AnalyticsShell() {
  const [shouldLoad, setShouldLoad] = useState(false);

  useEffect(() => {
    // Disable analytics in CI to prevent console noise/score penalties
    if (process.env.NEXT_PUBLIC_CI === 'true') {
      return;
    }

    // Wait until browser is completely idle before loading heavy analytics/logger/sentry SDKs
    if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
      window.requestIdleCallback(() => setShouldLoad(true), { timeout: 3000 });
    } else {
      const timer = setTimeout(() => setShouldLoad(true), 2500);
      return () => clearTimeout(timer);
    }
  }, []);

  if (!shouldLoad) return null;

  return (
    <Suspense fallback={null}>
      <DynamicAnalyticsProvider />
      <DynamicScrollDepthTracker />
      <DynamicWebVitalsTracker />
    </Suspense>
  );
}
