"use client";

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

/**
 * Page View Tracker Component
 * 
 * Tracks page views in Google Analytics and Yandex Metrika
 * when route changes occur (client-side navigation).
 * 
 * Must be included in the app layout or root component.
 */
export function PageViewTracker() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    const url = pathname + (searchParams?.toString() ? `?${searchParams.toString()}` : "");

    // Track page view in Google Analytics
    if (typeof window !== "undefined" && typeof window.gtag === "function") {
      window.gtag("event", "page_view", {
        page_path: url,
        page_location: window.location.href,
        page_title: document.title,
      });
      console.log(`[GA] Page view tracked: ${url}`);
    }

    // Track page view in Yandex Metrika
    if (typeof window !== "undefined" && typeof window.ym === "function") {
      const counterId = window.__YM_COUNTER_ID__;
      if (counterId) {
        window.ym(counterId, "hit", url);
        console.log(`[YM] Page view tracked: ${url}`);
      }
    }
  }, [pathname, searchParams]);

  return null;
}
