import { PRESENCE_META, type Presence } from "@/lib/presence";

type Props = {
  name: string;
  src?: string | null;
  size?: number;
  square?: boolean;
  className?: string;
  status?: Presence | null;
};

function initials(name: string): string {
  return (
    name
      .trim()
      .split(/\s+/)
      .map((p) => p[0])
      .filter(Boolean)
      .slice(0, 2)
      .join("")
      .toUpperCase() || "?"
  );
}

/** Avatar: Bild falls vorhanden, sonst Initialen im Marken-Verlauf. */
export function Avatar({ name, src, size = 36, square = false, className, status }: Props) {
  const radius = square ? Math.round(size * 0.3) : 9999;
  const common = {
    width: size,
    height: size,
    borderRadius: radius,
  } as const;

  const inner = src ? (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={src}
      alt={name}
      className={status ? undefined : className}
      style={{
        ...common,
        objectFit: "cover",
        border: "1px solid var(--line)",
        flexShrink: 0,
        display: "block",
      }}
    />
  ) : (
    <span
      className={status ? undefined : className}
      aria-label={name}
      style={{
        ...common,
        display: "grid",
        placeItems: "center",
        flexShrink: 0,
        background: "var(--grad-brand)",
        color: "#0a0e22",
        fontWeight: 900,
        fontSize: size * 0.4,
        lineHeight: 1,
        boxShadow: "inset 0 1px 0 rgba(255,255,255,.2)",
      }}
    >
      {initials(name)}
    </span>
  );

  if (!status) return inner;

  const meta = PRESENCE_META[status];
  const dot = Math.max(10, Math.round(size * 0.3));
  const ring = Math.max(2, Math.round(size * 0.06));
  return (
    <span
      className={`avatar-wrap ${className ?? ""}`}
      style={{ width: size, height: size }}
      title={`${name} · ${meta.label}`}
    >
      {inner}
      <span
        className="presence-dot"
        style={{
          width: dot,
          height: dot,
          background: meta.color,
          boxShadow: `0 0 0 ${ring}px var(--bg2), 0 0 10px ${meta.color}`,
        }}
        aria-label={meta.label}
      />
    </span>
  );
}
