$(document).ready(function() {

    // Function to handle AJAX request or redirection
    function handleAction(url, isAjax) {
        console.log('Action URL:', url);
        if (isAjax) {
            $.ajax({
                url: url,
                type: 'GET',
                success: function(response) {

                    console.log('Action URL response:', response.meta.description);
                    // Update the content
                    $('#main-content').html(response.html);

                    // Update the page URL
                    window.history.pushState({}, response.title, response.url);

                    // Update the page title
                    document.title = response.title;

                    // Update meta tags
                    $('meta[name="description"]').attr('content', response.meta.description);
                    $('meta[name="keywords"]').attr('content', response.meta.keywords);
                },
                error: function(xhr, status, error) {
                    console.error('Failed to load resource:', error);
                    if (xhr.status === 401) {
                        loadLoginForm();
                    } else {
                        alert('Failed to load resource.');
                    }
                },
                complete: function() {
                    // Hide loader and overlay
                    $('#ajax-loader').hide();
                    $('#overlay').hide();
                }
            });
        } else {
            window.location.href = url; // Redirect to the URL
        }
    }

    // Event handler for clicking links
    $(document).on('click', 'a.frintajax-link, button.frintajax-link', function(event) {
        event.preventDefault(); // Prevent default link behavior

        var url = $(this).attr('href') || $(this).data('url'); // Get the URL
        var isAjax = $(this).hasClass('frintajax-link'); // Determine if it's an AJAX link

        console.log('Action URL:', url);

        // Show loader and overlay
        $('#ajax-loader').show();
        $('#overlay').show();

        // First check authentication
        handleAction(url, isAjax); // Proceed with the intended action
    });
});
