'use client';

import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { getAppServices } from '@/lib/services/create-services';
import Script from 'next/script';

/**
 * AnalyticsProvider Component
 *
 * Automatically tracks pageviews on client-side route changes.
 * This component should be placed inside your layout to handle navigation events.
 *
 * @example
 * ```tsx
 * // In your layout.tsx
 * <NextIntlClientProvider messages={messages} locale={locale}>
 *   <UmamiScript />
 *   <Header />
 *   <main>{children}</main>
 *   <Footer />
 *   <AnalyticsProvider />
 * </NextIntlClientProvider>
 * ```
 */
export default function AnalyticsProvider() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (!pathname) return;
    
    const services = getAppServices();
    const url = `${pathname}${searchParams?.size ? `?${searchParams.toString()}` : ''}`;
    
    // Track pageview with the full URL
    services.analytics.trackPageview(url);
    
    if (process.env.NODE_ENV === 'development') {
      console.log('[Umami] Tracked pageview:', url);
    }
  }, [pathname, searchParams]);

  const websiteId = process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID;
  if (!websiteId) return null;

  return (
    <Script
      id="umami-analytics"
      src="/stats/script.js"
      data-website-id={websiteId}
      strategy="afterInteractive"
      defer
    />
  );
}

