(function ($) {
    'use strict';

    /**
     * ProQyz Dashboard AJAX Manager
     * Modern implementation for dashboard tab navigation and filtering
     */
    const ProQyzDashboard = {
        
        // Configuration
        config: {
            ajaxUrl: proqyzDashboard.ajaxUrl,
            nonce: proqyzDashboard.nonce,
            currentRequest: null
        },

        // Cache for JSON data
        cache: {
            users: null,
            courses: null,
            quizzes: null,
            widgets: null
        },

        /**
         * Initialize dashboard
         */
        init: function() {
            this.loadCache();
            this.bindEvents();
            console.log('ProQyz Dashboard initialized');
        },

        /**
         * Load JSON data from page into cache
         */
        loadCache: function() {
            try {
                this.cache.users = JSON.parse(document.getElementById('json-users-data').textContent);
                this.cache.courses = JSON.parse(document.getElementById('json-courses-data').textContent);
                this.cache.quizzes = JSON.parse(document.getElementById('json-quizz-data').textContent);
                this.cache.widgets = JSON.parse(document.getElementById('json-widgets-data').textContent);
            } catch (e) {
                console.error('Failed to load dashboard cache:', e);
            }
        },

        /**
         * Bind event handlers
         */
        bindEvents: function() {
            // Menu navigation
            $(document).on('click', '[data-proqyz-type="router"]', this.handleMenuClick.bind(this));
            
            // Tab filters (reviewed/unreviewed for writing/speaking)
            $(document).on('click', '[data-type="tab-filter"]', this.handleTabFilter.bind(this));
            
            // Filter apply button
            $(document).on('click', '.test-history__btn-filter', this.handleFilterApply.bind(this));
            
            // Filter reset button
            $(document).on('click', '.test-history__btn-reset', this.handleFilterReset.bind(this));
            
            // Pagination
            $(document).on('click', '#page-previous', this.handlePagePrevious.bind(this));
            $(document).on('click', '#page-next', this.handlePageNext.bind(this));
            $(document).on('click', '.pagination-btn[data-page]', this.handlePageClick.bind(this));
            $(document).on('click', '#per-page-btn', this.handlePerPageChange.bind(this));
            $(document).on('click', '#jump-page', this.handlePageJump.bind(this));
            
            // Per page selector
            $(document).on('change', '#per-page-select', this.handlePerPageSelectChange.bind(this));
            
            // Delete result
            $(document).on('click', '.proqyz__btn-confirm', this.handleDeleteResult.bind(this));
            $(document).on('click', '[data-proqyz-delete-modal]', this.showDeleteModal.bind(this));
            
            // Other UI interactions
            $(document).on('click', '#overlay-region', function() {
                $('body').removeClass('test-history-filtering');
            });
            
            $(document).on('click', '#js-btn-filter', function() {
                $('body').addClass('test-history-filtering');
            });
            
            // Mobile menu toggle
            $(document).on('click', '#js-menudb-mobile', function() {
                $(this).toggleClass('active');
                const $menuList = $('#dashboard-menu__list');
                
                if ($(this).hasClass('active')) {
                    $menuList.css('display', 'block').attr('aria-expanded', 'true');
                } else {
                    $menuList.css('display', 'none').attr('aria-expanded', 'false');
                }
            });
            
            $(document).on('click', '.history-table__other-btn', function() {
                $(this).toggleClass('active');
            });
        },

        /**
         * Generate skeleton preloader HTML
         */
        getSkeletonHTML: function() {
            return `
                <div class="dashboard-preloader">
                    <h1 class="section-title skeleton-title"></h1>
                    
                    <!-- Widgets Skeleton -->
                    <section class="performance-board">
                        <div class="performance-board__item-wrap">
                            <div class="performance-board__item skeleton-widget">
                                <div class="skeleton-icon"></div>
                                <div class="skeleton-text skeleton-text-sm"></div>
                                <div class="skeleton-text skeleton-text-lg"></div>
                            </div>
                            <div class="performance-board__item skeleton-widget">
                                <div class="skeleton-icon"></div>
                                <div class="skeleton-text skeleton-text-sm"></div>
                                <div class="skeleton-text skeleton-text-lg"></div>
                            </div>
                            <div class="performance-board__item skeleton-widget">
                                <div class="skeleton-icon"></div>
                                <div class="skeleton-text skeleton-text-sm"></div>
                                <div class="skeleton-text skeleton-text-lg"></div>
                            </div>
                            <div class="performance-board__item skeleton-widget">
                                <div class="skeleton-icon"></div>
                                <div class="skeleton-text skeleton-text-sm"></div>
                                <div class="skeleton-text skeleton-text-lg"></div>
                            </div>
                        </div>
                    </section>
                    
                    <br />
                    
                    <h1 class="section-title skeleton-title"></h1>
                    
                    <!-- Table Skeleton -->
                    <section class="test-history">
                        <div class="test-history__filter skeleton-filters">
                            <div class="skeleton-filter"></div>
                            <div class="skeleton-filter"></div>
                            <div class="skeleton-filter"></div>
                            <div class="skeleton-button"></div>
                            <div class="skeleton-button-round"></div>
                        </div>
                        
                        <table class="table table-hover history-table iot-responsive-table skeleton-table">
                            <thead>
                                <tr>
                                    <th><div class="skeleton-text"></div></th>
                                    <th><div class="skeleton-text"></div></th>
                                    <th><div class="skeleton-text"></div></th>
                                    <th><div class="skeleton-text"></div></th>
                                    <th><div class="skeleton-text"></div></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text skeleton-text-long"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                </tr>
                                <tr>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text skeleton-text-long"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                </tr>
                                <tr>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text skeleton-text-long"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                    <td><div class="skeleton-text"></div></td>
                                </tr>
                            </tbody>
                        </table>
                        
                        <!-- Pagination Skeleton -->
                        <div class="test-history__bottom">
                            <div class="test-history__per-page">
                                <div class="skeleton-text" style="width: 50px; height: 16px; margin-right: 8px;"></div>
                                <div class="skeleton-filter" style="width: 80px; height: 32px;"></div>
                            </div>
                            <div class="pager">
                                <ul class="pager__items">
                                    <li class="pager__item"><div class="skeleton-button" style="width: 60px; height: 32px;"></div></li>
                                    <li class="pager__item"><div class="skeleton-button" style="width: 60px; height: 32px;"></div></li>
                                    <li class="pager__item"><div class="skeleton-button" style="width: 35px; height: 32px;"></div></li>
                                    <li class="pager__item"><div class="skeleton-button" style="width: 60px; height: 32px;"></div></li>
                                    <li class="pager__item"><div class="skeleton-button" style="width: 60px; height: 32px;"></div></li>
                                </ul>
                            </div>
                        </div>
                    </section>
                </div>
            `;
        },

        /**
         * Handle menu click (tab navigation)
         */
        handleMenuClick: function(e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const action = $btn.data('proqyz-action');
            
            if (!action) return;
            
            // Update mobile menu button text
            const menuItemHTML = $btn.html();
            $('#js-menudb-mobile .dashboard-menu__link').html(menuItemHTML);
            
            // Close mobile menu after clicking
            $('#js-menudb-mobile').removeClass('active');
            $('#dashboard-menu__list').css('display', 'none').attr('aria-expanded', 'false');
            
            // Show skeleton preloader immediately when switching tabs
            $('[data-ajax-response="true"]').html(this.getSkeletonHTML());
            
            const requestData = this.buildRequestData(action);
            
            if (requestData) {
                // Mark this as a tab switch (should reset filters)
                this.makeAjaxRequest(requestData, $btn, true);
            }
        },

        /**
         * Get current per-page value
         */
        getCurrentPerPage: function() {
            // Try to get from select dropdown first, fallback to default
            const selectValue = $('#per-page-select').val();
            if (selectValue) {
                return parseInt(selectValue);
            }
            // Fallback to old input if exists
            const inputValue = $('#per-page-input').data('per-page');
            return inputValue ? parseInt(inputValue) : 10;
        },

        /**
         * Build request data based on action
         */
        buildRequestData: function(action) {
            const perPage = this.getCurrentPerPage();
            
            const actionMap = {
                'proqyz-ajax-my-dashboard': {
                    action: 'proqyz_ajax_dashboard_overall',
                    filters: { category: 'all', review: 'all' }
                },
                'proqyz-ajax-ielts-listening': {
                    action: 'proqyz_ajax_dashboard_listening',
                    filters: { category: 'ielts-listening' }
                },
                'proqyz-ajax-ielts-reading': {
                    action: 'proqyz_ajax_dashboard_reading',
                    filters: { category: 'ielts-reading' }
                },
                'proqyz-ajax-ielts-writing': {
                    action: 'proqyz_ajax_dashboard_writing',
                    filters: { category: 'ielts-writing', review: 0 }
                },
                'proqyz-ajax-ielts-speaking': {
                    action: 'proqyz_ajax_dashboard_speaking',
                    filters: { category: 'ielts-speaking', review: 0 }
                },
                'proqyz-ajax-load-gov-sectional-non-sectional-timing': {
                    action: 'proqyz_ajax_dashboard_gov_exam',
                    filters: { category: 'gov-exam' }
                },
                'proqyz-ajax-load-pdf-quiz': {
                    action: 'proqyz_ajax_dashboard_pdf_quiz',
                    filters: { category: 'proqyz-pdf-quiz' }
                },
                'proqyz-ajax-abandoned-tests': {
                    action: 'proqyz_ajax_dashboard_abandoned_tests',
                    filters: { category: 'all' }
                }
            };
            
            const mapped = actionMap[action];
            if (!mapped) return null;
            
            // Include cached data to avoid server recalculation
            return {
                action: mapped.action,
                nonce: this.config.nonce,
                cached_user: JSON.stringify(this.cache.users),
                cached_courses: JSON.stringify(this.cache.courses),
                cached_quizzes: JSON.stringify(this.cache.quizzes),
                filters: {
                    current_page: 1,
                    per_page: perPage,
                    user: 'all',
                    course: 'all',
                    session_type: 'all',
                    ...mapped.filters
                }
            };
        },

        /**
         * Make AJAX request
         */
        makeAjaxRequest: function(data, $btn, isTabSwitch) {
            const self = this;
            
            // Abort previous request
            if (this.config.currentRequest) {
                this.config.currentRequest.abort();
            }
            
            this.config.currentRequest = $.ajax({
                url: this.config.ajaxUrl,
                method: 'POST',
                data: data,
                beforeSend: function() {
                    if ($btn) {
                        $('[data-ilms-menu-xs="true"]').html('<span class="ioticon-clock"></span> Loading...');
                    }
                    
                    // Add loading state
                    $('[data-ajax-response="true"]').addClass('is-loading');
                    
                    // Disable all filter controls and buttons
                    $('.selectpicker').prop('disabled', true);
                    $('.filter_btns').prop('disabled', true);
                    $('.test-history__btn-reset').prop('disabled', true);
                    $('.pagination-btn').prop('disabled', true).css('pointer-events', 'none');
                    $('.per-page-select').prop('disabled', true);
                    
                    // Show table preloader
                    if ($('.history-table tbody').length) {
                        $('.history-table tbody').css('opacity', '0.5').css('pointer-events', 'none');
                    }
                    
                    // Refresh selectpicker to show disabled state
                    if ($.fn.selectpicker) {
                        $('.selectpicker').selectpicker('refresh');
                    }
                },
                success: function(response) {
                    self.handleAjaxSuccess(response, $btn, isTabSwitch);
                },
                error: function(xhr, status, error) {
                    self.handleAjaxError(xhr, status, error);
                },
                complete: function() {
                    // Re-enable all controls after request completes
                    $('.selectpicker').prop('disabled', false);
                    $('.filter_btns').prop('disabled', false);
                    $('.test-history__btn-reset').prop('disabled', false);
                    $('.pagination-btn').prop('disabled', false).css('pointer-events', '');
                    $('.per-page-select').prop('disabled', false);
                    
                    // Remove table preloader
                    if ($('.history-table tbody').length) {
                        $('.history-table tbody').css('opacity', '1').css('pointer-events', '');
                    }
                    
                    // Remove rotation animation from reset button
                    $('.test-history__btn-reset').removeClass('active');
                    
                    // Close mobile filter panel after response
                    $('body').removeClass('test-history-filtering');
                    
                    // Refresh selectpicker to show enabled state
                    if ($.fn.selectpicker) {
                        $('.selectpicker').selectpicker('refresh');
                    }
                }
            });
        },

        /**
         * Handle successful AJAX response
         */
        handleAjaxSuccess: function(response, $btn, isTabSwitch) {
            console.log('AJAX Response:', response); // Debug
            
            if (!response.success) {
                console.error('AJAX request failed:', response);
                return;
            }
            
            const data = response.data;
            
            // Check if data was recalculated (meaning we should update cache)
            const wasRecalculated = data.recalculated || false;
            const usedCache = data.used_cache || false;
            
            console.log('Cache status - Used:', usedCache, 'Recalculated:', wasRecalculated);
            
            // Update menu active state
            if ($btn) {
                $('.dashboard-menu__item').removeClass('active');
                $btn.parent().addClass('active');
                $('[data-ilms-menu-xs="true"]').html($btn.html());
            }
            
            // Update HTML content
            if (data.has_html) {
                if (data.html.page) {
                    $('[data-ajax-response="true"]').html(data.html.page);
                    console.log('Updated page content');
                    
                    // Initialize selectpicker on new content (filters are inside page HTML)
                    if ($.fn.selectpicker) {
                        $('.selectpicker').selectpicker();
                        console.log('Selectpicker initialized');
                    }
                    
                    // Reinitialize charts after DOM update (with delay to ensure canvas elements are ready)
                    const self = this;
                    setTimeout(function() {
                        self.initProgressCharts();
                        console.log('Charts reinitialized after AJAX');
                    }, 300);
                }
                if (data.html.pagination) {
                    $('#pagination-main').html(data.html.pagination);
                }
                // Only update filters HTML when switching tabs (not when applying filters or paginating)
                if (data.html.filters && isTabSwitch) {
                    $('#test_filters').html(data.html.filters);
                    if ($.fn.selectpicker) {
                        $('.selectpicker').selectpicker();
                    }
                    console.log('Filters reset (tab switch)');
                }
            }
            
            // Update JSON cache ONLY if data was recalculated or provided
            if (data.has_json && data.json) {
                // Update courses cache if provided (and data was recalculated or cache was empty)
                if (data.json.courses && (wasRecalculated || !usedCache)) {
                    document.querySelector('#json-courses-data').textContent = JSON.stringify(data.json.courses);
                    this.cache.courses = data.json.courses;
                    console.log('Updated courses cache:', data.json.courses.length, 'courses');
                }
                
                // Update quiz analytics cache if provided
                if (data.json.quiz_analytics && (wasRecalculated || !usedCache)) {
                    document.querySelector('#json-quizz-data').textContent = JSON.stringify(data.json.quiz_analytics);
                    this.cache.quizzes = data.json.quiz_analytics;
                    console.log('Updated quiz analytics cache');
                }
                
                // Update widgets cache if provided
                if (data.json.widgets && (wasRecalculated || !usedCache)) {
                    document.querySelector('#json-widgets-data').textContent = JSON.stringify(data.json.widgets);
                    this.cache.widgets = data.json.widgets;
                    console.log('Updated widgets cache');
                }
            }
        },

        /**
         * Handle AJAX error
         */
        handleAjaxError: function(xhr, status, error) {
            // Check if server sent reload instruction
            if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.reload) {
                console.warn('User session changed - reloading page');
                alert('Your session has changed. The page will reload.');
                location.reload();
                return;
            }
            
            $('[data-ilms-menu-xs="true"]').html('<span class="ioticon-alert"></span> Failed');
            console.error('AJAX Error:', error);
        },

        /**
         * Handle tab filter click (reviewed/unreviewed)
         */
        handleTabFilter: function(e) {
            e.preventDefault();
            const $tab = $(e.currentTarget);
            const category = $tab.data('filter-category');
            const review = $tab.data('ajax-review');
            
            const data = {
                action: 'proqyz_ajax_dashboard_' + category.replace('ielts-', ''),
                nonce: this.config.nonce,
                cached_user: JSON.stringify(this.cache.users),
                cached_courses: JSON.stringify(this.cache.courses),
                cached_quizzes: JSON.stringify(this.cache.quizzes),
                filters: {
                    current_page: 1,
                    per_page: this.getCurrentPerPage(), // Preserve current per-page value
                    user: 'all',
                    course: 'all',
                    session_type: 'all',
                    category: category,
                    review: review
                }
            };
            
            // Not a tab switch, don't reset filters
            this.makeAjaxRequest(data, null, false);
            
            // Update active tab
            $('[data-type="tab-filter"]').removeClass('active');
            $tab.addClass('active');
        },

        /**
         * Handle filter apply
         */
        handleFilterApply: function(e) {
            e.preventDefault();
            
            const user = $('#filter-students').val() || 'all';
            const course = $('#filter-course').val() || 'all';
            const sessionType = $('#filter-session-type').val() || 'all';
            const category = $('#quiz_category').val() || 'dashboard';
            const categoryFilter = $('#filter-category').val() || 'all';
            
            // Get review status from dropdown if exists, otherwise from active tab
            let review = null;
            if ($('#filter-review').length) {
                review = $('#filter-review').val();
            } else {
                const tabReview = $('[data-type="tab-filter"].active').data('ajax-review');
                review = tabReview !== undefined ? tabReview : null;
            }
            
            // Map category to action name
            const actionName = this.getCategoryAction(category);
            
            const data = {
                action: actionName,
                nonce: this.config.nonce,
                cached_user: JSON.stringify(this.cache.users),
                cached_courses: JSON.stringify(this.cache.courses),
                cached_quizzes: JSON.stringify(this.cache.quizzes),
                filters: {
                    current_page: 1,
                    per_page: this.getCurrentPerPage(), // Preserve current per-page value
                    user: user,
                    course: course,
                    session_type: sessionType,
                    category: categoryFilter,
                    review: review
                }
            };
            
            // Not a tab switch, don't reset filters
            this.makeAjaxRequest(data, null, false);
        },

        /**
         * Handle filter reset
         */
        handleFilterReset: function(e) {
            e.preventDefault();
            
            // Add rotation animation to reset button
            const $resetBtn = $(e.currentTarget);
            $resetBtn.addClass('active');
            
            const category = $('#quiz_category').val() || 'dashboard';
            
            // Reset filter values
            if ($('#filter-students').length) $('#filter-students').val('all');
            if ($('#filter-course').length) $('#filter-course').val('all');
            if ($('#filter-session-type').length) $('#filter-session-type').val('all');
            if ($('#filter-category').length) $('#filter-category').val('all');
            
            // Get review status after potential reset
            let review = null;
            if ($('#filter-review').length) {
                // Reset review dropdown to first option (usually unreviewed)
                $('#filter-review').prop('selectedIndex', 0);
                review = $('#filter-review').val();
            } else {
                // Use tab filter value
                const tabReview = $('[data-type="tab-filter"].active').data('ajax-review');
                review = tabReview !== undefined ? tabReview : null;
            }
            
            if ($.fn.selectpicker) {
                $('.selectpicker').selectpicker('refresh');
            }
            
            // Map category to action name
            const actionName = this.getCategoryAction(category);
            
            // Reload with default filters
            const data = {
                action: actionName,
                nonce: this.config.nonce,
                cached_user: JSON.stringify(this.cache.users),
                cached_courses: JSON.stringify(this.cache.courses),
                cached_quizzes: JSON.stringify(this.cache.quizzes),
                filters: {
                    current_page: 1,
                    per_page: this.getCurrentPerPage(), // Preserve current per-page value
                    user: 'all',
                    course: 'all',
                    session_type: 'all',
                    category: 'all',
                    review: review
                }
            };
            
            // Reset filters - but don't replace HTML (values will be reset in form)
            this.makeAjaxRequest(data, null, false);
        },

        /**
         * Handle page click (numbered buttons)
         */
        handlePageClick: function(e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const targetPage = parseInt($btn.data('page'));
            
            // Don't reload if clicking current page
            if (!$btn.hasClass('active') && targetPage) {
                this.loadPage(targetPage);
            }
        },

        /**
         * Handle page previous
         */
        handlePagePrevious: function(e) {
            e.preventDefault();
            const currentPage = $('[data-current-page]').data('current-page');
            if (currentPage > 1) {
                this.loadPage(currentPage - 1);
            }
        },

        /**
         * Handle page next
         */
        handlePageNext: function(e) {
            e.preventDefault();
            const currentPage = $('[data-current-page]').data('current-page');
            const totalPages = $('[data-total-pages]').data('total-pages');
            if (currentPage < totalPages) {
                this.loadPage(currentPage + 1);
            }
        },

        /**
         * Handle per page change
         */
        handlePerPageChange: function(e) {
            e.preventDefault();
            const perPage = $('#per-page-input').val();
            $('#per-page-input').data('per-page', perPage);
            this.loadPage(1);
        },

        /**
         * Handle per page select change (new dropdown)
         */
        handlePerPageSelectChange: function(e) {
            const perPage = $(e.currentTarget).val();
            
            const user = $('#filter-students').val() || 'all';
            const course = $('#filter-course').val() || 'all';
            const sessionType = $('#filter-session-type').val() || 'all';
            const category = $('#quiz_category').val() || 'dashboard';
            const categoryFilter = $('#filter-category').val() || 'all';
            
            // Get review status from dropdown if exists, otherwise from active tab
            let review = null;
            if ($('#filter-review').length) {
                review = $('#filter-review').val();
            } else {
                const tabReview = $('[data-type="tab-filter"].active').data('ajax-review');
                review = tabReview !== undefined ? tabReview : null;
            }
            
            // Map category to action name
            const actionName = this.getCategoryAction(category);
            
            const data = {
                action: actionName,
                nonce: this.config.nonce,
                cached_user: JSON.stringify(this.cache.users),
                cached_courses: JSON.stringify(this.cache.courses),
                cached_quizzes: JSON.stringify(this.cache.quizzes),
                filters: {
                    current_page: 1, // Reset to page 1 when changing per page
                    per_page: parseInt(perPage),
                    user: user,
                    course: course,
                    session_type: sessionType,
                    category: categoryFilter,
                    review: review
                }
            };
            
            // Not a tab switch
            this.makeAjaxRequest(data, null, false);
        },

        /**
         * Handle page jump
         */
        handlePageJump: function(e) {
            e.preventDefault();
            const targetPage = parseInt($('#input-current-page').val());
            const totalPages = $('[data-total-pages]').data('total-pages');
            if (targetPage > 0 && targetPage <= totalPages) {
                this.loadPage(targetPage);
            }
        },

        /**
         * Load specific page
         */
        loadPage: function(page) {
            const user = $('#filter-students').val() || 'all';
            const course = $('#filter-course').val() || 'all';
            const sessionType = $('#filter-session-type').val() || 'all';
            const category = $('#quiz_category').val() || 'dashboard';
            const categoryFilter = $('#filter-category').val() || category;
            
            // Get review status from dropdown if exists, otherwise from active tab
            let review = null;
            if ($('#filter-review').length) {
                review = $('#filter-review').val();
            } else {
                const tabReview = $('[data-type="tab-filter"].active').data('ajax-review');
                review = tabReview !== undefined ? tabReview : null;
            }
            
            // Map category to action name
            const actionName = this.getCategoryAction(category);
            
            const data = {
                action: actionName,
                nonce: this.config.nonce,
                cached_user: JSON.stringify(this.cache.users),
                cached_courses: JSON.stringify(this.cache.courses),
                cached_quizzes: JSON.stringify(this.cache.quizzes),
                filters: {
                    current_page: page,
                    per_page: this.getCurrentPerPage(), // Preserve current per-page value
                    user: user,
                    course: course,
                    session_type: sessionType,
                    category: categoryFilter,
                    review: review
                }
            };
            
            // Pagination - don't reset filters
            this.makeAjaxRequest(data, null, false);
        },

        /**
         * Get AJAX action name from category
         */
        getCategoryAction: function(category) {
            const actionMap = {
                'dashboard': 'proqyz_ajax_dashboard_overall',
                'ielts-listening': 'proqyz_ajax_dashboard_listening',
                'ielts-reading': 'proqyz_ajax_dashboard_reading',
                'ielts-writing': 'proqyz_ajax_dashboard_writing',
                'ielts-speaking': 'proqyz_ajax_dashboard_speaking',
                'gov-exam': 'proqyz_ajax_dashboard_gov_exam',
                'gov-sectional-non-sectional-timing': 'proqyz_ajax_dashboard_gov_exam',
                'proqyz-pdf-quiz': 'proqyz_ajax_dashboard_pdf_quiz',
                'abandoned': 'proqyz_ajax_dashboard_abandoned_tests'
            };
            
            return actionMap[category] || 'proqyz_ajax_dashboard_overall';
        },

        /**
         * Show delete confirmation modal
         */
        showDeleteModal: function(e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const testId = $btn.data('test-id');
            const testCategory = $btn.data('test-category');
            
            // Store test ID for later use
            $btn.closest('.history-table__btn-group').data('pending-delete-id', testId);
            
            // Create modal if it doesn't exist
            if ($('#modal-delete-test').length === 0) {
                $('body').append(`
                    <div class="st-modal modal fade" id="modal-delete-test" tabindex="-1" role="dialog">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                    <h4 class="modal-title">Confirm Delete</h4>
                                </div>
                                <div class="modal-body">
                                    <p>Are you sure you want to delete this test result? This action cannot be undone.</p>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                    <button type="button" class="btn btn-danger proqyz__btn-confirm">
                                        <i class="fa fa-trash"></i> Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `);
            }
            
            // Store test ID in modal for confirm handler
            $('#modal-delete-test').data('test-id', testId);
            $('#modal-delete-test').removeClass('ielts-listening ielts-reading ielts-writing ielts-speaking gov-non-sectional-timing gov-sectional-timing');
            $('#modal-delete-test').addClass(testCategory);
            
            // Show modal
            $('#modal-delete-test').modal('show');
        },

        /**
         * Handle delete result
         */
        handleDeleteResult: function(e) {
            e.preventDefault();
            const self = this;
            const $btn = $(e.currentTarget);
            const testId = $('#modal-delete-test').data('test-id');
            const originalHtml = $btn.html();
            
            if (!testId) {
                alert('No test ID found');
                return;
            }
            
            $.ajax({
                url: this.config.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'proqyz_ajax_delete_result',
                    nonce: this.config.nonce,
                    id: testId
                },
                beforeSend: function() {
                    $btn.html('<i class="fa fa-spinner fa-spin"></i> Deleting...');
                    $('#modal-delete-test button').prop('disabled', true);
                },
                success: function(response) {
                    if (response.success) {
                        // Close modal
                        $('#modal-delete-test').modal('hide');
                        
                        // Show success message
                        console.log('Test deleted successfully:', testId);
                        
                        // Reload current tab to refresh data
                        const currentCategory = $('#quiz_category').val() || 'dashboard';
                        const actionName = self.getCategoryAction(currentCategory);
                        
                        // Get current filters and pagination settings
                        const user = $('#filter-students').val() || 'all';
                        const course = $('#filter-course').val() || 'all';
                        const sessionType = $('#filter-session-type').val() || 'all';
                        const categoryFilter = $('#filter-category').val() || 'all';
                        const currentPage = $('[data-current-page]').data('current-page') || 1;
                        
                        let review = null;
                        if ($('#filter-review').length) {
                            review = $('#filter-review').val();
                        } else {
                            const tabReview = $('[data-type="tab-filter"].active').data('ajax-review');
                            review = tabReview !== undefined ? tabReview : null;
                        }
                        
                        const reloadData = {
                            action: actionName,
                            nonce: self.config.nonce,
                            cached_user: JSON.stringify(self.cache.users),
                            cached_courses: JSON.stringify(self.cache.courses),
                            cached_quizzes: JSON.stringify(self.cache.quizzes),
                            filters: {
                                current_page: currentPage,
                                per_page: self.getCurrentPerPage(),
                                user: user,
                                course: course,
                                session_type: sessionType,
                                category: categoryFilter,
                                review: review
                            }
                        };
                        
                        // Reload the current tab view
                        self.makeAjaxRequest(reloadData, null, false);
                    } else {
                        alert('Failed to delete result: ' + (response.data.message || 'Unknown error'));
                    }
                },
                error: function(xhr) {
                    alert('Error deleting result. Please try again.');
                    console.error('Delete error:', xhr);
                },
                complete: function() {
                    $btn.html(originalHtml);
                    $('#modal-delete-test button').prop('disabled', false);
                }
            });
        },
        
        /**
         * Initialize progress analytics charts
         */
        initProgressCharts: function() {
            // Check if Chart.js is loaded and charts exist
            if (typeof Chart === 'undefined') {
                return;
            }
            
            // Get chart data from JSON scripts
            var listening = $('#listening-chatjs-json').text();
            var reading = $('#reading-chatjs-json').text();
            var writing = $('#writing-chatjs-json').text();
            var speaking = $('#speaking-chatjs-json').text();
            
            if (!listening || !reading || !writing || !speaking) {
                return; // No chart data available
            }
            
            try {
                var listening_json = JSON.parse(listening);
                var reading_json = JSON.parse(reading);
                var writing_json = JSON.parse(writing);
                var speaking_json = JSON.parse(speaking);
                
                // Destroy existing charts if they exist
                if (window.listeningEvaluation) {
                    window.listeningEvaluation.destroy();
                }
                if (window.readingEvaluation) {
                    window.readingEvaluation.destroy();
                }
                if (window.writingEvaluation) {
                    window.writingEvaluation.destroy();
                }
                if (window.speakingEvaluation) {
                    window.speakingEvaluation.destroy();
                }
                
                // Listening Chart Configuration
                var config_listening_evaluation = {
                    type: 'line',
                    data: {
                        labels: listening_json.listening.labels || [],
                        datasets: [{
                            label: 'Score',
                            backgroundColor: "#32b4c8",
                            borderColor: "#32b4c8",
                            data: listening_json.listening.bands || [],
                            fill: false,
                            score: listening_json.listening.scores || []
                        }]
                    },
                    options: {
                        layout: {
                            padding: {
                                left: 0,
                                right: 13,
                                top: 0,
                                bottom: 0
                            }
                        },
                        spanGaps: true,
                        legend: {
                            display: false
                        },
                        responsive: true,
                        maintainAspectRatio: false,
                        title: {
                            display: false
                        },
                        elements: {
                            line: {
                                tension: 0.000001
                            }
                        },
                        scales: {
                            yAxes: [{
                                ticks: {
                                    min: 0,
                                    max: 100
                                }
                            }]
                        },
                        tooltips: {
                            backgroundColor: '#fff',
                            borderColor: '#999',
                            borderWidth: 1,
                            xPadding: 12,
                            yPadding: 12,
                            cornerRadius: 10,
                            bodySpacing: 5,
                            displayColors: false,
                            callbacks: {
                                label: function(tooltipItem, data) {
                                    var currentElement = data.datasets[tooltipItem.datasetIndex].score[tooltipItem.index];
                                    var overallLabel = 'Overall : ' + (currentElement[0] || 0).toFixed(1);
                                    var correctLabel = 'Correct: ' + (currentElement[1] || 0);
                                    var incorrectLabel = 'Incorrect: ' + (currentElement[2] || 0);
                                    var unansweredLabel = 'Unanswered: ' + (currentElement[3] || 0);
                                    return [overallLabel, correctLabel, incorrectLabel, unansweredLabel];
                                },
                                title: function(tooltipItem, data) {
                                    return '';
                                },
                                labelTextColor: function(tooltipItem, chart) {
                                    return '#666';
                                }
                            }
                        }
                    }
                };
                
                // Reading Chart Configuration
                var config_reading_evaluation = {
                    type: 'line',
                    data: {
                        labels: reading_json.reading.labels || [],
                        datasets: [{
                            label: 'Score',
                            backgroundColor: "#327846",
                            borderColor: "#327846",
                            data: reading_json.reading.bands || [],
                            fill: false,
                            score: reading_json.reading.scores || []
                        }]
                    },
                    options: {
                        layout: {
                            padding: {
                                left: 0,
                                right: 13,
                                top: 0,
                                bottom: 0
                            }
                        },
                        spanGaps: true,
                        legend: {
                            display: false
                        },
                        responsive: true,
                        maintainAspectRatio: false,
                        title: {
                            display: false
                        },
                        elements: {
                            line: {
                                tension: 0.000001
                            }
                        },
                        scales: {
                            yAxes: [{
                                ticks: {
                                    min: 0,
                                    max: 100
                                }
                            }]
                        },
                        tooltips: {
                            backgroundColor: '#fff',
                            borderColor: '#999',
                            borderWidth: 1,
                            xPadding: 12,
                            yPadding: 12,
                            cornerRadius: 10,
                            bodySpacing: 5,
                            displayColors: false,
                            callbacks: {
                                label: function(tooltipItem, data) {
                                    var currentElement = data.datasets[tooltipItem.datasetIndex].score[tooltipItem.index];
                                    var overallLabel = 'Overall : ' + (currentElement[0] || 0).toFixed(1);
                                    var correctLabel = 'Correct: ' + (currentElement[1] || 0);
                                    var incorrectLabel = 'Incorrect: ' + (currentElement[2] || 0);
                                    var unansweredLabel = 'Unanswered: ' + (currentElement[3] || 0);
                                    return [overallLabel, correctLabel, incorrectLabel, unansweredLabel];
                                },
                                title: function(tooltipItem, data) {
                                    return '';
                                },
                                labelTextColor: function(tooltipItem, chart) {
                                    return '#666';
                                }
                            }
                        }
                    }
                };
                
                // Writing Chart Configuration
                var config_writing_evaluation = {
                    type: 'line',
                    data: {
                        labels: writing_json.writing.labels || [],
                        datasets: [{
                            label: 'Score',
                            backgroundColor: "#f9a95a",
                            borderColor: "#f9a95a",
                            data: writing_json.writing.bands || [],
                            fill: false,
                            score: writing_json.writing.scores || []
                        }]
                    },
                    options: {
                        layout: {
                            padding: {
                                left: 0,
                                right: 13,
                                top: 0,
                                bottom: 0
                            }
                        },
                        spanGaps: true,
                        legend: {
                            display: false
                        },
                        responsive: true,
                        maintainAspectRatio: false,
                        title: {
                            display: false
                        },
                        elements: {
                            line: {
                                tension: 0.000001
                            }
                        },
                        scales: {
                            yAxes: [{
                                ticks: {
                                    min: 0,
                                    max: 9
                                }
                            }]
                        },
                        tooltips: {
                            backgroundColor: '#fff',
                            borderColor: '#999',
                            borderWidth: 1,
                            xPadding: 12,
                            yPadding: 12,
                            cornerRadius: 10,
                            bodySpacing: 5,
                            displayColors: false,
                            callbacks: {
                                label: function(tooltipItem, data) {
                                    var currentElement = data.datasets[tooltipItem.datasetIndex].score[tooltipItem.index];
                                    var overallLabel = 'Overall : ' + (currentElement[0] || 0).toFixed(1);
                                    var task1Label = 'Task 1: ' + (currentElement[1] || 0).toFixed(1);
                                    var task2Label = 'Task 2: ' + (currentElement[2] || 0).toFixed(1);
                                    return [overallLabel, task1Label, task2Label];
                                },
                                title: function(tooltipItem, data) {
                                    return '';
                                },
                                labelTextColor: function(tooltipItem, chart) {
                                    return '#666';
                                }
                            }
                        }
                    }
                };
                
                // Speaking Chart Configuration
                var config_speaking_evaluation = {
                    type: 'line',
                    data: {
                        labels: speaking_json.speaking.labels || [],
                        datasets: [{
                            label: 'Score',
                            backgroundColor: "#c76378",
                            borderColor: "#c76378",
                            data: speaking_json.speaking.bands || [],
                            fill: false,
                            score: speaking_json.speaking.scores || []
                        }]
                    },
                    options: {
                        layout: {
                            padding: {
                                left: 0,
                                right: 13,
                                top: 0,
                                bottom: 0
                            }
                        },
                        spanGaps: true,
                        legend: {
                            display: false
                        },
                        responsive: true,
                        maintainAspectRatio: false,
                        title: {
                            display: false
                        },
                        elements: {
                            line: {
                                tension: 0.000001
                            }
                        },
                        scales: {
                            yAxes: [{
                                ticks: {
                                    min: 0,
                                    max: 9
                                }
                            }]
                        },
                        tooltips: {
                            backgroundColor: '#fff',
                            borderColor: '#999',
                            borderWidth: 1,
                            xPadding: 12,
                            yPadding: 12,
                            cornerRadius: 10,
                            bodySpacing: 5,
                            displayColors: false,
                            callbacks: {
                                label: function(tooltipItem, data) {
                                    var currentElement = data.datasets[tooltipItem.datasetIndex].score[tooltipItem.index];
                                    var overallLabel = 'Overall : ' + (currentElement[0] || 0).toFixed(1);
                                    return [overallLabel];
                                },
                                title: function(tooltipItem, data) {
                                    return '';
                                },
                                labelTextColor: function(tooltipItem, chart) {
                                    return '#666';
                                }
                            }
                        }
                    }
                };
                
                // Store chart configs globally for lazy initialization
                window.chartConfigs = {
                    listening: config_listening_evaluation,
                    reading: config_reading_evaluation,
                    writing: config_writing_evaluation,
                    speaking: config_speaking_evaluation
                };
                
                // Initialize only the listening chart (active tab)
                var listening_canvas = document.getElementById('listening_evaluation');
                if (listening_canvas) {
                    var listening_evaluation = listening_canvas.getContext('2d');
                    window.listeningEvaluation = new Chart(listening_evaluation, config_listening_evaluation);
                    console.log('Listening chart initialized');
                }
                
                // Track which charts have been initialized
                window.chartsInitialized = {
                    listening: !!window.listeningEvaluation,
                    reading: false,
                    writing: false,
                    speaking: false
                };
                
                // Handle tab switching - initialize chart when tab becomes visible
                $(document).off('shown.bs.tab', '.test-performance__nav-btn').on('shown.bs.tab', '.test-performance__nav-btn', function(e) {
                    var target = $(e.target).attr('href'); // e.g., #reading-performance
                    
                    // Initialize reading chart if not already done
                    if (target === '#reading-performance' && !window.chartsInitialized.reading) {
                        var reading_canvas = document.getElementById('reading_evaluation');
                        if (reading_canvas && window.chartConfigs.reading) {
                            if (window.readingEvaluation) {
                                window.readingEvaluation.destroy();
                            }
                            var reading_evaluation = reading_canvas.getContext('2d');
                            window.readingEvaluation = new Chart(reading_evaluation, window.chartConfigs.reading);
                            window.chartsInitialized.reading = true;
                            console.log('Reading chart initialized on tab show');
                        }
                    }
                    
                    // Initialize writing chart if not already done
                    if (target === '#writing-performance' && !window.chartsInitialized.writing) {
                        var writing_canvas = document.getElementById('writing_evaluation');
                        if (writing_canvas && window.chartConfigs.writing) {
                            if (window.writingEvaluation) {
                                window.writingEvaluation.destroy();
                            }
                            var writing_evaluation = writing_canvas.getContext('2d');
                            window.writingEvaluation = new Chart(writing_evaluation, window.chartConfigs.writing);
                            window.chartsInitialized.writing = true;
                            console.log('Writing chart initialized on tab show');
                        }
                    }
                    
                    // Initialize speaking chart if not already done
                    if (target === '#speaking-performance' && !window.chartsInitialized.speaking) {
                        var speaking_canvas = document.getElementById('speaking_evaluation');
                        if (speaking_canvas && window.chartConfigs.speaking) {
                            if (window.speakingEvaluation) {
                                window.speakingEvaluation.destroy();
                            }
                            var speaking_evaluation = speaking_canvas.getContext('2d');
                            window.speakingEvaluation = new Chart(speaking_evaluation, window.chartConfigs.speaking);
                            window.chartsInitialized.speaking = true;
                            console.log('Speaking chart initialized on tab show');
                        }
                    }
                });
                
                // Handle mobile select dropdown for chart tabs
                $(document).off('change', '#select-lesson').on('change', '#select-lesson', function() {
                    var index = $(this).val();
                    if ($('.test-performance__nav-btn')[index]) {
                        $('.test-performance__nav-btn')[index].click();
                    }
                });
                
                // Update select when clicking tabs
                $(document).off('click', '.test-performance__nav-btn').on('click', '.test-performance__nav-btn', function() {
                    var index = $(this).data('tab-index');
                    $('#select-lesson').val(index);
                    if ($.fn.selectpicker) {
                        $('.selectpicker').selectpicker('refresh');
                    }
                });
                
            } catch (error) {
                console.error('Error initializing charts:', error);
            }
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        ProQyzDashboard.init();
        
        // Auto-load dashboard on page load
        $('[data-proqyz-action="proqyz-ajax-my-dashboard"]').click();
        
        // Initialize selectpicker if available
        if ($.fn.selectpicker) {
            $('.selectpicker').selectpicker();
        }
        
        // Note: Charts are initialized automatically in handleAjaxSuccess after content loads
    });

    // Expose to global scope for debugging
    window.ProQyzDashboard = ProQyzDashboard;

})(jQuery);

