<div class="displayset-search-widget">
  {% if case %}
    <div id="current-case-meta" data-current-case="{{ case.pk }}" data-current-case-title="{{ case.title|escape }}" style="display:none;"></div>
  {% endif %}
  {% with input_id=input_id|default:'displayset-search-input' target_id=target_id|default:'displayset-search-results' %}
    <style>
      .displayset-search-loading { display: none; }
      .displayset-search-widget.is-loading .displayset-search-loading { display: inline-flex; }
    </style>
    <label for="{{ input_id }}" class="form-label">Search display sets</label>
    <input id="{{ input_id }}" name="q" class="form-control" type="search"
           placeholder="Type to search display sets..."
           hx-get="{% url 'atlas:displayset_search_partial' %}"
           hx-include="#{{ input_id }}"
           {% if case %}hx-vals='{"case": "{{ case.pk }}"}'{% endif %}
           hx-target="#{{ target_id }}"
           hx-trigger="keyup changed delay:400ms"
           hx-indicator="#{{ input_id }}-loading"
           autocomplete="off">

    <div id="{{ input_id }}-loading" class="displayset-search-loading align-items-center gap-2 mt-2 text-muted small">
      <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
      <span>Searching display sets...</span>
    </div>

    <div class="mt-1">
      <span id="{{ input_id }}-case-badge" class="badge bg-secondary" style="display: {% if case %}inline-block{% else %}none{% endif %};">
        {% if case %}Filtering: {{ case.title|escape }}{% endif %}
      </span>
      <button type="button" id="{{ input_id }}-clear-case" class="btn btn-sm btn-outline-secondary ms-2" style="display: {% if case %}inline-block{% else %}none{% endif %};">✕</button>
    </div>

    <div id="{{ target_id }}" class="mt-2">
      {% include 'atlas/partials/_displayset_search_results.html' with displaysets=displaysets case=case %}
    </div>
  {% endwith %}
</div>

<script>
  (function(){
    try {
      var input = document.getElementById('{{ input_id|default:"displayset-search-input" }}');
      if (!input) return;
      var widget = input.closest('.displayset-search-widget');
      var timer = null;

      function setLoading(on) {
        if (!widget) return;
        widget.classList.toggle('is-loading', !!on);
      }

      input.addEventListener('input', function(){
        if (timer) clearTimeout(timer);
        timer = setTimeout(function(){
          try {
            var q = encodeURIComponent(input.value || '');
            var url = "{% url 'atlas:displayset_search' %}?q=" + q + ({% if case %} "&case={{ case.pk }}" {% else %} '' {% endif %});
            var target = '#{{ target_id|default:"displayset-search-results" }}';
            if (window.htmx && typeof window.htmx.ajax === 'function') {
              window.htmx.ajax('GET', url, { target: target, swap: 'innerHTML', indicator: '#{{ input_id|default:"displayset-search-input" }}-loading' });
            } else {
              setLoading(true);
              fetch(url, { credentials: 'same-origin' }).then(function(r){ return r.text(); }).then(function(html){
                var el = document.querySelector(target);
                if (el) el.innerHTML = html;
              }).catch(function(e){ console.error('displayset search fetch error', e); }).finally(function(){ setLoading(false); });
            }
          } catch(e) { console.error(e); }
        }, 400);
      });

      document.body.addEventListener('htmx:beforeRequest', function (event) {
        if (event.target === input) {
          setLoading(true);
        }
      });
      document.body.addEventListener('htmx:afterRequest', function (event) {
        if (event.target === input) {
          setLoading(false);
        }
      });
    } catch(e) { console.error('displayset search widget init error', e); }
  })();
</script>

<script>
  (function(){
    try{
      var input = document.getElementById('{{ input_id|default:"displayset-search-input" }}');
      if(!input) return;

      // Ensure a current-case-meta element exists
      var meta = document.getElementById('current-case-meta');
      if(!meta){
        meta = document.createElement('div');
        meta.id = 'current-case-meta';
        meta.style.display = 'none';
        var container = document.currentScript && document.currentScript.parentNode ? document.currentScript.parentNode : document.body;
        container.insertBefore(meta, container.firstChild);
      }

      // Populate meta from server-rendered attributes if present (existing behavior)
      // If not present, do not attempt further heuristics here; widget owns filter logic.

      // If meta has case info, push it into the input dataset and to a nearby textarea so the inserter can read it
      var casePk = meta.getAttribute('data-current-case');
      var caseTitle = meta.getAttribute('data-current-case-title') || '';
      var badge = document.getElementById('{{ input_id }}-case-badge');
      var clearBtn = document.getElementById('{{ input_id }}-clear-case');

      function applyCaseToInputs(pk, title){
        if(pk){
          input.dataset.currentCase = pk;
          if(title) input.dataset.currentCaseTitle = title;
          // find a nearby textarea (same form or container)
          var container = input.closest('form,div') || document.body;
          var ta = container.querySelector('textarea');
          if(ta){ ta.dataset.currentCase = pk; if(title) ta.dataset.currentCaseTitle = title; }
          if(badge){ badge.style.display = 'inline-block'; badge.textContent = 'Filtering: ' + (title || ('#' + pk)); }
          if(clearBtn) clearBtn.style.display = 'inline-block';
        } else {
          delete input.dataset.currentCase; delete input.dataset.currentCaseTitle;
          var container = input.closest('form,div') || document.body;
          var ta = container.querySelector('textarea');
          if(ta){ delete ta.dataset.currentCase; delete ta.dataset.currentCaseTitle; }
          if(badge) badge.style.display = 'none';
          if(clearBtn) clearBtn.style.display = 'none';
        }
      }

      if(casePk){ applyCaseToInputs(casePk, caseTitle); }

      if(clearBtn){ clearBtn.addEventListener('click', function(){
        // clear widget-level filter state and refresh results without case
        applyCaseToInputs(null, null);
        // remove any hx-vals forcing a case param
        try{ input.removeAttribute('hx-vals'); }catch(e){}
        input.dispatchEvent(new Event('input'));
      }); }

    }catch(e){ console.error('displayset widget meta init error', e); }
  })();
</script>
