import { Avatar, type AvatarProps, type Theme } from '@mui/material'

export interface SeriesProps {
  /** Used for the avatar's first-letter glyph and as accessible label. */
  name: string
  /** Avatar background colour (any MUI palette path or CSS colour). */
  color?: string
  /** Diameter in px. Default `24`. */
  size?: number
  AvatarProps?: AvatarProps
}

/**
 * Series indicator — circular avatar showing the first letter of `name`.
 * Background colour is `color` (consumer-supplied) or a neutral disabled
 * colour, with text colour computed for contrast against it.
 */
export function Series({
  name,
  color,
  size = 24,
  AvatarProps: avatarProps,
}: SeriesProps) {
  const letter = name.charAt(0).toUpperCase()
  return (
    <Avatar
      aria-label={name}
      sx={{
        width: size,
        height: size,
        fontSize: size * 0.5,
        fontWeight: 600,
        bgcolor: color ?? 'action.disabledBackground',
        color: color
          ? (theme: Theme) =>
              theme.palette.getContrastText(toCssColor(theme, color))
          : 'text.primary',
      }}
      {...avatarProps}
    >
      {letter}
    </Avatar>
  )
}

/**
 * Resolve a palette path (e.g. `"primary.main"`) to a hex/rgb string so that
 * `getContrastText` — which doesn't accept dotted paths — produces a sensible
 * text colour. Non-palette strings (raw `#hex`, `rgb(...)`) pass through.
 */
function toCssColor(theme: Theme, value: string): string {
  if (!value.includes('.')) return value
  const parts = value.split('.')
  let cur: unknown = theme.palette
  for (const p of parts) {
    if (
      cur &&
      typeof cur === 'object' &&
      p in (cur as Record<string, unknown>)
    ) {
      cur = (cur as Record<string, unknown>)[p]
    } else {
      return value
    }
  }
  return typeof cur === 'string' ? cur : value
}
