/*
|--------------------------------------------------------------------------
| Viartas Admin Theme - Page Editor JavaScript
|--------------------------------------------------------------------------
*/

document.addEventListener('DOMContentLoaded', function() {

    // ========================================
    // Tab Navigation
    // ========================================
    /*const tabLinks = document.querySelectorAll('.nav-tabs-modern .nav-link');
    const tabPanes = document.querySelectorAll('.tab-pane');

    tabLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();

            const targetTab = this.getAttribute('data-tab');

            // Remove active from all links
            tabLinks.forEach(l => l.classList.remove('active'));

            // Add active to clicked link
            this.classList.add('active');

            // Hide all panes
            tabPanes.forEach(pane => {
                pane.style.display = 'none';
            });

            // Show target pane
            const targetPane = document.getElementById(targetTab);
            if (targetPane) {
                targetPane.style.display = 'block';
            }
        });
    });*/

    // ========================================
    // Rich Text Editor
    // ========================================
    const editorContent = document.getElementById('editorContent');
    const editorHtml = document.getElementById('editorHtml');
    const toolbarBtns = document.querySelectorAll('.toolbar-btn[data-command]');
    const formatSelect = document.getElementById('formatBlock');
    const modeBtns = document.querySelectorAll('.mode-btn');

    // Toolbar button commands
    toolbarBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const command = this.getAttribute('data-command');
            document.execCommand(command, false, null);
            editorContent.focus();
            updateToolbarState();
        });
    });

    // Format block select
    if (formatSelect) {
        formatSelect.addEventListener('change', function() {
            document.execCommand('formatBlock', false, this.value);
            editorContent.focus();
        });
    }

    // Update toolbar button states
    function updateToolbarState() {
        toolbarBtns.forEach(btn => {
            const command = btn.getAttribute('data-command');
            if (document.queryCommandState(command)) {
                btn.classList.add('active');
            } else {
                btn.classList.remove('active');
            }
        });
    }

    // Listen for selection changes
    if (editorContent) {
        editorContent.addEventListener('keyup', updateToolbarState);
        editorContent.addEventListener('mouseup', updateToolbarState);
    }

    // Editor mode toggle (Visual/HTML)
    modeBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const mode = this.getAttribute('data-mode');

            modeBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            if (mode === 'html') {
                editorHtml.value = editorContent.innerHTML;
                editorContent.style.display = 'none';
                editorHtml.style.display = 'block';
            } else {
                editorContent.innerHTML = editorHtml.value;
                editorHtml.style.display = 'none';
                editorContent.style.display = 'block';
            }
        });
    });

    // Insert Link
    const insertLinkBtn = document.getElementById('insertLink');
    if (insertLinkBtn) {
        insertLinkBtn.addEventListener('click', function() {
            const url = prompt('Enter URL:', 'https://');
            if (url) {
                document.execCommand('createLink', false, url);
                editorContent.focus();
            }
        });
    }

    // Insert Image
    const insertImageBtn = document.getElementById('insertImage');
    if (insertImageBtn) {
        insertImageBtn.addEventListener('click', function() {
            const url = prompt('Enter image URL:', 'https://');
            if (url) {
                document.execCommand('insertImage', false, url);
                editorContent.focus();
            }
        });
    }

    // ========================================
    // Featured Image Upload
    // ========================================
    const featuredImageUpload = document.getElementById('featuredImageUpload');
    const featuredImageInput = document.getElementById('featuredImageInput');
    const uploadPlaceholder = document.getElementById('uploadPlaceholder');
    const uploadPreview = document.getElementById('uploadPreview');
    const previewImage = document.getElementById('previewImage');
    const removeImageBtn = document.getElementById('removeImage');

    if (featuredImageUpload && featuredImageInput) {
        // Click to upload
        featuredImageUpload.addEventListener('click', function(e) {
            if (e.target !== removeImageBtn && !removeImageBtn.contains(e.target)) {
                featuredImageInput.click();
            }
        });

        // Handle file selection
        featuredImageInput.addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImage.src = e.target.result;
                    uploadPlaceholder.style.display = 'none';
                    uploadPreview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        });

        // Remove image
        if (removeImageBtn) {
            removeImageBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                previewImage.src = '';
                featuredImageInput.value = '';
                uploadPreview.style.display = 'none';
                uploadPlaceholder.style.display = 'block';
            });
        }

        // Drag and drop
        featuredImageUpload.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.classList.add('dragover');
        });

        featuredImageUpload.addEventListener('dragleave', function() {
            this.classList.remove('dragover');
        });

        featuredImageUpload.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('dragover');

            const file = e.dataTransfer.files[0];
            if (file && file.type.startsWith('image/')) {
                featuredImageInput.files = e.dataTransfer.files;
                const event = new Event('change');
                featuredImageInput.dispatchEvent(event);
            }
        });
    }

    // ========================================
    // Document Upload Zone
    // ========================================
    const documentUploadZone = document.getElementById('documentUploadZone');
    const documentInput = document.getElementById('documentInput');

    if (documentUploadZone && documentInput) {
        documentUploadZone.addEventListener('click', function() {
            documentInput.click();
        });

        documentUploadZone.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.classList.add('dragover');
        });

        documentUploadZone.addEventListener('dragleave', function() {
            this.classList.remove('dragover');
        });

        documentUploadZone.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('dragover');

            const files = e.dataTransfer.files;
            handleDocumentUpload(files);
        });

        documentInput.addEventListener('change', function() {
            handleDocumentUpload(this.files);
        });
    }

    function handleDocumentUpload(files) {
        const uploadQueue = document.getElementById('uploadQueue');
        const queueList = document.getElementById('queueList');

        if (files.length > 0 && uploadQueue && queueList) {
            uploadQueue.style.display = 'block';

            Array.from(files).forEach(file => {
                const item = document.createElement('div');
                item.className = 'upload-queue-item';
                item.innerHTML = `
                    <div class="queue-item-info">
                        <i class="fas fa-file"></i>
                        <span>${file.name}</span>
                        <small>${formatFileSize(file.size)}</small>
                    </div>
                    <div class="queue-item-progress">
                        <div class="progress-bar" style="width: 0%"></div>
                    </div>
                `;
                queueList.appendChild(item);

                // Simulate upload progress
                simulateUpload(item.querySelector('.progress-bar'));
            });
        }
    }

    function simulateUpload(progressBar) {
        let progress = 0;
        const interval = setInterval(function() {
            progress += Math.random() * 30;
            if (progress >= 100) {
                progress = 100;
                clearInterval(interval);
                progressBar.style.background = 'var(--success)';
            }
            progressBar.style.width = progress + '%';
        }, 200);
    }

    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // ========================================
    // Character Counters
    // ========================================
    const descriptionInput = document.getElementById('pageDescription');
    const descCount = document.getElementById('descCount');

    if (descriptionInput && descCount) {
        descriptionInput.addEventListener('input', function() {
            descCount.textContent = this.value.length;
        });
    }

    const metaTitleInput = document.getElementById('metaTitle');
    const metaTitleCount = document.getElementById('metaTitleCount');
    const googleTitle = document.getElementById('googleTitle');

    if (metaTitleInput && metaTitleCount) {
        metaTitleInput.addEventListener('input', function() {
            metaTitleCount.textContent = this.value.length;
            if (googleTitle) {
                googleTitle.textContent = this.value;
            }
        });
    }

    const metaDescInput = document.getElementById('metaDescription');
    const metaDescCount = document.getElementById('metaDescCount');
    const googleDescription = document.getElementById('googleDescription');

    if (metaDescInput && metaDescCount) {
        metaDescInput.addEventListener('input', function() {
            metaDescCount.textContent = this.value.length;
            if (googleDescription) {
                googleDescription.textContent = this.value;
            }
        });
    }

    // ========================================
    // Status Change Handler
    // ========================================
    const pageStatus = document.getElementById('pageStatus');
    const scheduledDateGroup = document.getElementById('scheduledDateGroup');

    if (pageStatus && scheduledDateGroup) {
        pageStatus.addEventListener('change', function() {
            if (this.value === 'scheduled') {
                scheduledDateGroup.style.display = 'block';
            } else {
                scheduledDateGroup.style.display = 'none';
            }
        });
    }

    // ========================================
    // Form Submission
    // ========================================
    const pageEditorForm = document.getElementById('pageEditorForm');

    if (pageEditorForm) {
        pageEditorForm.addEventListener('submit', function(e) {
            e.preventDefault();

            // Collect form data
            const formData = new FormData(this);

            // Add editor content
            formData.append('content', editorContent.innerHTML);

            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
            submitBtn.disabled = true;

            // Simulate save (replace with actual AJAX call)
            setTimeout(function() {
                submitBtn.innerHTML = '<i class="fas fa-check"></i> Saved!';
                submitBtn.classList.add('btn-success');

                setTimeout(function() {
                    submitBtn.innerHTML = originalText;
                    submitBtn.classList.remove('btn-success');
                    submitBtn.disabled = false;
                }, 2000);
            }, 1500);
        });
    }

    // ========================================
    // Save Draft Button
    // ========================================
    const saveDraftBtn = document.getElementById('saveDraft');

    if (saveDraftBtn) {
        saveDraftBtn.addEventListener('click', function() {
            const originalText = this.innerHTML;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
            this.disabled = true;

            // Simulate save
            setTimeout(() => {
                this.innerHTML = '<i class="fas fa-check"></i> Saved!';

                setTimeout(() => {
                    this.innerHTML = originalText;
                    this.disabled = false;
                }, 2000);
            }, 1000);
        });
    }

    // ========================================
    // Auto-save (Optional)
    // ========================================
    let autoSaveTimer;

    function setupAutoSave() {
        const inputs = document.querySelectorAll('.form-input, .form-textarea, .form-select');

        inputs.forEach(input => {
            input.addEventListener('input', function() {
                clearTimeout(autoSaveTimer);
                autoSaveTimer = setTimeout(function() {
                    console.log('Auto-saving...');
                    // Implement auto-save logic here
                }, 30000); // Auto-save after 30 seconds of inactivity
            });
        });
    }

    // setupAutoSave(); // Uncomment to enable auto-save

    // ========================================
    // Keyboard Shortcuts
    // ========================================
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + S to save
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            const submitBtn = document.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.click();
            }
        }
    });

    // ========================================
    // Gallery Image Click
    // ========================================
    const galleryUpload = document.querySelector('.gallery-upload');

    if (galleryUpload) {
        galleryUpload.addEventListener('click', function() {
            // Open file picker or media library
            alert('Open media library or file picker');
        });
    }

    // ========================================
    // Confirm Delete Actions
    // ========================================
    const deleteButtons = document.querySelectorAll('.btn-danger-glow, .gallery-btn.danger, .doc-btn.danger, .comment-btn.danger');

    deleteButtons.forEach(btn => {
        btn.addEventListener('click', function(e) {
            if (!confirm('Are you sure you want to delete this item?')) {
                e.preventDefault();
            }
        });
    });

});
