'use client';
import { FunctionComponent, useMemo } from 'react';
import Avatar from '@mui/material/Avatar';

/** Number of `--bal-avatar-*` color pairs defined in tokens.css (both scheme blocks). */
const AVATAR_TOKEN_COUNT = 6;

// Two-letter initials from the first two whitespace-separated words; Persian names have no case,
// so this stays a plain substring pick (never .toUpperCase() on non-Latin scripts).
function initialsOf(name: string): string {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return '';
  const first = parts[0].charAt(0);
  const second = parts.length > 1 ? parts[1].charAt(0) : '';
  return `${first}${second}`;
}

// A stable (non-cryptographic) hash so the same name always lands on the same token pair,
// across reloads and between the E1 card and E2 record header.
function colorIndexOf(name: string): number {
  let hash = 0;
  for (let i = 0; i < name.length; i += 1) hash = (hash * 31 + name.charCodeAt(i)) >>> 0;
  return (hash % AVATAR_TOKEN_COUNT) + 1;
}

export interface InitialsAvatarProps {
  /** The person's display name — source of both the initials and the deterministic color. */
  name: string;
  size?: number;
}

/**
 * Warm auto-colored initials avatar — the identity face for a person with no photo (a care-circle
 * patient, the account holder). Deterministic per name (stable hash → one of 6 `--bal-avatar-*`
 * token pairs, both color-scheme blocks in `tokens.css`), so the same person always renders the
 * same color. Purely decorative next to a visible name, so it's hidden from assistive tech.
 * @component InitialsAvatar
 */
const InitialsAvatar: FunctionComponent<InitialsAvatarProps> = ({ name, size = 40 }) => {
  const index = useMemo(() => colorIndexOf(name), [name]);
  const initials = useMemo(() => initialsOf(name), [name]);

  return (
    <Avatar
      aria-hidden
      sx={{
        width: size,
        height: size,
        bgcolor: `var(--bal-avatar-${index})`,
        color: `var(--bal-avatar-${index}-contrast)`,
        fontWeight: 700,
        fontSize: size * 0.4,
      }}
    >
      {initials}
    </Avatar>
  );
};

export default InitialsAvatar;
