<form id="llm-import-confirm-form" method="post" hx-post="{% url 'sbas:import_llm_confirm' %}" hx-target="#import-result" hx-swap="innerHTML">
  {% csrf_token %}
  <input type="hidden" name="session_key" value="{{ session_key }}">
  {% for item in items %}
    <div class="card mb-2" id="import-item-{{ item.index }}">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-start">
          <h5 class="card-title mb-0">Question {{ item.index|add:1 }}</h5>
          <div>
            <button type="button" class="btn btn-sm btn-outline-secondary ms-2" data-item-index="{{ item.index }}" onclick="toggleEdit(this)">Edit</button>
          </div>
        </div>
        {% if item.errors %}
          <div class="alert alert-danger" role="alert">
            <strong>Validation errors:</strong>
            <ul class="mb-0">
              {% for err in item.errors %}
                <li>{{ err }}</li>
              {% endfor %}
            </ul>
          </div>
        {% endif %}
        {% if item.dropped_fields %}
          <div class="alert alert-info" role="alert">
            <strong>Note:</strong> The following unsupported fields were dropped: <em>{{ item.dropped_fields|join:", " }}</em>
          </div>
        {% endif %}
        {% if item.stripped_fields %}
          <div class="alert alert-info" role="alert">
            <strong>Note:</strong> Numeric references were removed from fields: <em>{{ item.stripped_fields|join:", " }}</em>
          </div>
        {% endif %}
        <div class="mb-2">
          <label class="form-label"><strong>Title</strong></label>
          <input class="form-control form-control-sm" name="payload_{{ item.index }}_title" value="{{ item.payload.title|default_if_none:'' }}" disabled>
        </div>
        <div class="mb-2">
          <label class="form-label"><strong>Stem</strong></label>
          <textarea class="form-control form-control-sm" name="payload_{{ item.index }}_stem" rows="3" disabled>{{ item.payload.stem|default_if_none:'' }}</textarea>
        </div>
        <div class="mb-2">
          <label class="form-label"><strong>Answers</strong></label>
          <div class="mb-1">
            <label class="form-label small">A</label>
            <input class="form-control form-control-sm" name="payload_{{ item.index }}_a_answer" value="{{ item.payload.a_answer|default_if_none:'' }}" disabled>
            <label class="form-label small mt-1">A Feedback</label>
            <textarea class="form-control form-control-sm" name="payload_{{ item.index }}_a_feedback" rows="2" disabled>{{ item.payload.a_feedback|default_if_none:'' }}</textarea>
          </div>
          <div class="mb-1">
            <label class="form-label small">B</label>
            <input class="form-control form-control-sm" name="payload_{{ item.index }}_b_answer" value="{{ item.payload.b_answer|default_if_none:'' }}" disabled>
            <label class="form-label small mt-1">B Feedback</label>
            <textarea class="form-control form-control-sm" name="payload_{{ item.index }}_b_feedback" rows="2" disabled>{{ item.payload.b_feedback|default_if_none:'' }}</textarea>
          </div>
          <div class="mb-1">
            <label class="form-label small">C</label>
            <input class="form-control form-control-sm" name="payload_{{ item.index }}_c_answer" value="{{ item.payload.c_answer|default_if_none:'' }}" disabled>
            <label class="form-label small mt-1">C Feedback</label>
            <textarea class="form-control form-control-sm" name="payload_{{ item.index }}_c_feedback" rows="2" disabled>{{ item.payload.c_feedback|default_if_none:'' }}</textarea>
          </div>
          <div class="mb-1">
            <label class="form-label small">D</label>
            <input class="form-control form-control-sm" name="payload_{{ item.index }}_d_answer" value="{{ item.payload.d_answer|default_if_none:'' }}" disabled>
            <label class="form-label small mt-1">D Feedback</label>
            <textarea class="form-control form-control-sm" name="payload_{{ item.index }}_d_feedback" rows="2" disabled>{{ item.payload.d_feedback|default_if_none:'' }}</textarea>
          </div>
          <div class="mb-1">
            <label class="form-label small">E</label>
            <input class="form-control form-control-sm" name="payload_{{ item.index }}_e_answer" value="{{ item.payload.e_answer|default_if_none:'' }}" disabled>
            <label class="form-label small mt-1">E Feedback</label>
            <textarea class="form-control form-control-sm" name="payload_{{ item.index }}_e_feedback" rows="2" disabled>{{ item.payload.e_feedback|default_if_none:'' }}</textarea>
          </div>
          <div class="mb-1">
            <label class="form-label small">Best Answer</label>
            <input class="form-control form-control-sm" name="payload_{{ item.index }}_best_answer" value="{{ item.payload.best_answer|default_if_none:'' }}" disabled>
          </div>
          <div class="mb-1">
            <label class="form-label small">Feedback</label>
            <textarea class="form-control form-control-sm" name="payload_{{ item.index }}_feedback" rows="2" disabled>{{ item.payload.feedback|default_if_none:'' }}</textarea>
          </div>
          <div class="mb-1 small text-muted">Sources: {% if item.payload.sources %}{{ item.payload.sources|join:", " }}{% else %}None{% endif %}</div>
          <p><strong>M2M fields (click to exclude)</strong></p>
          <p class="small text-muted">Green = will be created/attached. Click a value to exclude it (grey).</p>
          <div class="mb-2">
          <!-- Finding -->
            <div class="m2m-group" data-model="Finding"><strong>Finding:</strong>
              {% if item.resolved_m2m.finding %}
                {% for val in item.resolved_m2m.finding %}
                  <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Finding" data-value="{{ val }}">{{ val }}</button>
                {% endfor %}
              {% endif %}
              {% if item.missing_map.finding %}
                {% for val in item.missing_map.finding %}
                  <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Finding" data-value="{{ val }}">{{ val }}</button>
                {% endfor %}
              {% endif %}
              <span class="text-muted m2m-none" style="display:none">(none)</span>
              {% if item.missing_map.finding %}
                <div class="small text-info">Would create: {{ item.missing_map.finding|join:", " }}</div>
              {% endif %}
            </div>
          </div>

          <!-- Structure -->
          <div class="m2m-group" data-model="Structure"><strong>Structure:</strong>
            {% if item.resolved_m2m.structure %}
              {% for val in item.resolved_m2m.structure %}
                <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Structure" data-value="{{ val }}">{{ val }}</button>
              {% endfor %}
            {% endif %}
            {% if item.missing_map.structure %}
              {% for val in item.missing_map.structure %}
                <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Structure" data-value="{{ val }}">{{ val }}</button>
              {% endfor %}
            {% endif %}
            <span class="text-muted m2m-none" style="display:none">(none)</span>
            {% if item.missing_map.structure %}
              <div class="small text-info">Would create: {{ item.missing_map.structure|join:", " }}</div>
            {% endif %}
          </div>

          <!-- Condition -->
          <div class="m2m-group" data-model="Condition"><strong>Condition:</strong>
            {% if item.resolved_m2m.condition %}
              {% for val in item.resolved_m2m.condition %}
                <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Condition" data-value="{{ val }}">{{ val }}</button>
              {% endfor %}
            {% endif %}
            {% if item.missing_map.condition %}
              {% for val in item.missing_map.condition %}
                <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Condition" data-value="{{ val }}">{{ val }}</button>
              {% endfor %}
            {% endif %}
            <span class="text-muted m2m-none" style="display:none">(none)</span>
            {% if item.missing_map.condition %}
              <div class="small text-info">Would create: {{ item.missing_map.condition|join:", " }}</div>
            {% endif %}
          </div>

          <!-- Presentation -->
          <div class="m2m-group" data-model="Presentation"><strong>Presentation:</strong>
            {% if item.resolved_m2m.presentation %}
              {% for val in item.resolved_m2m.presentation %}
                <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Presentation" data-value="{{ val }}">{{ val }}</button>
              {% endfor %}
            {% endif %}
            {% if item.missing_map.presentation %}
              {% for val in item.missing_map.presentation %}
                <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Presentation" data-value="{{ val }}">{{ val }}</button>
              {% endfor %}
            {% endif %}
            <span class="text-muted m2m-none" style="display:none">(none)</span>
            {% if item.missing_map.presentation %}
              <div class="small text-info">Would create: {{ item.missing_map.presentation|join:", " }}</div>
            {% endif %}
          </div>

          <!-- Subspecialty -->
          <div class="m2m-group" data-model="Subspecialty"><strong>Subspecialty:</strong>
            {% if item.resolved_m2m.subspecialty %}
              {% for val in item.resolved_m2m.subspecialty %}
                <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Subspecialty" data-value="{{ val }}">{{ val }}</button>
              {% endfor %}
            {% endif %}
            {% if item.missing_map.subspecialty %}
              {% for val in item.missing_map.subspecialty %}
                <button type="button" class="m2m-toggle btn btn-sm btn-success ms-1" data-idx="{{ item.index }}" data-model="Subspecialty" data-value="{{ val }}">{{ val }}</button>
              {% endfor %}
            {% endif %}
            <span class="text-muted m2m-none" style="display:none">(none)</span>
            {% if item.missing_map.subspecialty %}
              <div class="small text-info">Would create: {{ item.missing_map.subspecialty|join:", " }}</div>
            {% endif %}
          </div>
          <! -- Category -->
          <div class="m2m-group" data-model="Category"><strong>Category:</strong>
            {{ item.payload.category|default:'(none)' }}

          </div>
      <!-- DEBUG: show raw resolved and missing maps for troubleshooting -->
          <div class="card-footer text-monospace small">
            <details>
              <summary>Debug: resolved_m2m / missing_map (click to expand)</summary>
          <pre style="white-space:pre-wrap;">resolved_m2m: {{ item.resolved_m2m|default:"{}" }}
