"use client";

import { Avatar } from "@heroui/react";

export type AthenaAuthProfileAvatarProps = {
  name: string;
  avatarUrl?: string | null;
  className?: string;
};

function getInitials(name: string): string {
  const tokens = name
    .split(/\s+/)
    .map((token) => token.trim())
    .filter((token) => token.length > 0);
  if (tokens.length === 0) {
    return "?";
  }
  if (tokens.length === 1) {
    return tokens[0].slice(0, 1).toUpperCase();
  }
  return `${tokens[0].slice(0, 1)}${tokens[1].slice(0, 1)}`.toUpperCase();
}

export function AthenaAuthProfileAvatar({
  name,
  avatarUrl,
  className,
}: AthenaAuthProfileAvatarProps) {
  const initials = getInitials(name);
  const trimmedAvatarUrl = avatarUrl?.trim();

  return (
    <Avatar
      size="lg"
      color="accent"
      className={className ?? "ring-1 ring-slate-200"}
    >
      {trimmedAvatarUrl ? (
        <Avatar.Image alt={`${name} avatar`} src={trimmedAvatarUrl} />
      ) : null}
      <Avatar.Fallback delayMs={trimmedAvatarUrl ? 600 : undefined}>
        {initials}
      </Avatar.Fallback>
    </Avatar>
  );
}