{% load cache card_badge %}
<label for="{{ field_id }}" class="label">
  <span class="label-text">{{ label }}</span>
</label>
<select name="{{ field_name }}" id="{{ field_id }}" class="select select-bordered w-full card-multiselect" data-placeholder="{{ placeholder }}" multiple x-cloak>
  {% cache cache_timeout card_multiselect selected_values|join:"," %}
    <option value="" disabled>{{ placeholder }}</option>
    {% for card in cards %}
      <option 
        value="{{ card.pk }}"
        data-card-id="{{ card.pk }}"
        data-quantity="{{ card.selected_quantity }}"
        {% if card.selected %}selected{% endif %}
        data-html-content='{{ card|card_badge_inline:"__QUANTITY__" }}'
        data-name="{{ card.name }}"
        data-rarity="{{ card.rarity_icon }}"
        data-cardset="{{ card.cardset }}">
        {{ card.name }} {{ card.rarity_icon }} {{ card.cardset }}
      </option>
    {% endfor %}
  {% endcache %}
</select>

<script defer>
if (!window.updateGlobalCardFilters) {
  window.updateGlobalCardFilters = function() {
      console.log("updateGlobalCardFilters called.");
      const selects = document.querySelectorAll('.card-multiselect');

      // Rebuild global selections and rarity filtering.
      const globalSelectedIds = [];
      let globalRarity = null;

      selects.forEach(select => {
          const selectedValues = select.choicesInstance ? select.choicesInstance.getValue(true) : [];
          selectedValues.forEach(cardId => {
              if (cardId && globalSelectedIds.indexOf(cardId) === -1) {
                  globalSelectedIds.push(cardId);
              }
          });
          if (selectedValues.length > 0 && globalRarity === null) {
              const option = select.querySelector(`option[value="${selectedValues[0]}"]`);
              if (option) {
                  globalRarity = option.getAttribute('data-rarity');
              }
          }
      });

      console.log("Global selected card IDs:", globalSelectedIds, "Current Global rarity:", globalRarity);

      selects.forEach(select => {
        if (select.choicesInstance && select.choicesInstance.dropdown.element) {
            // Reset all options to enabled.
            select.querySelectorAll('option').forEach(function(option) {
                option.disabled = false;
            });
            // Reset all items to visible.
            select.choicesInstance.dropdown.element.querySelectorAll('[data-card-id]').forEach(function(item) {
                item.style.display = '';
            });
            // Filter out options/items that do not match the global rarity.
            if (globalRarity) {
              select.querySelectorAll('option[data-rarity]:not([data-rarity="'+globalRarity+'"])').forEach(function(option) {
                  option.disabled = true;
              });
              select.choicesInstance.dropdown.element.querySelectorAll('[data-rarity]:not([data-rarity="'+globalRarity+'"])').forEach(function(item) {
                  item.style.display = 'none';
              });
            }
            // Filter out options/items that match the global selected card IDs.
            for (const cardId of globalSelectedIds) {
                select.choicesInstance.dropdown.element.querySelectorAll('[data-card-id="' + cardId + '"]').forEach(function(item) {
                    item.style.display = 'none';
                });
                select.querySelectorAll('option[data-card-id="'+cardId+'"]:not(option[selected])').forEach(function(option) {
                    option.disabled = true;
                });
            }
        }
      });
  };
}

