{% comment %}
  Renders product variant-picker
  Accepts:
  - product: {Object} product object.
  - block: {Object} passing the block information.
  - product_form_id: {String} Id of the product form to which the variant picker is associated.
  - update_url: {Boolean} whether or not to update url when changing variants. If false, the url isn't updated. Default: true (optional).
  Usage:
  {% render 'product-variant-picker', product: product, block: block, product_form_id: product_form_id %}
{% endcomment %}

{%- assign items_in_cart = cart.items | map: 'id' -%}
{%- assign unique_items_in_cart = items_in_cart | join: ',' | uniq -%}

{% for item in cart.items %}
  <input type="hidden" id="cart_items_id" value="{{ item.id }}" data-quantity="{{ item.quantity }}" data-title="{{ item.title }}">
{% endfor %}

{%- unless product.has_only_default_variant -%}
  {%- if block.settings.picker_type == 'button' -%}
    <variant-radios
      id="variant-radios-{{ section.id }}"
      class="no-js-hidden product_table"
      data-section="{{ section.id }}"
      data-url="{{ product.url }}"
      {% if update_url == false %}
        data-update-url="false"
      {% endif %}
      {{ block.shopify_attributes }}
    >

    {%- comment %}
      Find the selected collection that matches the product title.
    {%- endcomment %}
    {% for collection in collections %}
      {% assign collection_title_lower = collection.title | downcase %}
      {% assign product_title_lower = product.title | downcase %}
      {% if product_title_lower contains collection_title_lower %}
        {% assign selected_collection = collection %}
        {% break %}
      {% endif %}
    {% endfor %}

    {% if selected_collection %}
      {% assign metal_set = '' | split: ',' %}
      {% assign karat_set = '' | split: ',' %}
      {% assign metal_color_set = '' | split: ',' %}
      {% assign length_set = '' | split: ',' %}
      {% assign width_set = '' | split: ',' %}
      {% assign type_set = '' | split: ',' %}
      {% assign bracelet_length_set = '' | split: ',' %}
      {% assign necklace_length_set = '' | split: ',' %}
      {% assign anklet_length_set = '' | split: ',' %}

      {%- assign metal_color_images_array = '' -%}
      {%- assign metal_colors_processed = '' | split: ',' -%}
      {% for product2 in selected_collection.products %}
        {% for variant in product2.variants %}
          {% assign metal_option = variant.option3 %}
          {% if metal_option != '' %}
            {% assign karat = metal_option | remove: 'YG' | remove: 'RG' | remove: 'WG' %}
            {% if metal_option == '10K' or metal_option == '14K' or metal_option == '18K' or metal_option == '21K' or metal_option == '22K' %}
              {% assign metal_option = metal_option | append: 'YG' %}
              {% assign metal_color = 'YG' %}
            {% else %}
              {% assign metal_color = metal_option | remove: karat %}
            {% endif %}
            {% unless metal_colors_processed contains metal_color %}
              {% if variant.featured_image %}
                {% assign image_url = variant.featured_image.src | json %}
                {% assign metal_color_images_array = metal_color_images_array | append: '{"metal_color":"' | append: metal_color | append: '", "image_url":' | append: image_url | append: '},' %}
                {% assign metal_colors_processed = metal_colors_processed | append: metal_color %}
              {% endif %}
            {% endunless %}
          {% endif %}
        {% endfor %}
      {% endfor %}


      
      {%- comment %}
        Collect unique metals, lengths, widths, types, karats, and metal colors from the variants.
      {%- endcomment %}
      {% for product2 in selected_collection.products %}
        {% assign product_type = product2.metafields.custom.type.value %}
        {%- for variant in product2.variants %}
          {% assign metal_option = variant.option3 %}
          {% if metal_option != '' %}
            {% comment %} Extract karat and metal color {% endcomment %}
            {% assign karat = metal_option | remove: 'YG' | remove: 'RG' | remove: 'WG' %}
            {% if metal_option == '10K' or metal_option == '14K' or metal_option == '18K' or metal_option == '21K' or metal_option == '22K' %}
              {% assign metal_option = metal_option | append: 'YG' %}
              {% assign metal_color = 'YG' %}
            {% else %}
              {% assign metal_color = metal_option | remove: karat %}
            {% endif %}
            
            {% assign karat_set = karat_set | join: ',' | append: ',' | append: karat | split: ',' | uniq | sort %}
            {% assign metal_color_set = metal_color_set | join: ',' | append: ',' | append: metal_color | split: ',' | uniq | sort %}
            {% assign metal_set = metal_set | join: ',' | append: ',' | append: metal_option | split: ',' | uniq | sort %}
          {% endif %}

          {% assign length_option = variant.option1 %}
          {% if length_option != '' %}
            {% if product_type == 'Bracelet' %}
              {% assign bracelet_length_set = bracelet_length_set | join: ',' | append: ',' | append: length_option | split: ',' | uniq | sort %}
            {% elsif product_type == 'Anklet' %}
              {% assign anklet_length_set = anklet_length_set | join: ',' | append: ',' | append: length_option | split: ',' | uniq | sort %}
            {% elsif product_type == 'Necklace' %}
              {% assign necklace_length_set = necklace_length_set | join: ',' | append: ',' | append: length_option | split: ',' | uniq | sort %}
            {% endif %}
          {% endif %}

          {% assign width_option = variant.option2 %}
          {% if width_option != '' %}
            {% assign width_set = width_set | join: ',' | append: ',' | append: width_option | split: ',' | uniq %}
          {% endif %}
        {% endfor %}
      {% endfor %}

      {%- comment %}
        Build the variants map, including 'type' in the key.
      {%- endcomment %}
      {% assign variants_array = "" %}
      {% for product2 in selected_collection.products %}
        {% assign product_type = product2.metafields.custom.type.value %}
        {% for variant in product2.variants %}
          {% assign length_option = variant.option1 %}
          {% assign width_option = variant.option2 %}
          {% assign metal_option = variant.option3 %}
          {% if metal_option != '' %}
            {% assign karat = metal_option | remove: 'YG' | remove: 'RG' | remove: 'WG' %}
            {% if metal_option == '10K' or metal_option == '14K' or metal_option == '18K' or metal_option == '21K' or metal_option == '22K'  %}
                  {% assign metal_color =  "YG"  %}
            {% else %}
            {% assign metal_color = metal_option | remove: karat %}
            {% endif %}
          {% endif %}
          {% assign key = length_option | append: "_" | append: width_option | append: "_" | append: karat | append: "_" | append: metal_color %}
          {% capture value %}
            {
              "id": {{ variant.id }},
              "length": "{{ length_option }}",
              "width": "{{ width_option }}",
              "karat": "{{ karat }}",
              "metal_color": "{{ metal_color }}",
              "type": "{{ product_type }}",
              "weight": "{{ variant.metafields.custom.weight }}"
            }
          {% endcapture %}
          {% assign variant_json = '{ "key": "' | append: key | append: '", "value": ' | append: value | append: ' }' %}
          {% assign variants_array = variants_array | append: variant_json | append: "," %}
        {% endfor %}
      {% endfor %}
      {% assign variants_json = "[" | append: variants_array | append: "]" %}

      {%- comment %}
        Initialize the variantsMap JavaScript object.
      {%- endcomment %}
      <script>
        const variantsMap = {};
        const variantsArray = {{ variants_json | strip }};
        // Populate the variants map
        variantsArray.forEach(item => {
          variantsMap[item.key] = item.value;
        });
        // Output the variants map for debugging
        console.log('Variants Map:', variantsMap);
      </script>

      {%- comment %}
        Generate the karat option buttons.
      {%- endcomment %}
      <div  style="display: flex;" class="metals_whole">
              {% for karat_option in karat_set %}
          {% if karat_option != '' %}
      <div class="karat_options metal_options_sub" style="display: flex; justify-content: center; margin-top: 2%;">
            <button type="button" name="karat_option" value="{{ karat_option }}" class="karat_option_button buttonss button-karat-third{% if karat_option == '10K' %} selected{% endif %}">
              {{ karat_option }}
            </button>
      </div>
          {% endif %}
        {% endfor %}
      </div>
      {%- comment %}
        Generate the metal color option buttons.
      {%- endcomment %}
      {%- assign metal_color_order = 'YG,RG,WG' | split: ',' -%}
      <div  style="display: flex; margin-bottom: 1%; margin-top: 10px;" class="metals_whole">
        {% for metal_color_option in metal_color_order %}
     
      <div class="metal_color_options metal_options_sub_color" style="display: flex; justify-content: center; margin-top: 2%;">

            <button type="button" name="metal_color_option" value="{{ metal_color_option }}" class="metal_color_option_button buttonss button-metal-color-third{% if metal_color_option == 'YG' %} selected{% endif %}">
              {% if metal_color_option == 'YG' %}
              YELLOW
              {% elsif metal_color_option == 'RG' %}
              ROSE
              {% else %}
              WHITE
              {% endif %}
            </button>

      </div>
       
        {% endfor %}
      </div>
      {%- comment %}
        Generate separate tables for each type (Bracelet, Anklet, Necklace) and for each combination of karat and metal color.
      {%- endcomment %}
      {% assign types = 'Bracelet' %}
      {% assign types2 = 'Anklet,Necklace' | split: ',' %}

      {% for karat_option in karat_set %}
        {% if karat_option == '' %}
          {% continue %}
        {% endif %}
        {% for metal_color_option in metal_color_set %}
          {% if metal_color_option == '' %}
            {% continue %}
          {% endif %}
          {% assign metal_key = karat_option | append: metal_color_option %}
          {% for metal in metal_set %}
            {% if metal == '' %}
              {% continue %}
            {% endif %}
            {% if metal contains karat_option and metal contains metal_color_option %}
              {%- comment %}
                MOBILE VERSION
              {%- endcomment %}
              {%- assign is_mobile = true -%}
              {% if is_mobile %}
                {% for type in types %}
                  {% assign length_set_for_type = '' %}
                  {% if type == 'Bracelet' %}
                    {% assign length_set_for_type = bracelet_length_set %}
                  {% endif %}

                  {% if length_set_for_type != blank %}
                    <div class="product_table_main mobile karat-{{ karat_option }} metal-color-{{ metal_color_option }} {{ type }}" id="product-table-container-{{ karat_option }}-{{ metal_color_option }}-{{ type }}" style="display: none;">
                      <table class="table_style">
                        <thead>
                          <tr>
                            <th class="product_photo_header" style="border-bottom-color: white;"></th>
                            <th class="header_t_{{ type | slice:0,1 | downcase }}" colspan="{{ length_set_for_type.size }}" style="background-color: #A6A6A6;">{{ type | upcase }}</th>
                          </tr>
                          <tr class="length_table_text">
                            <th style="border-bottom: 1px solid black;"></th>
                            {% for length_option in length_set_for_type %}
                              {% if length_option == '' %}
                                {% continue %}
                              {% else %}
                                <th style="border-bottom: 1px solid black;">{{ length_option }}</th>
                              {% endif %}
                            {% endfor %}
                          </tr>
                        </thead>
                        <tbody>
                          {% for width_option in width_set %}
                            {% if width_option == '' %}
                              {% continue %}
                            {% else %}
                              <tr>
                                <th class="width_table_text" style="border-right: 1px solid black;">{{ width_option }}</th>
                                {% for length_option in length_set_for_type %}
                                  {% if length_option == '' %}
                                    {% continue %}
                                  {% else %}
                                    {% assign key = length_option | append: '_' | append: width_option | append: '_' | append: karat_option | append: '_' | append: metal_color_option %}
                                    <td class="table_body_input" id="variant-cell-{{ key }}">
                                      <!-- JavaScript code will populate this cell -->
                                      <script>
                                        if (variantsMap) {
                                          const key = "{{ key }}";
                                          const variant = variantsMap[key];
                                          const cell = document.getElementById("variant-cell-" + key);

                                          if (variant) {
                                            cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" ' +
                                              'data-variant-id="' + variant.id + '" ' +
                                              'data-length-option="' + variant.length + '" ' +
                                              'data-width-option="' + variant.width + '" ' +
                                              'data-karat="' + variant.karat + '" ' +
                                              'data-metal-color="' + variant.metal_color + '" ' +
                                              'data-type="' + variant.type + '" ' +
                                              'data-weight="' + variant.weight + '"' +
                                              (variant.weight === '' ? ' placeholder="N/A" disabled' : '') +
                                              '>';
                                          } else {
                                            cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" placeholder="N/A" disabled ' +
                                              'data-type="' + '{{ type }}' + '">';
                                          }
                                        }
                                      </script>
                                    </td>
                                  {% endif %}
                                {% endfor %}
                              </tr>
                            {% endif %}
                          {% endfor %}
                        </tbody>
                      </table>
                    </div>
                  {% endif %}
                {% endfor %}
                <div class="anklet_and_necklace_container mobile karat-{{ karat_option }} metal-color-{{ metal_color_option }}" style="gap: 4%; margin-top: 3%;">
                  {% for type in types2 %}
                    {% assign length_set_for_type = '' %}
                    {% if type == 'Anklet' %}
                      {% assign length_set_for_type = anklet_length_set %}
                    {% elsif type == 'Necklace' %}
                      {% assign length_set_for_type = necklace_length_set %}
                    {% endif %}

                    {% if length_set_for_type != blank %}
                      <div class="product_table_main mobile karat-{{ karat_option }} metal-color-{{ metal_color_option }} {{ type }}" id="product-table-container-{{ karat_option }}-{{ metal_color_option }}-{{ type }}" style="display: none;">
                        <table class="table_style">
                          <thead>
                            <tr>
                              <th class="product_photo_header" style="border-bottom-color: white;"></th>
                              <th class="header_t_{{ type | slice:0,1 | downcase }}" colspan="{{ length_set_for_type.size }}" style="background-color: #A6A6A6;">{{ type | upcase }}</th>
                            </tr>
                            <tr class="length_table_text">
                              <th style="border-bottom: 1px solid black;"></th>
                              {% for length_option in length_set_for_type %}
                                {% if length_option == '' %}
                                  {% continue %}
                                {% else %}
                                  <th style="border-bottom: 1px solid black;">{{ length_option }}</th>
                                {% endif %}
                              {% endfor %}
                            </tr>
                          </thead>
                          <tbody>
                            {% for width_option in width_set %}
                              {% if width_option == '' %}
                                {% continue %}
                              {% else %}
                                <tr>
                                  <th class="width_table_text" style="border-right: 1px solid black;">{{ width_option }}</th>
                                  {% for length_option in length_set_for_type %}
                                    {% if length_option == '' %}
                                      {% continue %}
                                    {% else %}
                                      {% assign key = length_option | append: '_' | append: width_option | append: '_' | append: karat_option | append: '_' | append: metal_color_option %}
                                      <td class="table_body_input" id="variant-cell-{{ key }}">
                                        <!-- JavaScript code will populate this cell -->
                                        <script>
                                          if (variantsMap) {
                                            const key = "{{ key }}";
                                            const variant = variantsMap[key];
                                            const cell = document.getElementById("variant-cell-" + key);

                                            if (variant) {
                                              cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" ' +
                                                'data-variant-id="' + variant.id + '" ' +
                                                'data-length-option="' + variant.length + '" ' +
                                                'data-width-option="' + variant.width + '" ' +
                                                'data-karat="' + variant.karat + '" ' +
                                                'data-metal-color="' + variant.metal_color + '" ' +
                                                'data-type="' + variant.type + '" ' +
                                                'data-weight="' + variant.weight + '"' +
                                                (variant.weight === '' ? ' placeholder="N/A" disabled' : '') +
                                                '>';
                                            } else {
                                              cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" placeholder="N/A" disabled ' +
                                                'data-type="' + '{{ type }}' + '">';
                                            }
                                          }
                                        </script>
                                      </td>
                                    {% endif %}
                                  {% endfor %}
                                </tr>
                              {% endif %}
                            {% endfor %}
                          </tbody>
                        </table>
                      </div>
                    {% endif %}
                  {% endfor %}
                </div>
              {% endif %}

              {%- comment %}
                DESKTOP VERSION
              {%- endcomment %}
              {%- assign is_mobile = false -%}
              {% unless is_mobile %}
                <div class="product_table_main desktop karat-{{ karat_option }} metal-color-{{ metal_color_option }}" id="product-table-container-{{ karat_option }}-{{ metal_color_option }}" style="display: none;">
                  <table>
                    <thead>
                      <tr>
                        <th rowspan="2" class="product_photo_header" style="border-bottom-color: white;"></th>
                        {% assign br_head =  bracelet_length_set.size | minus: 1 %}
                        <th class="header_t_b" colspan={{ br_head }} style="background-color: #A6A6A6; border-right: 2px solid black;">BRACELET</th>
                        {% if anklet_length_set != blank %}
                          <th class="header_t_b anklet" colspan="1" style="background-color: #A6A6A6; border-right: 2px solid black;">ANKLET</th>
                        {% endif %}
                        <th class="header_t_n" colspan="{{ necklace_length_set.size }}" style="background-color: #737373;">NECKLACE</th>
                      </tr>
                      <tr class="length_table_text">
                        {% for length_option in bracelet_length_set %}
                          {% if length_option == '' %}
                            {% continue  %}
                          {% else %}
                            <th style="border-bottom: 2px solid black;">{{ length_option }}</th>
                          {% endif %}
                        {% endfor %}
                        {% for length_option in anklet_length_set %}
                          {% if length_option == '' %}
                            {% continue %}
                          {% else %}
                            <th style="border-bottom: 2px solid black; border-right: 2px solid black;">{{ length_option }}</th>
                          {% endif %}
                        {% endfor %}
                        {% for length_option in necklace_length_set %}
                          {% if length_option == '' %}
                            {% continue %}
                          {% else %}
                            <th style="border-bottom: 2px solid black;">{{ length_option }}</th>
                          {% endif %}
                        {% endfor %}
                      </tr>
                    </thead>
                    <tbody>
                      {% for width_option in width_set %}
                        {% if width_option == '' %}
                          {% continue %}
                        {% else %}
                          <tr>
                            <th class="width_table_text" style="border-right: 2px solid black;">{{ width_option }}</th>
                            {%- comment %}
                              Bracelet length options
                            {%- endcomment %}
                            {% for length_option in bracelet_length_set %}
                              {% if length_option == '' %}
                                {% continue %}
                              {% else %}
                                {% assign key = length_option | append: '_' | append: width_option | append: '_' | append: karat_option | append: '_' | append: metal_color_option %}
                                <td class="table_body_input" id="variant-cell-desktop-{{ key }}">
                                  <!-- JavaScript code will populate this cell -->
                                  <script>
                                    if (variantsMap) {
                                      const key = "{{ key }}";
                                      const variant = variantsMap[key];
                                      const cell = document.getElementById("variant-cell-desktop-" + key);

                                      if (variant) {
                                        cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" ' +
                                          'data-variant-id="' + variant.id + '" ' +
                                          'data-length-option="' + variant.length + '" ' +
                                          'data-width-option="' + variant.width + '" ' +
                                          'data-karat="' + variant.karat + '" ' +
                                          'data-metal-color="' + variant.metal_color + '" ' +
                                          'data-type="' + variant.type + '" ' +
                                          'data-weight="' + variant.weight + '"' +
                                          (variant.weight === '' ? ' placeholder="N/A" disabled' : '') +
                                          '>';
                                      } else {
                                        cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" placeholder="N/A" disabled ' +
                                          'data-type="Bracelet">';
                                      }
                                    }
                                  </script>
                                </td>
                              {% endif %}
                            {% endfor %}
                            {%- comment %}
                              Anklet length options
                            {%- endcomment %}
                            {% for length_option in anklet_length_set %}
                              {% if length_option == '' %}
                                {% continue %}
                              {% else %}
                                {% assign key = length_option | append: '_' | append: width_option | append: '_' | append: karat_option | append: '_' | append: metal_color_option %}
                                <td class="table_body_input" id="variant-cell-desktop-{{ key }}">
                                  <!-- JavaScript code will populate this cell -->
                                  <script>
                                    if (variantsMap) {
                                      const key = "{{ key }}";
                                      const variant = variantsMap[key];
                                      const cell = document.getElementById("variant-cell-desktop-" + key);

                                      if (variant) {
                                        cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" ' +
                                          'data-variant-id="' + variant.id + '" ' +
                                          'data-length-option="' + variant.length + '" ' +
                                          'data-width-option="' + variant.width + '" ' +
                                          'data-karat="' + variant.karat + '" ' +
                                          'data-metal-color="' + variant.metal_color + '" ' +
                                          'data-type="' + variant.type + '" ' +
                                          'data-weight="' + variant.weight + '"' +
                                          (variant.weight === '' ? ' placeholder="N/A" disabled' : '') +
                                          '>';
                                      } else {
                                        cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" placeholder="N/A" disabled ' +
                                          'data-type="Anklet">';
                                      }
                                    }
                                  </script>
                                </td>
                              {% endif %}
                            {% endfor %}
                            {%- comment %}
                              Necklace length options
                            {%- endcomment %}
                            {% for length_option in necklace_length_set %}
                              {% if length_option == '' %}
                                {% continue %}
                              {% else %}
                                {% assign key = length_option | append: '_' | append: width_option | append: '_' | append: karat_option | append: '_' | append: metal_color_option %}
                                <td class="table_body_input" id="variant-cell-desktop-{{ key }}">
                                  <!-- JavaScript code will populate this cell -->
                                  <script>
                                    if (variantsMap) {
                                      const key = "{{ key }}";
                                      const variant = variantsMap[key];
                                      const cell = document.getElementById("variant-cell-desktop-" + key);

                                      if (variant) {
                                        cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" ' +
                                          'data-variant-id="' + variant.id + '" ' +
                                          'data-length-option="' + variant.length + '" ' +
                                          'data-width-option="' + variant.width + '" ' +
                                          'data-karat="' + variant.karat + '" ' +
                                          'data-metal-color="' + variant.metal_color + '" ' +
                                          'data-type="' + variant.type + '" ' +
                                          'data-weight="' + variant.weight + '"' +
                                          (variant.weight === '' ? ' placeholder="N/A" disabled' : '') +
                                          '>';
                                      } else {
                                        cell.innerHTML = '<input type="number" class="variant-quantity-input2" min="0" value="" placeholder="N/A" disabled ' +
                                          'data-type="Necklace">';
                                      }
                                    }
                                  </script>
                                </td>
                              {% endif %}
                            {% endfor %}
                          </tr>
                        {% endif %}
                      {% endfor %}
                    </tbody>
                  </table>
                </div>
              {% endunless %}

            {% endif %}
          {% endfor %}
        {% endfor %}
      {% endfor %}

      {%- comment %}
        Total weight displays for each karat and metal color combination.
      {%- endcomment %}
      <div class="product-button-container">
        <div class="product-button-weights" style="display: flex; flex-direction: row; margin-top: 5%; justify-content: space-between; align-items:center;">
          <!-- Code will add spans with product-table weights -->
          {% for karat_option in karat_set %}
              {% if karat_option != '' %}
            <div class="weights_container" style="display: flex; flex-direction: column;">

            <span style="font-weight: bold;">{{ karat_option }}</span>
          {% assign ordered_metal_colors = 'YG,RG,WG' | split: ',' %}
          
          {% for metal_color_option in ordered_metal_colors %}
            {% if metal_color_set contains metal_color_option %}
              {% assign metal_key = karat_option | append: metal_color_option %}
              <div id="{{ metal_key }}-total-weight" class="metalTextGram-{{ metal_key }}">
                <span>{{ metal_color_option | remove: karat_option }}:</span> 
                <span id="{{ metal_key }}-table_grams" style="font-weight: normal;"> 0 g</span>
              </div>
            {% endif %}
          {% endfor %}
              
            </div>
              {% else %}
              {% continue %}
              {% endif %}
          {% endfor %}
        </div>

            <div id="add-to-cart-button" class="product_table_add_to_card">
              <span style="color: black; font-size: 20px;">ADD TO CART</span>
            </div>
        
      </div>

      {%- comment %}
        JavaScript code to handle the tables and interactions.
      {%- endcomment %}
