---
/**
 * Portable Text Gallery block component
 *
 * Renders image galleries from WordPress imports.
 * Uses Astro's Image component for optimization when dimensions are available.
 */
import { Image as AstroImage } from "astro:assets";
import { buildRenderMediaUrl } from "../media/url.js";

export interface Props {
	node: {
		_type: "gallery";
		_key: string;
		images: Array<{
			_type: "image";
			_key: string;
			asset: {
				_ref: string;
				url?: string;
			};
			alt?: string;
			caption?: string;
			width?: number;
			height?: number;
		}>;
		columns?: number;
	};
}

const { node } = Astro.props;
const images = node?.images ?? [];
const columns = node?.columns ?? 3;

if (!images.length) {
	return null;
}
---

<div class="emdash-gallery" style={`--columns: ${columns}`}>
	{
		images.map((image) => {
			const src = buildRenderMediaUrl(Astro.locals.emdash?.getPublicMediaUrl, {
				url: image.asset.url,
				id: image.asset._ref,
			});
			const hasSize = image.width && image.height;
			return (
				<figure class="emdash-gallery-item">
					{hasSize ? (
						<AstroImage
							src={src}
							alt={image.alt || ""}
							width={image.width!}
							height={image.height!}
							layout="constrained"
						/>
					) : (
						<img src={src} alt={image.alt || ""} loading="lazy" decoding="async" />
					)}
					{image.caption && <figcaption>{image.caption}</figcaption>}
				</figure>
			);
		})
	}
</div>

<style>
	.emdash-gallery {
		display: grid;
		grid-template-columns: repeat(var(--columns, 3), 1fr);
		gap: 1rem;
		margin: 1.5rem 0;
	}
	.emdash-gallery-item {
		margin: 0;
	}
	.emdash-gallery-item img {
		width: 100%;
		height: auto;
		object-fit: cover;
		aspect-ratio: 1;
	}
	.emdash-gallery-item figcaption {
		font-size: 0.75rem;
		color: var(--emdash-caption-color, var(--color-muted, #666));
		margin-top: 0.25rem;
		text-align: center;
	}
	@media (max-width: 640px) {
		.emdash-gallery {
			grid-template-columns: repeat(2, 1fr);
		}
	}
</style>
