{% load static %}
<dialog
  id="set_scenario_modal"
  class="modal"
  x-data="{
    isSubmitting: false,
    isLoading: false,
    loaded: false,
    scenarios: [],
    attachedScenarios: [{% for scen in current_object.scenarios.all %}'{{ scen.url }}'{% if not forloop.last %},{% endif %}{% endfor %}],

    reset() {
      this.isSubmitting = false;
    },

    async loadScenarios() {
      if (this.loaded) return;

      this.isLoading = true;
      try {
        const response = await fetch('{% url "package scenario list" meta.current_package.uuid %}', {
          headers: {
            'Accept': 'application/json'
          }
        });
        const data = await response.json();
        this.scenarios = data;
        this.loaded = true;
      } catch (error) {
        console.error('Error loading scenarios:', error);
      } finally {
        this.isLoading = false;
      }
    },

    isSelected(url) {
      return this.attachedScenarios.includes(url);
    },

    submit() {
      this.isSubmitting = true;
      const select = document.getElementById('scenario-select');
      if (select.selectedOptions.length === 0) {
        // Add hidden empty option to indicate clearing all scenarios
        const emptyOption = document.createElement('option');
        emptyOption.value = '';
        emptyOption.selected = true;
        select.appendChild(emptyOption);
      }
      document.getElementById('set_scenario_modal_form').submit();
    }
  }"
  @close="reset()"
  x-init="
        new MutationObserver(() => {
            if ($el.hasAttribute('open')) {
                loadScenarios();
            }
        }).observe($el, { attributes: true });
    "
>
  <div class="modal-box max-w-4xl">
    <!-- Header -->
    <h3 class="text-lg font-bold">
      Set Scenarios for {{ current_object.name|safe }}
    </h3>

    <!-- Close button (X) -->
    <form method="dialog">
      <button
        class="btn btn-sm btn-circle btn-ghost absolute top-2 right-2"
        :disabled="isSubmitting"
      >
        ✕
      </button>
    </form>

    <!-- Body -->
    <div class="py-4">
      <!-- Loading indicator -->
      <div x-show="isLoading" x-cloak class="mb-4 text-center">
        <span class="loading loading-spinner loading-lg"></span>
        <div class="alert alert-info mt-2">Loading Scenarios...</div>
      </div>

      <form
        id="set_scenario_modal_form"
        accept-charset="UTF-8"
        action="{{ current_object.url }}"
        data-remote="true"
        method="post"
        x-show="!isLoading"
      >
        {% csrf_token %}
        <div class="form-control">
          <label class="label" for="scenario-select">
            <span class="label-text">Scenarios</span>
          </label>
          <select
            id="scenario-select"
            name="selected-scenarios"
            class="select select-bordered h-48 w-full"
            multiple
          >
            <template x-for="scenario in scenarios" :key="scenario.url">
              <option
                :value="scenario.url"
                :selected="isSelected(scenario.url)"
                x-text="scenario.name"
              ></option>
            </template>
          </select>
          <label class="label">
            <span class="label-text-alt"
              >Hold Ctrl/Cmd to select multiple scenarios. Ctrl/Cmd + click one
              item to deselect it</span
            >
          </label>
        </div>
      </form>
    </div>

    <!-- Footer -->
    <div class="modal-action">
      <button
        type="button"
        class="btn"
        onclick="this.closest('dialog').close()"
        :disabled="isSubmitting"
      >
        Close
      </button>
      <button
        type="button"
        class="btn btn-primary"
        @click="submit()"
        :disabled="isSubmitting || isLoading"
      >
        <span x-show="!isSubmitting">Submit</span>
        <span
          x-show="isSubmitting"
          class="loading loading-spinner loading-sm"
        ></span>
        <span x-show="isSubmitting">Submitting...</span>
      </button>
    </div>
  </div>

  <!-- Backdrop -->
  <form method="dialog" class="modal-backdrop">
    <button :disabled="isSubmitting">close</button>
  </form>
</dialog>
