'use client';

import { useEffect, type ReactNode } from 'react';
import dynamic from 'next/dynamic';
import { CommandRegistryProvider } from '@bytelyst/command-palette';
import { ToastProvider } from '@/components/ui/Primitives';
import { AuthProvider } from '@/lib/auth-context';
import { ThemeProvider } from '@/lib/theme-context';
import { ProductProvider } from '@/lib/product-context';
import { initTelemetry } from '@/lib/telemetry';

import { CSPostHogProvider } from '@/components/posthog-provider';

// ⌘K palette — loaded lazily so its code stays out of the initial bundle (UX-5).
const CommandMenu = dynamic(() => import('@/components/command-menu'), { ssr: false });

export function Providers({ children }: { children: ReactNode }) {
  useEffect(() => {
    initTelemetry();
  }, []);

  return (
    <CSPostHogProvider>
      <ThemeProvider>
        <ProductProvider>
          <AuthProvider>
            <ToastProvider>
              <CommandRegistryProvider>
                {children}
                <CommandMenu />
              </CommandRegistryProvider>
            </ToastProvider>
          </AuthProvider>
        </ProductProvider>
      </ThemeProvider>
    </CSPostHogProvider>
  );
}
