import type { ImagePayload } from "@/lib/api";

/**
 * One image, as a <picture> over pre-generated derivatives.
 *
 * This is the React translation of `<x-media-image>` and it deliberately does
 * NOT use next/image. The API hands over a srcset built from the backend's
 * ladder (config/images.php), generated from each file's *recorded* source
 * width so it never advertises a width the file cannot fill. Those files are
 * static and CDN-cacheable.
 *
 * Running them through next/image would re-encode already-optimised bytes at a
 * second quality setting, route static assets back through a Node process, and
 * replace an honest srcset with a generated one. The browser trusts width
 * descriptors; a lying descriptor paints blurry.
 *
 * `sources` is empty when the file is not a convertible image, or when
 * `media:optimise` has not reached it yet. One honest src beats a srcset whose
 * descriptors would be guesses, so the picture simply carries no sources and
 * the browser uses the img.
 */
export default function MediaImage({
  image,
  className,
  eager = false,
  alt,
}: {
  image: ImagePayload | null | undefined;
  className?: string;
  /** Only the LCP element. Anywhere else this competes with it for bandwidth. */
  eager?: boolean;
  /** Overrides the stored alt — for decorative uses that want an empty string. */
  alt?: string;
}) {
  if (!image?.src) {
    return null;
  }

  const sources = image.sources ?? {};

  return (
    <picture>
      {Object.entries(sources).map(([type, srcSet]) => (
        <source key={type} type={type} srcSet={srcSet} sizes={image.sizes} />
      ))}
      <img
        className={className}
        src={image.src}
        // An empty alt on a decorative image is correct; a missing alt
        // attribute never is. Always rendered.
        alt={alt ?? image.alt ?? ""}
        // Always present when known. These are what stop the page reflowing as
        // each image arrives, and CLS is part of the performance case for this
        // whole rebuild.
        {...(image.width ? { width: image.width } : {})}
        {...(image.height ? { height: image.height } : {})}
        loading={eager ? "eager" : "lazy"}
        decoding={eager ? "sync" : "async"}
        {...(eager ? { fetchPriority: "high" as const } : {})}
      />
    </picture>
  );
}
