'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,
});

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

  useEffect(() => {
    // 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 />
    </Suspense>
  );
}
