// Shared Avatar primitive — renders an image when `src` is set, otherwise
// falls back to deterministic colored initials. Used by the workspace
// switcher, members list, settings panels, and the bottom user pill in
// the sidebar.

const AV_PALETTE = [
  'oklch(0.55 0.16 35)',
  'oklch(0.55 0.16 75)',
  'oklch(0.50 0.16 145)',
  'oklch(0.52 0.18 200)',
  'oklch(0.52 0.18 265)',
  'oklch(0.50 0.18 305)',
];

function avatarBg(seed) {
  let h = 0;
  const s = String(seed || '');
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
  return AV_PALETTE[h % AV_PALETTE.length];
}

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

function Avatar({ src, name, seed, size = 32, radius = 8, fontSize, style, ...rest }) {
  const dim = { width: size, height: size, borderRadius: radius, flexShrink: 0 };
  const fs = fontSize ?? Math.max(10, Math.round(size * 0.42));
  if (src) {
    return (
      <img
        src={src}
        alt={name || ''}
        style={{ ...dim, objectFit: 'cover', display: 'block', ...style }}
        {...rest}
      />
    );
  }
  return (
    <div
      style={{
        ...dim,
        background: avatarBg(seed ?? name),
        color: 'white',
        display: 'grid',
        placeItems: 'center',
        fontWeight: 700,
        fontSize: fs,
        ...style,
      }}
      {...rest}
    >
      {avatarInitials(name)}
    </div>
  );
}

Object.assign(window, { Avatar, avatarBg, avatarInitials });
