{% import "partials/icons.html" as icons %}

{% macro location_search(error_signal) %}
  <div
    data-location-root
    data-on:location-found="$_locating = false; $_locationFound = true; $_userLat = evt.detail.lat; $_userLng = evt.detail.lng; @get('/api/v1/nearby-cafes?lat=' + evt.detail.lat + '&lng=' + evt.detail.lng + '&q=coffee', {responseOverrides: {selector: '#nearby-results', mode: 'replace'}})"
    data-on:location-error="$_locating = false; {{ error_signal }} = evt.detail.message"
    data-on:location-start="$_locating = true"
  >
    <div class="flex items-center gap-2 mb-3">
      <button
        type="button"
        data-on:click="locateUser(el)"
        class="shrink-0 inline-flex items-center justify-center rounded-md border p-2.5 transition hover:bg-surface-alt"
        data-class="{'text-accent': $_locationFound, 'text-text': !$_locationFound}"
        data-attr:disabled="$_locating || $_locationFound"
        aria-label="Use my location"
      >
        <span data-show="!$_locating">{{ icons::location("h-5 w-5") }}</span>
        <span data-show="$_locating" style="display: none"
          >{{ icons::spinner("h-5 w-5") }}</span
        >
      </button>
      <input
        type="text"
        data-bind:_city-name
        class="input-field w-full"
        data-attr:placeholder="$_locationFound ? 'Using current location (' + $_userLat.toFixed(2) + ', ' + $_userLng.toFixed(2) + ')' : 'Name of city or area'"
        data-attr:disabled="$_locationFound"
        data-on:input__debounce.350ms="$_cityName.length >= 2 && $_cafeSearch.length >= 2 && @get('/api/v1/nearby-cafes?near=' + encodeURIComponent($_cityName) + '&q=' + encodeURIComponent($_cafeSearch), {responseOverrides: {selector: '#nearby-results', mode: 'replace'}})"
      />
    </div>
    <input
      type="text"
      data-bind:_cafe-search
      class="input-field w-full"
      placeholder="Search for a cafe&hellip;"
      data-on:keydown="nearbyKeydown(evt, el)"
      data-on:input__debounce.350ms="if ($_locationFound) { @get('/api/v1/nearby-cafes?lat=' + $_userLat + '&lng=' + $_userLng + '&q=' + encodeURIComponent($_cafeSearch), {responseOverrides: {selector: '#nearby-results', mode: 'replace'}}) } else { $_cityName.length >= 2 && $_cafeSearch.length >= 2 && @get('/api/v1/nearby-cafes?near=' + encodeURIComponent($_cityName) + '&q=' + encodeURIComponent($_cafeSearch), {responseOverrides: {selector: '#nearby-results', mode: 'replace'}}) }"
    />
    <div
      id="nearby-results"
      class="hidden mt-3 max-h-60 overflow-y-auto rounded-lg border bg-surface"
    ></div>
  </div>
{% endmacro %}
