"use client";

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

/**
 * Wait for Yandex Metrika to be loaded
 * Retry mechanism with timeout to handle async script loading
 */
async function waitForYandexMetrika(maxAttempts = 10, delayMs = 100): Promise<boolean> {
  for (let i = 0; i < maxAttempts; i++) {
    if (typeof window !== "undefined" &&
        typeof window.ym === "function" &&
        window.__YM_COUNTER_ID__) {
      return true;
    }
    await new Promise(resolve => setTimeout(resolve, delayMs));
  }
  return false;
}

/**
 * Page View Tracker Component
 *
 * Tracks page views in 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 Yandex Metrika (with retry logic)
    const trackYandexMetrika = async () => {
      const isYmAvailable = await waitForYandexMetrika();

      if (isYmAvailable && typeof window.ym === "function") {
        const counterId = window.__YM_COUNTER_ID__;
        if (counterId) {
          window.ym(counterId, "hit", url);
        }
      }
    };

    // Execute YM tracking
    trackYandexMetrika();
  }, [pathname, searchParams]);

  return null;
}
