/**
 * Edit Blog Page JavaScript
 * Handles fetching blog data, form population, and updates
 */

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']
            ]
        }
    });

    // Get Blog ID from URL
    const urlParams = new URLSearchParams(window.location.search);
    const blogId = urlParams.get('id');

    if (blogId) {
        loadBlogData(blogId, quill);
    }

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

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

        updateBlog(new FormData(this));
    });

    // Image Upload Handling
    setupImageUpload();

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

/**
 * Load blog data from API
 */
async function loadBlogData(id, quill) {
    try {
        const response = await fetch(`api/blog-detail.php?id=${id}`);
        const data = await response.json();

        if (data.success) {
            const blog = data.data;

            // Populate Form Fields
            document.getElementById('blogTitle').value = blog.title || '';
            document.getElementById('blogCategory').value = blog.category || '';
            document.getElementById('blogExcerpt').value = blog.excerpt || '';
            document.getElementById('seoTitle').value = blog.seo_title || '';
            document.getElementById('seoDescription').value = blog.seo_description || '';

            // Populate Quill Editor
            if (blog.content) {
                quill.root.innerHTML = blog.content;
            }

            // Visibility
            if (blog.visibility === 'hidden') {
                document.getElementById('visHidden').checked = true;
            } else {
                document.getElementById('visVisible').checked = true;
            }

            // Featured Image
            if (blog.featured_image) {
                const preview = document.getElementById('imagePreview');
                preview.src = blog.featured_image;
                preview.style.display = 'block';
                document.getElementById('uploadPlaceholder').style.display = 'none';
                document.getElementById('imageActions').style.display = 'block';
            }

            // Update SEO Preview
            updateSEOPreviewText();

            // Show Form, Hide Loading
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('editBlogForm').style.display = 'block';

        } else {
            alert('Failed to load blog data: ' + data.message);
            window.location.href = 'blogs.php';
        }
    } catch (error) {
        console.error('Error loading blog:', error);
        alert('An error occurred while loading blog data');
    }
}

/**
 * Update blog via API
 */
async function updateBlog(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 (using a toast or alert)
            alert('Blog updated successfully!');
            // Optional: Redirect or stay on page
        } else {
            alert(data.message || 'Failed to update blog');
        }
    } catch (error) {
        console.error('Error updating blog:', error);
        alert('An error occurred while updating 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');

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

    // 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');

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

    descInput.addEventListener('input', () => {
        descCount.textContent = descInput.value.length;
        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;
}
