<select name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>
{% for group_name, group_choices, group_index in widget.optgroups %}
  {% for option in group_choices %}
    {% include option.template_name with widget=option %}
  {% endfor %}
{% endfor %}
</select>
<button type="button" class="btn btn-sm btn-outline-secondary mt-1" data-bs-toggle="modal" data-bs-target="#addVariantModal">
  + Add variant
</button>

<div class="modal fade" id="addVariantModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Add Variant</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label for="newVariantName" class="form-label">Name</label>
          <input type="text" class="form-control" id="newVariantName" placeholder="e.g. Map A">
        </div>
        <div class="mb-3">
          <label for="newVariantDescription" class="form-label">Description (optional)</label>
          <input type="text" class="form-control" id="newVariantDescription">
        </div>
        <p class="text-danger d-none" id="variantError"></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="saveVariantBtn">Add</button>
      </div>
    </div>
  </div>
</div>

<script>
(function() {
  var select = document.getElementById('{{ widget.attrs.id }}');
  if (!select) return;

  var saveBtn = document.getElementById('saveVariantBtn');
  if (!saveBtn) return;

  var modalEl = document.getElementById('addVariantModal');
  var nameInput = document.getElementById('newVariantName');
  var descInput = document.getElementById('newVariantDescription');
  var errorEl = document.getElementById('variantError');

  saveBtn.addEventListener('click', function() {
    var name = nameInput.value.trim();
    if (!name) return;

    var boardGameId = select.getAttribute('data-board-game-id');
    var ajaxUrl = select.getAttribute('data-ajax-url');
    var csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
    if (!csrfToken) return;

    errorEl.classList.add('d-none');

    fetch(ajaxUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-CSRFToken': csrfToken.value,
      },
      body: new URLSearchParams({
        name: name,
        description: descInput.value.trim(),
        board_game_id: boardGameId,
      }),
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
      if (data.error) {
        errorEl.textContent = data.error;
        errorEl.classList.remove('d-none');
        return;
      }
      var opt = document.createElement('option');
      opt.value = data.id;
      opt.textContent = data.name;
      opt.selected = true;
      select.appendChild(opt);
      var modal = bootstrap.Modal.getInstance(modalEl);
      if (modal) modal.hide();
      nameInput.value = '';
      descInput.value = '';
    })
    .catch(function() {
      errorEl.textContent = 'Failed to create variant';
      errorEl.classList.remove('d-none');
    });
  });
})();
</script>
