<template>
  <div class="flex flex-col h-full bg-white dark:bg-gray-900 relative">

    <div v-if="editor" class="border-b border-gray-100 dark:border-gray-800 px-4 py-2 flex flex-wrap gap-1 items-center sticky top-0 bg-white dark:bg-gray-900 z-20 shadow-sm select-none">

      <div class="flex gap-0.5 border-r border-gray-200 dark:border-gray-700 pr-2 mr-2">
        <button @click="editor.chain().focus().toggleBold().run()" :class="{ 'is-active': editor.isActive('bold') }" class="toolbar-btn font-bold" title="Fett">B</button>
        <button @click="editor.chain().focus().toggleItalic().run()" :class="{ 'is-active': editor.isActive('italic') }" class="toolbar-btn italic" title="Kursiv">I</button>
        <button @click="editor.chain().focus().toggleStrike().run()" :class="{ 'is-active': editor.isActive('strike') }" class="toolbar-btn line-through" title="Durchgestrichen">S</button>
        <button @click="editor.chain().focus().toggleHighlight().run()" :class="{ 'is-active': editor.isActive('highlight') }" class="toolbar-btn text-yellow-500 font-bold" title="Markieren">M</button>
      </div>

      <div class="flex gap-0.5 border-r border-gray-200 dark:border-gray-700 pr-2 mr-2">
        <button @click="editor.chain().focus().toggleHeading({ level: 1 }).run()" :class="{ 'is-active': editor.isActive('heading', { level: 1 }) }" class="toolbar-btn" title="Überschrift 1">H1</button>
        <button @click="editor.chain().focus().toggleHeading({ level: 2 }).run()" :class="{ 'is-active': editor.isActive('heading', { level: 2 }) }" class="toolbar-btn" title="Überschrift 2">H2</button>
        <button @click="editor.chain().focus().toggleCodeBlock().run()" :class="{ 'is-active': editor.isActive('codeBlock') }" class="toolbar-btn font-mono text-xs" title="Code Block">&lt;/&gt;</button>
      </div>

      <div class="flex gap-0.5 border-r border-gray-200 dark:border-gray-700 pr-2 mr-2">
        <button @click="editor.chain().focus().toggleBulletList().run()" :class="{ 'is-active': editor.isActive('bulletList') }" class="toolbar-btn" title="Liste">•</button>
        <button @click="editor.chain().focus().toggleTaskList().run()" :class="{ 'is-active': editor.isActive('taskList') }" class="toolbar-btn" title="Aufgabenliste">☑</button>
      </div>

      <div class="flex gap-0.5 items-center">
        <button @click="editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()" class="toolbar-btn" title="Tabelle">▦</button>
        <button @click="addVideo" class="toolbar-btn text-red-600" title="YouTube Video">
          <UIcon name="i-heroicons-video-camera" class="w-4 h-4" />
        </button>
      </div>
    </div>

    <BubbleMenu
        v-if="editor"
        :editor="editor"
        :tippy-options="{ duration: 200, placement: 'top-start', animation: 'scale' }"
        class="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl flex items-center p-1 gap-1 z-50"
    >
      <button @click="editor.chain().focus().toggleBold().run()" :class="{ 'is-active': editor.isActive('bold') }" class="bubble-btn font-bold">B</button>
      <button @click="editor.chain().focus().toggleItalic().run()" :class="{ 'is-active': editor.isActive('italic') }" class="bubble-btn italic">I</button>
      <button @click="editor.chain().focus().toggleHighlight().run()" :class="{ 'is-active': editor.isActive('highlight') }" class="bubble-btn text-yellow-500 font-bold">M</button>
      <div class="w-px h-4 bg-gray-200 mx-1"></div>
      <button @click="editor.chain().focus().toggleHeading({ level: 2 }).run()" :class="{ 'is-active': editor.isActive('heading', { level: 2 }) }" class="bubble-btn font-bold text-sm">H2</button>
      <div class="w-px h-4 bg-gray-200 mx-1"></div>
      <button @click="setLink" :class="{ 'is-active': editor.isActive('link') }" class="bubble-btn text-sm">Link</button>
    </BubbleMenu>

    <FloatingMenu
        v-if="editor"
        :editor="editor"
        :tippy-options="{ duration: 100, placement: 'right-start' }"
        class="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg flex items-center p-1 gap-1 -ml-4"
    >
      <button @click="editor.chain().focus().toggleHeading({ level: 1 }).run()" class="bubble-btn text-xs font-bold">H1</button>
      <button @click="editor.chain().focus().toggleHeading({ level: 2 }).run()" class="bubble-btn text-xs font-bold">H2</button>
      <button @click="editor.chain().focus().toggleBulletList().run()" class="bubble-btn">•</button>
      <button @click="editor.chain().focus().toggleTaskList().run()" class="bubble-btn">☑</button>
      <button @click="editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()" class="bubble-btn">▦</button>
      <button @click="editor.chain().focus().toggleCodeBlock().run()" class="bubble-btn font-mono text-xs">&lt;&gt;</button>
    </FloatingMenu>

    <editor-content
        :editor="editor"
        class="flex-1 overflow-y-auto px-8 py-6 prose prose-slate dark:prose-invert max-w-none focus:outline-none custom-editor-area"
    />

    <div v-if="editor" class="border-t border-gray-100 dark:border-gray-800 px-4 py-1 text-xs text-gray-400 flex justify-end bg-gray-50 dark:bg-gray-900/50">
      {{ editor.storage.characterCount.words() }} Wörter
    </div>
  </div>
