<template>
  <div class="select-none text-sm text-gray-700 dark:text-gray-200 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 dark:bg-primary-900/10 text-primary-600 dark:text-primary-400 font-medium' : 'hover:bg-gray-100 dark:hover:bg-gray-800',
            item.isVirtual ? 'opacity-90' : ''
        ]"
        :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 dark:hover:text-gray-300 transition-transform duration-200"
          :class="{ 'rotate-90': isOpen }"
          @click.stop="toggleFolder"
      >
        <UIcon name="i-heroicons-chevron-right-20-solid" class="w-3 h-3" />
      </button>
      <span v-else class="w-4"></span>

      <span class="shrink-0 flex items-center">
        <UIcon
            v-if="item.isFolder && item.isVirtual"
            name="i-heroicons-folder"
            class="w-4 h-4 text-primary-500 dark:text-primary-400"
        />
        <UIcon
            v-else-if="item.isFolder"
            name="i-heroicons-folder-solid"
            class="w-4 h-4 text-yellow-400"
        />
        <UIcon
            v-else
            name="i-heroicons-document-text"
            class="w-4 h-4 text-gray-400"
        />
      </span>

      <span class="truncate flex-1" :class="{'italic text-gray-500': item.isVirtual && !item.parentId}">
        {{ item.title }}
      </span>

      <div v-if="!item.isVirtual" 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 dark:hover:bg-gray-700 text-gray-500">
          <UIcon name="i-heroicons-ellipsis-horizontal" class="w-4 h-4" />
        </button>
      </div>

      <div v-else class="absolute right-1 top-1 opacity-0 group-hover:opacity-50 transition-opacity flex items-center justify-center pt-0.5 pr-0.5">
        <UTooltip text="Automatisch generiert">
          <UIcon name="i-heroicons-lock-closed" class="w-3 h-3 text-gray-300" />
        </UTooltip>
      </div>

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

        <template v-if="item.isFolder">
          <button @click.stop="triggerCreate(false)" class="w-full text-left px-3 py-1.5 hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-2">
            <UIcon name="i-heroicons-plus" class="w-3 h-3" /> Neue Seite
          </button>
          <button @click.stop="triggerCreate(true)" class="w-full text-left px-3 py-1.5 hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-2">
            <UIcon name="i-heroicons-folder-plus" class="w-3 h-3 text-yellow-500" /> Neuer Ordner
          </button>
          <div class="h-px bg-gray-100 dark:bg-gray-700 my-1"></div>
        </template>

        <button @click.stop="triggerDelete" class="w-full text-left px-3 py-1.5 hover:bg-red-50 dark:hover:bg-red-900/30 text-red-600 flex items-center gap-2">
          <UIcon name="i-heroicons-trash" class="w-3 h-3" /> Löschen
        </button>
      </div>
    </div>

    <div v-if="item.isFolder && isOpen">
      <WikiTreeItem 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 { vOnClickOutside } from '@vueuse/components'
import type { WikiPageItem } from '~/composables/useWikiTree'

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

const openWikiAction = inject('openWikiAction') as (action: 'create' | 'delete', contextItem: WikiPageItem | null, isFolder?: boolean) => void

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: Active Page
watch(() => route.params.id, (newId) => {
  if (props.item.isFolder && hasActiveChild(props.item, newId as string)) isOpen.value = true
}, { immediate: true })

// Auto-Open: Search
watch(searchQuery, (newVal) => {
  if (newVal.trim().length > 0 && props.item.isFolder) {
    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() {
  if (props.item.isFolder) {
    isOpen.value = !isOpen.value
  } else {
    // Falls es eine virtuelle Seite ist (Read only Entity View?), leiten wir trotzdem weiter
    // oder verhindern es, je nach Wunsch. Aktuell erlauben wir Navigation:
    router.push(`/wiki/${props.item.id}`)
  }
}

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

function triggerCreate(isFolder: boolean) {
  // Sicherheitscheck: Virtuelle Ordner dürfen nichts erstellen
  if (props.item.isVirtual) return

  showMenu.value = false
  isOpen.value = true
  openWikiAction('create', props.item, isFolder)
}

function triggerDelete() {
  // Sicherheitscheck
  if (props.item.isVirtual) return

  showMenu.value = false
  openWikiAction('delete', props.item)
}
</script>