<script setup>
/**
 * TiptapEditor - Rich text editor component
 */
import { useEditor, EditorContent } from '@tiptap/vue-3';
import StarterKit from '@tiptap/starter-kit';
import Image from '@tiptap/extension-image';
import Link from '@tiptap/extension-link';
import Placeholder from '@tiptap/extension-placeholder';
import TextAlign from '@tiptap/extension-text-align';
import Underline from '@tiptap/extension-underline';
import Highlight from '@tiptap/extension-highlight';
import { ref, watch, onMounted } from 'vue';

const props = defineProps({
    modelValue: {
        type: String,
        default: '',
    },
    placeholder: {
        type: String,
        default: 'Escribe aquí...',
    },
    uploadUrl: {
        type: String,
        default: null,
    },
});

const emit = defineEmits(['update:modelValue']);

const editor = useEditor({
    content: props.modelValue,
    extensions: [
        StarterKit.configure({
            heading: {
                levels: [1, 2, 3],
            },
        }),
        Image.configure({
            inline: true,
            allowBase64: true,
        }),
        Link.configure({
            openOnClick: false,
            HTMLAttributes: {
                class: 'text-blue-600 underline',
            },
        }),
        Placeholder.configure({
            placeholder: props.placeholder,
        }),
        TextAlign.configure({
            types: ['heading', 'paragraph'],
        }),
        Underline,
        Highlight.configure({
            multicolor: true,
        }),
    ],
    editorProps: {
        attributes: {
            class: 'prose prose-sm sm:prose max-w-none focus:outline-none min-h-[300px] p-4 dark:prose-invert',
        },
    },
    onUpdate: ({ editor }) => {
        emit('update:modelValue', editor.getHTML());
    },
});

watch(() => props.modelValue, (value) => {
    if (editor.value && value !== editor.value.getHTML()) {
        editor.value.commands.setContent(value, false);
    }
});

// Link modal
const showLinkModal = ref(false);
const linkUrl = ref('');

const setLink = () => {
    if (linkUrl.value) {
        editor.value
            .chain()
            .focus()
            .extendMarkRange('link')
            .setLink({ href: linkUrl.value })
            .run();
    }
    showLinkModal.value = false;
    linkUrl.value = '';
};

const removeLink = () => {
    editor.value.chain().focus().unsetLink().run();
};

// Image upload
const fileInput = ref(null);

const uploadImage = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    if (props.uploadUrl) {
        const formData = new FormData();
        formData.append('image', file);

        try {
            const response = await fetch(props.uploadUrl, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'),
                },
            });
            const data = await response.json();
            if (data.url) {
                editor.value.chain().focus().setImage({ src: data.url }).run();
            }
        } catch (error) {
        }
    } else {
        // Convert to base64
        const reader = new FileReader();
        reader.onload = () => {
            editor.value.chain().focus().setImage({ src: reader.result }).run();
        };
        reader.readAsDataURL(file);
    }
    
    event.target.value = '';
};

const triggerImageUpload = () => {
    fileInput.value?.click();
};
</script>

