"use client";

import { useState } from "react";
import { cn } from "@/shared/lib/utils";
import { displayInitials } from "@/shared/lib/user-display";

const PALETTE = [
  "from-sky-500 to-blue-600",
  "from-emerald-500 to-teal-600",
  "from-amber-500 to-orange-600",
  "from-rose-500 to-pink-600",
  "from-violet-500 to-purple-600",
  "from-cyan-500 to-sky-600",
];

function paletteFor(seed: string): string {
  let hash = 0;
  for (let i = 0; i < seed.length; i++) hash = (hash * 31 + seed.charCodeAt(i)) >>> 0;
  return PALETTE[hash % PALETTE.length];
}

interface PersonAvatarProps {
  name?: string | null;
  email?: string | null;
  initials?: string | null;
  avatarUrl?: string | null;
  size?: number;
  /** Small green dot, e.g. for the conversation owner being active. */
  online?: boolean;
  className?: string;
}

/** Photo when available, otherwise initials on a gradient derived from the name. */
export function PersonAvatar({ name, email, initials, avatarUrl, size = 36, online, className }: PersonAvatarProps) {
  const label = displayInitials({ name, email, initials });
  // Missing or deleted pictures fall back to initials.
  const [broken, setBroken] = useState(false);

  return (
    <span className={cn("relative inline-flex shrink-0", className)} style={{ width: size, height: size }}>
      {avatarUrl && !broken ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img src={avatarUrl} alt="" onError={() => setBroken(true)} className="h-full w-full rounded-full object-cover ring-1 ring-black/5" />
      ) : (
        <span
          className={cn(
            "flex h-full w-full items-center justify-center rounded-full bg-gradient-to-br font-semibold text-white",
            paletteFor(name || email || label),
          )}
          style={{ fontSize: Math.max(10, size * 0.38) }}
          aria-label={name ?? label}
        >
          {label}
        </span>
      )}
      {online && (
        <span className="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full border-2 border-card bg-emerald-500" />
      )}
    </span>
  );
}
