---
// @design-system: primitives/Image
// Head-only fragment that emits `<link rel="preload" as="image">` tags
// for above-fold images so the browser starts fetching them in parallel
// with HTML parsing — kills first-paint image flash on cached SSR HTML.
//
// Mirrors the `<Image>` primitive's variant→srcSet/sizes pipeline so the
// preload matches the eventual `<img srcset>` request and the browser
// reuses the same fetch.

import { buildSrcSet, DEFAULT_IMAGE_SIZES, type PreloadImageEntry } from './buildVariantUrl';

const DEFAULT_SIZES = DEFAULT_IMAGE_SIZES;

interface Props {
  images: ReadonlyArray<PreloadImageEntry>;
}

const { images } = Astro.props as Props;
---

{
  images
    .filter((img) => img?.src)
    .map((img) => {
      const variant = img.variant ?? 'card';
      const srcset = buildSrcSet(img.src, variant);
      if (!srcset) return null;
      // Absolute URLs / public static paths skip the /api/img/ proxy and have
      // no `<url> <w>w` descriptors — preload them via `href` instead. Proxy
      // paths return a real comma-separated srcset → use `imagesrcset+imagesizes`.
      const isResponsive = srcset.includes(' ');
      if (isResponsive) {
        const sizes = img.sizes ?? DEFAULT_SIZES[variant];
        return (
          <link
            rel="preload"
            as="image"
            imagesrcset={srcset}
            imagesizes={sizes}
            fetchpriority={img.fetchpriority}
          />
        );
      }
      return <link rel="preload" as="image" href={srcset} fetchpriority={img.fetchpriority} />;
    })
}
