import type { JSX } from "solid-js";
import { onMount, splitProps } from "solid-js";
import type { AvatarImageProps } from "./avatar.props";
import { useAvatarContext } from "./avatar-context";

/** The image element. Probes load status and updates Avatar context on load/error. */
export function AvatarImage(props: AvatarImageProps): JSX.Element {
  const [local, rest] = splitProps(props, ["src", "alt"]);
  const context = useAvatarContext();

  onMount(() => {
    context.setImageLoadingStatus("loading");
    const img = new window.Image();
    img.src = local.src;
    img.onload = () => context.setImageLoadingStatus("loaded");
    img.onerror = () => context.setImageLoadingStatus("error");
  });

  return (
    <img
      data-scope="avatar"
      data-part="image"
      src={local.src}
      alt={local.alt}
      {...rest}
    />
  );
}