document.addEventListener('DOMContentLoaded', function() {
  console.log("DOM fully loaded. Initializing card multiselect for field '{{ field_id }}'");
  const selectField = document.getElementById('{{ field_id }}');
  const placeholder = selectField.getAttribute('data-placeholder') || '';

  const choicesInstance = new Choices(selectField, {
    removeItemButton: false,
    placeholderValue: placeholder,
    searchEnabled: true,
    shouldSort: false,
    allowHTML: true,
    closeDropdownOnSelect: true,
    removeItemButton: true,
    searchFields: ['label'],
    resetScrollPosition: false,
    callbackOnCreateTemplates: function(template) {
      const getCardContent = (data) => {
        let htmlContent = (data.element && data.element.getAttribute('data-html-content')) || data.label;
        let quantity = data.element.getAttribute('data-quantity');
        quantity = quantity ? parseInt(quantity) : 1;
        htmlContent = htmlContent.replace('__QUANTITY__', quantity);
        return htmlContent;
      };

      const renderCard = (classNames, data, type) => {
        const rarity = data.element ? data.element.getAttribute('data-rarity') : '';
        const cardId = data.element ? data.element.getAttribute('data-card-id') : 0;
        const cardname = data.element ? data.element.getAttribute('data-name') : '';
        const content = getCardContent(data);
        if (type === 'item') {
          return template(`
            <div class="${classNames.item} mx-auto w-max ${data.highlighted ? classNames.highlightedState : ''} relative"
              data-id="${data.id}"
              data-card-id="${cardId}"
              data-item
              data-rarity="${rarity}"
              data-name="${cardname}"
              aria-selected="true"
              style="cursor: pointer; padding: 1rem;">
              <button type="button" class="decrement absolute left-[-1.5rem] top-1/2 transform -translate-y-1/2 bg-base-300 text-base-content px-2">-</button>
              <button type="button" class="increment absolute right-[-1.5rem] top-1/2 transform -translate-y-1/2 bg-base-300 text-base-content px-2">+</button>
              <div class="card-content">${content}</div>
            </div>
          `);
        } else {
          const extraAttributes = `data-select-text="${this.config.itemSelectText}" data-choice ${
            data.disabled ? 'data-choice-disabled aria-disabled="true"' : 'data-choice-selectable'
          }`;
          const extraClasses = classNames.itemChoice;
          return template(`
            <div class="${classNames.item} ${extraClasses} ${data.highlighted ? classNames.highlightedState : ''} mx-auto w-max"
              ${extraAttributes}
              data-id="${data.id}"
              data-card-id="${cardId}"
              data-name="${cardname}"
              data-choice
              data-rarity="${rarity}"
              style="cursor: pointer;">
              ${content}
            </div>
          `);
        }
      };

      return {
        choice: function(classNames, data) {
          return renderCard(classNames, data, 'choice');
        },
        item: function(classNames, data) {
          return renderCard(classNames, data, 'item');
        }
      };
    }
  });

  console.log("Initialized Choices.js instance for field '{{ field_id }}':", choicesInstance);
  // Associate the Choices instance with the select field.
  selectField.choicesInstance = choicesInstance;

  if (!window.cardMultiselectInstances) {
    window.cardMultiselectInstances = [];
  }
  window.cardMultiselectInstances.push(selectField);

  selectField.addEventListener('change', function() {
    console.log("Select field changed. Current selected values:", selectField.choicesInstance.getValue(true));
    if (window.updateGlobalCardFilters) {
      window.updateGlobalCardFilters();
    }
  });

  // Listen for increment/decrement clicks (scoped to the choices container).
  const choicesContainer = selectField.closest('.choices') || document;

  choicesContainer.addEventListener('click', function(e) {
    if (e.target.classList.contains('increment')) {
      console.log("Increment button clicked.");
      e.preventDefault();
      e.stopPropagation();
      e.stopImmediatePropagation();
      const container = e.target.closest('[data-item]');
      if (container) {
        let quantityBadge = container.querySelector('.card-quantity-badge');
        let quantity = getOptionQuantity(container);
        console.log("Increment action on card", container.getAttribute('data-card-id'), "original quantity:", quantity, "new quantity:", quantity + 1);
        quantity = quantity + 1;
        quantityBadge.innerText = quantity;
        updateOptionQuantity(container, quantity);
      }
    }
    if (e.target.classList.contains('decrement')) {
      console.log("Decrement button clicked.");
      e.preventDefault();
      e.stopPropagation();
      e.stopImmediatePropagation();
      const container = e.target.closest('[data-item]');
      if (container) {
        let quantityBadge = container.querySelector('.card-quantity-badge');
        let quantity = getOptionQuantity(container);
        const cardId = container.getAttribute('data-card-id');
        if (quantity === 1) {
          console.log("Decrement action: quantity is 1 for card", cardId, "initiating removal.");
          const option = selectField.querySelector('option[value="' + cardId + '"]');
          if (option) {
              console.log("Removing card from Choices.js instance. Value removed:", option.value);
              choicesInstance.removeActiveItemsByValue(option.value);
              option.selected = false;
          } else {
            console.log("No active item found for card", cardId);
          }
          if (window.updateGlobalCardFilters) {
            window.updateGlobalCardFilters();
          }
        } else {
          console.log("Decrement action on card", cardId, "reducing quantity from", quantity, "to", quantity - 1);
          quantity = quantity - 1;
          quantityBadge.innerText = quantity;
          updateOptionQuantity(container, quantity);
        }
      }
    }
    if (e.target.closest('[data-item]') && 
        !e.target.classList.contains('increment') && 
        !e.target.classList.contains('decrement')) {
      e.stopPropagation();
      e.stopImmediatePropagation();
    }
  });

  function updateOptionQuantity(item, quantity) {
    const cardId = item.getAttribute('data-card-id');
    console.log("Updating option quantity for card", cardId, "to", quantity);
    const option = item.closest('.choices__inner').querySelector('option[value="' + cardId + '"]');
    if (option) {
      option.setAttribute('data-quantity', quantity);
      console.log("Updated data-quantity for card", cardId, "to", quantity);
    }
  }

  function getOptionQuantity(item) {
    const cardId = item.getAttribute('data-card-id');
    const option = item.closest('.choices__inner').querySelector('option[value="' + cardId + '"]');
    return option ? parseInt(option.getAttribute('data-quantity')) : 1;
  }

  if (choicesInstance.getValue(true).length > 0 && window.updateGlobalCardFilters) {
    window.updateGlobalCardFilters();
  }
});
</script>

<style>
  .choices.select {
    height: inherit;
    padding-inline-start: 0;
  }
  .choices__inner {
    border: 1px solid var(--color-gray-500) !important;
  }
  .choices__list {
    border: none !important;
  }
  .choices__list--dropdown {
    border-left: 1px solid var(--color-gray-500) !important;
    border-right: 1px solid var(--color-gray-500) !important;
    border-bottom: 1px solid var(--color-gray-500) !important;
    border-top: none !important;
  }
  .choices.select[data-type*="select-one"]::after {
    display: none;
  }
  .choices__inner.bg-secondary {
    background-color: var(--color-secondary);
    border: none;
    z-index: 10;
  }
  .choices__item.mx-auto.w-max:hover {
    background-color: #e2e8f0;
  }
  .choices__input,
  .choices__input--cloned {
    width: 100% !important;
  }
  .choices__list--dropdown span.card-quantity-badge {
    display: none;
  }
</style>