import { JSX, Show, splitProps } from "solid-js";

interface AvatarProps extends JSX.HTMLAttributes<HTMLDivElement> {
  src?: string;
  alt?: string;
  fallback?: string;
  size?: "xs" | "sm" | "md" | "lg" | "xl";
  variant?: "circle" | "rounded" | "square";
  status?: "online" | "offline" | "away" | "busy";
}

export function Avatar(props: AvatarProps) {
  const [local, rest] = splitProps(props, [
    "src",
    "alt",
    "fallback",
    "size",
    "variant",
    "status",
    "class",
  ]);

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

  const variantClasses = {
    circle: "rounded-full",
    rounded: "rounded-card",
    square: "rounded-lg",
  };

  const getInitials = () => {
    if (!local.fallback) return "?";
    return local.fallback
      .split(" ")
      .map((n) => n[0])
      .join("")
      .slice(0, 2)
      .toUpperCase();
  };

  const statusColors = {
    online: "bg-success",
    offline: "bg-ink-subtle",
    away: "bg-warning",
    busy: "bg-error",
  };

  const statusSizeClasses = {
    xs: "w-2 h-2",
    sm: "w-2.5 h-2.5",
    md: "w-3 h-3",
    lg: "w-3.5 h-3.5",
    xl: "w-4 h-4",
  };

  return (
    <div class="relative inline-flex" {...rest}>
      <div
        class={[
          "relative overflow-hidden bg-accent-subtle flex items-center justify-center",
          "font-display font-semibold text-accent",
          sizeClasses[local.size || "md"],
          variantClasses[local.variant || "circle"],
          local.class || "",
        ].join(" ")}
      >
        <Show
          when={local.src}
          fallback={
            <span class="select-none">{getInitials()}</span>
          }
        >
          <img
            src={local.src}
            alt={local.alt || local.fallback || "Avatar"}
            class="w-full h-full object-cover"
            loading="lazy"
          />
        </Show>
      </div>
      
      <Show when={local.status}>
        <span
          class={[
            "absolute -bottom-0.5 -right-0.5 rounded-full ring-2 ring-canvas",
            statusColors[local.status!],
            statusSizeClasses[local.size || "md"],
          ].join(" ")}
        />
      </Show>
    </div>
  );
}
