<template>
  <div class="h-full flex flex-col relative">

    <div v-if="pending" class="flex h-full items-center justify-center text-gray-400">
      <div class="flex flex-col items-center gap-2">
        <svg class="animate-spin h-6 w-6 text-gray-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
        <span>Lade Inhalt...</span>
      </div>
    </div>

    <div v-else-if="page" class="flex flex-col h-full bg-white">
      <header class="px-8 pt-8 pb-2">
        <input
            v-model="page.title"
            @blur="saveTitle"
            @keydown.enter="($event.target as HTMLInputElement).blur()"
            class="text-4xl font-bold text-gray-900 w-full outline-none placeholder-gray-300 bg-transparent"
            placeholder="Unbenannte Seite"
        />

        <div class="flex items-center gap-4 mt-2 text-xs text-gray-400 h-6">
          <span>Erstellt am {{ new Date(page.createdAt).toLocaleDateString() }}</span>

          <transition name="fade">
            <span v-if="isSaving" class="text-primary-600 flex items-center gap-1">
              <svg class="animate-spin h-3 w-3" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
              Speichert...
            </span>
            <span v-else-if="lastSaved" class="text-green-600">Gespeichert</span>
          </transition>
        </div>
      </header>

      <div class="flex-1 overflow-hidden">
        <WikiEditor
            v-model="contentBuffer"
            @update:modelValue="handleContentChange"
        />
      </div>
    </div>

    <div v-else class="flex h-full items-center justify-center text-gray-500">
      Seite nicht gefunden oder keine Berechtigung.
    </div>
  </div>
</template>

<script setup lang="ts">
import WikiEditor from '~/components/wiki/WikiEditor.vue'

const route = useRoute()
const { $api } = useNuxtApp()
const { loadTree } = useWikiTree()

const pageId = route.params.id as string

const isSaving = ref(false)
const lastSaved = ref(false)
const saveTimeout = ref<any>(null)
const contentBuffer = ref(null) // Zwischenspeicher für Editor

// Daten asynchron laden
// Wir nutzen eine unique Key-Strategy basierend auf der ID
const { data: page, pending } = await useAsyncData(`wiki-page-${pageId}`, async () => {
  const res = await $api<any>(`/api/wiki/${pageId}`)
  contentBuffer.value = res.content // Initiale Daten in Buffer
  return res
}, {
  // Wichtig: Neu laden wenn sich die Route ID ändert
  watch: [() => route.params.id]
})

// Titel Speichern (Sofort bei Blur)
async function saveTitle() {
  if (!page.value) return
  isSaving.value = true

  try {
    await $api(`/api/wiki/${pageId}`, {
      method: 'PATCH',
      body: { title: page.value.title }
    })

    // Sidebar neu laden, damit Titel dort aktuell ist
    loadTree()

    showSavedFeedback()
  } finally {
    isSaving.value = false
  }
}

// Inhalt Speichern (Mit Debounce Verzögerung)
function handleContentChange(newContent: any) {
  contentBuffer.value = newContent
  isSaving.value = true
  lastSaved.value = false

  if (saveTimeout.value) clearTimeout(saveTimeout.value)

  // Warte 1000ms nach dem letzten Tippen
  saveTimeout.value = setTimeout(async () => {
    try {
      await $api(`/api/wiki/${pageId}`, {
        method: 'PATCH',
        body: { content: contentBuffer.value }
      })
      showSavedFeedback()
    } catch (e) {
      // Fehler behandelt Plugin
    } finally {
      isSaving.value = false
    }
  }, 1000)
}

function showSavedFeedback() {
  lastSaved.value = true
  setTimeout(() => { lastSaved.value = false }, 2000)
}
</script>

<style scoped>
.fade-enter-active, .fade-leave-active { transition: opacity 0.5s; }
.fade-enter-from, .fade-leave-to { opacity: 0; }
</style>