// @design-system: domain/BusinessProfile

/**
 * BusinessProfile - compact business info widget used in the deal detail sidebar
 * and other pages that reference a specific vendor. Shows logo thumbnail, name,
 * aggregated rating, address, today's opening hours, and a link to the business page.
 */

import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n/react';
import { Icon } from '@/components/ui/icons/Icon';
import { Image } from '@/components/ui/primitives/Image';
import { Button } from '@/components/ui/primitives/Button';
import { VendorLogoFallback } from '@/components/ui/domain/VendorLogoFallback';

export type BusinessProfileWeekday =
  | 'sunday'
  | 'monday'
  | 'tuesday'
  | 'wednesday'
  | 'thursday'
  | 'friday'
  | 'saturday';

export interface BusinessProfileHours {
  weekday: BusinessProfileWeekday;
  closed: boolean;
  open: string | null;
  close: string | null;
}

export interface BusinessProfileVendor {
  id: string;
  slug: string;
  businessName: string;
  displayName: string;
  logoUrl: string | null;
  reviewsScore: number;
  reviewsCount: number;
  address: string | null;
  city: string | null;
  todayHours: BusinessProfileHours | null;
}

export interface BusinessProfileProps {
  vendor: BusinessProfileVendor;
  /**
   * Visual layout.
   * - `sidebar` (default) — vertical card used as a sidebar widget.
   * - `inline` — condensed horizontal row for use inline in mobile flows.
   */
  variant?: 'sidebar' | 'inline';
  className?: string;
}

// "01:00:00" → "01:00"; passthrough for already-short or nullish values.
function trimSeconds(value: string | null): string | null {
  if (!value) return value;
  return value.length >= 5 ? value.slice(0, 5) : value;
}

