"use client";

import { useEffect, useRef } from "react";

import type { PaymentPlan } from "@/data/schemas/payment";
import {
  behaviorAnalytics,
  type PaymentAnalyticsContext,
} from "@/lib/analytics";

export function usePaymentPlanAnalytics(
  plans: readonly PaymentPlan[],
  context: PaymentAnalyticsContext,
): void {
  const trackedRef = useRef(new Set<string>());
  const { entryPoint, triggerReason } = context;

  useEffect(() => {
    plans.forEach((plan, index) => {
      const key = `${entryPoint}:${triggerReason}:${plan.planId}`;
      if (trackedRef.current.has(key)) return;
      trackedRef.current.add(key);
      behaviorAnalytics.planImpression(plan, index + 1, {
        entryPoint,
        triggerReason,
      });
    });
  }, [entryPoint, plans, triggerReason]);
}
