<template>
  <div class="select-none text-sm text-gray-700 relative">

    <div
        class="group flex items-center gap-2 rounded-md px-2 py-1.5 cursor-pointer transition-colors mb-0.5 relative pr-8"
        :class="[isActive ? 'bg-primary-50 text-primary-700 font-medium' : 'hover:bg-gray-100']"
        :style="{ paddingLeft: `${indent}rem` }"
        @click.stop="handleClick"
    >
      <button
          v-if="item.isFolder"
          class="h-4 w-4 flex items-center justify-center text-gray-400 hover:text-gray-600 transition-transform duration-200"
          :class="{ 'rotate-90': isOpen }"
          @click.stop="toggleFolder"
      >
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3"><path fill-rule="evenodd" d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z" clip-rule="evenodd" /></svg>
      </button>
      <span v-else class="w-4"></span>

      <span class="text-gray-400 shrink-0">
        <svg v-if="item.isFolder" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4 text-yellow-400"><path d="M3.75 3A1.75 1.75 0 002 4.75v3.26a3.235 3.235 0 011.75-.51h12.5c.644 0 1.245.188 1.75.51V6.75A1.75 1.75 0 0016.25 5h-4.836a.25.25 0 01-.177-.073L9.823 3.513A1.75 1.75 0 008.586 3H3.75zM3.75 9A1.75 1.75 0 002 10.75v4.5c0 .966.784 1.75 1.75 1.75h12.5A1.75 1.75 0 0018 15.25v-4.5A1.75 1.75 0 0016.25 9H3.75z" /></svg>
        <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4"><path fill-rule="evenodd" d="M4.5 2A1.5 1.5 0 003 3.5v13A1.5 1.5 0 004.5 18h11a1.5 1.5 0 001.5-1.5V7.621a1.5 1.5 0 00-.44-1.06l-4.12-4.122A1.5 1.5 0 0011.378 2H4.5zm2.25 8.5a.75.75 0 000 1.5h6.5a.75.75 0 000-1.5h-6.5zm0 3a.75.75 0 000 1.5h6.5a.75.75 0 000-1.5h-6.5z" clip-rule="evenodd" /></svg>
      </span>

      <span class="truncate flex-1">{{ item.title }}</span>

      <div class="absolute right-1 top-1 opacity-0 group-hover:opacity-100 transition-opacity" :class="{ '!opacity-100': showMenu }">
        <button
            @click.stop="showMenu = !showMenu"
            class="p-0.5 rounded hover:bg-gray-200 text-gray-500"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4"><path d="M3 10a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zM8.5 10a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zM15.5 8.5a1.5 1.5 0 100 3 1.5 1.5 0 000-3z" /></svg>
        </button>
      </div>

      <div v-if="showMenu" v-on-click-outside="() => showMenu = false" class="absolute right-0 top-8 z-50 w-40 bg-white rounded-md shadow-lg border border-gray-100 py-1 text-xs text-gray-700 animate-in fade-in slide-in-from-top-1 duration-100">

        <template v-if="item.isFolder">
          <button @click.stop="createChild(false)" class="w-full text-left px-3 py-1.5 hover:bg-gray-50 flex items-center gap-2">
            <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
            Neue Seite
          </button>
          <button @click.stop="createChild(true)" class="w-full text-left px-3 py-1.5 hover:bg-gray-50 flex items-center gap-2">
            <svg class="w-3 h-3 text-yellow-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" /></svg>
            Neuer Ordner
          </button>
          <div class="h-px bg-gray-100 my-1"></div>
        </template>

        <button @click.stop="handleDelete" class="w-full text-left px-3 py-1.5 hover:bg-red-50 text-red-600 flex items-center gap-2">
          <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
          Löschen
        </button>
      </div>

    </div>

    <div v-if="item.isFolder && isOpen">
      <TreeItem v-for="child in item.children" :key="child.id" :item="child" :depth="depth + 1" />
      <div v-if="!item.children?.length" class="text-xs text-gray-400 py-1 italic" :style="{ paddingLeft: `${indent + 1.8}rem` }">Leer</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { WikiPageItem } from '~/composables/useWikiTree'
import TreeItem from './TreeItem.vue'
// Simple Click Outside Directive (kannst du auch global registrieren)
import { vOnClickOutside } from '@vueuse/components'

const props = defineProps<{ item: WikiPageItem; depth?: number }>()
const router = useRouter()
const route = useRoute()

// Composable Actions holen
const { createItem, deleteItem } = useWikiTree()

const depth = props.depth ?? 0
const indent = computed(() => 0.5 + (depth * 0.7))
const isOpen = ref(false)
const showMenu = ref(false)
const isActive = computed(() => route.params.id === props.item.id)

// Auto-Open Logic
watch(() => route.params.id, (newId) => {
  if (props.item.isFolder && hasActiveChild(props.item, newId as string)) isOpen.value = true
}, { immediate: true })

function hasActiveChild(node: WikiPageItem, targetId: string): boolean {
  if (node.id === targetId) return true
  return node.children?.some(c => hasActiveChild(c, targetId)) ?? false
}

function handleClick() {
  props.item.isFolder ? (isOpen.value = !isOpen.value) : router.push(`/wiki/${props.item.id}`)
}

function toggleFolder() { isOpen.value = !isOpen.value }

// --- ACTIONS ---

async function createChild(isFolder: boolean) {
  showMenu.value = false
  // Wir öffnen den Ordner automatisch, damit man das neue Item sieht
  isOpen.value = true

  const type = isFolder ? "Ordner" : "Seite"
  const title = prompt(`Name für ${type}:`)
  if (!title) return

  const newItem = await createItem(title, props.item.id, isFolder)

  // Wenn es eine Seite ist, direkt hin navigieren
  if (newItem && !isFolder) {
    // @ts-ignore
    router.push(`/wiki/${newItem.id}`)
  }
}

async function handleDelete() {
  showMenu.value = false
  const success = await deleteItem(props.item.id)

  if (success && isActive.value) {
    // Wenn wir die aktive Seite gelöscht haben, zurück zum Root
    router.push('/wiki')
  }
}
</script>