import React, { ReactElement, cloneElement, MouseEvent } from 'react';
import { useSuggestionsContext } from './SuggestionsContext';

export interface SuggestionCtaWrapperProps {
  /** The offer ID to report when CTA is clicked */
  offerId: string;
  /** The target URL to report when CTA is clicked */
  referredUrl: string;
  /** A single clickable element (must accept onClick prop) */
  children: ReactElement<{ onClick?: (e: MouseEvent) => void }>;
}

/**
 * Wrapper component that adds automatic CTA click reporting to the dealer BI service.
 *
 * Note: The child component must be clickable (accept an onClick prop).
 */
export const SuggestionCtaWrapper: React.FC<SuggestionCtaWrapperProps> = ({
  offerId,
  referredUrl,
  children,
}) => {
  const { onOfferClicked } = useSuggestionsContext();

  return cloneElement(children, {
    onClick: (e: MouseEvent) => {
      onOfferClicked(offerId, referredUrl);
      children.props.onClick?.(e);
    },
  });
};
