'use client';

import { useQuery } from '@tanstack/react-query';
import { useTranslations } from 'next-intl';

import { promotionsApi } from '@/lib/api';
import { formatPrice } from '@/lib/utils';
import { FlashSaleCountdown } from '@/components/home-blocks/FlashSaleCountdown';
import type { ActivePromotionsResponse } from '@/types/api';

/**
 * Feature 054 — US11 (T084). When the vendor has a live promotion, show its
 * discount + countdown above the services grid. Renders nothing otherwise.
 */
export function VendorPromotionBanner({
  vendorPublicId,
  locale,
}: {
  vendorPublicId: string;
  locale: string;
}) {
  const t = useTranslations('offers.card');

  const { data } = useQuery<ActivePromotionsResponse>({
    queryKey: ['promotions', 'active', 'vendor', vendorPublicId, locale],
    queryFn: () =>
      promotionsApi.listActive(locale, { scope: 'vendor', vendor_public_id: vendorPublicId, limit: 1 }),
    staleTime: 60_000,
  });

  const promo = data?.data?.[0];
  if (!promo) return null;

  const discountLabel =
    promo.discount.kind === 'percentage'
      ? `${promo.discount.value_minor / 100}%`
      : formatPrice(promo.discount.value_minor, locale, promo.discount.currency);

  return (
    <section
      data-testid="vendor-promotion-banner"
      className="mb-6 flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-primary-200 bg-primary-50 px-5 py-4"
    >
      <div className="flex items-center gap-3">
        <span className="rounded-full bg-primary-600 px-2.5 py-0.5 text-sm font-bold text-white">
          -{discountLabel}
        </span>
        <div>
          <p className="font-heading text-base font-bold text-neutral-900">{promo.title}</p>
          <p className="text-xs text-neutral-600">
            {t('code_label')}:{' '}
            <span className="font-mono font-semibold text-neutral-800">{promo.code}</span>
          </p>
        </div>
      </div>
      {promo.ends_at ? <FlashSaleCountdown endsAt={promo.ends_at} size="sm" className="text-neutral-700" /> : null}
    </section>
  );
}
