import { useState } from 'react';
import type { HTMLAttributes } from 'react';
import { cx } from '../../utils/cx';
import './Avatar.css';

export type AvatarSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl';

export interface AvatarProps extends Omit<HTMLAttributes<HTMLSpanElement>, 'children'> {
  /** Image URL. Falls back to initials if it fails to load or is omitted. */
  src?: string;
  /** Person or entity name. Drives the initials and the accessible name. */
  name?: string;
  size?: AvatarSize;
  shape?: 'circle' | 'square';
}

/** Derives up to two initials: "Ada Lovelace" → "AL", "gokce" → "G". */
function initialsFrom(name: string): string {
  const words = name.trim().split(/\s+/).filter(Boolean);
  if (words.length === 0) return '';
  if (words.length === 1) return words[0]!.slice(0, 1).toUpperCase();
  return (words[0]!.slice(0, 1) + words[words.length - 1]!.slice(0, 1)).toUpperCase();
}

/** Small image or initials representing a person or entity. */
export function Avatar({
  src,
  name,
  size = 'md',
  shape = 'circle',
  className,
  ...rest
}: AvatarProps) {
  const [failed, setFailed] = useState(false);
  const showImage = src != null && src !== '' && !failed;
  const initials = name ? initialsFrom(name) : '';

  return (
    <span
      {...rest}
      className={cx('ds-avatar', `ds-avatar--${size}`, `ds-avatar--${shape}`, className)}
      role="img"
      aria-label={name || undefined}
    >
      {showImage ? (
        <img
          className="ds-avatar__image"
          src={src}
          alt=""
          onError={() => setFailed(true)}
        />
      ) : initials ? (
        <span className="ds-avatar__initials" aria-hidden="true">
          {initials}
        </span>
      ) : (
        <svg
          className="ds-avatar__placeholder"
          viewBox="0 0 24 24"
          fill="currentColor"
          aria-hidden="true"
        >
          <path d="M12 12a4.5 4.5 0 100-9 4.5 4.5 0 000 9zm0 1.8c-3.6 0-8 1.8-8 4.5V21h16v-2.7c0-2.7-4.4-4.5-8-4.5z" />
        </svg>
      )}
    </span>
  );
}
