<div class="finding-search-widget">
  {% with input_id=input_id|default:'finding-search-input' target_id=target_id|default:'finding-search-results' %}
    <style>
      .finding-search-loading { display: none; }
      .finding-search-widget.is-loading .finding-search-loading { display: inline-flex; }
    </style>
    <label for="{{ input_id }}" class="form-label">Search findings</label>
    <input id="{{ input_id }}" name="q" class="form-control" type="search"
           placeholder="Type to search findings..."
           hx-get="{% url 'atlas:finding_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="finding-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 findings...</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/_finding_search_results.html' with findings=findings case=case %}
    </div>
  {% endwith %}
</div>

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

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

      // If server provided a case via inclusion, ensure widget sets dataset and nearby textarea dataset
      var meta = document.getElementById('current-case-meta');
      var casePk = meta ? meta.getAttribute('data-current-case') : null;
      var caseTitle = meta ? 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;
          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(){ applyCaseToInputs(null, null); try{ input.removeAttribute('hx-vals'); }catch(e){}; input.dispatchEvent(new Event('input')); }); }

      input.addEventListener('input', function(){
        if (timer) clearTimeout(timer);
        timer = setTimeout(function(){
          try {
            var q = encodeURIComponent(input.value || '');
            // Respect dataset-based case filter if present
            var caseParam = input.dataset.currentCase ? '&case=' + encodeURIComponent(input.dataset.currentCase) : '';
            var url = "{% url 'atlas:finding_search' %}?q=" + q + caseParam;
            var target = '#{{ target_id|default:"finding-search-results" }}';
            if (window.htmx && typeof window.htmx.ajax === 'function') {
              window.htmx.ajax('GET', url, { target: target, swap: 'innerHTML', indicator: '#{{ input_id|default:"finding-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('finding 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('finding search widget init error', e); }
  })();
</script>
