'use client';

import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { discoveryApi } from '@/lib/api';
import { AddToEventButton } from '@/components/vendor/AddToEventButton';

type VendorPageCtasProps = {
  vendorPublicId: string;
  locale: string;
  fallbackLabel: string;
  /** `sticky` renders the full-width mobile bottom variant; default is sidebar. */
  variant?: 'sidebar' | 'sticky';
};

/**
 * Renders the vendor page primary CTA. If the vendor has services, the CTA is
 * "Add to event" on the first service. Otherwise we degrade to a "Browse"
 * link that points at the empty search filtered by vendor.
 *
 * Feature 054 (B2): demotes the historical "Browse services" CTA which only
 * sent users into the catalog round-trip.
 */
export function VendorPageCtas({ vendorPublicId, locale, fallbackLabel, variant = 'sidebar' }: VendorPageCtasProps) {
  const { data } = useQuery({
    queryKey: ['vendor-services', vendorPublicId, locale],
    queryFn: () => {
      const q = new URLSearchParams({ vendor_public_id: vendorPublicId, per_page: '1' });
      return discoveryApi.searchServices(q, locale);
    },
    staleTime: 60_000,
  });

  const firstService = data?.items[0];

  if (firstService) {
    return (
      <AddToEventButton
        service={firstService}
        variant={variant === 'sticky' ? 'sticky' : 'card'}
        className={variant === 'sticky' ? '' : 'w-full'}
      />
    );
  }

  return (
    <Link
      href={`/${locale}/search?vendor_public_id=${vendorPublicId}`}
      className="btn-primary block text-center"
      data-testid={variant === 'sticky' ? 'vendor-cta-mobile' : 'vendor-cta'}
    >
      {fallbackLabel}
    </Link>
  );
}
