"use client";

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

/**
 * AnalyticsProvider Component
 *
 * Automatically tracks pageviews on client-side route changes.
 * This component should be placed inside your layout to handle navigation events.
 *
 * @param {Object} props - Component props
 * @param {string} [props.websiteId] - The Umami website ID (passed from server config)
 *
 * @example
 * ```tsx
 * // In your layout.tsx
 * const { websiteId } = config.analytics.umami;
 * <AnalyticsProvider websiteId={websiteId} />
 * ```
 */
export default function AnalyticsProvider({
  websiteId,
}: {
  websiteId?: string;
}) {
  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]);

  if (!websiteId) return null;

  return null;
}
