"use client";

import { useEffect, useMemo } from "react";
import type { FunnelDefinition } from "@/lib/funnel/types";
import type { IFunnelPaymentPlacement } from "@/entities/session/funnel/types";
import { usePaymentPlacementContext } from "@/entities/session/payment/PaymentPlacementProvider";

interface UsePaymentPlacementArgs {
  funnel: FunnelDefinition;
  paymentId: string;
}

interface UsePaymentPlacementResult {
  placement: IFunnelPaymentPlacement | null;
  isLoading: boolean;
  error: string | null;
}

export function usePaymentPlacement({
  funnel,
  paymentId,
}: UsePaymentPlacementArgs): UsePaymentPlacementResult {
  const { getPlacement, loadPlacement } = usePaymentPlacementContext();

  const funnelKey = useMemo(() => funnel?.meta?.id ?? "", [funnel]);

  useEffect(() => {
    if (!funnelKey || !paymentId) return;
    loadPlacement(funnelKey, paymentId);
  }, [funnelKey, paymentId, loadPlacement]);

  const cached = getPlacement(funnelKey, paymentId);

  return {
    placement: cached.placement,
    isLoading: cached.isLoading,
    error: cached.error,
  };
}
