"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect } from "react";

import { trackEvent } from "@/components/PostHogProvider";

type PageType = "commercial" | "use_case_hub" | "use_case" | "industry" | "industry_hub";

type TrackingContext = {
  pageType: PageType;
  cluster?: string;
  useCase?: string;
};

function getUtmPropertiesFromWindow() {
  if (typeof window === "undefined") return {};
  const params = new URLSearchParams(window.location.search);
  return {
    utm_source: params.get("utm_source") || undefined,
    utm_medium: params.get("utm_medium") || undefined,
    utm_campaign: params.get("utm_campaign") || undefined,
    utm_content: params.get("utm_content") || undefined,
  };
}

export function MarketingPageTracker({
  pageType,
  cluster,
  useCase,
}: TrackingContext) {
  const pathname = usePathname();

  useEffect(() => {
    if (!pathname) {
      return;
    }

    trackEvent("landing_page_viewed", {
      landing_page_slug: pathname,
      page_type: pageType,
      cluster,
      use_case: useCase,
      ...getUtmPropertiesFromWindow(),
    });
  }, [cluster, pageType, pathname, useCase]);

  return null;
}

type TrackedCtaLinkProps = TrackingContext & {
  href: string;
  ctaLabel: string;
  ctaLocation: string;
  destination?: string;
  className?: string;
  children: React.ReactNode;
};

export function TrackedCtaLink({
  href,
  ctaLabel,
  ctaLocation,
  destination,
  className,
  children,
  pageType,
  cluster,
  useCase,
}: TrackedCtaLinkProps) {
  const pathname = usePathname();

  return (
    <Link
      href={href}
      className={className}
      onClick={() => {
        trackEvent("cta_clicked", {
          landing_page_slug: pathname,
          page_type: pageType,
          cluster,
          use_case: useCase,
          cta_label: ctaLabel,
          cta_location: ctaLocation,
          destination: destination || href,
          ...getUtmPropertiesFromWindow(),
        });
      }}
    >
      {children}
    </Link>
  );
}