<template>
    <div class="border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden bg-white dark:bg-gray-800">
        <!-- Toolbar -->
        <div v-if="editor" class="flex flex-wrap items-center gap-1 p-2 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900">
            <!-- Text formatting -->
            <button 
                type="button"
                @click="editor.chain().focus().toggleBold().run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('bold') }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Negrita"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z"/></svg>
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().toggleItalic().run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('italic') }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Cursiva"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M10 4v3h2.21l-3.42 8H6v3h8v-3h-2.21l3.42-8H18V4z"/></svg>
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().toggleUnderline().run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('underline') }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Subrayado"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M12 17c3.31 0 6-2.69 6-6V3h-2.5v8c0 1.93-1.57 3.5-3.5 3.5S8.5 12.93 8.5 11V3H6v8c0 3.31 2.69 6 6 6zm-7 2v2h14v-2H5z"/></svg>
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().toggleStrike().run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('strike') }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Tachado"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M10 19h4v-3h-4v3zM5 4v3h5v3h4V7h5V4H5zM3 14h18v-2H3v2z"/></svg>
            </button>
            
            <div class="w-px h-6 bg-gray-300 dark:bg-gray-600 mx-1"></div>
            
            <!-- Headings -->
            <button 
                type="button"
                @click="editor.chain().focus().toggleHeading({ level: 1 }).run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('heading', { level: 1 }) }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors text-sm font-bold"
                title="Título 1"
            >
                H1
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().toggleHeading({ level: 2 }).run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('heading', { level: 2 }) }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors text-sm font-bold"
                title="Título 2"
            >
                H2
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().toggleHeading({ level: 3 }).run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('heading', { level: 3 }) }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors text-sm font-bold"
                title="Título 3"
            >
                H3
            </button>
            
            <div class="w-px h-6 bg-gray-300 dark:bg-gray-600 mx-1"></div>
            
            <!-- Lists -->
            <button 
                type="button"
                @click="editor.chain().focus().toggleBulletList().run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('bulletList') }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Lista"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M4 10.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm0-6c-.83 0-1.5.67-1.5 1.5S3.17 7.5 4 7.5 5.5 6.83 5.5 6 4.83 4.5 4 4.5zm0 12c-.83 0-1.5.68-1.5 1.5s.68 1.5 1.5 1.5 1.5-.68 1.5-1.5-.67-1.5-1.5-1.5zM7 19h14v-2H7v2zm0-6h14v-2H7v2zm0-8v2h14V5H7z"/></svg>
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().toggleOrderedList().run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('orderedList') }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Lista numerada"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M2 17h2v.5H3v1h1v.5H2v1h3v-4H2v1zm1-9h1V4H2v1h1v3zm-1 3h1.8L2 13.1v.9h3v-1H3.2L5 10.9V10H2v1zm5-6v2h14V5H7zm0 14h14v-2H7v2zm0-6h14v-2H7v2z"/></svg>
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().toggleBlockquote().run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('blockquote') }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Cita"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z"/></svg>
            </button>
            
            <div class="w-px h-6 bg-gray-300 dark:bg-gray-600 mx-1"></div>
            
            <!-- Text alignment -->
            <button 
                type="button"
                @click="editor.chain().focus().setTextAlign('left').run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive({ textAlign: 'left' }) }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Alinear izquierda"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M15 15H3v2h12v-2zm0-8H3v2h12V7zM3 13h18v-2H3v2zm0 8h18v-2H3v2zM3 3v2h18V3H3z"/></svg>
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().setTextAlign('center').run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive({ textAlign: 'center' }) }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Centrar"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z"/></svg>
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().setTextAlign('right').run()"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive({ textAlign: 'right' }) }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Alinear derecha"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z"/></svg>
            </button>
            
            <div class="w-px h-6 bg-gray-300 dark:bg-gray-600 mx-1"></div>
            
            <!-- Link & Image -->
            <button 
                type="button"
                @click="showLinkModal = true"
                :class="{ 'bg-gray-200 dark:bg-gray-700': editor.isActive('link') }"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Insertar enlace"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/></svg>
            </button>
            <button 
                v-if="editor.isActive('link')"
                type="button"
                @click="removeLink"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors text-red-500"
                title="Quitar enlace"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M17 7h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1 0 1.43-.98 2.63-2.31 2.98l1.46 1.46C20.88 15.61 22 13.95 22 12c0-2.76-2.24-5-5-5zm-1 4h-2.19l2 2H16v-2zM2 4.27l3.11 3.11C3.29 8.12 2 9.91 2 12c0 2.76 2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1 0-1.59 1.21-2.9 2.76-3.07L8.73 11H8v2h2.73L13 15.27V17h1.73l4.01 4L20 19.74 3.27 3 2 4.27z"/></svg>
            </button>
            <button 
                type="button"
                @click="triggerImageUpload"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                title="Insertar imagen"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/></svg>
            </button>
            <input 
                ref="fileInput"
                type="file"
                accept="image/*"
                class="hidden"
                @change="uploadImage"
            />
            
            <div class="w-px h-6 bg-gray-300 dark:bg-gray-600 mx-1"></div>
            
            <!-- Undo/Redo -->
            <button 
                type="button"
                @click="editor.chain().focus().undo().run()"
                :disabled="!editor.can().undo()"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors disabled:opacity-30"
                title="Deshacer"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/></svg>
            </button>
            <button 
                type="button"
                @click="editor.chain().focus().redo().run()"
                :disabled="!editor.can().redo()"
                class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors disabled:opacity-30"
                title="Rehacer"
            >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M18.4 10.6C16.55 8.99 14.15 8 11.5 8c-4.65 0-8.58 3.03-9.96 7.22L3.9 16c1.05-3.19 4.05-5.5 7.6-5.5 1.95 0 3.73.72 5.12 1.88L13 16h9V7l-3.6 3.6z"/></svg>
            </button>
        </div>

        <!-- Editor -->
        <editor-content :editor="editor" />

        <!-- Link Modal -->
        <Teleport to="body">
            <div v-if="showLinkModal" class="fixed inset-0 z-50 flex items-center justify-center">
                <div class="fixed inset-0 bg-black/50" @click="showLinkModal = false"></div>
                <div class="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-md">
                    <h3 class="text-lg font-semibold mb-4 text-gray-900 dark:text-white">Insertar Enlace</h3>
                    <input 
                        v-model="linkUrl"
                        type="url"
                        placeholder="https://ejemplo.com"
                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white mb-4"
                        @keyup.enter="setLink"
                    />
                    <div class="flex justify-end gap-3">
                        <button 
                            type="button"
                            @click="showLinkModal = false"
                            class="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
                        >
                            Cancelar
                        </button>
                        <button 
                            type="button"
                            @click="setLink"
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                        >
                            Insertar
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>
    </div>
</template>

<style>
/* Tiptap Editor Styles */
.ProseMirror {
    @apply min-h-[300px] p-4;
}

.ProseMirror p.is-editor-empty:first-child::before {
    @apply text-gray-400 dark:text-gray-500;
    content: attr(data-placeholder);
    float: left;
    height: 0;
    pointer-events: none;
}

.ProseMirror:focus {
    outline: none;
}

.ProseMirror img {
    @apply max-w-full h-auto rounded-lg my-4;
}

.ProseMirror blockquote {
    @apply border-l-4 border-gray-300 dark:border-gray-600 pl-4 italic;
}

.ProseMirror h1 {
    @apply text-3xl font-bold mb-4;
}

.ProseMirror h2 {
    @apply text-2xl font-bold mb-3;
}

.ProseMirror h3 {
    @apply text-xl font-bold mb-2;
}

.ProseMirror ul, .ProseMirror ol {
    @apply pl-6 mb-4;
}

.ProseMirror ul {
    @apply list-disc;
}

.ProseMirror ol {
    @apply list-decimal;
}
</style>
