// packages/core/src/components/image/image-img.tsx
import type { JSX } from "solid-js";
import { onMount, splitProps } from "solid-js";
import { useImageContext } from "./image-context";

export interface ImageImgProps extends JSX.ImgHTMLAttributes<HTMLImageElement> {
  /** Image source URL. */
  src?: string | undefined;
  /** Alternative text for the image. */
  alt?: string | undefined;
}

/**
 * The <img> element. Updates loading status context on load/error events.
 */
export function ImageImg(props: ImageImgProps): JSX.Element {
  const [local, rest] = splitProps(props, ["src", "alt"]);
  const ctx = useImageContext();

  onMount(() => {
    if (!local.src) {
      ctx.setLoadingStatus("error");
    }
  });

  const handleLoad = () => {
    ctx.setLoadingStatus("loaded");
  };

  const handleError = () => {
    ctx.setLoadingStatus("error");
  };

  return (
    <img
      src={local.src}
      alt={local.alt}
      data-state={ctx.loadingStatus()}
      onLoad={handleLoad}
      onError={handleError}
      {...rest}
    />
  );
}
