import { useEffect, type ReactNode } from "react";
import { useLocation } from "react-router-dom";
import { initAnalytics, trackCtaClick, trackPageView } from "@/lib/analytics";

type AnalyticsProviderProps = {
  children: ReactNode;
};

/**
 * SPA-Seitenaufrufe + Klicks auf Elemente mit
 * data-analytics-cta und data-analytics-location.
 */
export function AnalyticsProvider({ children }: AnalyticsProviderProps) {
  const location = useLocation();

  useEffect(() => {
    initAnalytics();
  }, []);

  useEffect(() => {
    const path = location.pathname + location.search + location.hash;
    trackPageView(path);
  }, [location]);

  useEffect(() => {
    const onClick = (event: MouseEvent) => {
      const target = event.target;
      if (!(target instanceof Element)) return;

      const el = target.closest("[data-analytics-cta]");
      if (!el || !(el instanceof HTMLElement)) return;

      const buttonText = el.dataset.analyticsCta ?? "";
      const clickLocation = el.dataset.analyticsLocation ?? "unknown";
      if (!buttonText) return;

      trackCtaClick(buttonText, clickLocation);
    };

    document.addEventListener("click", onClick, true);
    return () => document.removeEventListener("click", onClick, true);
  }, []);

  return <>{children}</>;
}
