$(document).ready(function() {

    // Function to check authentication
    function checkAuth(callback) {
        $.ajax({
            url: baseUrl +  '/check-auth',
            type: 'GET',
            success: function(response) {
                console.log('Authentication Check Response:', response);
                if (response.authenticated === false) {
                    console.log('Not authenticated');
                    loadLoginForm();
                } else {
                    console.log('Authenticated');
                    callback(); // Proceed with the intended action
                }
            },
            error: function(xhr, status, error) {
                console.error('Failed to check authentication status:', error);
                alert('Failed to check authentication status.');
            }
        });
    }

    function loadLoginForm() {
        $.ajax({
            url: baseUrl + '/login',
            type: 'GET',
            success: function(response) {
                // 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 login form:', error);
                alert('Failed to load login form.');
            },
            complete: function() {
                // Hide loader and overlay
                $('#ajax-loader').hide();
                $('#overlay').hide();
            }
        });
    }

    // 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.ajax-link, button.ajax-button', function(event) {
        event.preventDefault(); // Prevent default link behavior

        var url = $(this).attr('href') || $(this).data('url'); // Get the URL
        var isAjax = $(this).hasClass('ajax-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
        checkAuth(function() {
            handleAction(url, isAjax); // Proceed with the intended action
        });
    });
});
