<script setup lang="ts">
import { Editor, EditorToolbar } from "@enesis/editor"
import { computed, ref, watch } from "vue"
import { useFileSystem } from "~/composables/useFileSystem"
import { useIndexSuggestions } from "~/composables/useIndexSuggestions"
import { markInFlight, useWorkspaceStore } from "~/stores/workspace"

const props = defineProps<{
  date: string
  isToday: boolean
}>()

const emit = defineEmits<{
  "page-ref-clicked": [payload: { pageName: string; alias?: string }]
  "block-ref-clicked": [payload: { blockId: string }]
  "tag-clicked": [payload: { tag: string }]
}>()

const { data: mentionData, refresh: refreshSuggestions } = useIndexSuggestions()

const content = ref("")
const loading = ref(false)
const opened = ref(false)

const fs = useFileSystem()
const ws = useWorkspaceStore()

const dayLabel = computed(() => {
  const d = new Date(`${props.date}T12:00:00`)
  const weekday = d.toLocaleDateString("en-US", { weekday: "long" })
  const month = d.toLocaleDateString("en-US", { month: "long" })
  const day = d.getDate()
  return props.isToday ? "Today" : `${weekday}, ${month} ${day}`
})

const fullPath = computed(() => {
  if (!ws.workspacePath) return ""
  return `${ws.workspacePath}/journals/${props.date}.md`
})

let saveTimer: ReturnType<typeof setTimeout> | null = null

watch(content, (val) => {
  if (!fullPath.value) return

  if (saveTimer) clearTimeout(saveTimer)
  saveTimer = setTimeout(async () => {
    try {
      markInFlight(fullPath.value)
      await fs.writeFile(fullPath.value, val)
    } catch (e) {
      console.warn("[JournalDay] save failed:", e)
    }
  }, 500)
})

// Re-fetch content when the workspace path changes
watch(
  fullPath,
  async (path) => {
    if (!path) return
    loading.value = true
    try {
      try {
        content.value = await fs.readFile(path)
      } catch {
        content.value = ""
      }
    } finally {
      loading.value = false
    }
  },
  { immediate: true },
)
</script>

<template>
  <div class="border-b border-default last:border-b-0 min-h-[80vh]">
    <!-- Day header -->
    <div class="flex items-baseline gap-3 pt-12 pb-4 px-6 max-w-4xl mx-auto w-full">
      <h2
        class="text-3xl font-normal tracking-normal text-highlighted"
        :class="{ 'text-(--ui-primary)': isToday }"
      >
        {{ dayLabel }}
      </h2>
      <span class="text-sm text-muted">{{ props.date }}</span>
    </div>

    <div class="pb-12 px-6 max-w-4xl mx-auto w-full">
      <!-- Loading -->
      <div v-if="loading" class="py-12 text-center text-sm text-muted">
        Loading...
      </div>

      <!-- Editor — shown when the user opened the page or content exists -->
      <div v-else-if="opened || content" class="min-h-[3rem]">
        <Editor
          v-model:content="content"
          marker-mode="live-preview"
          :focused="opened ? 'last-zone' : 'last-block'"
          :mention-data="mentionData"
          @page-ref-clicked="({ pageName, alias }: { pageName: string; alias?: string }) => emit('page-ref-clicked', { pageName, alias })"
          @block-ref-clicked="({ blockId }: { blockId: string }) => emit('block-ref-clicked', { blockId })"
          @tag-clicked="({ tag }: { tag: string }) => emit('tag-clicked', { tag })"
        >
          <template #toolbar="{ handlers, selectionVersion, canUndo, canRedo, undo, redo }">
            <EditorToolbar
              mode="bubble"
              :handlers="handlers"
              :selection-version="selectionVersion"
              :can-undo="canUndo"
              :can-redo="canRedo"
              :undo="undo"
              :redo="redo"
            />
          </template>
        </Editor>
      </div>

      <!-- Empty state — warm invitation for days without entries -->
      <div v-else
        class="py-16 text-center cursor-text select-none"
        @click="opened = true"
      >
        <div class="w-12 h-px bg-muted mx-auto mb-8" />
        <p class="text-xl italic text-muted/50">
          A quiet page, waiting for words.
        </p>
        <p class="text-sm text-muted/30 mt-4">
          click to begin writing
        </p>
      </div>
    </div>
  </div>
</template>
