import type { ThreadsAccount } from "../../domain/types";

type Props = {
  account: Pick<ThreadsAccount, "display_name" | "username" | "avatar_color"> & {
    avatar_url?: string | null;
  };
  size?: "sm" | "md" | "lg";
  className?: string;
};

function initialsOf(account: Props["account"]): string {
  const name = (account.display_name || account.username || "?").trim();
  // 取顯示名最後一段中文／英文
  const parts = name.replace(/·/g, " ").split(/\s+/).filter(Boolean);
  const last = parts[parts.length - 1] || name;
  if (/[\u4e00-\u9fff]/.test(last)) return last.slice(0, 1);
  return last.slice(0, 2).toUpperCase();
}

export function AccountAvatar({ account, size = "md", className = "" }: Props) {
  const sizeClass = size === "lg" ? "hb-avatar--lg" : size === "sm" ? "hb-avatar--sm" : "";
  const url = account.avatar_url?.trim();

  if (url) {
    return (
      <img
        className={`hb-avatar hb-avatar--img ${sizeClass} ${className}`.trim()}
        src={url}
        alt=""
        width={size === "lg" ? 44 : size === "sm" ? 22 : 28}
        height={size === "lg" ? 44 : size === "sm" ? 22 : 28}
        loading="lazy"
        referrerPolicy="no-referrer"
      />
    );
  }

  return (
    <span
      className={`hb-avatar hb-avatar--initials ${sizeClass} ${className}`.trim()}
      style={{ background: account.avatar_color || "var(--hb-brand)" }}
      aria-hidden
    >
      {initialsOf(account)}
    </span>
  );
}

/** mock 頭像 URL（Dicebear 軟粉彩；接真後改 Threads profile picture） */
export function mockAvatarUrl(username: string): string {
  const seed = encodeURIComponent(username.replace(/^@/, "") || "harbor");
  // teal / mint / coral / peach / cream — 對齊 Pokémon 色系
  return `https://api.dicebear.com/9.x/thumbs/svg?seed=${seed}&backgroundColor=20b49c,69d4c5,b6f3e4,ff7b73,ffd5dc,ffdfbf`;
}
