<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from "vue"
import { useRoute } from "vue-router"
import { useDates } from "~/composables/useDates"
import { usePageNavigation } from "~/composables/usePageNavigation"
import { useUiStore } from "~/stores/ui"
import JournalDay from "./JournalDay.vue"

const route = useRoute()
const ui = useUiStore()
const { getToday } = useDates()
const { navigateToPage, navigateToBlock, navigateToTag } = usePageNavigation()

const today = getToday()
const days = ref<string[]>([today])
const loadingMore = ref(false)

function loadOlderDays() {
  if (loadingMore.value) return
  loadingMore.value = true

  const last = days.value[days.value.length - 1]
  if (!last) return

  const d = new Date(`${last}T12:00:00`)
  for (let i = 0; i < 7; i++) {
    d.setDate(d.getDate() - 1)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, "0")
    const day = String(d.getDate()).padStart(2, "0")
    days.value.push(`${y}-${m}-${day}`)
  }

  loadingMore.value = false
}

onMounted(() => {
  loadOlderDays()

  // If navigated from sidebar/timeline with a ?date= param, scroll there
  const dateParam = route.query.date as string | undefined
  if (dateParam) {
    ui.setActiveDate(dateParam)
    nextTick(() => {
      document
        .getElementById(`day-${dateParam}`)
        ?.scrollIntoView({ behavior: "smooth" })
    })
  }
})

function onScroll(event: Event) {
  const el = event.target as HTMLElement
  if (
    el.scrollTop + el.clientHeight >= el.scrollHeight - 400 &&
    !loadingMore.value
  ) {
    loadOlderDays()
  }
}

/** Scroll to a journal day when the store's activeDate changes. */
watch(
  () => ui.activeDate,
  (date) => {
    if (!date) return
    nextTick(() => {
      document
        .getElementById(`day-${date}`)
        ?.scrollIntoView({ behavior: "smooth" })
    })
  },
)

function onPageRefClick(payload: { pageName: string; alias?: string }) {
  navigateToPage(payload.pageName)
}

function onBlockRefClick(payload: { blockId: string }) {
  navigateToBlock(payload.blockId)
}

function onTagClick(payload: { tag: string }) {
  navigateToTag(payload.tag)
}
</script>

<template>
  <div class="flex-1 overflow-y-auto bg-default" @scroll="onScroll">
    <JournalDay
      v-for="(date, i) in days"
      :id="`day-${date}`"
      :key="date"
      :date="date"
      :is-today="i === 0"
      @page-ref-clicked="onPageRefClick"
      @block-ref-clicked="onBlockRefClick"
      @tag-clicked="onTagClick"
    />

    <div
      v-if="loadingMore"
      class="flex items-center justify-center gap-2 py-8 text-xs text-muted"
    >
      <UIcon name="i-lucide-loader" class="size-4 animate-spin" />
      Loading earlier days...
    </div>
  </div>
</template>
