// @design-system: domain/VendorCard

/**
 * VendorCard - card for the public stores directory.
 *
 * Shows business hero image with initial badge, business name,
 * rating, business type, city, and active deals count.
 * Links to /business/{id}.
 *
 * @example
 * <VendorCard vendor={vendorData} locale="he" />
 */

import { useEffect, useState } from 'react';
import { Star } from 'lucide-react';
import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n/react';
import { Image } from '@/components/ui/primitives/Image';
import { buildVariantUrl } from '@/components/ui/primitives/Image/buildVariantUrl';
import type { Locale } from '@/lib/i18n';
import { getOpenNowSignal } from '@/lib/open-now';

export interface VendorCardData {
  id: string;
  businessName: string;
  displayName: string;
  logoUrl: string | null;
  heroImageUrl: string | null;
  reviewsScore: string;
  reviewsCount: number;
  city: string;
  lat: string | null;
  lng: string | null;
  activeDealsCount: number;
  activeDealsTypes: string[];
  todayHours: string | null;
  yesterdayHours?: string | null;
  businessTypeNames: string[];
}

export interface VendorCardProps {
  vendor: VendorCardData;
  locale: Locale;
  className?: string;
}

export function VendorCard({ vendor, locale: _locale, className }: VendorCardProps) {
  const t = useT('stores');
  const [, setNow] = useState(() => new Date());

  useEffect(() => {
    const intervalId = window.setInterval(() => setNow(new Date()), 60_000);
    return () => window.clearInterval(intervalId);
  }, []);

  const score = parseFloat(vendor.reviewsScore);
  const hasRating = vendor.reviewsCount > 0 && !isNaN(score) && score > 0;
  const openSignal = getOpenNowSignal(vendor.todayHours, vendor.yesterdayHours);
  const showHoursSignal = openSignal.state !== 'unknown';

  const initial = (vendor.displayName || vendor.businessName).charAt(0).toUpperCase();

  return (
    <a
      href={`/business/${vendor.id}`}
      className={cn(
        'group flex flex-col overflow-hidden rounded-xl',
        'border-border bg-surface-raised border shadow-sm',
        'transition-shadow duration-[var(--duration-fast)]',
        'focus-visible:outline-brand-primary-500 hover:shadow-md focus-visible:outline focus-visible:outline-2',
        className,
      )}
    >
      {/* Hero image area — fixed h-40 */}
      <div className="relative h-40 w-full overflow-hidden rounded-t-xl bg-neutral-100">
        {vendor.heroImageUrl ? (
          <Image
            src={vendor.heroImageUrl}
            alt=""
            decorative
            variant="hero"
            className="h-full w-full object-cover transition-transform duration-[var(--duration-slow)] motion-safe:group-hover:scale-105 motion-reduce:transition-none"
            loading="lazy"
            width={400}
            height={160}
          />
        ) : (
          <div className="from-brand-primary-700 to-brand-primary-500 h-full w-full bg-gradient-to-br" />
        )}

        {/* Logo badge — bottom end corner. Shows logo img when available, else letter initial. */}
        <div
          aria-hidden="true"
          className="absolute end-3 bottom-1 flex h-9 w-9 items-center justify-center overflow-hidden rounded-full bg-white shadow-sm"
        >
          {vendor.logoUrl ? (
            <img
              src={buildVariantUrl(vendor.logoUrl, 'thumb', 240) ?? vendor.logoUrl}
              alt=""
              width={36}
              height={36}
              className="h-full w-full object-cover"
              loading="lazy"
            />
          ) : (
            <span className="text-brand-primary-600 text-sm font-bold">{initial}</span>
          )}
        </div>

        {/* Active deals badge — top start corner */}
        {vendor.activeDealsCount > 0 && (
          <div className="bg-brand-primary-600 text-text-inverse absolute start-2 top-2 rounded-full px-2 py-[var(--spacing-0-5)] text-xs font-semibold">
            {t('deals_count').replace('{n}', String(vendor.activeDealsCount))}
          </div>
        )}
      </div>

      {/* Info rows */}
      <div className="flex flex-col gap-1 p-3">
        {/* Row 1: name + rating */}
        <div className="flex items-center justify-between gap-2">
          <h2 className="text-text-primary line-clamp-1 text-sm font-semibold">
            {vendor.businessName}
          </h2>
          {hasRating && (
            <span
              className="text-text-secondary shrink-0 text-xs"
              aria-label={t('rating_aria').replace('{score}', score.toFixed(1))}
            >
              <Star width={12} height={12} fill="currentColor" aria-hidden="true" />
              {score.toFixed(1)}
            </span>
          )}
        </div>

        {/* Row 2: type·city + deal count */}
        <div className="text-text-muted flex items-center justify-between gap-2 text-xs">
          <div className="flex min-w-0 items-center gap-2">
            <span className="line-clamp-1">
              {vendor.businessTypeNames.length > 0
                ? `${vendor.businessTypeNames.slice(0, 2).join(' · ')} · ${vendor.city}`
                : vendor.city}
            </span>
            {showHoursSignal && (
              <span
                className={cn(
                  'inline-flex shrink-0 items-center gap-1 rounded-full px-1.5 py-0.5',
                  openSignal.state === 'open'
                    ? 'bg-success-50 text-success-700'
                    : 'bg-surface-subtle text-text-muted',
                )}
              >
                <span
                  aria-hidden="true"
                  className={cn(
                    'size-1.5 rounded-full',
                    openSignal.state === 'open' ? 'bg-success-600' : 'bg-text-muted',
                  )}
                />
                <span>{openSignal.state === 'open' ? t('open_now') : t('closed_now')}</span>
              </span>
            )}
          </div>
          {vendor.activeDealsCount > 0 && (
            <span className="shrink-0">
              {t('deals_count').replace('{n}', String(vendor.activeDealsCount))}
            </span>
          )}
        </div>
      </div>
    </a>
  );
}
