/**
 * Avatar colours, taken from the prototype's `P` map (Voxi.dc.html). The
 * design hard-codes one pair per named mock person; real users obviously
 * aren't in that map, so a stable hash of the user id picks a pair. Same
 * user always gets the same colour, and the set of colours on screen is
 * exactly the design's.
 */

export interface AvatarColor {
  bg: string;
  fg: string;
}

/** In the prototype's own order: Lisa, Zane, Matt, Sarah, Emily, Olivia. */
export const AVATAR_PALETTE: AvatarColor[] = [
  { bg: "#f6cdbb", fg: "#7c3c22" },
  { bg: "#cbe7d3", fg: "#2c5b3b" },
  { bg: "#ccd8f4", fg: "#283d6e" },
  { bg: "#e6d4f7", fg: "#4a2a73" },
  { bg: "#f7ddc8", fg: "#7a4a24" },
  { bg: "#d7d4f7", fg: "#3a3477" },
];

/** Fallback pair for an unnamed user — retinted from the prototype's purple
 * to the connectHUB accent so it matches the rest of the UI. */
export const AVATAR_FALLBACK: AvatarColor = { bg: "#e8f1fd", fg: "#1254ad" };

export function avatarColor(key: string | null | undefined): AvatarColor {
  if (!key) return AVATAR_FALLBACK;
  let hash = 0;
  for (let i = 0; i < key.length; i += 1) {
    hash = (hash * 31 + key.charCodeAt(i)) >>> 0;
  }
  return AVATAR_PALETTE[hash % AVATAR_PALETTE.length]!;
}

/** "Sarah Parker" → "SP", "sarah" → "SA" — the prototype's two-letter form. */
export function initials(name: string | null | undefined): string {
  const trimmed = (name ?? "").trim();
  if (!trimmed) return "?";
  const parts = trimmed.split(/\s+/);
  if (parts.length >= 2) return (parts[0]![0]! + parts[1]![0]!).toUpperCase();
  return trimmed.slice(0, 2).toUpperCase();
}
