<template>
  <div class="flex h-full w-full bg-white overflow-hidden">

    <aside class="flex w-72 flex-col border-r border-gray-200 bg-gray-50/50">

      <div class="flex items-center justify-between border-b border-gray-200 px-4 py-3 bg-white h-14">
        <h2 class="font-semibold text-gray-800">Wiki</h2>
        <button
            @click="createNewPage"
            class="p-1.5 text-gray-500 hover:text-primary-600 rounded hover:bg-gray-100 transition-colors"
            title="Neue Seite erstellen"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5 h-5"><path d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z" /></svg>
        </button>
      </div>

      <div class="flex-1 overflow-y-auto px-2 py-3 custom-scrollbar">
        <div v-if="isLoading && !tree.length" class="space-y-2 px-2 mt-2">
          <div class="h-4 w-3/4 bg-gray-200 animate-pulse rounded"></div>
          <div class="h-4 w-1/2 bg-gray-200 animate-pulse rounded"></div>
          <div class="h-4 w-5/6 bg-gray-200 animate-pulse rounded"></div>
        </div>

        <div v-else>
          <WikiTreeItem v-for="node in tree" :key="node.id" :item="node" />

          <div v-if="!tree.length" class="text-center text-sm text-gray-400 mt-10 px-4">
            Keine Einträge vorhanden.<br>Erstelle die erste Seite!
          </div>
        </div>
      </div>
    </aside>

    <main class="flex-1 overflow-hidden relative bg-white h-full">
      <NuxtPage />
    </main>
  </div>
</template>

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

const { tree, isLoading, loadTree } = useWikiTree()
const { $api } = useNuxtApp()
const router = useRouter()

// Initiales Laden des "Allgemeinen" Wikis
onMounted(() => loadTree())

async function createNewPage() {
  const title = prompt("Titel der neuen Seite:", "Neue Notiz")
  if (!title) return

  try {
    // API Call: POST mit body
    const newPage = await $api('/api/wiki', {
      method: 'POST',
      body: {
        title,
        parentId: null,
        isFolder: false,
        // EntityType ist hier null, da es im Haupt-Wiki erstellt wird
        entityType: null
      }
    })

    await loadTree() // Baum refreshen

    // @ts-ignore (Falls Typen nicht perfekt gematcht)
    if (newPage?.id) {
      // @ts-ignore
      router.push(`/wiki/${newPage.id}`)
    }
  } catch (e) {
    // Fehler werden durch Plugin angezeigt
  }
}
</script>

<style scoped>
.custom-scrollbar::-webkit-scrollbar { width: 4px; }
.custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
.custom-scrollbar::-webkit-scrollbar-thumb { background-color: #e5e7eb; border-radius: 10px; }
</style>