/**
 * Blogs Page JavaScript
 * Handles dynamic blog loading, search, and pagination
 */

let currentPage = 1;
let searchTimeout = null;

// Load blogs on page load
document.addEventListener('DOMContentLoaded', function () {
    loadBlogs();

    // Search functionality
    const searchInput = document.getElementById('searchBlogs');
    if (searchInput) {
        searchInput.addEventListener('input', function () {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                currentPage = 1;
                loadBlogs();
            }, 500);
        });
    }
});

/**
 * Load blogs from API
 */
async function loadBlogs(page = 1) {
    currentPage = page;

    // Show loading state
    document.getElementById('loadingState').style.display = 'block';
    document.getElementById('blogsGrid').style.display = 'none';
    document.getElementById('paginationContainer').style.display = 'none';

    // Get search value
    const search = document.getElementById('searchBlogs')?.value || '';

    // Build query string
    const params = new URLSearchParams({
        page: currentPage,
        limit: 9,
        search: search
    });

    try {
        const response = await fetch(`api/blogs.php?${params.toString()}`);
        const data = await response.json();

        if (data.success) {
            renderBlogs(data.data);
            renderPagination(data.pagination);

            // Hide loading, show grid
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('blogsGrid').style.display = 'flex';
            document.getElementById('paginationContainer').style.display = 'block';
        } else {
            showError(data.message || 'Failed to load blogs');
        }
    } catch (error) {
        console.error('Error loading blogs:', error);
        showError('An error occurred while loading blogs');
    }
}

/**
 * Render blogs in grid
 */
function renderBlogs(blogs) {
    const grid = document.getElementById('blogsGrid');

    if (blogs.length === 0) {
        grid.innerHTML = `
            <div class="col-12 text-center py-5">
                <i class="las la-newspaper fs-1 text-muted"></i>
                <p class="text-muted mt-2">No blogs found</p>
            </div>
        `;
        return;
    }

    grid.innerHTML = blogs.map(blog => `
        <div class="col-md-6 col-lg-4">
            <div class="card">
                <div class="card-body">
                    <div class="">
                        <img src="${escapeHtml(blog.featured_image)}" alt="" class="img-fluid rounded" style="height: 200px; width: 100%; object-fit: cover;"/>
                        <div class="mt-3">
                            <span class="badge bg-purple-subtle text-purple px-2 py-1 fw-semibold ">${escapeHtml(blog.category || 'Uncategorized')}</span> |   
                            <p class="mb-0 text-muted fs-12 d-inline-block">${blog.published_at}</p>
                        </div> 
                        <a href="edit-blog.php?id=${blog.id}" class="d-block fs-22 fw-semibold text-body my-2 text-truncate">${escapeHtml(blog.title)}</a>
                        <p class="text-muted text-truncate-2-lines" style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; height: 3em;">
                            ${escapeHtml(blog.excerpt || 'No excerpt available')}
                        </p>
                        <hr class="hr-dashed">
                        <div class="d-flex justify-content-between">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <img src="${escapeHtml(blog.author_avatar)}" alt="" class="thumb-md rounded-circle">
                                </div>                                      
                                <div class="flex-grow-1 ms-2 text-truncate text-start">
                                    <h6 class="m-0 text-dark">${escapeHtml(blog.author_name)}</h6>
                                    <p class="mb-0 text-muted">by <a href="#">admin</a></p>
                                </div><!--end media-body-->
                            </div>                                             
                            <div class="align-self-center">
                                <a href="edit-blog.php?id=${blog.id}" class="btn btn-sm btn-primary">Edit <i class="fas fa-edit"></i></a>
                                <button onclick="deleteBlog(${blog.id})" class="btn btn-sm btn-danger">Delete <i class="fas fa-trash"></i></button>
                            </div>
                        </div>                                        
                    </div><!--end blog-card-->               
                </div><!--end card-body--> 
            </div><!--end card--> 
        </div> <!--end col-->
    `).join('');
}

/**
 * Render pagination
 */
function renderPagination(pagination) {
    const paginationList = document.getElementById('paginationList');

    if (pagination.total_pages <= 1) {
        paginationList.innerHTML = '';
        return;
    }

    let html = '';

    // Previous button
    html += `
        <li class="page-item ${!pagination.has_prev ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadBlogs(${currentPage - 1}); return false;" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>
    `;

    // Page numbers
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(pagination.total_pages, currentPage + 2);

    if (startPage > 1) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadBlogs(1); return false;">1</a></li>`;
        if (startPage > 2) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
    }

    for (let i = startPage; i <= endPage; i++) {
        html += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadBlogs(${i}); return false;">${i}</a>
            </li>
        `;
    }

    if (endPage < pagination.total_pages) {
        if (endPage < pagination.total_pages - 1) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadBlogs(${pagination.total_pages}); return false;">${pagination.total_pages}</a></li>`;
    }

    // Next button
    html += `
        <li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadBlogs(${currentPage + 1}); return false;" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
    `;

    paginationList.innerHTML = html;
}

/**
 * Delete blog
 */
async function deleteBlog(id) {
    if (!confirm('Are you sure you want to delete this blog?')) {
        return;
    }

    try {
        const response = await fetch(`api/blogs.php?id=${id}`, {
            method: 'DELETE'
        });
        const data = await response.json();

        if (data.success) {
            loadBlogs(currentPage);
        } else {
            alert(data.message || 'Failed to delete blog');
        }
    } catch (error) {
        console.error('Error deleting blog:', error);
        alert('An error occurred while deleting blog');
    }
}

/**
 * Escape HTML
 */
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * Show error message
 */
function showError(message) {
    document.getElementById('loadingState').innerHTML = `
        <div class="alert alert-danger" role="alert">
            <i class="las la-exclamation-triangle me-2"></i>${message}
        </div>
    `;
}
