// apps/web/src/components/ui/domain/DealCTA/BuyButton.tsx
// @design-system: domain/DealCTA

'use client';

import { useCallback, useRef } from 'react';
import { cn } from '@/lib/cn';
import { Icon } from '@/components/ui/icons/Icon';
import { useT } from '@/lib/i18n/react';
import { captureCaught } from '@/lib/observability';
import { useCheckoutModalStore } from '@/features/checkout-modal/checkoutModalStore';
import type {
  CheckoutModalPreview,
  DealContext,
} from '@/features/checkout-modal/checkoutModalStore';
import { buyButtonVariants } from './variants';
import type { DealType } from '@/lib/deal-types';

export interface BuyButtonProps {
  dealId: string;
  size?: 'sm' | 'md' | 'lg';
  soldOut?: boolean;
  disabled?: boolean;
  iconOnly?: boolean;
  className?: string;
  // Routing props
  skuId?: string | null; // explicit (deal-detail); undefined = derive from hasAxes/defaultSkuId
  hasAxes?: boolean; // true = multi-variant listing card → navigate to deal page
  defaultSkuId?: string | null; // sole SKU id for single-SKU listing cards
  dealType?: DealType; // 'GROUP' bypass: open modal with skuId:null
  heSlug?: string; // canonical deal slug for navigation fallback
  preview?: CheckoutModalPreview;
}

export function BuyButton({
  dealId,
  size = 'md',
  soldOut = false,
  disabled = false,
  iconOnly,
  className,
  skuId,
  hasAxes,
  defaultSkuId,
  dealType,
  heSlug,
  preview,
}: BuyButtonProps) {
  const t = useT('domain_deal_cta');
  const isDisabled = soldOut || disabled;
  const resolvedIconOnly = iconOnly ?? size === 'sm';

  const buyLabel = size === 'lg' ? t('buy_now') : size === 'md' ? t('buy_short') : t('buy');
  const ariaLabel = soldOut ? t('sold_out') : buyLabel;

  const openCheckoutModal = useCheckoutModalStore((s) => s.open);
  const dealUrl = heSlug ? `/deals/${heSlug}` : '/deals';

  const pendingFetchRef = useRef<Promise<{ ok: boolean; deal?: DealContext }> | null>(null);

  const handlePointerDown = useCallback(() => {
    if (isDisabled) return;
    // Mirror the navigation guard from handleClick — skip prefetch if click would navigate
    const wouldNavigate = dealType !== 'GROUP' && skuId === undefined && !hasAxes && !defaultSkuId;
    if (wouldNavigate) return;
    const resolvedSkuId =
      dealType === 'GROUP'
        ? null
        : skuId !== undefined
          ? skuId
          : hasAxes
            ? null
            : (defaultSkuId ?? null);
    const skuParam = resolvedSkuId ? `?skuId=${resolvedSkuId}` : '';
    pendingFetchRef.current = fetch(`/api/deals/${dealId}/checkout-context${skuParam}`)
      .then((r) => r.json() as Promise<{ ok: boolean; deal?: DealContext }>)
      .catch((err) => {
        captureCaught(err, { scope: 'buy-button.prefetch', severity: 'info' });
        return { ok: false as const };
      });
  }, [dealId, dealType, defaultSkuId, hasAxes, isDisabled, skuId]);

  const handleClick = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();
      if (isDisabled) return;

      // GROUP deals have no SKU — open modal directly with skuId:null
      if (dealType === 'GROUP') {
        openCheckoutModal({
          dealId,
          skuId: null,
          preview,
          pendingContextFetch: pendingFetchRef.current ?? undefined,
        });
        pendingFetchRef.current = null;
        return;
      }

      // skuId prop present = deal-detail (variant selected or explicitly null)
      // skuId prop absent  = listing-card: derive from hasAxes / defaultSkuId
      const resolvedSkuId =
        skuId !== undefined
          ? skuId
          : hasAxes
            ? null // multi-variant → open modal for variant selection
            : (defaultSkuId ?? null); // single-SKU → open modal

      if (!resolvedSkuId) {
        if (hasAxes) {
          openCheckoutModal({
            dealId,
            skuId: null,
            preview,
            pendingContextFetch: pendingFetchRef.current ?? undefined,
          });
          pendingFetchRef.current = null;
        } else {
          window.location.href = dealUrl;
        }
        return;
      }

      openCheckoutModal({
        dealId,
        skuId: resolvedSkuId,
        preview,
        pendingContextFetch: pendingFetchRef.current ?? undefined,
      });
      pendingFetchRef.current = null;
    },
    [
      dealId,
      isDisabled,
      openCheckoutModal,
      skuId,
      hasAxes,
      defaultSkuId,
      dealType,
      dealUrl,
      preview,
    ],
  );

  return (
    <button
      type="button"
      onClick={handleClick}
      onPointerDown={handlePointerDown}
      disabled={isDisabled}
      aria-label={resolvedIconOnly ? ariaLabel : undefined}
      className={cn(buyButtonVariants({ size, soldOut }), className)}
    >
      <Icon name="ShoppingCart" size="sm" aria-hidden />
      {!resolvedIconOnly && <span>{soldOut ? t('sold_out') : buyLabel}</span>}
    </button>
  );
}
