---
/**
 * Portable Text Image block component
 *
 * Renders image blocks from WordPress imports and EmDash media.
 * Uses the provider's getSrc function for responsive srcset generation.
 */
import type { ImageEmbed } from "../media/types.js";
import { getMediaProvider } from "../media/provider-loader.js";
// Standard responsive breakpoints
const BREAKPOINTS = [640, 750, 828, 960, 1080, 1280, 1600, 1920];

export interface Props {
	node: {
		_type: "image";
		_key: string;
		asset: {
			_ref: string;
			url?: string;
			/** Provider ID for external media (e.g., "cloudflare-images") */
			provider?: string;
			/** Provider metadata (blurhash, dominantColor, etc.) */
			meta?: Record<string, unknown>;
		};
		alt?: string;
		caption?: string;
		/** Original image width */
		width?: number;
		/** Original image height */
		height?: number;
		/** Display width for this instance (overrides original) */
		displayWidth?: number;
		/** Display height for this instance (overrides original) */
		displayHeight?: number;
	};
}

/**
 * Generate srcset using provider's getSrc function
 */
function generateSrcset(
	getSrc: NonNullable<ImageEmbed["getSrc"]>,
	maxWidth: number,
	aspectRatio?: number,
): string {
	return BREAKPOINTS.filter((w) => w <= maxWidth * 2)
		.map((w) => {
			const h = aspectRatio ? Math.round(w / aspectRatio) : undefined;
			return `${getSrc({ width: w, height: h })} ${w}w`;
		})
		.join(", ");
}

const { node } = Astro.props;

if (!node?.asset) {
	return null;
}

const { asset, alt = "", caption, width, height, displayWidth, displayHeight } = node;

// Calculate aspect ratio from original dimensions
const aspectRatio = width && height ? width / height : undefined;

// Calculate render dimensions
let renderWidth: number | undefined;
let renderHeight: number | undefined;

if (displayWidth && displayHeight) {
	renderWidth = displayWidth;
	renderHeight = displayHeight;
} else if (displayWidth && aspectRatio) {
	renderWidth = displayWidth;
	renderHeight = Math.round(displayWidth / aspectRatio);
} else if (displayHeight && aspectRatio) {
	renderWidth = Math.round(displayHeight * aspectRatio);
	renderHeight = displayHeight;
} else {
	renderWidth = width;
	renderHeight = height;
}

// Get the image source URL and srcset
let src = "";
let srcset: string | undefined;
let sizes: string | undefined;
const providerId = asset.provider;

if (providerId && providerId !== "local") {
	// External provider
	const provider = await getMediaProvider(providerId);
	if (provider) {
		try {
			const mediaValue = {
				provider: providerId,
				id: asset._ref,
				width: renderWidth,
				height: renderHeight,
				alt,
			};
			const result = provider.getEmbed(mediaValue, {
				width: renderWidth,
				height: renderHeight,
			});
			const embed = result instanceof Promise ? await result : result;
			if (embed.type === "image") {
				src = embed.src;

				// Generate srcset if provider supports dynamic sizing
				if (embed.getSrc) {
					const maxWidth = renderWidth || 1200;
					const ar = renderWidth && renderHeight ? renderWidth / renderHeight : aspectRatio;
					srcset = generateSrcset(embed.getSrc, maxWidth, ar);
					sizes = renderWidth
						? `(min-width: ${renderWidth}px) ${renderWidth}px, 100vw`
						: "100vw";
				}
			}
		} catch (error) {
			console.warn(`Failed to get embed for image ${asset._ref}:`, error);
		}
	}
}

// Fallback for local provider — prefer stored URL (includes storage key with extension),
// fall back to _ref (bare ULID, works if media file endpoint supports ID lookup)
if (!src) {
	src = asset.url || `/_emdash/api/media/file/${asset._ref}`;
}

// Build placeholder background style
const blurhash = asset.meta?.blurhash as string | undefined;
const dominantColor = asset.meta?.dominantColor as string | undefined;

let placeholderStyle = "";
if (blurhash) {
	const { blurhashToImageCssString } = await import("@unpic/placeholder");
	placeholderStyle = blurhashToImageCssString(blurhash);
} else if (dominantColor) {
	placeholderStyle = `background-color: ${dominantColor};`;
}

const baseStyle = aspectRatio
	? `aspect-ratio: ${aspectRatio}; max-width: 100%; height: auto;`
	: "max-width: 100%; height: auto;";
const imgStyle = placeholderStyle ? `${baseStyle} ${placeholderStyle}` : baseStyle;
---

<figure class="emdash-image">
	<img
		src={src}
		srcset={srcset}
		sizes={sizes}
		alt={alt}
		width={renderWidth}
		height={renderHeight}
		loading="lazy"
		decoding="async"
		style={imgStyle}
	/>
	{caption && <figcaption>{caption}</figcaption>}
</figure>

<style>
	.emdash-image {
		margin: 1.5rem 0;
	}
	.emdash-image img {
		max-width: 100%;
		height: auto;
	}
	.emdash-image figcaption {
		font-size: 0.875rem;
		color: #666;
		margin-top: 0.5rem;
		text-align: center;
	}
</style>
