import { cn } from '@ump/shared';

// A deterministic palette so the same person keeps the same colour across the page.
const COLORS = [
  'bg-rose-500',
  'bg-orange-500',
  'bg-amber-500',
  'bg-emerald-500',
  'bg-teal-500',
  'bg-sky-500',
  'bg-indigo-500',
  'bg-fuchsia-500',
];

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

function colorFor(seed: string): string {
  let hash = 0;
  for (let i = 0; i < seed.length; i += 1) hash = (hash * 31 + seed.charCodeAt(i)) | 0;
  return COLORS[Math.abs(hash) % COLORS.length];
}

/** A small initials chip standing in for a user avatar (assignee column + sidebar header). */
export function InitialsAvatar({
  name,
  seed,
  className,
}: {
  name: string;
  /** Stable colour key — pass a user id so renames don't change the colour. */
  seed?: string;
  className?: string;
}) {
  return (
    <span
      className={cn(
        'inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold text-white',
        colorFor(seed ?? name),
        className,
      )}
      aria-hidden
    >
      {initials(name)}
    </span>
  );
}