</template>

<script setup lang="ts">
import { watch } from 'vue'
import { useRouter } from '#app'
import { useEditor, EditorContent, VueNodeViewRenderer } from '@tiptap/vue-3'
// @ts-ignore
import { BubbleMenu, FloatingMenu } from '@tiptap/vue-3/menus'

// Tiptap Extensions
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
import Link from '@tiptap/extension-link'
import TaskList from '@tiptap/extension-task-list'
import TaskItem from '@tiptap/extension-task-item'
import Image from '@tiptap/extension-image'
import Highlight from '@tiptap/extension-highlight'
import Youtube from '@tiptap/extension-youtube'
import Typography from '@tiptap/extension-typography'
import CharacterCount from '@tiptap/extension-character-count'
import CodeBlock from '@tiptap/extension-code-block'

// -----------------------------------------------------------
// WICHTIGE ÄNDERUNG: NUR Table, KEINE Row/Cell/Header Imports
// -----------------------------------------------------------
import { Table } from '@tiptap/extension-table'
import { TableRow } from '@tiptap/extension-table-row'
import { TableCell } from '@tiptap/extension-table-cell'
import { TableHeader } from '@tiptap/extension-table-header'

import BubbleMenuExtension from '@tiptap/extension-bubble-menu'
import FloatingMenuExtension from '@tiptap/extension-floating-menu'
import Mention from '@tiptap/extension-mention'

import TiptapTaskItem from './TiptapTaskItem.vue'
import wikiSuggestion from '~/composables/useWikiSuggestion'

const props = defineProps<{ modelValue: any }>()
const emit = defineEmits(['update:modelValue'])
const router = useRouter()

// Damit wir TaskItem nicht ständig neu initialisieren
const CustomTaskItem = TaskItem.extend({
  addNodeView() {
    return VueNodeViewRenderer(TiptapTaskItem)
  },
})

const editor = useEditor({
  content: props.modelValue,
  extensions: [
    StarterKit.configure({ codeBlock: false }),
    Placeholder.configure({ placeholder: 'Tippe "/" für Befehle oder "#" für Seiten...' }),

    BubbleMenuExtension.configure({ shouldShow: ({ editor, from, to }) => !editor.state.selection.empty && (to - from > 0) }),
    FloatingMenuExtension,

    Link.configure({ openOnClick: false, autolink: true }),
    Image, Highlight, Typography, CharacterCount, CodeBlock,
    Youtube.configure({ width: 640, height: 480 }),

    // -----------------------------------------------------------
    // WICHTIGE ÄNDERUNG: Nur Table.configure()
    // TableRow, TableHeader, TableCell wurden HIER ENTFERNT
    // -----------------------------------------------------------
    Table.configure({ resizable: true }),
    TableRow,
    TableHeader,
    TableCell,

    // TASK LIST
    TaskList,
    CustomTaskItem.configure({
      nested: true,
    }),

    // INTERNAL LINKING
    Mention.configure({
      HTMLAttributes: {
        class: 'wiki-mention',
      },
      suggestion: {
        ...wikiSuggestion,
        char: '#'
      },

    }),
  ],
  editorProps: {
    attributes: {
      class: 'min-h-[500px] pb-40',
    },
    handleClick: (view, pos, event) => {
      const target = event.target as HTMLElement
      if (target.closest('.wiki-mention')) {
        const id = target.getAttribute('data-id')
        if (id) {
          router.push(`/wiki/${id}`)
          return true
        }
      }
      return false
    }
  },
  onUpdate: ({ editor }) => {
    emit('update:modelValue', editor.getJSON())
  },
})

// Sync Model -> Editor
watch(() => props.modelValue, (val) => {
  if (editor.value && JSON.stringify(val) !== JSON.stringify(editor.value.getJSON())) {
    //@ts-ignore
    editor.value.commands.setContent(val, false)
  }
})