<script>
  const metalColorImagesArray = {{ '[' | append: metal_color_images_array | append: ']' | replace: ',]', ']' | strip }};
  const metalColorImages = {};
  console.log(metalColorImages);

  // Build the metalColorImages object
  metalColorImagesArray.forEach(function(item) {
    metalColorImages[item.metal_color] = item.image_url;
  });
  console.log('Metal Color Images:', metalColorImages);

  document.addEventListener("DOMContentLoaded", function() {
    let selectedKarat = '10K'; // Default value
    let selectedMetalColor = 'YG'; // Default value

    const karatOptionButtons = document.querySelectorAll('.karat_option_button');
    const metalColorOptionButtons = document.querySelectorAll('.metal_color_option_button');

  function updateTables() {
      const isMobile = window.matchMedia("(max-width: 768px)").matches;
    
      // Hide all tables first
      document.querySelectorAll('.product_table_main').forEach(function(table) {
        table.style.display = 'none';
      });
    
      // Hide all anklet_and_necklace_container elements
      document.querySelectorAll('.anklet_and_necklace_container').forEach(function(container) {
        container.style.display = 'none';
      });
    
      // Show tables and containers matching the selected karat and metal color
      const elementsToShow = document.querySelectorAll(`.karat-${selectedKarat}.metal-color-${selectedMetalColor}`);
    
      elementsToShow.forEach(function(element) {
        if (isMobile) {
          if (element.classList.contains('mobile')) {
            // If the element is an anklet_and_necklace_container, display it as flex
            if (element.classList.contains('anklet_and_necklace_container')) {
              element.style.display = 'flex';
            } else {
              element.style.display = 'block';
            }
          }
        } else {
          if (element.classList.contains('desktop')) {
            element.style.display = 'block';
          }
        }
      });
    }

      function updateProductImage() {
        const imageUrl = metalColorImages[selectedMetalColor];
        const mainProductImage = document.querySelector('.product__media.media.media--transparent img.image-magnify-none');
        if (mainProductImage && imageUrl) {
          mainProductImage.src = imageUrl;
          // Update srcset and other attributes if necessary
          mainProductImage.srcset = imageUrl;
          mainProductImage.setAttribute('data-src', imageUrl);
          mainProductImage.setAttribute('data-srcset', imageUrl);
        }
      }

    // Initialize selections
    karatOptionButtons.forEach(function(button) {
      if (button.value === selectedKarat) {
        button.classList.add('selected');
      } else {
        button.classList.remove('selected');
      }
    });

    metalColorOptionButtons.forEach(function(button) {
      if (button.value === selectedMetalColor) {
        button.classList.add('selected');
      } else {
        button.classList.remove('selected');
      }
    });

    // Update tables and image on page load
    updateTables();
    updateProductImage();
    window.addEventListener('resize', updateTables);

    // Event listeners for option buttons
    karatOptionButtons.forEach(function(button) {
      button.addEventListener('click', function() {
        karatOptionButtons.forEach(function(btn) {
          btn.classList.remove('selected');
        });
        button.classList.add('selected');
        selectedKarat = button.value;
        updateTables();
        // Optionally update image if needed
      });
    });

    metalColorOptionButtons.forEach(function(button) {
      button.addEventListener('click', function() {
        metalColorOptionButtons.forEach(function(btn) {
          btn.classList.remove('selected');
        });
        button.classList.add('selected');
        selectedMetalColor = button.value;
        updateTables();
        updateProductImage(); // Update image when metal color changes
      });
    });
  updateTables();
  window.addEventListener('resize', updateTables);


  
  // Function to update total sum for each metal option
    function updateTotalSum() {
      var metalTotalWeights = {}; // Keyed by metal combination (e.g., '10KYG')

      // Collect all the metalKeys from the total weight elements
      var totalWeightElements = document.querySelectorAll('[id$="-table_grams"]');
      totalWeightElements.forEach(function(element) {
        var metalKey = element.id.replace('-table_grams', '');
        metalTotalWeights[metalKey] = 0; // Initialize to zero
      });

      // Now sum up the weights
      document.querySelectorAll(".variant-quantity-input2").forEach(function(input) {
        var weight = parseFloat(input.getAttribute("data-weight"));
        var quantity = parseFloat(input.value) || 0;
        var karat = input.getAttribute("data-karat");
        var metalColor = input.getAttribute("data-metal-color");
        var metalKey = karat + metalColor;

        if (!isNaN(weight) && quantity > 0) {
          metalTotalWeights[metalKey] += weight * quantity;
        }
      });

      // Update the total weight display for each metal
      for (var metalKey in metalTotalWeights) {
        var totalWeightElement = document.getElementById(metalKey + "-table_grams");
        if (totalWeightElement) {
          totalWeightElement.textContent = ' ' + metalTotalWeights[metalKey].toFixed(2) + " g";
        }
      }
    }

  // Attach event listener to inputs
  document.addEventListener("input", function(event) {
    if (event.target.classList.contains("variant-quantity-input2")) {
      updateTotalSum();
    }
  });

  // Initialize total sum
  updateTotalSum();

});

    var tables = document.querySelectorAll('.product_table_main table');
  
