<!--
  -   This file is a part of the SteamWar software.
  -
  -   Copyright (C) 2024 SteamWar.de-Serverteam
  -
  -   This program is free software: you can redistribute it and/or modify
  -   it under the terms of the GNU Affero General Public License as published by
  -   the Free Software Foundation, either version 3 of the License, or
  -   (at your option) any later version.
  -
  -   This program is distributed in the hope that it will be useful,
  -   but WITHOUT ANY WARRANTY; without even the implied warranty of
  -   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  -   GNU Affero General Public License for more details.
  -
  -   You should have received a copy of the GNU Affero General Public License
  -   along with this program.  If not, see <https://www.gnu.org/licenses/>.
  -->

<script lang="ts">

    import {slide, fade} from "svelte/transition";
    import {onMount} from "svelte";
    import {importPagefind, type Pagefind, type PagefindDocument} from "@type/pagefind.js";
    import Card from "@components/Card.svelte";
    import {l} from "@utils/util.ts";
    let pagefind: Pagefind;

    onMount(async () => {
        pagefind = await importPagefind();

        pagefind.init();
    });

    let results: PagefindDocument[] = $state([]);

    async function search(e: KeyboardEvent) {
        if (e.target instanceof HTMLInputElement) {
            let search: {results: any[]} = await pagefind.debouncedSearch(e.target.value);

            results = await Promise.all(search.results.slice(0, 10).map(value => value.data()))
        }
    }

  interface Props {
    open?: boolean;
  }

  let { open = $bindable(false) }: Props = $props();
</script>

<button transition:fade class="fixed top-0 left-0 w-screen h-screen backdrop-blur z-20 cursor-default" onclick={() => open = false}>
</button>
<div transition:slide style="width: min(100%, 75em);" class="fixed top-0 left-1/2 -translate-x-1/2 h-2/3 dark:bg-zinc-900 rounded-b-2xl shadow-2xl z-30 p-4 text-white flex flex-col">
    <input placeholder="Search..." onkeypress={search}>

    <div class="overflow-y-scroll flex-1 w-full mt-2 rounded-2xl">
        {#each results as result}
            <Card extraClasses="w-full m-0 my-2" hoverEffect={false}>
                <a class="grid grid-cols-3" href={l(result.url)}>
                    <h1>{result.meta.title}</h1>
                    {#each result.sub_results.slice(0, 2) as sub_result}
                        <p>{@html sub_result.excerpt}</p>
                    {/each}
                </a>
            </Card>
        {/each}
    </div>
</div>

<style lang="postcss">
    input {
        @apply border-2 rounded-md p-2 shadow-2xl w-full
        dark:bg-neutral-800
        focus:outline-none focus:ring-2 focus:ring-neutral-500 focus:border-transparent;
    }

    label {
        @apply text-neutral-300;
    }
</style>