import { z } from 'zod';
export const GradialImageSchema = z.object({
    $type: z.literal('gradial.image'),
    assetId: z.string().min(1),
    versionId: z.string().min(1),
    alt: z.string(),
    fallback: z.object({
        src: z.string().min(1),
        width: z.number().int().nonnegative(),
        height: z.number().int().nonnegative(),
        type: z.string().min(1),
    }),
    sources: z.array(z.object({
        media: z.string().optional(),
        type: z.string().min(1),
        srcset: z.string().min(1),
        sizes: z.string().optional(),
    })).nullable().default([]),
});
export function renderImageHTML(image, attrs = {}) {
    const imgAttrs = renderAttrs({
        ...attrs,
        src: image.fallback.src,
        alt: image.alt,
        width: image.fallback.width > 0 ? image.fallback.width : undefined,
        height: image.fallback.height > 0 ? image.fallback.height : undefined,
    });
    const img = `<img${imgAttrs}>`;
    if (!image.sources.length) {
        return img;
    }
    const sources = image.sources.map((source) => `<source${renderAttrs({
        media: source.media,
        type: source.type,
        srcset: source.srcset,
        sizes: source.sizes,
    })}>`).join('');
    return `<picture>${sources}${img}</picture>`;
}
function renderAttrs(attrs) {
    const rendered = Object.entries(attrs)
        .filter(([, value]) => value !== undefined && value !== null && value !== false)
        .map(([name, value]) => value === true ? escapeName(name) : `${escapeName(name)}="${escapeAttr(String(value))}"`);
    if (!rendered.length) {
        return '';
    }
    return ' ' + rendered.join(' ');
}
function escapeName(name) {
    return name.replace(/[^A-Za-z0-9_:-]/g, '');
}
function escapeAttr(value) {
    return value
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}
