
    let nameAvailable = false;
    let urlAvailable = false;

    // Generate URL slug from page name
    function generateSlug(text) {
        return text.trim().toLowerCase()
            .replace(/[^a-z0-9\s-]/g, '')  // Remove invalid characters
            .replace(/\s+/g, '-')          // Replace spaces with hyphens
            .replace(/-+/g, '-');          // Remove multiple hyphens
    }

    // Check if the page name and URL exist in the database
 
    
    function checkPageAvailability(pageName, pageUrl) {
        axios.post(base_url+'/webapi/page/check-page-existence', { page_name: pageName, page_url: pageUrl })
            .then(response => {
                if (response.data) {
                    // Handle name existence
                    if (response.data.name_exists) {
                        $("#page-name").addClass("is-invalid");
                        $("#page-name-error").removeClass("d-none").text("Page name already exists!");
                        nameAvailable = false;
                    } else {
                        $("#page-name").removeClass("is-invalid");
                        $("#page-name-error").addClass("d-none");
                        nameAvailable = true;
                    }

                    // Handle URL existence
                    if (response.data.url_exists) {
                        $("#page-url").addClass("is-invalid");
                        $("#page-url-error").removeClass("d-none").text("Page URL already exists!");
                        urlAvailable = false;
                    } else {
                        $("#page-url").removeClass("is-invalid");
                        $("#page-url-error").addClass("d-none");
                        urlAvailable = true;
                    }
                }
            })
            .catch(error => {
                console.error("Error checking availability:", error);
                nameAvailable = false;
                urlAvailable = false;
            });
    }

    function randerPageCard(page) {
        let avatar = page.avatar ? page.avatar : 'assets/images/avatar/placeholder.jpg';
        let cover = page.cover ? page.cover : 'assets/images/default.jpg';
        let category = page.page_category ? page.page_category : "Uncategorized";
        let followers = page.likes_count ? `${page.likes_count} followers` : "No followers yet";
        let verifiedBadge = page.is_verified ? `<span class="badge bg-primary"><i class="fas fa-check-circle me-1"></i>Verified</span>` : '';
        let deleteButton = ``;
        if(page.is_page_owner){
            deleteButton = `<li><a class="dropdown-item" href="javascript:void(0)" onclick="deletePage(${page.id})"><i class="fas fa-trash-alt me-2"></i>Delete</a></li>`;
        }
        return `
            <div class="col-md-6 col-lg-4 mb-4 data-page-${page.id}" >
                <div class="card h-100 border-0 shadow-sm hover-shadow-md transition-hover">
                    <div class="position-relative">
                        <img src="${cover}" class="card-img-top" alt="Page Cover"
                            style="height: 140px; object-fit: cover;">
                        <div class="position-absolute top-0 start-0 m-3">
                            ${verifiedBadge}
                        </div>
                        <div class="position-absolute bottom-0 start-50 translate-middle-x mb-n4">
                            <img src="${avatar}" class="rounded-circle border-4 border-white"
                                style="width: 80px; height: 80px;" alt="Page Logo">
                        </div>
                    </div>
                    <div class="card-body pt-5 mt-2">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="card-title mb-0"><a href="/page/${page.page_username}">${page.page_title}</a></h5>
                            <div class="dropdown">
                                <button class="btn btn-icon btn-sm btn-light rounded-circle" data-bs-toggle="dropdown">
                                    <i class="fas fa-ellipsis-h"></i>
                                </button>
                                <ul class="dropdown-menu">
                                    ${deleteButton}
                                    <li><a class="dropdown-item" href="#"><i class="fas fa-share me-2"></i>Share</a></li>
                                    <li><a class="dropdown-item" href="#"><i class="fas fa-flag me-2"></i>Report</a></li>
                                </ul>
                            </div>
                        </div>
                        <div class="d-flex flex-wrap gap-2 mb-3">
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-building me-1"></i>${category}
                            </span>
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-users me-1"></i>${followers}
                            </span>
                        </div>
                        <p class="card-text small text-muted mb-3">${page.page_description}</p>
                    </div>
                    <div class="card-footer bg-white border-0 pt-0">
                        <div class="d-grid gap-2">
                            ${!page.is_page_owner ? `
                            <button class="btn ${page.is_liked ? 'btn-outline-primary' : 'btn-primary'}" 
                                onclick="likeUnlikePage(${page.id}, this)">
                                <i class="fas fa-thumbs-up me-2"></i>${page.is_liked ? 'Unlike' : 'Follow'}
                            </button>
                            ` : ''}
                            <a href="/page/${page.page_username}" class="btn btn-outline-primary">
                                <i class="fas fa-external-link-alt me-2"></i>Visit Page
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    // Ensure auth cookies are sent on same-origin requests
    if (typeof axios !== 'undefined') {
        axios.defaults.withCredentials = true;
        if (!axios.defaults.headers) axios.defaults.headers = {};
        if (!axios.defaults.headers.common) axios.defaults.headers.common = {};
        axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    }

    function get_all_pages(page = 1, isMe = false, additionalFilters = {}) {
        var search = $(".search-page").val() ?? null;
        var category = $(".category-filter").val() ?? null;
        
        // Show loading state
        $("#pages_list").html(`
            <div class="col-12 text-center py-5">
                <i class="fas fa-spinner fa-spin fa-3x text-primary"></i>
                <p class="mt-3 text-muted">Loading pages...</p>
            </div>
        `);
        
        // Build query parameters
        var params = {
            page: page,
            search: search,
            is_me: isMe,
            category: category
        };
        
        // Add additional filters
        if (additionalFilters.following) params.following = true;
        if (additionalFilters.verified) params.verified = true;
        if (additionalFilters.unverified) params.unverified = true;
        if (additionalFilters.sort) params.sort = additionalFilters.sort;
        if (additionalFilters.categories) params.categories = additionalFilters.categories.join(',');
        if (additionalFilters.followers) params.followers = additionalFilters.followers.join(',');
        
        // Convert to query string
        var queryString = Object.keys(params)
            .filter(key => params[key] !== null && params[key] !== undefined && params[key] !== '')
            .map(key => `${key}=${encodeURIComponent(params[key])}`)
            .join('&');
        
        axios.get(`${base_url}/webapi/page/get-all?${queryString}`)
            .then(response => {
                if (response.data.status === 200) {
                    let pages = response.data.data;
                    let pagination = response.data.pagination;
                    let html = '';
    
                    if (pages.length === 0) {
                        const searchTerm = $(".search-page").val();
                        const category = $(".category-filter").val();
                        
                        if (searchTerm || category) {
                            // Show filtered results message
                            html = `
                                <div class="col-12 text-center py-5">
                                    <i class="fas fa-search fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">No pages found</h5>
                                    <p class="text-muted">Try adjusting your search criteria or create a new page.</p>
                                    <button class="btn btn-outline-primary" onclick="clearFilters()">Clear Filters</button>
                                </div>
                            `;
                        } else {
                            // Show no pages created message
                            html = `
                                <div class="col-12 text-center py-5">
                                    <i class="fas fa-plus-circle fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">No pages created yet</h5>
                                    <p class="text-muted">Create your first page to get started and connect with your audience.</p>
                                    <a href="${base_url}/pages/create" class="btn btn-primary">
                                        <i class="fas fa-plus-circle me-2"></i>Create Your First Page
                                    </a>
                                </div>
                            `;
                        }
                    } else {
                        pages.forEach(page => {
                            html += randerPageCard(page);
                        });
                    }
    
                    $("#pages_list").html(html);

                    // Generate pagination links only if pagination exists
                    if (pagination && typeof pagination.current_page !== 'undefined') {
                        let paginationHtml = '';
                        // Previous button
                        paginationHtml += `
                            <li class="page-item ${pagination.current_page === 1 ? 'disabled' : ''}">
                                <a class="page-link" href="#" onclick="get_all_pages(${pagination.current_page - 1}, ${isMe})" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        `;
                        // Page numbers
                        for (let i = 1; i <= pagination.last_page; i++) {
                            paginationHtml += `
                                <li class="page-item ${pagination.current_page === i ? 'active' : ''}">
                                    <a class="page-link" href="#" onclick="get_all_pages(${i}, ${isMe})">${i}</a>
                                </li>
                            `;
                        }
                        // Next button
                        paginationHtml += `
                            <li class="page-item ${pagination.current_page === pagination.last_page ? 'disabled' : ''}">
                                <a class="page-link" href="#" onclick="get_all_pages(${pagination.current_page + 1}, ${isMe})" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        `;
                        $("#pagination").html(paginationHtml);
                    } else {
                        $("#pagination").html('');
                    }

                } else {
                    console.error("Error fetching pages:", response.data.message);
                    $("#pages_list").html(`
                        <div class="col-12 text-center py-5">
                            <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                            <h5 class="text-muted">Error loading pages</h5>
                            <p class="text-muted">${response.data.message || 'Something went wrong. Please try again.'}</p>
                            <button class="btn btn-primary" onclick="get_all_pages(1, ${isMe}, ${JSON.stringify(additionalFilters)})">Retry</button>
                        </div>
                    `);
                }
            })
            .catch(error => {
                console.error("API request failed:", error);
                // Handle auth-related errors explicitly
                if (error && error.response && (error.response.status === 401 || error.response.status === 419)) {
                    $("#pages_list").html(`
                        <div class="col-12 text-center py-5">
                            <i class="fas fa-lock fa-3x text-warning mb-3"></i>
                            <h5 class="text-muted">Authentication Required</h5>
                            <p class="text-muted">Please log in to view your pages.</p>
                            <a class="btn btn-primary" href="${base_url}/login">Go to Login</a>
                        </div>
                    `);
                    return;
                }
                $("#pages_list").html(`
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
                        <h5 class="text-muted">Connection Error</h5>
                        <p class="text-muted">Unable to connect to the server. Please check your internet connection and try again.</p>
                        <button class="btn btn-primary" onclick="get_all_pages(1, ${isMe}, ${JSON.stringify(additionalFilters)})">Retry</button>
                    </div>
                `);
            });
    }
    
    function deletePage(pageId) {
        axios.post(base_url+'/webapi/page/delete-page', { page_id: pageId })
            .then(response => {
                if (response.data.status === 200) {
                    myAlert.fire({
                        icon: "success",
                        title: "Success",
                        text: "Page deleted successfully!"
                    });
                    $(`.data-page-${pageId}`).remove();
                    setTimeout(() => {
                        window.location.reload();
                    }, 3500);
                }
            })
            .catch(error => {
                console.error("Error deleting page:", error);
            });
    }
    
    function likeUnlikePage(pageId, buttonElement) {
        axios.post(base_url+'/webapi/page/like-unlike-page', { page_id: pageId })
            .then(response => {
                if (response.data.status === 200) {
                    const button = $(buttonElement);
                    const isLiked = response.data.data === 1;
                    
                    if (isLiked) {
                        button.removeClass('btn-primary').addClass('btn-outline-primary');
                        button.html('<i class="fas fa-thumbs-up me-2"></i>Unlike');
                    } else {
                        button.removeClass('btn-outline-primary').addClass('btn-primary');
                        button.html('<i class="fas fa-thumbs-up me-2"></i>Follow');
                    }
                    
                    // Update followers count
                    const followersElement = button.closest('.card').find('.badge:contains("followers")');
                    const currentCount = parseInt(followersElement.text().replace(/\D/g, ''));
                    const newCount = isLiked ? currentCount + 1 : Math.max(0, currentCount - 1);
                    followersElement.text(`${newCount} followers`);
                }
            })
            .catch(error => {
                console.error("Error liking/unliking page:", error);
                myAlert.fire({
                    icon: "error",
                    title: "Error",
                    text: "Something went wrong. Please try again."
                });
            });
    }
    
    function clearFilters() {
        $(".search-page").val("");
        $(".category-filter").val("");
        $(".clear-search-btn").hide();
        get_all_pages(1, true);
    }
    
    // Get liked pages specifically
    function get_liked_pages(page = 1) {
        var search = $(".search-page").val() ?? null;
        var category = $(".category-filter").val() ?? null;
        
        // Show loading state
        $("#pages_list").html(`
            <div class="col-12 text-center py-5">
                <i class="fas fa-spinner fa-spin fa-3x text-primary"></i>
                <p class="mt-3 text-muted">Loading liked pages...</p>
            </div>
        `);
        
        // Build query parameters for liked pages
        var params = {
            page: page,
            search: search,
            is_me: false,
            following: true, // This will filter for liked pages
            category: category
        };
        
        // Convert to query string
        var queryString = Object.keys(params)
            .filter(key => params[key] !== null && params[key] !== undefined && params[key] !== '')
            .map(key => `${key}=${encodeURIComponent(params[key])}`)
            .join('&');
        
        axios.get(`${base_url}/webapi/page/get-all?${queryString}`)
            .then(response => {
                if (response.data.status === 200) {
                    let pages = response.data.data;
                    let pagination = response.data.pagination;
                    let html = '';
    
                    if (pages.length === 0) {
                        const searchTerm = $(".search-page").val();
                        const category = $(".category-filter").val();
                        
                        if (searchTerm || category) {
                            // Show filtered results message
                            html = `
                                <div class="col-12 text-center py-5">
                                    <i class="fas fa-search fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">No liked pages found</h5>
                                    <p class="text-muted">Try adjusting your search criteria or explore more pages.</p>
                                    <button class="btn btn-outline-primary" onclick="clearFilters()">Clear Filters</button>
                                </div>
                            `;
                        } else {
                            // Show no liked pages message
                            html = `
                                <div class="col-12 text-center py-5">
                                    <i class="fas fa-heart fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">No liked pages yet</h5>
                                    <p class="text-muted">Start exploring pages and like the ones you're interested in to see them here.</p>
                                    <a href="${base_url}/pages" class="btn btn-primary">
                                        <i class="fas fa-compass me-2"></i>Explore Pages
                                    </a>
                                </div>
                            `;
                        }
                    } else {
                        pages.forEach(page => {
                            html += randerPageCard(page);
                        });
                    }
    
                    $("#pages_list").html(html);

                    // Generate pagination links only if pagination exists
                    if (pagination && typeof pagination.current_page !== 'undefined') {
                        let paginationHtml = '';
                        // Previous button
                        paginationHtml += `
                            <li class="page-item ${pagination.current_page === 1 ? 'disabled' : ''}">
                                <a class="page-link" href="#" onclick="get_liked_pages(${pagination.current_page - 1})" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        `;
                        // Page numbers
                        for (let i = 1; i <= pagination.last_page; i++) {
                            paginationHtml += `
                                <li class="page-item ${pagination.current_page === i ? 'active' : ''}">
                                    <a class="page-link" href="#" onclick="get_liked_pages(${i})">${i}</a>
                                </li>
                            `;
                        }
                        // Next button
                        paginationHtml += `
                            <li class="page-item ${pagination.current_page === pagination.last_page ? 'disabled' : ''}">
                                <a class="page-link" href="#" onclick="get_liked_pages(${pagination.current_page + 1})" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        `;
                        $("#pagination").html(paginationHtml);
                    } else {
                        $("#pagination").html('');
                    }

                } else {
                    console.error("Error fetching liked pages:", response.data.message);
                    $("#pages_list").html(`
                        <div class="col-12 text-center py-5">
                            <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                            <h5 class="text-muted">Error loading liked pages</h5>
                            <p class="text-muted">${response.data.message || 'Something went wrong. Please try again.'}</p>
                            <button class="btn btn-primary" onclick="get_liked_pages(1)">Retry</button>
                        </div>
                    `);
                }
            })
            .catch(error => {
                console.error("API request failed:", error);
                // Handle auth-related errors explicitly
                if (error && error.response) {
                    const status = error.response.status;
                    if (status === 401 || status === 419) {
                        $("#pages_list").html(`
                            <div class="col-12 text-center py-5">
                                <i class="fas fa-lock fa-3x text-warning mb-3"></i>
                                <h5 class="text-muted">Authentication Required</h5>
                                <p class="text-muted">Please log in to view your liked pages.</p>
                                <a class="btn btn-primary" href="${base_url}/login">Go to Login</a>
                            </div>
                        `);
                        return;
                    }
                    // If backend signals empty/none with 204/404/422, show an empty state instead
                    if (status === 204 || status === 404 || status === 422) {
                        $("#pages_list").html(`
                            <div class="col-12 text-center py-5">
                                <i class="fas fa-heart fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">No liked pages yet</h5>
                                <p class="text-muted">Start exploring pages and like the ones you're interested in to see them here.</p>
                                <a href="${base_url}/pages" class="btn btn-primary">
                                    <i class="fas fa-compass me-2"></i>Explore Pages
                                </a>
                            </div>
                        `);
                        $("#pagination").html("");
                        return;
                    }
                }
                $("#pages_list").html(`
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
                        <h5 class="text-muted">Connection Error</h5>
                        <p class="text-muted">Unable to connect to the server. Please check your internet connection and try again.</p>
                        <button class="btn btn-primary" onclick="get_liked_pages(1)">Retry</button>
                    </div>
                `);
            });
    }
    
    // Load page statistics
    function loadPageStats() {
        axios.get(`${base_url}/webapi/page/stats`)
            .then(response => {
                if (response.data.status === 200) {
                    const stats = response.data.data;
                    
                    // Update stats with loading state
                    updateStatDisplay("#following-count-stat", "#following-text", "#following-spinner", stats.following_count || 0);
                    updateStatDisplay("#verified-count-stat", "#verified-text", "#verified-spinner", stats.verified_count || 0);
                    updateStatDisplay("#total-pages-count", "#total-pages-text", "#total-pages-spinner", stats.total_pages || 0);
                    
                    // Update quick filter counts
                    $("#all-count").text(stats.total_pages || 0);
                    $("#following-count").text(stats.following_count || 0);
                    $("#verified-count").text(stats.verified_count || 0);
                    $("#popular-count").text(stats.popular_count || 0);
                    $("#recent-count").text(stats.recent_count || 0);
                }
            })
            .catch(error => {
                console.error("Error loading stats:", error);
                // Hide spinners on error
                $(".spinner-border").hide();
            });
    }
    
    // Update stat display with loading state
    function updateStatDisplay(containerId, textId, spinnerId, value) {
        $(textId).text(value);
        $(spinnerId).hide();
    }
    
    // Handle quick filter pills
    function handleQuickFilters() {
        $(".quick-filter").on("click", function() {
            $(".quick-filter").removeClass("active");
            $(this).addClass("active");
            
            const filter = $(this).data("filter");
            applyQuickFilter(filter);
        });
    }
    
    // Apply quick filter
    function applyQuickFilter(filter) {
        // Reset advanced filters
        $(".advanced-filter").prop("checked", false);
        $("#sortBy").val("newest");
        
        switch(filter) {
            case "all":
                get_all_pages(1, false);
                break;
            case "following":
                get_all_pages(1, false, { following: true });
                break;
            case "verified":
                get_all_pages(1, false, { verified: true });
                break;
            case "popular":
                get_all_pages(1, false, { sort: "most_followers" });
                break;
            case "recent":
                get_all_pages(1, false, { sort: "newest" });
                break;
        }
    }
    
    // Handle advanced filters
    function handleAdvancedFilters() {
        $("#applyFilters").on("click", function() {
            const filters = getAdvancedFilters();
            get_all_pages(1, false, filters);
        });
        
        $("#resetFilters").on("click", function() {
            $(".advanced-filter").prop("checked", false);
            $("#sortBy").val("newest");
            get_all_pages(1, false);
        });
    }
    
    // Get advanced filter values
    function getAdvancedFilters() {
        const filters = {};
        
        // Category filters
        const categories = [];
        $(".advanced-filter[value='business'], .advanced-filter[value='entertainment'], .advanced-filter[value='education'], .advanced-filter[value='technology']").each(function() {
            if ($(this).is(":checked")) {
                categories.push($(this).val());
            }
        });
        if (categories.length > 0) {
            filters.categories = categories;
        }
        
        // Follower filters
        const followerFilters = [];
        $(".advanced-filter[value='small'], .advanced-filter[value='medium'], .advanced-filter[value='large']").each(function() {
            if ($(this).is(":checked")) {
                followerFilters.push($(this).val());
            }
        });
        if (followerFilters.length > 0) {
            filters.followers = followerFilters;
        }
        
        // Verification filters
        if ($("#filter-verified").is(":checked")) {
            filters.verified = true;
        }
        if ($("#filter-unverified").is(":checked")) {
            filters.unverified = true;
        }
        
        // Sort by
        const sortBy = $("#sortBy").val();
        if (sortBy) {
            filters.sort = sortBy;
        }
        
        return filters;
    }
    


$(document).ready(function() {
    // Handle page name input
    $("#page-name").on("input", function() {
        let pageName = $(this).val();
        let pageUrl = generateSlug(pageName);

        if (pageName.length >= 3) {
            $("#page-url").val(pageUrl);
            checkPageAvailability(pageName, pageUrl);
        }
    });
    
    // Handle search input with debouncing
    let searchTimeout;
    $(".search-page").on("input", function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            // Check if we're on liked pages or my pages
            if (window.location.pathname.includes('liked-pages')) {
                get_liked_pages(1);
            } else {
                get_all_pages(1, true);
            }
        }, 500); // Wait 500ms after user stops typing
    });
    
    // Handle search button click
    $(".search-btn").on("click", function() {
        if (window.location.pathname.includes('liked-pages')) {
            get_liked_pages(1);
        } else {
            get_all_pages(1, true);
        }
    });
    
    // Handle Enter key press in search input
    $(".search-page").on("keypress", function(e) {
        if(e.which == 13) { // Enter key pressed
            e.preventDefault();
            if (window.location.pathname.includes('liked-pages')) {
                get_liked_pages(1);
            } else {
                get_all_pages(1, true);
            }
        }
    });
    
    // Handle category filter change
    $(".category-filter").on("change", function() {
        if (window.location.pathname.includes('liked-pages')) {
            get_liked_pages(1);
        } else {
            get_all_pages(1, true);
        }
    });
    
    // Handle clear search button
    $(".clear-search-btn").on("click", function() {
        $(".search-page").val("");
        $(this).hide();
        if (window.location.pathname.includes('liked-pages')) {
            get_liked_pages(1);
        } else {
            get_all_pages(1, true);
        }
    });
    
    // Show/hide clear button based on input
    $(".search-page").on("input", function() {
        if ($(this).val().length > 0) {
            $(".clear-search-btn").show();
        } else {
            $(".clear-search-btn").hide();
        }
    });
    
    // Initialize new functionality
    handleQuickFilters();
    handleAdvancedFilters();

    // Handle form submission
    $("#create-page-form").on("submit", function(e) {
        e.preventDefault();

        let pageName = $("#page-name").val();
        let pageUrl = $("#page-url").val();
        let category = $("#category").val();
        let description = $("#description").val();

        if (pageName == "" || pageUrl=="" || category == "" ) {
            myAlert.fire("Please Enter All fields.");
            return;
        }


        if (!nameAvailable || !urlAvailable) {
            myAlert.fire("Please choose a different name or URL.");
            return;
        }

        // Submit the form via Axios
        axios.post(base_url+'/webapi/page/add-new', {
            page_title: pageName,
            page_username: pageUrl,
            page_category: category,
            page_description: description
        })
        .then(response => {
            if (response.data.status === 201) {
               
                myAlert.fire({
                    icon: "success",
                    title: "Success",
                    text: "Page created successfully!"
                  });
                  
                setTimeout(() => {
                    window.location.href = base_url+"/pages";
                }, 3500);
            } else {
                myAlert.fire("Page creation failed: " + response.data.message);
            }
        })
        .catch(error => {
            console.error("Error creating page:", error);
            myAlert.fire("An error occurred while creating the page.");
        });
    });
});
