<script setup lang="ts">
import { formatDate } from '@/utils/helpers'
import {
  activeNote,
  deleteNote,
  rootNote,
  setRootNote,
  setActiveNote,
  getNoteReferences
} from '@/composables/useNotes'

const props = defineProps<{
  note: Note
}>()

const emit = defineEmits<{
  update: [note: Note]
}>()

const noteTitle = ref(props.note.title)
watch(noteTitle, () => {
  const updatedNote: Note = { ...props.note, title: noteTitle.value }
  emit('update', updatedNote)
})

const updateNoteContent = (content: string) => {
  const updatedNote: Note = { ...props.note, content }
  emit('update', updatedNote)
}

const references = computed<Note[]>(() => getNoteReferences(props.note))

const del = async (closeModal: () => Promise<Boolean>) => {
  await closeModal()
  setActiveNote(rootNote.value?.id)
  deleteNote(props.note.id)
}

const setRoot = async (closeModal: () => Promise<Boolean>) => {
  setRootNote(props.note.id)
  closeModal()
}
</script>
<template>
  <div class="flex h-full flex-col">
    <NoteToolbar :note="props.note" @delete="del" @set-root="setRoot">
      <template #title>
        <i
          class="fas fa-fw fa-home mr-2 text-base text-secondary opacity-40"
          v-if="props.note.isRoot"
        ></i>
        <input type="text" class="bg-transparent py-1 outline-none w-full" v-model="noteTitle" />
      </template>
    </NoteToolbar>
    <NoteEditor
      class="flex-grow"
      :note="activeNote"
      @update="updateNoteContent"
      v-if="activeNote"
    ></NoteEditor>
    <NoteReferences :references="references" />
    <hr class="my-3" />
    <div class="flex text-sm text-secondary">
      <span>{{ note.wordCount }} {{ note.wordCount === 1 ? 'word' : 'words' }}</span>
      <span class="ml-auto">Last modified {{ formatDate(note.modified) }}</span>
    </div>
  </div>
</template>
<style scoped lang="scss">
.btn-group .btn {
  @apply border-[1px] border-neutral-200 text-opacity-70;
  &:not(:first-child) {
    @apply ml-[-1px];
  }
}
</style>
