"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()}` : "");
    const timestamp = new Date().toISOString();

    // Track page view in Google Analytics
    if (typeof window !== "undefined" && typeof window.gtag === "function") {
      const payload = {
        page_path: url,
        page_location: window.location.href,
        page_title: document.title,
      };
      
      window.gtag("event", "page_view", payload);
      
      // Детальное логирование
      console.groupCollapsed(
        `%c[GA] 📊 Page View Event Sent`,
        'color: #4285F4; font-weight: bold'
      );
      console.log('🕐 Timestamp:', timestamp);
      console.log('📍 URL:', url);
      console.log('🌐 Full Location:', window.location.href);
      console.log('📄 Page Title:', document.title);
      console.log('📦 Payload:', payload);
      console.log('✅ Status: Successfully sent to Google Analytics');
      console.groupEnd();
    } else {
      console.warn(
        `%c[GA] ⚠️ Page View NOT Sent`,
        'color: #FFA500; font-weight: bold',
        '\nReason: Google Analytics not available (window.gtag is undefined)'
      );
    }

    // 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.groupCollapsed(
          `%c[YM] 📊 Page View Event Sent`,
          'color: #FF0000; font-weight: bold'
        );
        console.log('🕐 Timestamp:', timestamp);
        console.log('📍 URL:', url);
        console.log('🔢 Counter ID:', counterId);
        console.log('✅ Status: Successfully sent to Yandex Metrika');
        console.groupEnd();
      } else {
        console.warn(
          `%c[YM] ⚠️ Page View NOT Sent`,
          'color: #FFA500; font-weight: bold',
          '\nReason: Counter ID not found'
        );
      }
    }
  }, [pathname, searchParams]);

  return null;
}
