{%- doc -%}
  Renders a swatch either from a variant image object or a swatch object.

  @param {object} swatch - a swatch object
  @param {object} [variant_image] - an alternate image when there is no swatch value
  @param {string} [mode] - one of 'unscaled', 'filter', 'pill'
  @param {string} [label] - visually-hidden accessible label for the swatch (e.g. the color name)

  @example
  {% render 'swatch', swatch: swatch, variant_image: variant_image, mode: 'unscaled', label: option_value.name %}
{%- enddoc -%}

{% liquid
  assign swatch_value = null
  assign extra_classes = ''
  if settings.show_variant_image and variant_image
    assign swatch_image_width = settings.variant_swatch_width | times: 2
    assign swatch_image_url = variant_image | image_url: width: swatch_image_width
    assign swatch_value = 'url(' | append: swatch_image_url | append: ')'
    assign extra_classes = extra_classes | append: ' swatch--variant-image'
  elsif swatch.image
    assign swatch_image_url = swatch.image | image_url: width: 80
    assign swatch_value = 'url(' | append: swatch_image_url | append: ')'
  elsif swatch.color
    assign swatch_value = 'rgb(' | append: swatch.color.rgb | append: ')'
  endif

  case mode
    when 'unscaled'
      assign extra_classes = extra_classes | append: ' swatch--unscaled'
    when 'filter'
      assign extra_classes = extra_classes | append: ' swatch--filter'
    when 'pill'
      assign extra_classes = extra_classes | append: ' swatch--pill'
  endcase
%}

<span
  class="
    swatch
    {{ extra_classes }}
    {% if swatch_value == null %} swatch--unavailable{% endif %}
  "
  style="
    --swatch-background: {{ swatch_value }};
    {% if swatch.image and settings.show_variant_image == false %} --swatch-focal-point: {{ swatch.image.presentation.focal_point }};{% endif %}
  "
>
</span>
{%- if label != blank -%}
  <span class="visually-hidden">{{ label }}</span>
{%- endif -%}
