"use client";

import { useEffect } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { useAnalytics } from "./context";

/**
 * Automatically tracks pageviews on client-side route changes in Next.js.
 */
export function AnalyticsAutoTracker() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const analytics = useAnalytics();

  useEffect(() => {
    if (!pathname) return;

    const url = `${pathname}${searchParams?.size ? `?${searchParams.toString()}` : ""}`;
    analytics.trackPageview(url);
  }, [pathname, searchParams, analytics]);

  return null;
}
