"use client";

import Image from "next/image";
import { useState } from "react";
import { dispatchAppEvent } from "@/lib/events";

export function PlayerAvatar({
  name,
  size = 24,
  className = "",
  interactive = true,
}: {
  name: string;
  size?: number;
  className?: string;
  interactive?: boolean;
}) {
  const [failed, setFailed] = useState(false);
  const dim = `${size}px`;
  const initial = name.slice(0, 1).toUpperCase();

  const inner =
    failed || !name ? (
      <div
        className="rounded bg-muted text-muted-foreground shrink-0 flex items-center justify-center font-bold"
        style={{ width: dim, height: dim, fontSize: size * 0.5 }}
        aria-label={name}
      >
        {initial}
      </div>
    ) : (
      <Image
        src={`https://mc-heads.net/avatar/${encodeURIComponent(name)}/${size}`}
        alt=""
        width={size}
        height={size}
        unoptimized
        onError={() => setFailed(true)}
        className="rounded shrink-0 bg-muted"
      />
    );

  if (!interactive || !name) {
    return <span className={`inline-flex shrink-0 ${className}`}>{inner}</span>;
  }

  return (
    <button
      type="button"
      aria-label={`Open profile for ${name}`}
      onClick={(e) => {
        e.stopPropagation();
        dispatchAppEvent("player:open", { name });
      }}
      className={`inline-flex shrink-0 rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-ring hover:brightness-110 transition ${className}`}
    >
      {inner}
    </button>
  );
}
