import { fileAssetUrl } from '@/business/files/api';
import { cn } from '@/lib/utils';

interface TenantLogoProps {
  readonly name?: string | null;
  readonly logoUrl?: string | null;
  readonly className?: string;
  readonly imageClassName?: string;
}

export function TenantLogo({
  name,
  logoUrl,
  className,
  imageClassName,
}: TenantLogoProps) {
  const label = name?.trim() || 'Tenant';
  return (
    <span
      className={cn(
        'inline-flex shrink-0 items-center justify-center overflow-hidden rounded-lg bg-gradient-to-br from-violet-500 to-indigo-600 text-xs font-bold text-white',
        className,
      )}
      aria-hidden="true"
    >
      {logoUrl ? (
        <img
          src={fileAssetUrl(logoUrl)}
          alt=""
          className={cn('h-full w-full object-cover', imageClassName)}
        />
      ) : (
        tenantInitials(label)
      )}
    </span>
  );
}

function tenantInitials(name: string): string {
  const words = name.trim().split(/\s+/).filter(Boolean);
  if (words.length === 0) {
    return '-';
  }
  if (words.length === 1) {
    return words[0].slice(0, 2).toUpperCase();
  }
  return `${words[0][0]}${words[words.length - 1][0]}`.toUpperCase();
}
