{% doc %}
  Renders an image using the illustrative custom.localized_images JSON contract.
  @param {product} product - Product owning the mapping
  @param {media} media - Original image media
  @param {string} [image_class] - Theme image classes
  @param {string} [loading] - eager for the first visible image, otherwise lazy
{% enddoc %}
{%- liquid
  assign locale = localization.language.iso_code
  assign mappings = product.metafields.custom.localized_images.value
  assign position_key = media.position | append: ''
  assign replacement = nil
  assign image_loading = loading | default: 'lazy'
  unless localization.language.primary
    assign replacement = mappings[locale][position_key]
  endunless
  assign replacement_width = replacement.width | plus: 0
  assign replacement_height = replacement.height | plus: 0
-%}
{%- if media.media_type == 'image' -%}
  {%- if replacement.url != blank and replacement_width > 0 and replacement_height > 0 -%}
    <img
      src="{{ replacement.url | escape }}"
      alt="{{ replacement.alt | default: media.alt | escape }}"
      width="{{ replacement_width }}"
      height="{{ replacement_height }}"
      class="{{ image_class | escape }}"
      loading="{{ image_loading | escape }}"
    >
  {%- else -%}
    {{- media.preview_image | image_url: width: 2000 | image_tag: widths: '320, 640, 960, 1280, 1600, 2000', sizes: '(min-width: 990px) 50vw, 100vw', loading: image_loading, class: image_class, alt: media.alt -}}
  {%- endif -%}
{%- endif -%}
