import { cx } from '@/site/lib/cx';
import type { Media } from '@/site/types';

type PictureProps = {
    media: Media;
    /**
     * Set it for an image on the first screen (usually the LCP element): it
     * is then fetched right away with high priority instead of lazily.
     * `'low'` is for a first-screen image that is decoration (a backdrop):
     * fetched right away as well, but behind everything the first paint
     * needs — the stylesheet, the fonts, the logo.
     */
    priority?: boolean | 'low';
    /**
     * How wide the picture is shown (the `sizes` attribute), so the browser
     * picks the right copy from the srcset. Defaults to the full width.
     */
    sizes?: string;
    /** `cover` fills the frame (default); `contain` shows the whole picture. */
    fit?: 'cover' | 'contain';
    className?: string;
};

/**
 * A photograph that fills its frame. The browser picks the best encoding it
 * supports (AVIF → WebP → JPEG/PNG); width and height reserve the space, so
 * nothing shifts while it loads.
 */
export function Picture({
    media,
    priority = false,
    sizes = '100vw',
    fit = 'cover',
    className,
}: PictureProps) {
    if (media.src === null) {
        return null;
    }

    return (
        // `contents`: the <img> is laid out as a direct child of the frame.
        <picture className="contents">
            {media.sources.map((source) => (
                <source
                    key={source.src}
                    srcSet={source.srcset ?? source.src}
                    sizes={source.srcset ? sizes : undefined}
                    type={source.type}
                />
            ))}
            <img
                src={media.src}
                srcSet={media.srcset ?? undefined}
                sizes={media.srcset ? sizes : undefined}
                alt={media.alt}
                width={media.width ?? undefined}
                height={media.height ?? undefined}
                loading={priority ? 'eager' : 'lazy'}
                fetchPriority={
                    priority === 'low' ? 'low' : priority ? 'high' : undefined
                }
                decoding="async"
                className={cx(
                    'size-full',
                    fit === 'cover' ? 'object-cover' : 'object-contain',
                    className,
                )}
            />
        </picture>
    );
}
