import React, { useEffect, useState } from "react";
import { avatarImageCandidates, placeholderAvatarUrl } from "../avatar";

/**
 * 用户头像：支持自选 URL（含 GIF 动图）、API 解析后的 avatarUrl、QQ 数字邮箱时的多 CDN 回退。
 * 圆角裁切做在外层容器上，避免部分浏览器在圆角 img 上只播 GIF 第一帧。
 */
export default function AvatarImg({
  user,
  placeholderSize = 120,
  alt = "avatar",
  className = "",
  previewable = false,
  onPreviewImage,
  previewLabel
}) {
  const chain = avatarImageCandidates(user, placeholderSize);
  const [idx, setIdx] = useState(0);
  const src = chain[Math.min(idx, chain.length - 1)] || placeholderAvatarUrl(placeholderSize);

  useEffect(() => {
    setIdx(0);
  }, [
    user?.account,
    user?.customAvatarUrl,
    user?.avatarUrl,
    user?.email,
    (user?.secondaryEmails || []).join(",")
  ]);

  const handleError = () => {
    if (idx < chain.length - 1) setIdx((i) => i + 1);
  };

  const handlePreview = () => {
    if (!onPreviewImage) return;
    const primary = chain[0] || "";
    onPreviewImage(primary, previewLabel || alt);
  };

  const shellClass = ["avatar-shell", className].filter(Boolean).join(" ");

  const previewProps = previewable
    ? {
        role: "button",
        tabIndex: 0,
        "aria-label": previewLabel || alt || "查看头像",
        onClick: handlePreview,
        onKeyDown: (e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            handlePreview();
          }
        }
      }
    : {};

  return (
    <span className={shellClass} {...previewProps}>
      <img
        src={src}
        alt={alt}
        className="avatar-img"
        onError={handleError}
        decoding="async"
        draggable={false}
      />
    </span>
  );
}
