<script lang="ts">
  /**
   * Shows all the location-results
   */
  import Translations from "../i18n/Translations"
  import SidebarUnit from "../Base/SidebarUnit.svelte"
  import Loading from "../Base/Loading.svelte"
  import { default as GeocodeResultSvelte } from "./GeocodeResult.svelte"
  import Tr from "../Base/Tr.svelte"
  import { ImmutableStore, Store, UIEventSource } from "../../Logic/UIEventSource"
  import type { GeocodeResult } from "../../Logic/Search/GeocodingProvider"
  import type { MapProperties } from "../../Models/MapProperties"

  export let state: {
    searchState: {
      searchTerm: UIEventSource<string>
      suggestions: Store<GeocodeResult[]>
      suggestionsSearchRunning: Store<boolean>
    }
    mapProperties: MapProperties
  }

  let searchTerm = state.searchState.searchTerm
  let results = state.searchState.suggestions
  let isSearching = state.searchState.suggestionsSearchRunning ?? new ImmutableStore(false)

  const t = Translations.t.general.search
</script>

{#if $searchTerm.length > 0}
  <SidebarUnit>
    <h3>
      <Tr t={t.locations} />
    </h3>

    {#if $results?.length > 0}
      {#each $results as entry (entry)}
        <GeocodeResultSvelte on:select {entry} {state} />
      {/each}
    {/if}

    {#if $isSearching}
      <div class="m-4 my-8 flex justify-center">
        <Loading>
          <Tr t={t.searching} />
        </Loading>
      </div>
    {/if}

    {#if !$isSearching && $results?.length === 0}
      <b class="flex justify-center p-4">
        <Tr t={t.nothingFor.Subs({ term: "<i>" + $searchTerm + "</i>" })} />
      </b>
    {/if}
  </SidebarUnit>
{:else}
  <slot name="if-no-results" />
{/if}