tables.forEach(function (table) {
  var rows = table.querySelectorAll('tbody tr');
  rows.forEach(function (row, rowIndex) {
    var cells = row.querySelectorAll('td');
    cells.forEach(function (cell) {
      var inputType = cell.querySelector('input[data-type]');
      if (inputType && inputType.getAttribute('data-type') === 'Necklace'  && rowIndex % 2 === 1) {
        cell.style.backgroundColor = '#D9D9D9';
        inputType.style.backgroundColor = '#D9D9D9';
      }
      if (inputType && inputType.getAttribute('data-type') === 'Bracelet' && rowIndex % 2 === 1) {
        inputType.style.backgroundColor = '#EFEFEF';
      }
      if (inputType && inputType.getAttribute('data-type') === 'Anklet' && rowIndex % 2 === 1) {
        cell.style.backgroundColor = '#D9D9D9';
        inputType.style.backgroundColor = '#D9D9D9';
      }
    });
  });
});

     var bivalue;
    {% for loy in bracelet_length_set %}
      {% if forloop.last %}
        bivalue = "{{ loy }}";
      {% endif -%}
    {% endfor %}
    var inputSelector = document.querySelectorAll(".variant-quantity-input2");
    var lengthSelector = document.querySelectorAll("th")
        lengthSelector.forEach(function (length_selection) {
      var length = length_selection.textContent;
      if (length == bivalue) {
        length_selection.style.borderRight = "2px solid black";
      }
    });

    var tables = document.querySelectorAll('.product_table_main table');

  tables.forEach(function(table) {
    var rows = table.querySelectorAll('tbody tr');
    rows.forEach(function(row) {
      var cells = row.querySelectorAll('td');
      cells.forEach(function(cell) {
        var inputElement = cell.querySelector('input[data-type]');
        if (inputElement && inputElement.getAttribute('data-type') === 'Anklet') {
          // Add borders to the td element
          cell.style.borderLeft = '2px solid black';
          cell.style.borderRight = '2px solid black';
        }
      });
    });
  });

