"use client";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { cn } from "@/lib/utils";

export type UserStatus = "online" | "away" | "offline";

interface UserAvatarProps {
  photo?: string | null;
  name: string;
  size?: "sm" | "md" | "lg";
  status?: UserStatus;
  /** @deprecated use status instead */
  online?: boolean;
}

const sizeMap = {
  sm: "h-7 w-7 text-xs",
  md: "h-9 w-9 text-sm",
  lg: "h-11 w-11 text-base",
};

const dotSizeMap = {
  sm: "h-2.5 w-2.5",
  md: "h-3 w-3",
  lg: "h-3.5 w-3.5",
};

const statusColorMap: Record<UserStatus, string> = {
  online: "bg-green-500",
  away: "bg-yellow-400",
  offline: "bg-gray-500",
};

export function UserAvatar({ photo, name, size = "md", status, online }: UserAvatarProps) {
  // Resolve effective status (support legacy `online` prop)
  const effectiveStatus: UserStatus | undefined =
    status ?? (online === true ? "online" : online === false ? "offline" : undefined);

  return (
    <div className="relative inline-block shrink-0">
      <Avatar className={cn(sizeMap[size])}>
        {photo && <AvatarImage src={photo} alt={name} />}
        <AvatarFallback className="bg-muted text-muted-foreground">
          {name.charAt(0).toUpperCase()}
        </AvatarFallback>
      </Avatar>
      {effectiveStatus !== undefined && (
        <span
          className={cn(
            "absolute bottom-0 right-0 rounded-full border-2 border-background",
            dotSizeMap[size],
            statusColorMap[effectiveStatus]
          )}
        />
      )}
    </div>
  );
}
