import type { User } from "@/lib/types";
import clsx from "clsx";
import { KiEnergy } from "./KiEnergy";
import { AvatarDecoration, DECORATIONS, type DecorationId } from "./AvatarDecoration";

export function Avatar({
  user,
  size = 44,
  ring = false,
  effect = true,
}: {
  user: User;
  size?: number;
  ring?: boolean;
  /** Set false to opt out of the admin aura (e.g. inside dense lists). */
  effect?: boolean;
}) {
  const initials = user.name
    .split(" ")
    .map((p) => p[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

  const deco =
    effect && user.decoration && user.decoration in DECORATIONS ? (
      <AvatarDecoration id={user.decoration as DecorationId} size={size} />
    ) : null;

  const inner = (
    <div
      className={clsx(
        "rounded-full flex items-center justify-center shrink-0 font-semibold text-white select-none",
        ring && "p-[2px] bg-gradient-to-tr from-fuchsia-500 via-orange-400 to-amber-300"
      )}
      style={{ width: ring ? size + 4 : size, height: ring ? size + 4 : size }}
    >
      {user.avatarUrl ? (
        // eslint-disable-next-line @next/next/no-img-element -- local data-URL avatars, no need for next/image optimization here
        <img
          src={user.avatarUrl}
          alt={user.name}
          className={clsx(
            "rounded-full w-full h-full object-cover",
            ring && "ring-2 ring-white dark:ring-neutral-950"
          )}
        />
      ) : (
        <div
          className={clsx(
            "rounded-full flex items-center justify-center w-full h-full bg-gradient-to-br",
            user.avatarColor,
            ring && "ring-2 ring-white dark:ring-neutral-950"
          )}
          style={{ fontSize: size * 0.38 }}
        >
          {initials}
        </div>
      )}
    </div>
  );

  // Admins get the green storm; premium members get the cyan/gold frost.
  if (deco) {
    return (
      <span className="relative inline-block shrink-0" style={{ width: size, height: size }}>
        {inner}
        {deco}
      </span>
    );
  }

  if (effect && (user.admin || user.premium)) {
    return (
      <KiEnergy
        size={ring ? size + 4 : size}
        variant={user.admin ? "storm" : "frost"}
      >
        {inner}
      </KiEnergy>
    );
  }
  return inner;
}