import { getTemplateRenderingStrategy } from '@reddit/faceplate-ui/faceplateUIConfig.js';
import { nothing } from 'lit';
import { defaultClasses, defaultStyles, imageClasses, imageStyle, onClickAction, } from '../attributes.js';
import { blockTypeToString } from '../block-type.js';
import { isValidImageURL, sanitizeImageURL, VerifiedPublicImageHosts } from './imageUtil.js';
import { classMap, getSizes } from './util.js';
const FALLBACK_IMG_URL = 'https://i.redd.it/p1vmc5ulmpib1.png';
export function renderImageBlock(block, ctx) {
    const { html, styleMap, ifDefined } = getTemplateRenderingStrategy();
    if (!block.config?.imageConfig) {
        console.error('Invalid block: Image missing ImageConfig');
        return nothing;
    }
    const sizes = getSizes(block);
    const { width: imageWidth, height: imageHeight, url, description, resizeMode, } = block.config.imageConfig;
    // Sanitize only affects data URIs, so do this first
    let imageUrl = sanitizeImageURL(url.trim()) || FALLBACK_IMG_URL;
    if (!ctx.disableAssetSandbox) {
        if (!isValidImageURL(imageUrl)) {
            console.error(`Invalid image URL: Image URL domain must be one of ${VerifiedPublicImageHosts.join(', ')}.`);
            // Replace url with a fallback snoo
            imageUrl = FALLBACK_IMG_URL;
        }
    }
    const classes = {
        ...defaultClasses(block, ctx),
        ...imageClasses(resizeMode),
    };
    const styles = {
        ...imageStyle(imageUrl, resizeMode, imageWidth, imageHeight, sizes),
        ...defaultStyles(block, ctx),
    };
    const onClick = onClickAction(block, ctx);
    return html `
    <div
      aria-description="${description}"
      class="${classMap(classes)}"
      style="${styleMap(styles)}"
      @click="${ifDefined(onClick)}"
      data-block-type="${blockTypeToString(block.type)}"
    >
      <img
        src="${imageUrl}"
        class="w-100 h-100"
        style="display: none"
        @error="${{
        handleEvent: (event) => {
            console.error(`Error loading image:`, imageUrl);
            event.target.parentElement.style.backgroundImage = `url(${FALLBACK_IMG_URL})`;
        },
        once: true,
    }}"
      />
    </div>
  `;
}
//# sourceMappingURL=renderImageBlock.js.map