<script lang="ts">
    import SpaceCard from "$lib/components/SpaceCard.svelte";
    import defaultImg from "$lib/assets/study_space.png";
    import crossUrl from "$lib/assets/cross.svg";
    import Navbar from "$lib/components/Navbar.svelte";
    import TagFilter from "$lib/components/inputs/TagFilter.svelte";
    import { allTags } from "$lib";

    const { data } = $props();
    const { studySpaces, supabase } = $derived(data);

    let selectedTags = $state<string[]>([]);
    let tagFilter = $state("");
    let tagFilterElem = $state<HTMLInputElement>();
    let filteredTags = $derived(
        allTags
            .filter((tag) => tag.toLowerCase().includes(tagFilter.toLowerCase()))
            .filter((tag) => allTags.includes(tag))
    );

    let filteredStudySpaces = $derived(() =>
        selectedTags.length === 0
            ? studySpaces
            : studySpaces.filter((space) => {
                  const allTags = [
                      ...(space.tags || []),
                      space.volume,
                      space.wifi,
                      space.power
                  ].filter(Boolean);

                  return selectedTags.every((tag) => allTags.includes(tag));
              })
    );

    let dropdownVisible = $state(false);

    function deleteTag(tagName: string) {
        return () => {
            selectedTags = selectedTags.filter((tag) => tag !== tagName);
        };
    }

    function addTag(tagName: string) {
        return () => {
            if (!selectedTags.includes(tagName)) {
                selectedTags.push(tagName);
            }
            tagFilter = "";
        };
    }
</script>

<Navbar>
    <a href="/space">
        <img src={crossUrl} alt="new" class="new-space" />
    </a>
</Navbar>

<main>
    <TagFilter
        {selectedTags}
        {tagFilter}
        {tagFilterElem}
        {filteredTags}
        {dropdownVisible}
        {deleteTag}
        {addTag}
    />

    {#each filteredStudySpaces() as studySpace (studySpace.id)}
        {@const imgUrl =
            studySpace.study_space_images.length > 0
                ? supabase.storage
                      .from("files_bucket")
                      .getPublicUrl(studySpace.study_space_images[0].image_path).data.publicUrl
                : defaultImg}
        <SpaceCard
            alt="Photo of {studySpace.description}"
            href="/space/{studySpace.id}"
            imgSrc={imgUrl}
            space={studySpace}
        />
    {/each}
</main>

<style>
    main {
        display: grid;
        box-sizing: border-box;
        grid-template-columns: 1fr 1fr;
        gap: 1rem;
        padding: 1rem;
        max-width: 600px;
        width: 100%;
        margin: 0 auto;
    }

    .new-space {
        transform: rotate(45deg);
    }

    @media (max-width: 20rem) {
        main {
            grid-template-columns: 1fr;
        }
    }
</style>
