"use client";

import React from "react";
import Link, { LinkProps } from "next/link";
import { useAnalytics } from "./useAnalytics";
import { AnalyticsEvents } from "./analytics-events";

interface TrackedLinkProps extends LinkProps {
  eventName?: string;
  eventProperties?: Record<string, any>;
  className?: string;
  children: React.ReactNode;
  onClick?: (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => void;
  // allow passing other props
  [key: string]: any;
}

/**
 * A wrapper around next/link that tracks the click event.
 */
export function TrackedLink({
  href,
  eventName = AnalyticsEvents.LINK_CLICK,
  eventProperties = {},
  className,
  children,
  onClick,
  ...props
}: TrackedLinkProps) {
  const { trackEvent } = useAnalytics();

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
    trackEvent(eventName, {
      href: href.toString(),
      ...eventProperties,
    });
    if (onClick) onClick(e);
  };

  return (
    <Link href={href} className={className} onClick={handleClick} {...props}>
      {children}
    </Link>
  );
}
