// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)

/**
 * Stable 2-letter avatar derived from the visitor handle. Industry convention
 * (Intercom / Front / Gorgias) — gives a scannable left-rail anchor without
 * needing real user identity.
 */

const PALETTE = [
  ['bg-emerald-500', 'text-white'],
  ['bg-violet-500', 'text-white'],
  ['bg-amber-500', 'text-white'],
  ['bg-cyan-500', 'text-white'],
  ['bg-rose-500', 'text-white'],
  ['bg-indigo-500', 'text-white'],
  ['bg-teal-500', 'text-white'],
] as const;

function hash(str: string): number {
  let h = 0;
  for (let i = 0; i < str.length; i++) {
    h = (h * 31 + str.charCodeAt(i)) >>> 0;
  }
  return h;
}

function initials(handle: string): string {
  const cleaned = handle.replace(/^(guest_|cust_)/i, '');
  return cleaned.slice(0, 2).toUpperCase();
}

export function VisitorAvatar({ handle, size = 'md' }: { handle: string; size?: 'sm' | 'md' | 'lg' }) {
  const [bg, fg] = PALETTE[hash(handle) % PALETTE.length];
  const sizing = size === 'sm' ? 'w-7 h-7 text-[10px]' : size === 'lg' ? 'w-12 h-12 text-base' : 'w-9 h-9 text-xs';
  return (
    <span
      className={`inline-flex items-center justify-center rounded-full font-semibold ${bg} ${fg} ${sizing}`}
      data-testid={`avatar-${handle}`}
      aria-hidden="true"
    >
      {initials(handle)}
    </span>
  );
}
