// @design-system: domain/MerchantAvatar
// Registered at /design-system#merchantavatar-domain

import { cn } from '@/lib/cn';
import { buildVariantUrl } from '@/components/ui/primitives/Image/buildVariantUrl';
import { useT } from '@/lib/i18n/react';

/** Minimal merchant shape required by MerchantAvatar */
export interface MerchantAvatarMerchant {
  id: string;
  name: string;
  logoUrl?: string | null;
}

export interface MerchantAvatarProps {
  /** Merchant to display */
  merchant: MerchantAvatarMerchant;
  /** Size variant */
  size?: 'sm' | 'md' | 'lg';
  /**
   * When true renders an animated ring around the avatar indicating
   * active club status (used by club-stories module).
   */
  pulse?: boolean;
  /** When provided wraps the avatar in an anchor tag */
  href?: string;
  className?: string;
}

const sizeClasses: Record<NonNullable<MerchantAvatarProps['size']>, string> = {
  sm: 'size-8 text-xs',
  md: 'size-12 text-sm',
  lg: 'size-16 text-base',
};

const pulseRingClasses: Record<NonNullable<MerchantAvatarProps['size']>, string> = {
  sm: 'p-0.5',
  md: 'p-(--size-avatar-ring)',
  lg: 'p-1',
};

/**
 * MerchantAvatar — round logo avatar with optional club-pulse ring.
 * Used by club-stories, merchant-scroll, and MerchantCard.
 *
 * @example
 * <MerchantAvatar merchant={m} size="lg" pulse />
 * <MerchantAvatar merchant={m} size="md" href="/business/slug" />
 */
export function MerchantAvatar({
  merchant,
  size = 'md',
  pulse = false,
  href,
  className,
}: MerchantAvatarProps) {
  const t = useT('merchant_avatar');
  const altText = t('avatar_alt').replace('{{name}}', merchant.name);

  const inner = (
    <span
      className={cn(
        'inline-flex items-center justify-center overflow-hidden rounded-full',
        'bg-surface-subtle border-border-default border',
        sizeClasses[size],
        className,
      )}
    >
      {merchant.logoUrl ? (
        <img
          src={buildVariantUrl(merchant.logoUrl, 'thumb', 240) ?? merchant.logoUrl}
          alt={altText}
          width={64}
          height={64}
          className="h-full w-full object-cover"
          loading="lazy"
        />
      ) : (
        <span aria-label={altText} className="text-text-secondary font-semibold select-none">
          {merchant.name.charAt(0)}
        </span>
      )}
    </span>
  );

  const avatar = pulse ? (
    <span
      className={cn(
        'inline-flex rounded-full',
        'from-brand-primary-400 to-brand-primary-600 bg-gradient-to-br',
        pulseRingClasses[size],
        '@media (prefers-reduced-motion: no-preference) animate-[merchant-avatar-pulse_2s_ease-in-out_infinite]',
      )}
    >
      {inner}
    </span>
  ) : (
    inner
  );

  if (href) {
    return (
      <a
        href={href}
        className="focus-visible:outline-brand-primary-500 rounded-full focus-visible:outline-2 focus-visible:outline-offset-2"
      >
        {avatar}
      </a>
    );
  }

  return avatar;
}