export function BusinessProfile({ vendor, variant = 'sidebar', className }: BusinessProfileProps) {
  const t = useT('business_profile');
  const tWeekday = useT('weekday');

  const hours = vendor.todayHours;
  const hasReviews = vendor.reviewsCount > 0;
  const isInline = variant === 'inline';

  const weekdayLabel = hours ? tWeekday(hours.weekday) : '';
  const openStr = trimSeconds(hours?.open ?? null);
  const closeStr = trimSeconds(hours?.close ?? null);
  const hoursLabel = hours
    ? hours.closed
      ? t('closed_today')
      : openStr && closeStr
        ? `${openStr}–${closeStr}`
        : t('hours_unavailable')
    : t('hours_unavailable');

  const addressLine = vendor.address ?? vendor.city;
  const businessHref = `/business/${vendor.slug}`;

  // Inline variant keeps the condensed horizontal row used in mobile flows.
  if (isInline) {
    return (
      <aside
        aria-label={t('aria_label')}
        className={cn(
          'border-border-subtle bg-surface-elevated flex items-center gap-3 rounded-2xl border p-3 shadow-sm',
          className,
        )}
      >
        <div
          className="bg-surface-inset relative size-12 shrink-0 overflow-hidden rounded-xl"
          aria-hidden={true}
        >
          {vendor.logoUrl ? (
            <Image
              src={vendor.logoUrl}
              alt=""
              aria-hidden={true}
              loading="lazy"
              fetchpriority="auto"
              className="size-full object-cover"
            />
          ) : (
            <VendorLogoFallback
              name={vendor.displayName || vendor.businessName}
              size="sm"
              className="size-full rounded-none"
            />
          )}
        </div>
        <div className="min-w-0 flex-1">
          <a
            href={businessHref}
            className="text-text-primary hover:text-brand-primary-700 block truncate text-base font-semibold"
            data-user-content
          >
            {vendor.businessName}
          </a>
          {hasReviews && (
            <div className="mt-1 flex items-center gap-1">
              <Icon name="Star" size="xs" color="primary" aria-hidden={true} />
              <span className="text-text-primary text-sm font-medium">
                {vendor.reviewsScore.toFixed(1)}
              </span>
              <span className="text-text-muted text-xs">({vendor.reviewsCount})</span>
            </div>
          )}
        </div>
      </aside>
    );
  }

  // Sidebar variant — mirrors the purchase sidebar card on the same page:
  // bg-surface-elevated, rounded-2xl, border, p-6, shadow-lg, gap-5 sections
  // separated by border-b pb-4, closed by a full-width primary CTA.
  return (
    <aside
      aria-label={t('aria_label')}
      className={cn(
        'border-border-subtle bg-surface-elevated flex flex-col gap-5 rounded-2xl border p-6 shadow-lg',
        className,
      )}
    >
      {/* Header: logo + name + rating — section separator below */}
      <a
        href={businessHref}
        className={cn(
          'border-border-subtle -m-6 mb-0 flex items-start gap-3 border-b p-6 pb-4',
          'rounded-t-2xl transition-colors',
          'hover:bg-surface-inset/60',
          'focus-visible:ring-2 focus-visible:ring-[var(--color-brand-primary-500)] focus-visible:outline-none focus-visible:ring-inset',
        )}
      >
        <div
          className="bg-surface-inset relative size-14 shrink-0 overflow-hidden rounded-xl"
          aria-hidden={true}
        >
          {vendor.logoUrl ? (
            <Image
              src={vendor.logoUrl}
              alt=""
              aria-hidden={true}
              loading="lazy"
              fetchpriority="auto"
              className="size-full object-cover"
            />
          ) : (
            <VendorLogoFallback
              name={vendor.displayName || vendor.businessName}
              size="md"
              className="size-full rounded-none"
            />
          )}
        </div>

        <div className="min-w-0 flex-1">
          <span
            className="text-text-primary line-clamp-2 block text-base leading-tight font-semibold"
            data-user-content
          >
            {vendor.businessName}
          </span>

          {hasReviews ? (
            <div
              className="mt-1 flex items-center gap-1"
              aria-label={t('rating_aria')
                .replace('{score}', vendor.reviewsScore.toFixed(1))
                .replace('{count}', String(vendor.reviewsCount))}
            >
              <Icon name="Star" size="xs" color="primary" aria-hidden={true} />
              <span className="text-text-primary text-sm font-medium">
                {vendor.reviewsScore.toFixed(1)}
              </span>
              <span className="text-text-muted text-xs">({vendor.reviewsCount})</span>
            </div>
          ) : (
            <p className="text-text-muted mt-1 text-xs">{t('no_reviews')}</p>
          )}
        </div>
      </a>

      {/* Address */}
      {addressLine && (
        <div className="flex items-start gap-3">
          <Icon
            name="MapPin"
            size="md"
            color="muted"
            className="mt-0.5 shrink-0"
            aria-hidden={true}
          />
          <div className="min-w-0">
            <p className="text-text-muted text-xs font-medium">{t('address')}</p>
            <p className="text-text-primary text-base leading-snug" data-user-content>
              {addressLine}
            </p>
          </div>
        </div>
      )}

      {/* Today's hours */}
      <div className="flex items-start gap-3">
        <Icon name="Clock" size="md" color="muted" className="mt-0.5 shrink-0" aria-hidden={true} />
        <div className="min-w-0">
          <p className="text-text-muted text-xs font-medium">
            {t('today_hours')}
            {hours ? ` · ${weekdayLabel}` : ''}
          </p>
          <p
            className={cn(
              'text-base',
              hours?.closed ? 'text-text-muted' : 'text-text-primary font-medium',
            )}
          >
            {hoursLabel}
          </p>
        </div>
      </div>

      {/* Primary CTA — matches the buy-now button's size + full width */}
      <Button
        asChild
        variant="primary"
        size="lg"
        className="w-full"
        iconEnd={<Icon name="ChevronLeft" size="sm" aria-hidden={true} />}
      >
        <a href={businessHref}>{t('view_business_page')}</a>
      </Button>
    </aside>
  );
}
