<template>
    <main class="search layout-block">
        <router-link class="back" to="/"><- Back</router-link>

        <form @submit.prevent="onSearch">
            <div class="input-wrap">
                <input
                    v-model="query"
                    type="text"
                    placeholder="Search"
                    ref="searchInput"
                    @input="onInput"
                />
            </div>
        </form>

        <div class="results">
            <note-row
                v-for="note in searchResults"
                :key="note.id"
                :note="note"
            />
        </div>
    </main>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import useNotes from '@/composables/useNotes'
import NoteRow from '@/components/NoteRow.vue'
import _debounce from 'lodash/debounce'

const query = ref('')
const searchInput = ref()

const { search, searchResults } = useNotes()

onMounted(async () => {
    await new Promise((resolve) => setTimeout(resolve, 100))
    searchInput.value?.focus()
})
onBeforeUnmount(() => {
    query.value = ''
    searchResults.value = []
})

const onSearch = async () => {
    await search(query.value)
}
const onInput = _debounce(async () => {
    await search(query.value)
}, 300)
</script>

<style lang="scss">
main.search {
    .back {
        display: block;
        opacity: 0.25;
        margin-top: 9px;
    }
    .input-wrap {
        margin-top: 19px;
        position: relative;

        input {
            display: block;
            width: 100%;
            position: relative;
            padding: 5px 15px 6px;
            background: var(--theme-bg);
            --clip-start: 16px;
            clip-path: polygon(
                var(--clip-start) 1px,
                calc(100% - var(--clip-start)) 1px,
                calc(100% - 1.5px) 50%,
                calc(100% - var(--clip-start)) calc(100% - 1px),
                var(--clip-start) calc(100% - 1px),
                1.5px 50%
            );
        }
        &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: var(--theme-fg);
            --clip-start: 15px;
            clip-path: polygon(
                var(--clip-start) 0,
                calc(100% - var(--clip-start)) 0,
                100% 50%,
                calc(100% - var(--clip-start)) 100%,
                var(--clip-start) 100%,
                0% 50%
            );
        }
    }

    .results {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        gap: 14px;
    }
}
</style>
