<div
    x-data="{
        task: {
            title: '',
            description: '',
            priority: 'medium',
            rating: 0,
            priority_score: 0,
            estimates: null,
            due_date: '',
            start_date: '',
            url: '',
            email: '',
            phone: '',
            tags: [],
            assignee_id: null,
            workspace_id: null,
            folder_id: null,
            parent_id: null,
            is_recurring: false,
            recurring_interval: null,
            properties: [],
            sub_tasks: [],
            supporting_files: [],
            kanban_column_id: null
        },
        editor: null,
        mode: 'create',
        taskId: null,
        show: false,
        showBlockMenu: false,
        newSubTask: '',
        editorRetryCount: 0,
        init() {
            this.$watch('task.is_recurring', value => {
                if (!value) this.task.recurring_interval = null;
            });
        },
        reset() {
            this.task = {
                title: '',
                description: '',
                priority: 'medium',
                rating: 0,
                priority_score: 0,
                estimates: null,
                due_date: '',
                start_date: '',
                url: '',
                email: '',
                phone: '',
                tags: [],
                assignee_id: null,
                workspace_id: null,
                folder_id: null,
                parent_id: null,
                is_recurring: false,
                recurring_interval: null,
                properties: [],
                sub_tasks: [],
                supporting_files: [],
                kanban_column_id: null
            };
            this.mode = 'create';
            this.taskId = null;
            this.showBlockMenu = false;
            this.editorRetryCount = 0;
        },
        submit() {
            // Frontend validation
            if (!this.task.title || this.task.title.trim() === '') {
                window.dispatchEvent(new CustomEvent('notify', { 
                    detail: { message: 'Judul tugas (Title) wajib diisi!', type: 'error' } 
                }));
                return;
            }

            // Clone data to avoid reference issues when reset() is called immediately
            const taskClone = JSON.parse(JSON.stringify(this.task));
            
            // JSON.stringify loses File objects, so we must restore them for supporting_files
            if (this.task.supporting_files) {
                taskClone.supporting_files = this.task.supporting_files.map((file, index) => ({
                    ...taskClone.supporting_files[index],
                    raw_file: file.raw_file // Restore the original File object
                }));
            }

            console.log('📤 Submitting task data:', taskClone);

            if (this.mode === 'create') {
                this.$dispatch('create-task', taskClone);
            } else {
                this.$dispatch('update-task', { id: this.taskId, data: taskClone });
            }
            this.close();
        },
        close() {
            this.show = false;
            // Clean up editor to prevent memory leaks and transaction errors
            if (this.editor) {
                try {
                    this.editor.destroy();
                    this.editor = null;
                } catch (e) {
                    console.warn('Editor destruction failed:', e);
                }
            }
            this.reset();
        },
        initEditor() {
            console.log('🚀 initEditor called, editor state:', !!this.editor);
            if (!this.editor) {
                if (typeof window.setupRichEditor !== 'function') {
                    if (this.editorRetryCount > 10) {
                        console.error('❌ Rich Editor failed to load after 10 retries. Stopping.');
                        return;
                    }
                    console.warn(`⚠️ Rich Editor setup function not found, retrying (${this.editorRetryCount}/10)...`);
                    this.editorRetryCount++;
                    setTimeout(() => this.initEditor(), 500);
                    return;
                }
                
                try {
                    console.log('🛠️ Attempting window.setupRichEditor...');
                    this.editor = window.setupRichEditor(this.$refs.editor, this.task.description, (html) => {
                        this.task.description = html;
                    });
                    console.log('✅ Editor instance created:', !!this.editor);
                } catch (e) {
                    console.error('❌ Failed to initialize editor:', e);
                }
            } else if (this.editor) {
                console.log('♻️ Re-setting editor content - Checking for changes');
                // Use setTimeout to ensure we are outside of any current editor transaction
                setTimeout(() => {
                    if (!this.editor || this.editor.isDestroyed) return;
                    
                    const currentContent = this.editor.getHTML();
                    const newContent = this.task.description || '';
                    if (currentContent !== newContent && newContent !== '<p></p>') {
                        try {
                            this.editor.commands.setContent(newContent);
                        } catch (e) {
                            console.warn('⚠️ Tiptap content sync deferred or failed:', e.message);
                        }
                    }
                }, 0);
            }
        },
        insertBlock(type, level = null) {
            console.log('Inserting block:', type, level);
            if (!this.editor) {
                window.dispatchEvent(new CustomEvent('notify', { 
                    detail: { message: 'Editor is still loading, please wait...', type: 'error' } 
                }));
                return;
            }
            
            this.editor.chain().focus();
            
            switch(type) {
                case 'paragraph': this.editor.chain().setParagraph().run(); break;
                case 'h1': this.editor.chain().toggleHeading({ level: 1 }).run(); break;
                case 'h2': this.editor.chain().toggleHeading({ level: 2 }).run(); break;
                case 'h3': this.editor.chain().toggleHeading({ level: 3 }).run(); break;
                case 'bulletList': this.editor.chain().toggleBulletList().run(); break;
                case 'orderedList': this.editor.chain().toggleOrderedList().run(); break;
                case 'taskList': this.editor.chain().toggleTaskList().run(); break;
                case 'codeBlock': this.editor.chain().toggleCodeBlock().run(); break;
                case 'blockquote': this.editor.chain().toggleBlockquote().run(); break;
                case 'table': this.editor.chain().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(); break;
            }
            this.showBlockMenu = false;
            console.log('Block inserted successfully');
        },
        addSubTask() {
            if (this.newSubTask.trim()) {
                this.task.sub_tasks.push({ title: this.newSubTask, completed: false });
                this.newSubTask = '';
            }
        },
        triggerFileUpload(type) {
            this.$refs.fileInput.click();
            // In a real app, we'd handle the file selection and upload here
            window.dispatchEvent(new CustomEvent('notify', { 
                detail: { message: 'File upload started for: ' + type, type: 'info' } 
            }));
        },
        downloadFile(file) {
            // Priority: Raw file (fresh upload) > Existing URL (server file)
            let downloadUrl = file.url;
            let isFreshBlob = false;

            if (file.raw_file) {
                try {
                    downloadUrl = URL.createObjectURL(file.raw_file);
                    isFreshBlob = true;
                } catch (e) {
                    console.error('Failed to create object URL', e);
                }
            }

            if (!downloadUrl) {
                window.dispatchEvent(new CustomEvent('notify', { 
                    detail: { message: 'Download URL missing', type: 'error' } 
                }));
                return;
            }
            
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = downloadUrl;
            a.download = file.name;
            document.body.appendChild(a);
            a.click();
            
            // Cleanup fresh blobs immediately after trigger
            if (isFreshBlob) {
                setTimeout(() => {
                    URL.revokeObjectURL(downloadUrl);
                    document.body.removeChild(a);
                }, 1000); // 1s delay to ensure browser catches it
            } else {
                document.body.removeChild(a);
            }
        },
        handleFileSelect(event) {
            const files = event.target.files;
            if (files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    this.task.supporting_files.push({
                        name: file.name,
                        size: file.size,
                        size_formatted: this.formatFileSize(file.size),
                        raw_file: file, // Store raw file for submission
                        url: URL.createObjectURL(file) // Create preview URL
                    });
                }
                // Reset input
                event.target.value = '';
                
                window.dispatchEvent(new CustomEvent('notify', { 
                    detail: { message: files.length + ' file(s) added', type: 'success' } 
                }));
            }
        },
        removeFile(index) {
            const file = this.task.supporting_files[index];
            if (file && file.url) URL.revokeObjectURL(file.url); // Cleanup
            this.task.supporting_files.splice(index, 1);
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        },
        removeSubTask(index) {
            this.task.sub_tasks.splice(index, 1);
        },
        handleNewTask(detail) {
            // Prevent resetting if modal is already open
            if (this.show) {
                console.log('⏭️ Modal already open, ignoring handleNewTask to prevent data loss');
                return;
            }
            console.log('🆕 handleNewTask triggered with detail:', detail);
            this.show = true; 
            this.mode = 'create'; 
            this.reset(); 
            if(detail?.workspace_id) this.task.workspace_id = detail.workspace_id;
            if(detail?.parent_id) this.task.parent_id = detail.parent_id; 
            if(detail?.column_id) this.task.kanban_column_id = detail.column_id;
            this.$nextTick(() => this.initEditor());
        },
        handleEditTask(detail) {
            // Prevent resetting if we are already editing THIS task
            if (this.show && this.taskId === detail.id && this.mode === 'edit') {
                console.log('⏭️ Already editing this task, skipping reset');
                return;
            }
            console.log('📝 handleEditTask triggered for ID:', detail.id);
            this.show = true; 
            this.mode = 'edit'; 
            this.taskId = detail.id; 
            this.task = { ...detail }; 
            
            // Format dates for HTML5 date inputs (YYYY-MM-DD)
            if (this.task.due_date && this.task.due_date.includes('T')) {
                this.task.due_date = this.task.due_date.split('T')[0];
            }
            if (this.task.start_date && this.task.start_date.includes('T')) {
                this.task.start_date = this.task.start_date.split('T')[0];
            }

            this.task.properties = this.task.properties || []; 
            this.task.sub_tasks = this.task.sub_tasks || this.task.subtasks || []; 
            this.task.supporting_files = this.task.supporting_files || []; 
            this.task.kanban_column_id = this.task.kanban_column_id || null;
            this.$nextTick(() => this.initEditor());
        }
    }"
    x-show="show"
    class="fixed inset-0 z-[200] overflow-y-auto"
    style="display: none;"
    x-cloak
    x-on:open-new-task-modal.window="handleNewTask($event.detail)"
    x-on:open-edit-task-modal.window="handleEditTask($event.detail)"
