"use client";

import { useEffect, useState, useSyncExternalStore } from "react";
import { getImageUrl, AVATAR_PLACEHOLDER_SVG } from "@/lib/imageUrl";

interface AvatarImageProps {
  src?: string | null;
  alt?: string;
  className?: string;
  initials?: string;
  fallback?: React.ReactNode;
}

const emptySubscribe = () => () => {};

export default function AvatarImage({
  src,
  alt = "",
  className = "h-full w-full object-cover",
  initials,
  fallback,
}: AvatarImageProps) {
  const mounted = useSyncExternalStore(
    emptySubscribe,
    () => true,
    () => false
  );
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    setHasError(false);
  }, [src]);

  // If not mounted yet (SSR / initial hydration), render fallback consistently to prevent hydration mismatch
  if (!mounted) {
    if (fallback) return <>{fallback}</>;
    if (initials) {
      return (
        <span className="flex h-full w-full items-center justify-center text-inherit font-semibold">
          {initials}
        </span>
      );
    }
    return (
      <span className="flex h-full w-full items-center justify-center text-inherit font-semibold">
        &nbsp;
      </span>
    );
  }

  const resolved = src ? getImageUrl(src) : null;

  if (!resolved || hasError) {
    if (fallback) return <>{fallback}</>;
    if (initials) {
      return (
        <span className="flex h-full w-full items-center justify-center text-inherit font-semibold">
          {initials}
        </span>
      );
    }
    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src={AVATAR_PLACEHOLDER_SVG}
        alt={alt}
        className={className}
      />
    );
  }

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={resolved}
      alt={alt}
      className={className}
      onError={() => setHasError(true)}
    />
  );
}
