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

        <category-row
            :index="categoryIndex"
            :category="id"
            editable
            @edited="onCategoryEdited"
        />

        <div class="notes">
            <note-row v-for="note in notes" :note="note" :key="note.id" />
        </div>

        <new-note :category="id" />
    </main>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import useNotes from '@/composables/useNotes'
import NoteRow from '@/components/NoteRow.vue'
import CategoryRow from '@/components/CategoryRow.vue'
import NewNote from '@/components/NewNote.vue'

const route = useRoute()
const id = route.params?.id
const router = useRouter()

const { categories, loadCategoryNotes, updateCategory, notesChangeCount } =
    useNotes()

const notes = ref()

async function refreshNotes() {
    if (id) {
        notes.value = await loadCategoryNotes(id)
    }
}

onMounted(async () => {
    await refreshNotes()
})

watch(notesChangeCount, async () => {
    await refreshNotes()
})

const onCategoryEdited = async (editedCategory) => {
    await updateCategory(id, editedCategory)

    router.push({ name: 'category', params: { id: editedCategory } })
}

const categoryIndex = computed(() => {
    return categories.value?.findIndex((category) => category === id) || 1
})
</script>

<style lang="scss">
main.category {
    .back {
        display: block;
        opacity: 0.25;
        margin-top: 9px;
    }
    .category-row {
        margin-top: 4px;
    }
    .notes {
        display: flex;
        flex-direction: column;
        gap: 14px;
        margin-top: 9px;
    }
    .new-note {
        display: block;
        margin: 50px auto 0;
    }
}
</style>