</script>

      {%- comment %}
        Style adjustments (hide all tables by default).
      {%- endcomment %}
      <style>
        /* Hide all tables by default */
        .product_table_main {
          display: none;
        }

        .buttonss.selected {
          /* Your selected button styles here */
          background-color: black; /* Example style */
          color: white;
        }
        .metal_color_option_button {
    position: relative;
    border: none;
    cursor: pointer;
    background-color: white;
    overflow: hidden; /* This prevents the pseudo-element from overflowing */
          color: black;
}
  .metal_color_option_button[value="YG"] {
    border: 1px solid rgb(231,204,116);
  }
    .metal_color_option_button[value="RG"] {
    border: 1px solid rgb(190,135,124);
  }
    .metal_color_option_button[value="WG"] {
     border: 1px solid rgb(174,174,174);
  }


  @media screen and (max-width: 769px) {
    .metal_color_option_button {
        width: 60px;
      font-size: 11px;
    }
    .karat_option_button {
      width: 60px;
      font-size: 11px;
    }
  }
    @media screen and (min-width: 769px) {
    .metal_color_option_button {
        width: 76px;
        height: 28px;
    }

  }
        .metal_color_option_button::before {
          content: "";
          position: absolute;
          inset: 0; /* Ensures it matches the button’s exact size */
          border-radius: inherit; /* Ensures it matches the button’s border radius, if any */
          box-sizing: border-box; /* Ensures padding doesn't affect size */
          z-index: -1;
      }
      
      /* Set gradients based on the value attribute */
      .metal_color_option_button[value="YG"]::before {
          background: radial-gradient(circle at 30% 30%, #ffd700, #ffcc33, #e6b800);
      }
      
      .metal_color_option_button[value="RG"]::before {
          background: radial-gradient(circle at 30% 30%, #b76e79, #d9938e, #f4c2c2);
      }
      
      .metal_color_option_button[value="WG"]::before {
          background: radial-gradient(circle at 30% 30%, #c0c0c0, #d9d9d9, #f2f2f2);
      }
      
      /* Set the background to the gradient when the button is selected */
      .metal_color_option_button.selected[value="YG"] {
          background: radial-gradient(circle at 30% 30%, #ffd700, #ffcc33, #e6b800);
          color: white; /* Adjust text color if needed */
      }
      
      .metal_color_option_button.selected[value="RG"] {
          background: radial-gradient(circle at 30% 30%, #b76e79, #d9938e, #f4c2c2);
          color: white; /* Adjust text color if needed */
      }
      
      .metal_color_option_button.selected[value="WG"] {
          background: radial-gradient(circle at 30% 30%, #c0c0c0, #d9d9d9, #f2f2f2);
          color: black; /* Adjust text color if needed */
      }
      </style>

    {% else %}
      <!-- No collection found --><div><p>NO COLLECTION FOUND!</p></div>
    {% endif %}

    </variant-radios>
  {%- else -%}
    <!-- Variant selects code if needed -->
  {%- endif -%}
{%- endunless -%}

<noscript class="product-form__noscript-wrapper-{{ section.id }}">
  <div class="product-form__input{% if product.has_only_default_variant %} hidden{% endif %}">
    <label class="form__label" for="Variants-{{ section.id }}">
      {{- 'products.product.product_variants' | t -}}
    </label>
    <div class="select">
      <select
        name="id"
        id="Variants-{{ section.id }}"
        class="select__select"
        form="{{ product_form_id }}"
      >
        {%- for variant in product.variants -%}
          <option
            {% if variant == product.selected_or_first_available_variant %}
              selected="selected"
            {% endif %}
            {% if variant.available == false %}
              disabled
            {% endif %}
            value="{{ variant.id }}"
          >
            {%- liquid
              echo variant.title
              echo variant.price | money | strip_html | prepend: ' - '
              if variant.available == false
                echo 'products.product.sold_out' | t | prepend: ' - '
              endif
              if variant.quantity_rule.increment > 1
                echo 'products.product.quantity.multiples_of' | t: quantity: variant.quantity_rule.increment | prepend: ' - '
              endif
              if variant.quantity_rule.min > 1
                echo 'products.product.quantity.minimum_of' | t: quantity: variant.quantity_rule.min | prepend: ' - '
              endif
              if variant.quantity_rule.max != null
                echo 'products.product.quantity.maximum_of' | t: quantity: variant.quantity_rule.max | prepend: ' - '
              endif
              # TODO: enable theme-check once `item_count_for_variant` is accepted as valid filter
              # theme-check-disable
              assign cart_quantity = cart | item_count_for_variant: variant.id
              # theme-check-enable
              if cart_quantity > 0
                echo 'products.product.quantity.in_cart_html' | t: quantity: cart_quantity | prepend: ' - '
              endif
            -%}
          </option>
        {%- endfor -%}
      </select>
      {% render 'icon-caret' %}
    </div>
  </div>
</noscript>