/**
 * Add Collection Page Script
 * -------------------------
 * Handles rich text editor, image upload, SEO preview, and form submission.
 */

document.addEventListener('DOMContentLoaded', function () {
    // 1. Initialize Quill Editor
    const quill = new Quill('#collectionDescription', {
        theme: 'snow',
        modules: {
            toolbar: [
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['link', 'clean']
            ]
        },
        placeholder: 'Enter collection description...'
    });

    // 2. Load Parent Collections
    loadParentCollections();

    function loadParentCollections() {
        fetch('api/collections.php?limit=100') // Fetch all active collections
            .then(response => response.json())
            .then(data => {
                const parentSelect = document.getElementById('parentCollection');
                if (data.success && data.data) {
                    data.data.forEach(collection => {
                        const option = document.createElement('option');
                        option.value = collection.id;
                        option.textContent = collection.name;
                        parentSelect.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Error loading parent collections:', error));
    }

    // 3. Image Upload Handling
    const dropZone = document.getElementById('dropZone');
    const mediaFileInput = document.getElementById('mediaFileInput');
    const addMediaBtn = document.getElementById('addMediaBtn');
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');
    const imagePreview = document.getElementById('imagePreview');
    const removeImageBtn = document.getElementById('removeImageBtn');

    // Trigger file input
    addMediaBtn.addEventListener('click', () => mediaFileInput.click());
    dropZone.addEventListener('click', (e) => {
        if (e.target !== addMediaBtn && !addMediaBtn.contains(e.target)) {
            mediaFileInput.click();
        }
    });

    // Handle File Selection
    mediaFileInput.addEventListener('change', function () {
        handleFile(this.files[0]);
    });

    // Drag & Drop
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    dropZone.addEventListener('drop', function (e) {
        const dt = e.dataTransfer;
        handleFile(dt.files[0]);
    });

    function handleFile(file) {
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function (e) {
                imagePreview.src = e.target.result;
                dropZone.style.display = 'none';
                imagePreviewContainer.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
    }

    // Remove Image
    removeImageBtn.addEventListener('click', function (e) {
        e.stopPropagation(); // Prevent triggering dropZone click
        mediaFileInput.value = ''; // Clear input
        imagePreview.src = '';
        imagePreviewContainer.style.display = 'none';
        dropZone.style.display = 'block';
    });

    // 4. SEO Preview Logic
    const seoTitle = document.getElementById('seoTitle');
    const seoDescription = document.getElementById('seoDescription');
    const seoTitlePreview = document.querySelector('.seo-title-preview');
    const seoDescriptionPreview = document.querySelector('.seo-description-preview');
    const seoTitleCount = document.getElementById('seoTitleCount');
    const seoDescriptionCount = document.getElementById('seoDescriptionCount');

    if (seoTitle) {
        seoTitle.addEventListener('input', function () {
            const length = this.value.length;
            seoTitleCount.textContent = length;
            seoTitlePreview.textContent = this.value || 'Collection Title';
        });
    }

    if (seoDescription) {
        seoDescription.addEventListener('input', function () {
            const length = this.value.length;
            seoDescriptionCount.textContent = length;
            seoDescriptionPreview.textContent = this.value || 'Collection description will appear here...';
        });
    }

    // 5. Form Submission
    const form = document.getElementById('addCollectionForm');
    const saveBtn = document.getElementById('saveBtn');

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

        // Update hidden description field
        document.getElementById('descriptionInput').value = quill.root.innerHTML;

        // Show loading state
        const originalBtnText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...';
        saveBtn.disabled = true;

        const formData = new FormData(this);

        fetch('api/collections.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Success
                    alert('Collection created successfully!');
                    window.location.href = 'collections.php';
                } else {
                    // Error
                    alert(data.message || 'Failed to create collection');
                    saveBtn.innerHTML = originalBtnText;
                    saveBtn.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
                saveBtn.innerHTML = originalBtnText;
                saveBtn.disabled = false;
            });
    });
});
