/**
 * Add Blog Page JavaScript
 * Handles new blog creation, form validation, and submission
 */

document.addEventListener('DOMContentLoaded', function () {
    // Initialize Quill Editor
    var quill = new Quill('#blogContent', {
        theme: 'snow',
        placeholder: 'Write your blog post here...',
        modules: {
            toolbar: [
                [{ 'header': [1, 2, 3, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'color': [] }, { 'background': [] }],
                ['link', 'image', 'video'],
                ['clean']
            ]
        }
    });

    // Handle Form Submission
    const form = document.getElementById('addBlogForm');
    form.addEventListener('submit', function (e) {
        e.preventDefault();

        // Update hidden content input with Quill data
        document.getElementById('contentInput').value = quill.root.innerHTML;

        createBlog(new FormData(this));
    });

    // Image Upload Handling
    setupImageUpload();

    // SEO Preview Updates
    setupSEOPreview();
});

/**
 * Create blog via API
 */
async function createBlog(formData) {
    const submitBtn = document.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Saving...';

    try {
        const response = await fetch('api/blog-detail.php', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();

        if (data.success) {
            // Show success message
            alert('Blog created successfully!');
            // Redirect to blogs list
            window.location.href = 'blogs.php';
        } else {
            alert(data.message || 'Failed to create blog');
        }
    } catch (error) {
        console.error('Error creating blog:', error);
        alert('An error occurred while creating the blog');
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    }
}

/**
 * Setup Image Upload Interactions
 */
function setupImageUpload() {
    const area = document.getElementById('featuredImageArea');
    const input = document.getElementById('featuredImageInput');
    const changeBtn = document.getElementById('changeImageBtn');
    const removeBtn = document.getElementById('removeImageBtn');

    // Click to upload
    area.addEventListener('click', (e) => {
        if (e.target !== removeBtn && e.target !== changeBtn) {
            input.click();
        }
    });

    if (changeBtn) changeBtn.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        input.click();
    });

    if (removeBtn) removeBtn.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        input.value = '';
        document.getElementById('imagePreview').src = '';
        document.getElementById('imagePreview').style.display = 'none';
        document.getElementById('uploadPlaceholder').style.display = 'block';
        document.getElementById('imageActions').style.display = 'none';
    });

    // Handle file selection
    input.addEventListener('change', function () {
        if (this.files && this.files[0]) {
            const reader = new FileReader();
            reader.onload = function (e) {
                const preview = document.getElementById('imagePreview');
                preview.src = e.target.result;
                preview.style.display = 'block';
                document.getElementById('uploadPlaceholder').style.display = 'none';
                document.getElementById('imageActions').style.display = 'block';
            };
            reader.readAsDataURL(this.files[0]);
        }
    });
}

/**
 * Setup SEO Preview Logic
 */
function setupSEOPreview() {
    const titleInput = document.getElementById('seoTitle');
    const descInput = document.getElementById('seoDescription');
    const titleCount = document.getElementById('seoTitleCount');
    const descCount = document.getElementById('seoDescriptionCount');
    const mainTitleInput = document.getElementById('blogTitle');
    const excerptInput = document.getElementById('blogExcerpt');

    // Event Listeners
    titleInput.addEventListener('input', () => {
        titleCount.textContent = titleInput.value.length;
        updateSEOPreviewText();
    });

    descInput.addEventListener('input', () => {
        descCount.textContent = descInput.value.length;
        updateSEOPreviewText();
    });

    // Also update preview when main title/excerpt changes if SEO fields are empty
    mainTitleInput.addEventListener('input', updateSEOPreviewText);
    excerptInput.addEventListener('input', updateSEOPreviewText);
}

function updateSEOPreviewText() {
    const title = document.getElementById('seoTitle').value || document.getElementById('blogTitle').value || 'Blog Post Title';
    const desc = document.getElementById('seoDescription').value || document.getElementById('blogExcerpt').value || 'Blog post description will appear here...';

    document.querySelector('.seo-title-preview').textContent = title;
    document.querySelector('.seo-description-preview').textContent = desc;

    // Update char counts
    document.getElementById('seoTitleCount').textContent = document.getElementById('seoTitle').value.length;
    document.getElementById('seoDescriptionCount').textContent = document.getElementById('seoDescription').value.length;
}
