"use client";

import Image from "next/image";

/**
 * An image that fills a box the layout has already sized — a gallery tile, an
 * upload thumbnail, a map still.
 *
 * The companion to `RemoteImage`, for the other half of the problem. Where
 * `RemoteImage` is given the rendered pixel size and states it, these call
 * sites have no pixel size to state: the box is `aspect-square w-full` in a
 * responsive grid, or `w-20 h-20`, or `h-64` full-bleed. Inventing a
 * `width`/`height` pair for them would be a lie that happens to produce the
 * right aspect ratio, which is why they were left as bare `<img>` until now.
 *
 * `fill` is `next/image`'s answer to exactly that: no intrinsic size, the
 * element is absolutely positioned to its nearest **positioned ancestor**, and
 * the ancestor's own dimensions reserve the space. Two consequences every call
 * site has to honour, and which the conversions did:
 *
 *  - the ancestor needs `relative` (or another non-`static` position);
 *  - the ancestor needs a height that does not come from the image, so
 *    `aspect-*` / `h-*` moves from the image onto it.
 *
 * `object-cover` or `object-contain` is passed in `className`, as before —
 * `fill` alone would stretch.
 *
 * `sizes` is accepted but defaults to `100vw`. With `images.unoptimized: true`
 * (`next.config.ts`) no `srcset` is generated and the value is unused; it is
 * here so a call site can be honest about its box if optimisation is ever
 * switched on.
 */
export default function CoverImage({
  src,
  alt,
  className,
  sizes = "100vw",
  priority,
}: {
  src?: string | null;
  alt: string;
  className?: string;
  sizes?: string;
  priority?: boolean;
}) {
  /* `.trim()` rather than a bare `||`: a whitespace-only value is truthy and
     would reach `src="   "`, and `next/image` throws on an empty `src` where
     `<img>` merely drew a broken graphic. Same guard as `RemoteImage`. */
  const resolved = src?.trim() || "";
  if (!resolved) return null;

  return (
    <Image
      src={resolved}
      alt={alt}
      fill
      sizes={sizes}
      className={className}
      priority={priority}
      /* `alt=""` already hides a decorative image from the accessibility tree;
         `aria-hidden` is what the upload thumbnails set explicitly, kept so
         the behaviour is identical whichever call site a reviewer reads. */
      aria-hidden={alt === "" ? "true" : undefined}
      unoptimized
    />
  );
}
