import { Editor } from '@tiptap/core'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import Bold from '@tiptap/extension-bold'
import Italic from '@tiptap/extension-italic'
import Underline from '@tiptap/extension-underline'
import Heading from '@tiptap/extension-heading'
import BulletList from '@tiptap/extension-bullet-list'
import OrderedList from '@tiptap/extension-ordered-list'
import ListItem from '@tiptap/extension-list-item'
import Link from '@tiptap/extension-link'
import Image from '@tiptap/extension-image'
import Blockquote from '@tiptap/extension-blockquote'
import HorizontalRule from '@tiptap/extension-horizontal-rule'
import HardBreak from '@tiptap/extension-hard-break'
import History from '@tiptap/extension-history'
import TextAlign from '@tiptap/extension-text-align'

function slugify(str) {
    return str.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '')
}

function initToolbar(editor, container) {
    const COMMANDS = {
        bold:        () => editor.commands.toggleBold(),
        italic:      () => editor.commands.toggleItalic(),
        underline:   () => editor.commands.toggleUnderline(),
        h1:          () => editor.commands.toggleHeading({ level: 1 }),
        h2:          () => editor.commands.toggleHeading({ level: 2 }),
        h3:          () => editor.commands.toggleHeading({ level: 3 }),
        bulletList:  () => editor.commands.toggleBulletList(),
        orderedList: () => editor.commands.toggleOrderedList(),
        blockquote:  () => editor.commands.toggleBlockquote(),
        hr:          () => editor.commands.setHorizontalRule(),
        undo:        () => editor.commands.undo(),
        redo:        () => editor.commands.redo(),
        image:       () => document.dispatchEvent(new CustomEvent('editor:open-picker')),
        alignLeft:   () => editor.commands.setTextAlign('left'),
        alignCenter: () => editor.commands.setTextAlign('center'),
        alignRight:  () => editor.commands.setTextAlign('right'),
        alignJustify:() => editor.commands.setTextAlign('justify'),
    }

    container.addEventListener('mousedown', (e) => {
        const btn = e.target.closest('[data-cmd]')
        if (!btn) return
        e.preventDefault()
        const action = btn.dataset.cmd
        COMMANDS[action]?.()
    })

    function updateActive() {
        container.querySelectorAll('[data-cmd]').forEach(btn => {
            const cmd = btn.dataset.cmd
            const activeMap = {
                bold:         editor.isActive('bold'),
                italic:       editor.isActive('italic'),
                underline:    editor.isActive('underline'),
                h1:           editor.isActive('heading', { level: 1 }),
                h2:           editor.isActive('heading', { level: 2 }),
                h3:           editor.isActive('heading', { level: 3 }),
                bulletList:   editor.isActive('bulletList'),
                orderedList:  editor.isActive('orderedList'),
                blockquote:   editor.isActive('blockquote'),
                alignLeft:    editor.isActive({ textAlign: 'left' }),
                alignCenter:  editor.isActive({ textAlign: 'center' }),
                alignRight:   editor.isActive({ textAlign: 'right' }),
                alignJustify: editor.isActive({ textAlign: 'justify' }),
            }
            if (activeMap[cmd] !== undefined) {
                btn.classList.toggle('is-active', !!activeMap[cmd])
            }
        })
    }

    editor.on('selectionUpdate', updateActive)
    editor.on('update', updateActive)
}

export function initPostEditor(initial = {}) {
    const editorEl = document.getElementById('editor')
    const contentInput = document.getElementById('content-input')
    const titleInput = document.getElementById('post-title')
    const slugInput = document.getElementById('post-slug')
    const slugPreview = document.getElementById('slug-preview')
    const toolbar = document.getElementById('editor-toolbar')

    if (!editorEl) return

    // Slug auto-generation
    const regenBtn = document.getElementById('regenerate-slug')
    let autoSlug = !initial.slug
    if (titleInput && slugInput) {
        titleInput.addEventListener('input', () => {
            if (!autoSlug) return
            const s = slugify(titleInput.value)
            slugInput.value = s
            if (slugPreview) slugPreview.textContent = '/' + s
        })
        slugInput.addEventListener('input', () => {
            autoSlug = false
            if (slugPreview) slugPreview.textContent = '/' + slugInput.value
        })
    }
    if (regenBtn && titleInput && slugInput) {
        regenBtn.addEventListener('click', () => {
            const s = slugify(titleInput.value)
            slugInput.value = s
            if (slugPreview) slugPreview.textContent = '/' + s
        })
    }

    // TipTap
    const editor = new Editor({
        element: editorEl,
        extensions: [
            Document, Paragraph, Text, HardBreak, History,
            Bold, Italic, Underline, Blockquote, HorizontalRule,
            Heading.configure({ levels: [1, 2, 3] }),
            BulletList, OrderedList, ListItem,
            TextAlign.configure({ types: ['heading', 'paragraph'] }),
            Link.configure({ openOnClick: false }),
            Image,
        ],
        content: initial.content ?? '',
        editorProps: {
            attributes: {
                class: 'outline-none min-h-48 p-3',
            },
        },
        onUpdate({ editor }) {
            if (contentInput) contentInput.value = editor.getHTML()
        },
    })

    if (toolbar) initToolbar(editor, toolbar)

    window._tiptapEditor = editor
    return editor
}

// Alpine component — only handles slug display reactively
export function postEditorComponent(initial = {}) {
    return {
        slug: initial.slug ?? '',
        init() {
            this.$nextTick(() => initPostEditor(initial))
        },
    }
}
