<script>
  import Input from "./base/Input.svelte";

  let { dialog = $bindable() } = $props()

  let searchQuery = $state("")
  let searchResult = $state([])

  async function search() {
    searchResult = []
    if(searchQuery.length > 3) {
      fetch("/api/search?q=" + searchQuery)
          .then( response => response.json() )
          .then( data => { searchResult = data; console.log(data) } )
    }
  }
</script>

<dialog class="max-w-96 w-full backdrop:backdrop-blur-sm backdrop:bg-black/30 p-4 rounded-md"
    style="margin: auto; width: calc(100% - 20px);"
    bind:this={dialog}
  	onclick={(e) => { if (e.target === dialog) dialog.close(); }}>
  <div>
    <Input type="text" placeholder="Rechercher des cartes" bind:value={searchQuery} oninput={search} focus/>
    <div class="mt-4 flex flex-col gap-2 h-64 overflow-y-scroll items-center">
      {#if searchResult.length == 0}
        <span class="mt-8 text-xs">Pas de résultat...</span>
      {:else}
        {#each searchResult as result}
          <a class="flex flex-col gap-0 w-full" href={result.Url}>
            <span>{result.Name}</span>
            <span class="text-xs">{result.SetName}</span>
          </a>
        {/each}
      {/if}
    </div>
  </div>
</dialog>