missing_map: {{ item.missing_map|default:"{}" }}</pre>
            </details>
          </div>
          <div>
            <label><input type="checkbox" name="selected" value="{{ item.index }}" checked> Include</label>
          </div>
        <!-- container for hidden exclude inputs for this item -->
          <div id="exclude-container-{{ item.index }}"></div>
        </div>
      </div>
    </div>
  {% endfor %}

  <div class="d-flex gap-2">
    <label class="me-2"><input type="checkbox" name="allow_create_m2m" {% if allow_create_m2m %}checked{% endif %}> Create missing M2M</label>
    <button class="btn btn-success" type="submit">Import selected</button>
    <button class="btn btn-secondary" type="button" hx-get="{% url 'sbas:import_llm_questions' %}" hx-target="#import-preview">Cancel</button>
  </div>
  <div id="import-result" class="mt-3"></div>
</form>

<script>
  // Toggle exclude: clicking a M2M button will add/remove a hidden input and update styles
  function setupToggle(btn){
    btn.addEventListener('click', function(){
      const model = btn.dataset.model;
      const value = btn.dataset.value;

      // Find all buttons with same model+value and toggle them together
      document.querySelectorAll('.m2m-toggle').forEach(function(b){
        if(b.dataset.model === model && b.dataset.value === value){
          const idx2 = b.dataset.idx;
          const container = document.getElementById('exclude-container-' + idx2);
          const inputName = 'exclude_' + idx2;
          const existing = container ? container.querySelector('input[data-model="' + model + '"][data-value="' + value + '"]') : null;
          if(existing){
            existing.remove();
            b.classList.remove('btn-outline-secondary');
            b.classList.remove('btn-secondary');
            b.classList.add('btn-success');
          } else {
            const inp = document.createElement('input');
            inp.type = 'hidden';
            inp.name = inputName;
            inp.value = model + ':::' + value;
            inp.setAttribute('data-model', model);
            inp.setAttribute('data-value', value);
            container.appendChild(inp);
            b.classList.remove('btn-success');
            b.classList.add('btn-outline-secondary');
          }
        }
      });

      // Update empty placeholders after toggling
      refreshEmptyPlaceholders();
    });
  }

  document.querySelectorAll('.m2m-toggle').forEach(setupToggle);
  // keep backward compatibility with older toggle-exclude class
  document.querySelectorAll('.toggle-exclude').forEach(setupToggle);

  // Show '(none)' for empty groups
  function refreshEmptyPlaceholders(){
    document.querySelectorAll('.m2m-group').forEach(function(group){
      // consider a button 'active' only if it has the green btn-success class
      const activeButtons = group.querySelectorAll('.m2m-toggle.btn-success');
      const none = group.querySelector('.m2m-none');
      if(!none) return;
      if(activeButtons.length === 0){
        none.style.display = '';
      } else {
        none.style.display = 'none';
      }
    });
  }

  // run on load
  refreshEmptyPlaceholders();

  // when toggling, buttons are not removed from DOM, so no need to re-run on click;
  // however if you later add server-side mutation that rewrites the fragment, call refreshEmptyPlaceholders after update.
</script>

<!-- Bottom controls removed: submit and cancel are inside the form above -->

<script>
// Toggle editing of payload inputs for a specific item (disabled by default)
  function toggleEdit(btn){
    const idx = btn.getAttribute('data-item-index');
    if(!idx) return;
    const card = document.getElementById('import-item-' + idx);
    if(!card) return;
    const selector = 'input[name^="payload_' + idx + '_"], textarea[name^="payload_' + idx + '_"]';
    const inputs = card.querySelectorAll(selector);
    if(inputs.length === 0) return;
  // check current state from first input
    const currentlyDisabled = inputs[0].disabled === true;
  // toggle
    inputs.forEach(function(i){ i.disabled = currentlyDisabled ? false : true; });
  // update button text
    btn.textContent = currentlyDisabled ? 'Lock' : 'Edit';
  }
</script>
