"use client";

import { useMemo } from "react";
import { cn } from "@/lib/utils";

type AvatarProps = {
  username?: string | null;
  src?: string | null;
  size?: "sm" | "md" | "lg";
  className?: string;
};

const sizeClasses = {
  sm: "h-8 w-8 text-sm",
  md: "h-10 w-10 text-base",
  lg: "h-12 w-12 text-lg",
};

// Generate a consistent color based on username
const getAvatarColor = (username: string): string => {
  const colors = [
    "bg-blue-500",
    "bg-green-500",
    "bg-purple-500",
    "bg-orange-500",
    "bg-pink-500",
    "bg-teal-500",
    "bg-indigo-500",
    "bg-cyan-500",
  ];
  
  let hash = 0;
  for (let i = 0; i < username.length; i++) {
    hash = username.charCodeAt(i) + ((hash << 5) - hash);
  }
  
  return colors[Math.abs(hash) % colors.length];
};

const Avatar = ({ username, src, size = "md", className }: AvatarProps) => {
  const initial = useMemo(() => {
    if (!username) return "?";
    // Get the first character, handling unicode properly
    const firstChar = [...username][0];
    return firstChar?.toUpperCase() || "?";
  }, [username]);

  const bgColor = useMemo(() => {
    return username ? getAvatarColor(username) : "bg-slate-400";
  }, [username]);

  if (src) {
    return (
      <img
        src={src}
        alt={username || "Avatar"}
        className={cn(
          "rounded-full object-cover",
          sizeClasses[size],
          className
        )}
      />
    );
  }

  return (
    <div
      className={cn(
        "flex items-center justify-center rounded-full font-semibold text-white",
        sizeClasses[size],
        bgColor,
        className
      )}
      title={username || undefined}
    >
      {initial}
    </div>
  );
};

export default Avatar;
