import styled, { css } from 'styled-components';
import React from 'react';

const extractInitials = (value: string): string => {
  const trimmed = value.trim();
  if (!trimmed) return '';

  if (trimmed.split('-').length > 1) {
    return trimmed
      .split('-')
      .filter((part) => part.length > 0)
      .map((part) => part[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  }

  const initials = trimmed.split(' ').map((n) => n[0]);
  if (initials.length === 1) {
    return initials[0];
  }

  return initials[0] + initials[initials.length - 1];
};

export function CatalogAvatar({
  value,
  size,
}: {
  value: string;
  size: 'small' | 'medium' | 'large';
}) {
  return (
    <CatalogAvatarWrapper data-component-name="Catalog/CatalogAvatar" size={size}>
      {extractInitials(value)}
    </CatalogAvatarWrapper>
  );
}

const CatalogAvatarWrapper = styled.div<{ size: 'small' | 'medium' | 'large' }>`
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: var(--catalog-avatar-bg-color);
  flex-shrink: 0;
  font-weight: var(--catalog-avatar-font-weight);
  line-height: var(--catalog-avatar-line-height);
  ${({ size }) => SIZES[size]};
`;

const SIZES = {
  small: css`
    width: var(--catalog-avatar-small-size);
    height: var(--catalog-avatar-small-size);
    font-size: var(--catalog-avatar-font-size-small);
  `,
  medium: css`
    width: var(--catalog-avatar-medium-size);
    height: var(--catalog-avatar-medium-size);
    font-size: var(--catalog-avatar-font-size-medium);
  `,
  large: css`
    width: var(--catalog-avatar-large-size);
    height: var(--catalog-avatar-large-size);
    font-size: var(--catalog-avatar-font-size-large);
  `,
};
