import type { ProfileImage } from "@capila/contracts";

export const defaultProfileImageUrl = "/images/profile-default.png";

export function ProfileAvatar({
  image,
  displayName,
  className = "profile-image-avatar",
  priority = false,
}: {
  image: ProfileImage | null;
  displayName: string;
  className?: string;
  priority?: boolean;
}) {
  const initial = displayName.trim().slice(0, 1) || "؟";
  const imageUrl = image
    ? resolveProfileImageUrl(image.url)
    : defaultProfileImageUrl;
  return (
    <span className={className} aria-label={displayName}>
      <span aria-hidden="true">{initial}</span>
      {/* The API path is versioned; a native img also works for local/private hosts. */}
      <img
        src={imageUrl}
        alt=""
        loading={priority ? "eager" : "lazy"}
        decoding="async"
      />
    </span>
  );
}

export const resolveProfileImageUrl = (url: string) => {
  if (/^https?:\/\//i.test(url)) return url;
  const apiBase =
    process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:3001/api/v1";
  try {
    const origin = new URL(apiBase).origin;
    return new URL(url, `${origin}/`).toString();
  } catch {
    return url;
  }
};
