{% set secondImage = null %}
{% set mediaElements = product.media.elements %}

{% if product.media|length > 0 %}
    {% set coverId = product.cover.media.id %}
    {% set sortedMedia = product.media.elements|sort((a, b) => a.position <=> b.position) %}

    {% for media in sortedMedia %}
        {% if media.media.id != coverId %}
            {% set secondImage = media.media %}
            {% break %}
        {% endif %}
    {% endfor %}
    
    {% if secondImage is null %}
        {% set secondImage = product.cover.media %}
    {% endif %}
{% else %}
    {% set secondImage = product.cover.media %}
{% endif %}

{% if secondImage %}
    {% set attributes = {
        class: 'product-image is-' ~ displayMode ~ ' is--hover',
        title: (cover.translated.title ?: name),
        alt: (cover.translated.title ?: name)
    } %}

    {% if displayMode == 'cover' or displayMode == 'contain' %}
        {% set attributes = attributes|merge({ 'data-object-fit': displayMode }) %}
    {% endif %}

    {% sw_thumbnails 'product-image-thumbnails' with {
        media: secondImage,
        sizes: sizes,
        attributes: attributes
    } %}
{% endif %}