{# Search-select fragment — debounced search with dropdown results, Alpine state #}
{# ARIA combobox pattern for screen reader accessibility. #}

{# Resolve initial value for edit mode: ref objects have display names #}
{% set init_id = "" %}
{% set init_display = "" %}
{% if value is mapping %}
  {% set init_id = value.get("id", "") %}
  {% set init_display = value.get("name") or value.get("title") or value.get("label") or value.get("email") or value.get("id", "") %}
{% elif value %}
  {% set init_id = value %}
  {% set init_display = value %}
{% endif %}

<div class="relative w-full" x-data="{ open: false }">
  {# Hidden input stores the selected value #}
  <input type="hidden" name="{{ field.name }}" id="field-{{ field.name }}"
         data-dazzle-field="{{ field.name }}" value="{{ init_id }}" />

  {# Visible search input with HTMX debounced search #}
  <input type="text"
         id="search-input-{{ field.name }}"
         class="input input-bordered w-full"
         placeholder="{{ field.placeholder or ('Search ' + field.label + '...') }}"
         autocomplete="off"
         role="combobox"
         :aria-expanded="open"
         aria-controls="search-results-{{ field.name }}"
         aria-autocomplete="list"
         aria-haspopup="listbox"
         value="{{ init_display }}"
         hx-get="{{ field.source.endpoint }}"
         hx-trigger="keyup changed delay:{{ field.source.debounce_ms }}ms"
         hx-target="#search-results-{{ field.name }}"
         hx-indicator="#search-spinner-{{ field.name }}"
         hx-params="q"
         {% if field.source.min_chars %}hx-vals='{"min_chars": {{ field.source.min_chars }}}'{% endif %}
         @focus="open = true"
         @blur="setTimeout(() => { open = false }, 200)" />

  {# Loading indicator #}
  <span id="search-spinner-{{ field.name }}" class="htmx-indicator absolute right-3 top-3"
        role="status" aria-label="Searching">
    <span class="loading loading-spinner loading-sm" aria-hidden="true"></span>
  </span>

  {# Dropdown results container #}
  <div id="search-results-{{ field.name }}"
       x-show="open"
       x-cloak
       role="listbox"
       aria-label="{{ field.label }} suggestions"
       class="absolute z-50 w-full mt-1 bg-base-100 border border-base-300 rounded-box shadow-lg max-h-60 overflow-y-auto">
    {# Empty state shown before any search #}
    <div class="p-3 text-sm text-base-content/50" role="option" aria-disabled="true">
      Type at least {{ field.source.min_chars }} characters to search...
    </div>
  </div>
</div>