>
    <!-- Cinematic Overlay with Blur -->
    <div 
        x-show="show"
        x-transition:enter="ease-out duration-300"
        x-transition:enter-start="opacity-0 backdrop-blur-none"
        x-transition:enter-end="opacity-100 backdrop-blur-xl"
        x-transition:leave="ease-in duration-200"
        x-transition:leave-start="opacity-100 backdrop-blur-xl"
        x-transition:leave-end="opacity-0 backdrop-blur-none"
        class="fixed inset-0 bg-black/40 dark:bg-black/60 transition-opacity" 
        @click="close()"
    ></div>

    <!-- Modal Panel (Notion Style) -->
    <div class="flex min-h-full items-start justify-center p-4 sm:p-6 lg:p-8">
        <div 
            x-show="show"
            x-transition:enter="ease-out duration-300"
            x-transition:enter-start="opacity-0 scale-95 translate-y-8"
            x-transition:enter-end="opacity-100 scale-100 translate-y-0"
            x-transition:leave="ease-in duration-200"
            x-transition:leave-start="opacity-100 scale-100 translate-y-0"
            x-transition:leave-end="opacity-0 scale-95 translate-y-8"
            class="relative transform overflow-hidden rounded-[1.5rem] bg-white dark:bg-slate-950 text-left shadow-2xl transition-all w-full max-w-4xl border border-slate-200 dark:border-slate-800"
        >
            <!-- Header Actions -->
            <div class="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-slate-900">
                <div class="flex items-center gap-4">
                    <button @click="submit()" class="text-xs font-bold text-slate-500 hover:text-primary-500 transition-colors uppercase tracking-widest flex items-center gap-2">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"></path></svg>
                        Done
                    </button>
                </div>
                <div class="flex items-center gap-4">
                    <button @click="close()" class="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400 transition-all">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                    </button>
                </div>
            </div>

            <!-- Page Content -->
            <div class="p-8 lg:p-12 space-y-10 max-h-[85vh] overflow-y-auto premium-scrollbar">
                
                <!-- Title -->
                <div class="space-y-4">
                    <input 
                        type="text" 
                        x-model="task.title" 
                        required
                        class="w-full text-4xl lg:text-5xl font-black text-slate-900 dark:text-slate-50 border-none bg-transparent focus:ring-0 p-0 placeholder-slate-200 dark:placeholder-slate-800" 
                        placeholder="Untitled"
                    >
                </div>

                <!-- Properties Grid (Notion Style) -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-y-2 gap-x-8 text-sm">
                    <!-- Workspace Selection -->
                    <div class="flex items-center py-1 group">
                        <div class="w-32 flex items-center gap-2 text-slate-400 font-medium">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
                            Workspace
                        </div>
                        <div class="flex-1">
                            <select x-model="task.workspace_id" @change="task.kanban_column_id = null" class="w-full bg-transparent border-none focus:ring-0 text-slate-700 dark:text-slate-300 py-1 px-2 rounded hover:bg-slate-100 dark:hover:bg-slate-900 transition-colors cursor-pointer font-medium appearance-none">
                                <option :value="null">Select Workspace</option>
                                @foreach($workspaces as $ws)
                                    <option value="{{ $ws->id }}">{{ $ws->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <!-- Assignee -->
                    <div class="flex items-center py-1 group">
                        <div class="w-32 flex items-center gap-2 text-slate-400 font-medium">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
                            Assignee
                        </div>
                        <div class="flex-1">
                            <select x-model="task.assignee_id" class="w-full bg-transparent border-none focus:ring-0 text-slate-700 dark:text-slate-300 py-1 px-2 rounded hover:bg-slate-100 dark:hover:bg-slate-900 transition-colors cursor-pointer font-medium">
                                <option :value="null">Empty</option>
                                @foreach($collaborators ?? [] as $user)
                                    <option value="{{ $user->id }}">{{ $user->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <!-- Kanban Column -->
                    <div class="flex items-center py-1">
                        <div class="w-32 flex items-center gap-2 text-slate-400 font-medium">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2"></path></svg>
                            Column
                        </div>
                        <div class="flex-1">
                            <select x-model="task.kanban_column_id" class="w-full bg-transparent border-none focus:ring-0 text-slate-700 dark:text-slate-300 py-1 px-2 rounded hover:bg-slate-100 dark:hover:bg-slate-900 transition-colors cursor-pointer font-medium appearance-none">
                                <option :value="null">No Column</option>
                                <template x-if="task.workspace_id">
                                    @foreach($workspaces as $ws)
                                        <template x-if="task.workspace_id == {{ $ws->id }}">
                                            <optgroup label="{{ $ws->name }}">
                                                @foreach($ws->kanbanColumns as $column)
                                                    <option value="{{ $column->id }}">{{ $column->name }}</option>
                                                @endforeach
                                            </optgroup>
                                        </template>
                                    @endforeach
                                </template>
                            </select>
                        </div>
                    </div>

                    <!-- Priority -->
                    <div class="flex items-center py-1">
                        <div class="w-32 flex items-center gap-2 text-slate-400 font-medium">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
                            Priority
                        </div>
                        <div class="flex-1">
                            <select x-model="task.priority" class="bg-transparent border-none focus:ring-0 text-slate-700 dark:text-slate-300 py-1 px-2 rounded hover:bg-slate-100 dark:hover:bg-slate-900 transition-colors cursor-pointer font-medium appearance-none">
                                <option value="low">Low</option>
                                <option value="medium">Medium</option>
                                <option value="high">High</option>
                                <option value="urgent">Urgent</option>
                            </select>
                        </div>
                    </div>

                    <!-- Date -->
                    <div class="flex items-center py-1">
                        <div class="w-32 flex items-center gap-2 text-slate-400 font-medium">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                            Due Date
                        </div>
                        <div class="flex-1">
                            <input type="date" x-model="task.due_date" class="w-full bg-transparent border-none focus:ring-0 text-slate-700 dark:text-slate-300 py-1 px-2 rounded hover:bg-slate-100 dark:hover:bg-slate-900 transition-colors cursor-pointer font-medium">
                        </div>
                    </div>

                    <!-- Rating -->
                    <div class="flex items-center py-1">
                        <div class="w-32 flex items-center gap-2 text-slate-400 font-medium">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path></svg>
                            Impact
                        </div>
                        <div class="flex-1 flex gap-1">
                            <template x-for="i in 5">
                                <button @click="task.rating = i" class="text-lg hover:scale-110 transition-transform" :class="task.rating >= i ? 'text-yellow-400' : 'text-slate-200 dark:text-slate-800'">★</button>
                            </template>
                        </div>
                    </div>
                </div>

                <div class="h-px bg-slate-100 dark:bg-slate-900"></div>

                <!-- Main Content & Editor -->
                <div class="space-y-6 relative">
                    <div class="flex items-center justify-between">
                        <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest">Main Content</h4>
                        <div class="relative">
                            <button @click.stop="showBlockMenu = !showBlockMenu" class="w-8 h-8 rounded-full bg-slate-100 dark:bg-slate-900 text-slate-500 hover:bg-primary-500 hover:text-white transition-all flex items-center justify-center">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4"></path></svg>
                            </button>
                            
                            <!-- Block Menu -->
                            <div 
                                x-show="showBlockMenu" 
                                x-transition:enter="transition ease-out duration-200"
                                x-transition:enter-start="opacity-0 scale-95 -translate-y-2"
                                x-transition:enter-end="opacity-100 scale-100 translate-y-0"
                                @click.away="showBlockMenu = false" 
                                class="absolute right-0 top-full mt-2 w-64 bg-white dark:bg-slate-900 rounded-2xl shadow-2xl border border-slate-100 dark:border-slate-800 overflow-hidden z-[250] p-2 space-y-1"
                            >
                                <div class="px-3 py-2 text-[10px] font-black text-slate-400 uppercase tracking-widest">Basic Blocks</div>
                                <button @click="insertBlock('paragraph')" class="w-full flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-100 text-sm font-medium transition-colors">
                                    <span class="w-8 h-8 rounded bg-blue-50 dark:bg-blue-900/30 text-blue-500 flex items-center justify-center font-bold">T</span>
                                    Text
                                </button>
                                <button @click="insertBlock('h1')" class="w-full flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-100 text-sm font-medium transition-colors">
                                    <span class="w-8 h-8 rounded bg-purple-50 dark:bg-purple-900/30 text-purple-500 flex items-center justify-center font-bold">H1</span>
                                    Heading 1
                                </button>
                                <button @click="insertBlock('h2')" class="w-full flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-100 text-sm font-medium transition-colors">
                                    <span class="w-8 h-8 rounded bg-indigo-50 dark:bg-indigo-900/30 text-indigo-500 flex items-center justify-center font-bold">H2</span>
                                    Heading 2
                                </button>
                                <button @click="insertBlock('taskList')" class="w-full flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-100 text-sm font-medium transition-colors">
                                    <span class="w-8 h-8 rounded bg-emerald-50 dark:bg-emerald-900/30 text-emerald-500 flex items-center justify-center">☑</span>
                                    To-do List
                                </button>
                                <button @click="insertBlock('bulletList')" class="w-full flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-100 text-sm font-medium transition-colors">
                                    <span class="w-8 h-8 rounded bg-amber-50 dark:bg-amber-900/30 text-amber-500 flex items-center justify-center">☰</span>
                                    Bulleted List
                                </button>
                                <div class="h-px bg-slate-50 dark:bg-slate-800 my-1"></div>
                                <button @click="insertBlock('codeBlock')" class="w-full flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-100 text-sm font-medium transition-colors">
                                    <span class="w-8 h-8 rounded bg-slate-100 dark:bg-slate-800 text-slate-500 flex items-center justify-center font-mono">{}</span>
                                    Code Block
                                </button>
                                <button @click="insertBlock('table')" class="w-full flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-100 text-sm font-medium transition-colors">
                                    <span class="w-8 h-8 rounded bg-pink-50 dark:bg-pink-900/30 text-pink-500 flex items-center justify-center">田</span>
                                    Table
                                </button>
                            </div>
                        </div>
                    </div>
                    <div x-ref="editor" class="tiptap-editor min-h-[300px]">
                        <div x-show="!editor" class="animate-pulse space-y-4">
                            <div class="h-4 bg-slate-100 dark:bg-slate-900 rounded w-3/4"></div>
                            <div class="h-4 bg-slate-100 dark:bg-slate-900 rounded w-1/2"></div>
                            <div class="h-4 bg-slate-100 dark:bg-slate-900 rounded w-5/6"></div>
                        </div>
                    </div>
                </div>

                <!-- Sub-tasks -->
                <div class="space-y-6">
                    <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest">Sub-tasks</h4>
                    <div class="space-y-3">
                        <template x-for="(sub, index) in task.sub_tasks" :key="index">
                            <div class="flex items-start gap-3 group py-1">
                                <input type="checkbox" x-model="sub.completed" class="w-5 h-5 mt-1 rounded border-2 border-slate-200 dark:border-slate-800 text-primary-500 focus:ring-primary-500 bg-transparent transition-all cursor-pointer">
                                <textarea 
                                    x-model="sub.title" 
                                    class="flex-1 bg-transparent border-none focus:ring-0 text-slate-700 dark:text-slate-300 font-medium py-1 px-0 resize-none overflow-hidden min-h-[1.5rem]" 
                                    :class="sub.completed ? 'line-through text-slate-400 opacity-50' : ''"
                                    x-init="$nextTick(() => { $el.style.height = 'auto'; $el.style.height = $el.scrollHeight + 'px' })"
                                    x-on:input="$el.style.height = 'auto'; $el.style.height = $el.scrollHeight + 'px'"
                                    rows="1"
                                ></textarea>
                                <button @click="removeSubTask(index)" class="opacity-0 group-hover:opacity-100 mt-1.5 text-slate-300 hover:text-red-500 transition-all shrink-0">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                                </button>
                            </div>
                        </template>
                        <div class="flex items-start gap-3">
                            <div class="w-5 h-5 flex items-center justify-center text-slate-300 mt-1.5 shrink-0">+</div>
                            <textarea 
                                x-model="newSubTask" 
                                @keydown.enter.prevent="addSubTask()" 
                                class="flex-1 bg-transparent border-none focus:ring-0 text-slate-400 dark:text-slate-600 font-medium py-1 px-0 resize-none overflow-hidden min-h-[1.5rem]" 
                                placeholder="New sub-task..."
                                x-init="$el.style.height = 'auto'; $el.style.height = $el.scrollHeight + 'px'"
                                x-on:input="$el.style.height = 'auto'; $el.style.height = $el.scrollHeight + 'px'"
                                rows="1"
                            ></textarea>
                        </div>
                    </div>
                </div>

                <!-- Supporting Files -->
                <div class="space-y-6">
                    <div class="flex items-center justify-between">
                        <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest">Supporting Files</h4>
                        <span x-show="task.supporting_files.length > 0" class="text-xs text-slate-400" x-text="task.supporting_files.length + ' file(s)'"></span>
                    </div>

                    <input type="file" x-ref="fileInput" class="hidden" multiple @change="handleFileSelect($event)">
                    
                    <!-- File List -->
                    <div class="space-y-3" x-show="task.supporting_files.length > 0">
                        <template x-for="(file, index) in task.supporting_files" :key="index">
                            <div class="flex items-center gap-4 p-3 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 hover:border-indigo-500/30 transition-all group">
                                <!-- Icon -->
                                <div class="w-10 h-10 rounded-lg bg-indigo-50 dark:bg-indigo-900/20 text-indigo-500 flex items-center justify-center flex-shrink-0">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 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"></path></svg>
                                </div>
                                
                                <!-- Meta -->
                                <div class="flex-1 min-w-0">
                                    <div class="text-sm font-bold text-slate-700 dark:text-slate-200 truncate" x-text="file.name"></div>
                                    <div class="text-xs text-slate-400" x-text="file.size_formatted || formatFileSize(file.size || 0)"></div>
                                </div>

                                <!-- Actions -->
                                <div class="flex items-center gap-2">
                                    <button @click.prevent="downloadFile(file)" class="p-2 text-slate-400 hover:text-indigo-500 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 rounded-lg transition-colors flex items-center justify-center" title="Download">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                                    </button>
                                    <button @click="removeFile(index)" class="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors" title="Remove">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><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"></path></svg>
                                    </button>
                                </div>
                            </div>
                        </template>

                        <!-- Add Another File -->
                        <button @click="$refs.fileInput.click()" class="text-xs font-bold text-indigo-500 hover:text-indigo-600 flex items-center gap-2 px-1">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                            Add another file
                        </button>
                    </div>

                    <!-- Empty State Upload -->
                    <div 
                        x-show="task.supporting_files.length === 0"
                        @click="$refs.fileInput.click()"
                        class="border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-xl p-6 flex flex-col items-center justify-center text-center hover:border-primary-500 hover:bg-slate-50 dark:hover:bg-slate-900/50 transition-all cursor-pointer group min-h-[120px]"
                    >
                        <div class="w-12 h-12 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-400 group-hover:text-primary-500 group-hover:scale-110 transition-all flex items-center justify-center mb-3">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path></svg>
                        </div>
                        <h5 class="text-sm font-bold text-slate-700 dark:text-slate-300 mb-1">Click to upload file</h5>
                        <p class="text-xs text-slate-400">Any file type supported</p>
                    </div>
                </div>

            </div>

            <!-- Subtle Footer -->
            <div class="px-8 py-6 bg-slate-50/50 dark:bg-slate-950/50 border-t border-slate-100 dark:border-slate-900 flex items-center justify-between">
                <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                    Last edited: <span class="text-slate-700 dark:text-slate-300">Just now</span>
                </div>
                <div class="flex gap-2">
                    <button @click="close()" class="px-5 py-2 rounded-xl text-xs font-black text-slate-500 hover:text-red-500 transition-all uppercase tracking-widest">Discard</button>
                    <button @click="submit()" class="px-6 py-2 bg-slate-900 dark:bg-white text-white dark:text-slate-900 rounded-xl text-xs font-black transition-all hover:scale-105 active:scale-95 shadow-xl shadow-black/10 uppercase tracking-widest">Update Task</button>
                </div>
            </div>
        </div>
    </div>
</div>