// ACTIONS
const setLink = () => {
  if (!editor.value) return
  const previousUrl = editor.value.getAttributes('link').href
  const url = window.prompt('URL eingeben:', previousUrl)
  if (url === null) return
  if (url === '') {
    editor.value.chain().focus().extendMarkRange('link').unsetLink().run()
    return
  }
  editor.value.chain().focus().extendMarkRange('link').setLink({ href: url }).run()
}

const addVideo = () => {
  const url = prompt('Video URL:')
  if (url && editor.value) editor.value.commands.setYoutubeVideo({ src: url })
}
</script>

<style scoped>
/* Toolbar & Buttons */
.toolbar-btn {
  padding: 0.375rem;
  border-radius: 0.25rem;
  color: #4b5563;
  transition: background-color 0.2s ease, color 0.2s ease;
  font-size: 0.875rem;
  font-weight: 500;
  min-width: 28px;
  height: 28px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.toolbar-btn.is-active {
  background: #e5e7eb;
  color: #000;
  box-shadow: inset 0 2px 4px 0 rgb(0 0 0 / 0.05);
}
.bubble-btn {
  padding: 0.25rem 0.5rem;
  border-radius: 0.25rem;
  transition: background-color 0.2s ease, color 0.2s ease;
  font-size: 0.875rem;
  min-width: 24px;
  height: 24px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: #374151;
}
.bubble-btn.is-active {
  background: #e5e7eb;
  color: #000;
}

.toolbar-btn:hover,
.bubble-btn:hover {
  background: #f3f4f6;
}

:global(.dark) .toolbar-btn {
  color: #d1d5db;
}

:global(.dark) .toolbar-btn:hover,
:global(.dark) .bubble-btn:hover {
  background: #374151;
}

:global(.dark) .toolbar-btn.is-active,
:global(.dark) .bubble-btn.is-active {
  background: #4b5563;
  color: #fff;
}

:global(.dark) .bubble-btn {
  color: #e5e7eb;
}

/* GLOBAL EDITOR STYLES */
:deep(.prose) {
  .ProseMirror {
    outline: none;
    caret-color: currentColor;
  }

  /* LIST RESET */
  ul[data-type="taskList"] {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  /* MENTION */
  .wiki-mention {
    /* Pill-Shape, grau/neutral statt knallig blau */
    background: #f3f4f6;
    color: #374151;
    padding: 0.125rem 0.375rem;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
    text-decoration: none;
    display: inline-block;
    margin-inline: 0.125rem;
    vertical-align: middle;
    border: 1px solid #e5e7eb;
    box-decoration-break: clone;
  }

  .wiki-mention::before {
    color: #9ca3af;
    margin-right: 0.125rem;
  }

  .wiki-mention:hover {
    background: #eefbf0;
    border-color: #bbf7d0;
    color: #15803d;
    cursor: pointer;
  }

  :global(.dark) .wiki-mention {
    background: #1f2937;
    color: #e5e7eb;
    border-color: #374151;
  }

  :global(.dark) .wiki-mention::before {
    color: #6b7280;
  }

  :global(.dark) .wiki-mention:hover {
    background: rgb(20 83 45 / 0.3);
    border-color: #166534;
    color: #4ade80;
  }

  /* TABLE */
  table { width: 100% !important; border-collapse: collapse; table-layout: fixed; margin: 1rem 0; }
  th, td { border: 1px solid #d1d5db; padding: 0.5rem; vertical-align: top; box-sizing: border-box; min-width: 1em; }
  .dark th, .dark td { border-color: #374151; }
  th { background-color: #f3f4f6; font-weight: 600; text-align: left; }
  .dark th { background-color: #1f2937; }
  .column-resize-handle { background-color: #3b82f6; width: 4px; }

  /* CODE */
  pre { background: #0d1117; color: #c9d1d9; font-family: var(--font-mono); padding: 0.75rem 1rem; border-radius: 0.5rem; margin: 1rem 0; overflow-x: auto; }
  code { color: inherit; padding: 0; background: none; font-size: 0.9rem; }

  /* IMG */
  img { max-width: 100%; height: auto; border-radius: 6px; display: block; margin: 1rem 0; }

  /* MISC */
  p.is-editor-empty:first-child::before { color: #9ca3af; content: attr(data-placeholder); float: left; height: 0; pointer-events: none; }
  mark { background-color: #fef08a; padding: 0.1rem 0.2rem; border-radius: 0.2rem; }
  .ProseMirror-selectednode { outline: 2px solid #3b82f6; }
}
</style>
