<div class="case-search-widget">
  {% with input_id=input_id|default:'case-search-input' target_id=target_id|default:'case-search-results' %}
    <style>
      .case-search-loading {
        display: none;
      }
      .case-search-widget.is-loading .case-search-loading {
        display: inline-flex;
      }
    </style>
    <label for="{{ input_id }}" class="form-label">Search cases</label>
    {% if collection %}
      <input type="hidden" id="{{ input_id }}-collection" name="collection" value="{{ collection.pk }}">
    {% endif %}
    {% if show_select_button %}
      <input type="hidden" id="{{ input_id }}-show-select" name="show_select" value="1">
    {% endif %}
    <input id="{{ input_id }}" name="q" class="form-control" type="search"
           placeholder="Type to search cases..."
           hx-get="{% url 'atlas:case_search' %}"
           hx-include="closest .case-search-widget"
           hx-target="#{{ target_id }}"
           hx-trigger="input delay:400ms"
           hx-indicator="#{{ input_id }}-loading"
           autocomplete="off">

    <div id="{{ input_id }}-loading" class="case-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 cases...</span>
    </div>

    <div id="{{ target_id }}" 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 show_select_button=show_select_button %}
    </div>
  {% endwith %}
</div>

<script>
  (function(){
    try {
      var input = document.getElementById('{{ input_id|default:"case-search-input" }}');
      if (!input) return;
      var widget = input.closest('.case-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:case_search' %}?q=" + q + ({% if collection %} "&collection={{ collection.pk }}" {% else %} '' {% endif %}) + ({% if show_select_button %} "&show_select=1" {% else %} '' {% endif %});
            var target = '#{{ target_id|default:"case-search-results" }}';
            if (window.htmx && typeof window.htmx.ajax === 'function') {
              window.htmx.ajax('GET', url, { target: target, swap: 'innerHTML', indicator: '#{{ input_id|default:"case-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('case search fetch error', e); }).finally(function(){ setLoading(false); });
            }
          } catch(e) { console.error(e); }
        }, 400);
      });
        // No multi-select action bar; items provide per-item Add buttons.
    } catch(e) { console.error('case search widget init error', e); }
  })();
</script>

<script>
  (function(){
    try {
      var targetId = '{{ target_id|default:"case-search-results" }}';
      var inputId = '{{ input_id|default:"case-search-input" }}';
      var inputEl = document.getElementById(inputId);
      var container = inputEl ? inputEl.closest('.case-search-widget') : document.querySelector('.case-search-widget');
      var targetEl = document.getElementById(targetId);
      if (!container || !targetEl) return;

      document.body.addEventListener('htmx:beforeRequest', function (event) {
        if (event.target === inputEl) {
          container.classList.add('is-loading');
        }
      });
      document.body.addEventListener('htmx:afterRequest', function (event) {
        if (event.target === inputEl) {
          container.classList.remove('is-loading');
        }
      });

      // Delegate clicks on result items and dispatch a scoped custom event
      targetEl.addEventListener('click', function(e){
        var item = e.target.closest('.list-group-item');
        if (!item || !targetEl.contains(item)) return;

        var selectBtn = e.target.closest('.case-select-btn');
        if (selectBtn) {
          e.preventDefault();
        } else {
          // Ignore all non-select interactions so rows are passive unless
          // explicit selection controls are present.
          return;
        }

        var casePk = item.getAttribute('data-case-pk');
        if (!casePk) {
          var href = item.getAttribute('href') || (item.querySelector('a') ? item.querySelector('a').getAttribute('href') : '');
          var m = href.match(/case\/(\d+)\/?$/);
          if (m) casePk = m[1];
        }
        var caseTitleEl = item.querySelector('h6');
        var caseTitle = caseTitleEl ? caseTitleEl.textContent.trim() : (casePk ? ('#' + casePk) : null);
        if (!casePk) return;

        var ev = new CustomEvent('case:selected', { detail: { casePk: casePk, caseTitle: caseTitle }, bubbles: true });
        container.dispatchEvent(ev);
      }, false);
    } catch (e) { console.error('case search widget selection init error', e); }
  })();
</script>

