<div class="case-search-widget">
  <label for="case-search-input" class="form-label">Search cases</label>
  <input id="case-search-input" name="q" class="form-control" type="search"
    placeholder="Type to search cases..."
    hx-get="{% url 'atlas:case_search' %}"
    hx-include="#case-search-input"
    hx-vals='{"collection": "{{ collection.pk }}"}'
    hx-target="#case-search-results"
    hx-trigger="keyup changed delay:400ms"
    autocomplete="off">

  <div id="case-search-results" class="mt-2">
    {# Render initial results (search + recent) on initial GET; HTMX searches will replace this div with partial results #}
    {% include 'atlas/partials/case_search_results.html' with cases=cases recent_cases=recent_cases collection=collection %}
  </div>
</div>

<script>
  (function(){
    // Robust fallback: ensure repeated searches always work by using htmx.ajax when available.
    try {
      var input = document.getElementById('case-search-input');
      if (!input) return;
      var timer = null;
      input.addEventListener('input', function(){
        if (timer) clearTimeout(timer);
        timer = setTimeout(function(){
          try {
            var q = encodeURIComponent(input.value || '');
            var url = "{% url 'atlas:case_search' %}?q=" + q + "&collection={{ collection.pk }}";
            if (window.htmx && typeof window.htmx.ajax === 'function') {
              window.htmx.ajax('GET', url, { target: '#case-search-results', swap: 'innerHTML' });
            } else {
              // fallback to fetch
              fetch(url, { credentials: 'same-origin' }).then(function(r){ return r.text(); }).then(function(html){
                var el = document.getElementById('case-search-results');
                if (el) el.innerHTML = html;
              }).catch(function(e){ console.error('case search fetch error', e); });
            }
          } catch(e) { console.error(e); }
        }, 400);
      });
    } catch(e) { console.error('case search widget init error', e); }
  })();
</script>

