"use client";

import Image from "next/image";
import type { CSSProperties } from "react";

import type { AvatarInteractionProps } from "./avatar-interaction";

interface CharacterAvatarVisualProps {
  src: string;
  alt: string;
  className?: string;
  size?: number | string;
  imageSize?: number;
  priority?: boolean;
}

export type CharacterAvatarProps = CharacterAvatarVisualProps &
  AvatarInteractionProps;

export function CharacterAvatar({
  src,
  alt,
  className,
  size = 43,
  imageSize,
  priority = false,
  onClick,
  actionLabel,
  analyticsKey,
}: CharacterAvatarProps) {
  const resolvedImageSize =
    imageSize ?? (typeof size === "number" ? size : 96);
  const style: CSSProperties = {
    width: size,
    height: size,
  };

  const avatarClassName = [
    "inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full border-0 bg-(--color-avatar-border,#fbf3f5)",
    onClick
      ? "cursor-pointer p-0 transition-transform duration-150 focus-visible:outline-3 focus-visible:outline-offset-3 focus-visible:outline-accent active:scale-96"
      : undefined,
    className,
  ]
    .filter(Boolean)
    .join(" ");
  const image = (
    <Image
      src={src}
      alt={alt}
      width={resolvedImageSize}
      height={resolvedImageSize}
      priority={priority}
      className="size-full object-cover"
    />
  );

  if (onClick) {
    return (
      <button
        type="button"
        className={avatarClassName}
        style={style}
        aria-label={actionLabel}
        data-analytics-key={analyticsKey}
        data-analytics-label={actionLabel}
        onClick={onClick}
      >
        {image}
      </button>
    );
  }

  return (
    <span className={avatarClassName} style={style}>
      {image}
    </span>
  );
}
