const avatarColors: string[] = [
    "#FF5733", // Vivid Orange
    "#48ac2a", // Leaf Green
    "#0050eb", // Bright Blue
    "#FF33A1", // Hot Pink
    "#FF8C33", // Sunset Orange
    "#8C33FF", // Violet Purple
    "#FF3333", // Fiery Red
    "#43c06d", // Emerald Green
    "#A133FF", // Royal Purple
    "#C70039", // Crimson Red
    "#900C3F", // Deep Burgundy
    "#581845", // Plum Purple
    "#3859AD", // Steel Blue
    "#08873E", // Forest Green
    "#E74C3C", // Cherry Red
    "#00adff", // Sky Blue
    "#DBAD05", // Golden Yellow
    "#A13E31", // Brick Red
    "#94C40E", // Lime Green
    "#060C47", // Midnight Blue
    "#2FAFAF", // Teal
];

export function getAvatarColor(index: number, name?: string): string {
    // Check if the color is already stored in localStorage
    const localStorageKey = "userAvatarColors";
    // Check if local storage is available
    if (name) {
        let userColors = JSON.parse(localStorage.getItem(localStorageKey) ?? "{}");

        // Check if the user already has an assigned color
        if (userColors[name]) {
            return userColors[name];
        }

        // Find a new color not already assigned
        const usedColors = Object.values(userColors);
        const availableColors = avatarColors.filter(color => !usedColors.includes(color));

        // Assign a new color
        const assignedColor = availableColors.length > 0
            ? availableColors[0]
            : avatarColors[index % avatarColors.length];

        userColors[name] = assignedColor;

        // Save back to local storage
        localStorage.setItem(localStorageKey, JSON.stringify(userColors));

        return assignedColor;
    }

    // Fallback: Assign a color using the index if no name or local storage is unavailable
    return avatarColors[index % avatarColors.length];
}
