"use client";

import { useEffect } from "react";
import { trackCatalogEvent, type CatalogEventName } from "@/lib/catalog-analytics";

type CatalogAnalyticsTrackerProps = {
  slug: string;
  eventName: CatalogEventName | string;
  productId?: string | null;
  categoryId?: string | null;
  sectionId?: string | null;
  sourcePath?: string;
  searchTerm?: string;
  onceKey?: string;
  meta?: Record<string, unknown>;
};

export default function CatalogAnalyticsTracker({
  slug,
  eventName,
  productId,
  categoryId,
  sectionId,
  sourcePath,
  searchTerm,
  onceKey,
  meta,
}: CatalogAnalyticsTrackerProps) {
  useEffect(() => {
    let cancelled = false;
    const normalizedSlug = String(slug || "").trim();
    const normalizedEventName = String(eventName || "").trim();
    if (!normalizedSlug || !normalizedEventName) return;

    const marker = onceKey ? `ktalogu_catalog_once:${normalizedSlug}:${onceKey}` : "";
    if (onceKey && typeof window !== "undefined") {
      if (window.sessionStorage.getItem(marker)) return;
    }

    const run = async () => {
      const tracked = await trackCatalogEvent({
        slug: normalizedSlug,
        eventName: normalizedEventName,
        productId,
        categoryId,
        sectionId,
        sourcePath,
        searchTerm,
        meta,
      });
      if (cancelled) return;
      if (tracked && marker && typeof window !== "undefined") {
        window.sessionStorage.setItem(marker, "1");
      }
    };
    void run();
    return () => {
      cancelled = true;
    };
  }, [slug, eventName, productId, categoryId, sectionId, sourcePath, searchTerm, onceKey, meta]);

  return null;
}
