import { getInitials } from "@ax/helpers";

import * as S from "./style";

const AVATAR_COLORS = ["#7C9CDE", "#E07C7C", "#7CC8A0", "#C97CCC", "#D4A76A", "#6AB8C8", "#C8A86A", "#8E7CC8"];

const getAvatarColor = (name?: string): string => {
	if (!name) return AVATAR_COLORS[0];
	let hash = 0;
	const normalized = name.toLowerCase();
	for (let i = 0; i < normalized.length; i++) {
		hash = ((hash << 5) - hash) + normalized.charCodeAt(i);
		hash = hash & hash; // Convert to 32bit integer
	}
	return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
};

const Avatar = (props: IAvatarProps): JSX.Element => {
	const { image, name, size, fontSize, bold, background } = props;
	return (
		<S.AvatarWrapper data-testid="avatar-wrapper" size={size}>
			<S.Avatar
				image={image}
				initials={getInitials(name)}
				color={background ? getAvatarColor(name) : undefined}
				fontSize={fontSize}
				bold={bold}
				data-testid="avatar"
			/>
		</S.AvatarWrapper>
	);
};

export interface IAvatarProps {
	image?: string | null;
	name?: string;
	size?: number;
	fontSize?: number;
	background?: boolean;
	bold?: boolean;
}

export default Avatar;
