jQuery(document).ready(function($) {
    // -------------------------------------------------
    // Cache DOM elements
    // -------------------------------------------------
    const $clearCacheBtn        = $('#hvnly-clear-cache');
    const $clearSearchCacheBtn  = $('#hvnly-clear-search-cache');
    const $clearSidebarCacheBtn = $('#hvnly-clear-sidebar-cache');
    const $clearTermsCacheBtn   = $('#hvnly-clear-terms-cache');
    const $refreshStatsBtn      = $('#hvnly-refresh-stats');
    const $settingsForm         = $('#hvnly-cache-settings-form');
    
    // Shortcode cache buttons
    const $clearShortcodeCacheBtn     = $('#hvnly-clear-shortcode-cache');
    const $clearGridShortcodeBtn      = $('#hvnly-clear-grid-shortcode');
    const $clearListShortcodeBtn      = $('#hvnly-clear-list-shortcode');
    const $clearSearchShortcodeBtn    = $('#hvnly-clear-search-shortcode');

    // -------------------------------------------------
    // Progress overlay container
    // -------------------------------------------------
    if ($('#hvnly-progress-overlay').length === 0) {
        $('body').append(`
            <div class="hvnly-progress-overlay" id="hvnly-progress-overlay">
                <div class="hvnly-progress-card">
                    <div class="hvnly-progress-icon">
                        <i class="fas fa-broom"></i>
                    </div>
                    <h3 class="hvnly-progress-title" id="hvnly-progress-title">Clearing Cache</h3>
                    <p class="hvnly-progress-message" id="hvnly-progress-message">Please wait while we clear your cache...</p>
                    <div class="hvnly-progress-bar-container">
                        <div class="hvnly-progress-bar-bg">
                            <div class="hvnly-progress-bar-fill" id="hvnly-progress-bar-fill"></div>
                        </div>
                        <div class="hvnly-progress-percentage" id="hvnly-progress-percentage">0%</div>
                    </div>
                    <div class="hvnly-progress-stats" id="hvnly-progress-stats">
                        <span id="hvnly-progress-current">0</span> items cleared of <span id="hvnly-progress-total">0</span>
                    </div>
                </div>
            </div>
        `);
    }

    // -------------------------------------------------
    // Toast container
    // -------------------------------------------------
    if ($('#hvnly-toast-container').length === 0) {
        $('body').append('<div class="hvnly-toast-container" id="hvnly-toast-container"></div>');
    }

    // -------------------------------------------------
    // Modal container
    // -------------------------------------------------
    if ($('#hvnly-modal-overlay').length === 0) {
        $('body').append(`
            <div class="hvnly-modal-overlay" id="hvnly-modal-overlay">
                <div class="hvnly-modal" id="hvnly-modal">
                    <div class="hvnly-modal-header">
                        <h3 class="hvnly-modal-title" id="hvnly-modal-title"></h3>
                        <button type="button" class="hvnly-modal-close" id="hvnly-modal-close">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="hvnly-modal-body" id="hvnly-modal-body"></div>
                    <div class="hvnly-modal-footer" id="hvnly-modal-footer"></div>
                </div>
            </div>
        `);
    }

    // -------------------------------------------------
    // Initialize all buttons to disabled state with loading indicator
    // -------------------------------------------------
    function initializeButtonsAsLoading() {
        const allButtons = $('.action-buttons .button');
        
        // Disable all buttons initially
        allButtons.prop('disabled', true).css({
            'opacity': '0.6',
            'cursor': 'wait',
            'position': 'relative'
        });
        
        // Add loading text to main buttons
        $clearCacheBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        $clearSearchCacheBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        $clearSidebarCacheBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        $clearTermsCacheBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        $clearShortcodeCacheBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        $clearGridShortcodeBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        $clearListShortcodeBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        $clearSearchShortcodeBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        $refreshStatsBtn.html('<i class="fas fa-spinner fa-pulse"></i> Loading...');
        
        // Add loading overlay to action buttons container
        if ($('.hvnly-loading-overlay').length === 0) {
            $('.hvnly-cache-actions').css('position', 'relative');
            $('.hvnly-cache-actions').append(`
                <div class="hvnly-loading-overlay" style="
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(255, 255, 255, 0.8);
                    border-radius: 12px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 10;
                    backdrop-filter: blur(2px);
                ">
                    <div style="text-align: center;">
                        <i class="fas fa-sync-alt fa-spin" style="font-size: 32px; color: var(--hvnly-brand-primary); margin-bottom: 10px;"></i>
                        <p style="margin: 0; color: var(--hvnly-text-primary); font-size: 14px;">Loading cache data...</p>
                    </div>
                </div>
            `);
        }
    }
    
    // -------------------------------------------------
    // Remove loading overlay and restore buttons
    // -------------------------------------------------
    function removeLoadingOverlay() {
        $('.hvnly-loading-overlay').fadeOut(300, function() {
            $(this).remove();
        });
        
        // Restore button texts
        $clearCacheBtn.html('Clear All Cache');
        $clearSearchCacheBtn.html('Clear Main Search Cache');
        $clearSidebarCacheBtn.html('Clear Sidebar Cache');
        $clearTermsCacheBtn.html('Clear Terms Cache');
        $clearShortcodeCacheBtn.html('Clear All Shortcode Cache');
        $clearGridShortcodeBtn.html('Clear Grid Shortcode');
        $clearListShortcodeBtn.html('Clear List Shortcode');
        $clearSearchShortcodeBtn.html('Clear Search Shortcode');
        $refreshStatsBtn.html('Refresh Stats');
    }

    // -------------------------------------------------
    // Welcome message
    // -------------------------------------------------
    setTimeout(function() {
        const hasVisited = sessionStorage.getItem('hvnly_cache_visited');
        
        if (!hasVisited) {
            setTimeout(function() {
                showToast(
                    'Cache Management Ready',
                    'Your cache dashboard is loaded and ready. Monitor performance and manage cache settings.',
                    'success',
                    6000
                );
                sessionStorage.setItem('hvnly_cache_visited', 'true');
            }, 500);
        }
    }, 300);

// Dynamic CSS Clear Button Handler
$('#hvnly-clear-dynamic-css').on('click', function() {
    const $btn = $(this);
    const originalText = $btn.text();
    
    $btn.prop('disabled', true).text('Clearing...');
    
    $.ajax({
        url: hvnlyCacheAdmin.ajaxurl,
        type: 'POST',
        data: {
            action: 'hvnly_clear_dynamic_css',
            nonce: hvnlyCacheAdmin.nonce
        },
        success: function(response) {
            if (response.success) {
                showToast('Success', response.data, 'success', 3000);
                $btn.text('Cleared!');
                setTimeout(function() {
                    $btn.text(originalText).prop('disabled', false);
                }, 1500);
            } else {
                showToast('Error', response.data || 'Failed to clear dynamic CSS cache', 'error', 3000);
                $btn.text(originalText).prop('disabled', false);
            }
        },
        error: function() {
            showToast('Error', 'Network error. Please try again.', 'error', 3000);
            $btn.text(originalText).prop('disabled', false);
        }
    });
});


    // -------------------------------------------------
    // Modal close handlers
    // -------------------------------------------------
    $('#hvnly-modal-close').on('click', hideModal);
    $('#hvnly-modal-overlay').on('click', function(e) {
        if (e.target === this) {
            hideModal();
        }
    });

    // -------------------------------------------------
    // Quick-action buttons with cache checks
    // -------------------------------------------------
    $clearCacheBtn.on('click', () => {
        const totalItems = getTotalCacheItems();
        if (totalItems > 0) {
            showConfirmDialog(
                'Clear All Cache',
                'Are you sure you want to clear <strong>all</strong> Havenlytics cache? This will remove all cached search results, sidebar filters and term data.',
                'clearAllCache'
            );
        } else {
            showToast('No Cache to Clear', 'All cache is already empty.', 'info', 3000);
        }
    });

    $clearSearchCacheBtn.on('click', () => {
        const searchItems = getSearchCacheItems();
        if (searchItems > 0) {
            showConfirmDialog(
                'Clear Search Cache',
                'This will clear all cached property search results. Recent searches may be slower until the cache rebuilds.',
                'clearSearchCache'
            );
        } else {
            showToast('No Search Cache', 'Search cache is already empty.', 'info', 3000);
        }
    });

    $clearSidebarCacheBtn.on('click', () => {
        const sidebarItems = getSidebarCacheItems();
        if (sidebarItems > 0) {
            showConfirmDialog(
                'Clear Sidebar Cache',
                'This will clear all cached sidebar filter data. Sidebar filters will be reloaded on next use.',
                'clearSidebarCache'
            );
        } else {
            showToast('No Sidebar Cache', 'Sidebar cache is already empty.', 'info', 3000);
        }
    });

    $clearTermsCacheBtn.on('click', () => {
        const termsItems = getTermsCacheItems();
        if (termsItems > 0) {
            showConfirmDialog(
                'Clear Terms Cache',
                'This will clear all cached taxonomy terms (locations, types, features). Term data will be reloaded on next use.',
                'clearTermsCache'
            );
        } else {
            showToast('No Terms Cache', 'Terms cache is already empty.', 'info', 3000);
        }
    });

    // Shortcode cache buttons with cache checks
    $clearShortcodeCacheBtn.on('click', () => {
        const hasShortcodeCache = checkShortcodeCacheExists();
        if (hasShortcodeCache) {
            showConfirmDialog(
                'Clear All Shortcode Cache',
                'This will clear all cached shortcode outputs (grid, list, featured, search). This ensures fresh content is displayed immediately.',
                'clearAllShortcodeCache'
            );
        } else {
            showToast('No Shortcode Cache', 'Shortcode cache is already empty.', 'info', 3000);
        }
    });

    $clearGridShortcodeBtn.on('click', () => {
        const hasGridCache = checkGridShortcodeCache();
        if (hasGridCache) {
            showConfirmDialog(
                'Clear Grid Shortcode Cache',
                'This will clear only the [hvnly_property_grid] shortcode cache.',
                'clearGridShortcodeCache'
            );
        } else {
            showToast('No Grid Shortcode Cache', 'Grid shortcode cache is already empty.', 'info', 3000);
        }
    });

    $clearListShortcodeBtn.on('click', () => {
        const hasListCache = checkListShortcodeCache();
        if (hasListCache) {
            showConfirmDialog(
                'Clear List Shortcode Cache',
                'This will clear only the [hvnly_property_list] shortcode cache.',
                'clearListShortcodeCache'
            );
        } else {
            showToast('No List Shortcode Cache', 'List shortcode cache is already empty.', 'info', 3000);
        }
    });

    $clearSearchShortcodeBtn.on('click', () => {
        const hasSearchShortcodeCache = checkSearchShortcodeCache();
        if (hasSearchShortcodeCache) {
            showConfirmDialog(
                'Clear Search Shortcode Cache',
                'This will clear only the [hvnly_property_search] shortcode cache.',
                'clearSearchShortcodeCache'
            );
        } else {
            showToast('No Search Shortcode Cache', 'Search shortcode cache is already empty.', 'info', 3000);
        }
    });

    $refreshStatsBtn.on('click', function() {
        refreshStats($(this));
    });

    // -------------------------------------------------
    // Helper functions to get cache counts
    // -------------------------------------------------
    function getTotalCacheItems() {
        const totalItems = parseInt($('.stat-card:eq(5) .stat-value').text().replace(/,/g, '')) || 0;
        return totalItems;
    }
    
    function getSearchCacheItems() {
        const searchItems = parseInt($('.stat-card:eq(1) .stat-value').text().replace(/,/g, '')) || 0;
        return searchItems;
    }
    
    function getSidebarCacheItems() {
        const sidebarItems = parseInt($('.stat-card:eq(4) .stat-value').text().replace(/,/g, '')) || 0;
        return sidebarItems;
    }
    
    function getTermsCacheItems() {
        const termsItems = parseInt($('.stat-card:eq(2) .stat-value').text().replace(/,/g, '')) || 0;
        return termsItems;
    }
    
    function getCacheSize() {
        const cacheSize = $('.stat-card:eq(0) .stat-value').text();
        return cacheSize;
    }
    
    // Shortcode cache detection functions
    function checkShortcodeCacheExists() {
        const totalItems = getTotalCacheItems();
        return totalItems > 0;
    }
    
    function checkGridShortcodeCache() {
        const totalItems = getTotalCacheItems();
        return totalItems > 0;
    }
    
    function checkListShortcodeCache() {
        const totalItems = getTotalCacheItems();
        return totalItems > 0;
    }
    
    function checkSearchShortcodeCache() {
        const totalItems = getTotalCacheItems();
        return totalItems > 0;
    }
    
    // -------------------------------------------------
    // Update button states based on cache availability
    // -------------------------------------------------
    function updateButtonStates() {
        const totalItems = getTotalCacheItems();
        const searchItems = getSearchCacheItems();
        const sidebarItems = getSidebarCacheItems();
        const termsItems = getTermsCacheItems();
        const cacheSize = getCacheSize();
        const hasShortcodeCache = checkShortcodeCacheExists();
        
        // Update "Clear All Cache" button
        if (totalItems === 0 || cacheSize === '0 Bytes' || cacheSize === '0B') {
            $clearCacheBtn.prop('disabled', true).css({
                'opacity': '0.5',
                'cursor': 'not-allowed',
                'background': '#6c757d'
            }).attr('title', 'No cache to clear');
        } else {
            $clearCacheBtn.prop('disabled', false).css({
                'opacity': '',
                'cursor': 'pointer',
                'background': ''
            }).attr('title', 'Clear all cache');
        }
        
        // Update "Clear Main Search Cache" button
        if (searchItems === 0) {
            $clearSearchCacheBtn.prop('disabled', true).css({
                'opacity': '0.5',
                'cursor': 'not-allowed'
            }).attr('title', 'No search cache to clear');
        } else {
            $clearSearchCacheBtn.prop('disabled', false).css({
                'opacity': '',
                'cursor': 'pointer'
            }).attr('title', 'Clear search cache');
        }
        
        // Update "Clear Sidebar Cache" button
        if (sidebarItems === 0) {
            $clearSidebarCacheBtn.prop('disabled', true).css({
                'opacity': '0.5',
                'cursor': 'not-allowed'
            }).attr('title', 'No sidebar cache to clear');
        } else {
            $clearSidebarCacheBtn.prop('disabled', false).css({
                'opacity': '',
                'cursor': 'pointer'
            }).attr('title', 'Clear sidebar cache');
        }
        
        // Update "Clear Terms Cache" button
        if (termsItems === 0) {
            $clearTermsCacheBtn.prop('disabled', true).css({
                'opacity': '0.5',
                'cursor': 'not-allowed'
            }).attr('title', 'No terms cache to clear');
        } else {
            $clearTermsCacheBtn.prop('disabled', false).css({
                'opacity': '',
                'cursor': 'pointer'
            }).attr('title', 'Clear terms cache');
        }
        
        // Update Shortcode Cache buttons
        if (!hasShortcodeCache || totalItems === 0) {
            // Disable all shortcode buttons
            $clearShortcodeCacheBtn.prop('disabled', true).css({
                'opacity': '0.5',
                'cursor': 'not-allowed'
            }).attr('title', 'No shortcode cache to clear');
            
            $clearGridShortcodeBtn.prop('disabled', true).css({
                'opacity': '0.5',
                'cursor': 'not-allowed'
            }).attr('title', 'No grid shortcode cache to clear');
            
            $clearListShortcodeBtn.prop('disabled', true).css({
                'opacity': '0.5',
                'cursor': 'not-allowed'
            }).attr('title', 'No list shortcode cache to clear');
            
            $clearSearchShortcodeBtn.prop('disabled', true).css({
                'opacity': '0.5',
                'cursor': 'not-allowed'
            }).attr('title', 'No search shortcode cache to clear');
        } else {
            // Enable shortcode buttons
            $clearShortcodeCacheBtn.prop('disabled', false).css({
                'opacity': '',
                'cursor': 'pointer'
            }).attr('title', 'Clear all shortcode cache');
            
            $clearGridShortcodeBtn.prop('disabled', false).css({
                'opacity': '',
                'cursor': 'pointer'
            }).attr('title', 'Clear grid shortcode cache');
            
            $clearListShortcodeBtn.prop('disabled', false).css({
                'opacity': '',
                'cursor': 'pointer'
            }).attr('title', 'Clear list shortcode cache');
            
            $clearSearchShortcodeBtn.prop('disabled', false).css({
                'opacity': '',
                'cursor': 'pointer'
            }).attr('title', 'Clear search shortcode cache');
        }
        
        // Show or hide empty cache notice
        if (totalItems === 0) {
            if ($('.cache-empty-notice').length === 0) {
                $('.hvnly-cache-actions .action-buttons').prepend(`
                    <div class="cache-empty-notice" style="width:100%; margin-bottom:15px; padding:12px; background: rgba(108, 96, 254, 0.1); border-left: 4px solid var(--hvnly-brand-primary); border-radius: 8px;">
                        <i class="fas fa-check-circle" style="color: var(--hvnly-brand-success); margin-right: 10px;"></i>
                        <strong style="color: var(--hvnly-text-primary);">All caches are empty</strong>
                        <span style="color: var(--hvnly-text-secondary); margin-left: 5px;">No cache data to clear.</span>
                    </div>
                `);
            }
        } else {
            $('.cache-empty-notice').remove();
        }
    }
    
    // -------------------------------------------------
    // Settings form submission
    // -------------------------------------------------
    $settingsForm.on('submit', function (e) {
        const $submit = $(this).find('input[type="submit"]');
        $submit.prop('disabled', true).val('Saving...');
        sessionStorage.setItem('hvnly_settings_saved', 'true');
    });

    // -------------------------------------------------
    // Check for settings saved
    // -------------------------------------------------
    function checkForSettingsSaved() {
        const urlParams = new URLSearchParams(window.location.search);
        const settingsSaved = sessionStorage.getItem('hvnly_settings_saved');
        
        if (urlParams.get('settings-updated') === 'true' || settingsSaved === 'true') {
            setTimeout(function() {
                showToast(
                    'Settings Saved',
                    'Your cache settings have been updated successfully.',
                    'success',
                    5000
                );
                sessionStorage.removeItem('hvnly_settings_saved');
                
                if (window.history && window.history.replaceState) {
                    const newUrl = window.location.pathname + window.location.search.replace(/[?&]settings-updated=true/, '').replace(/^&/, '?');
                    window.history.replaceState({}, document.title, newUrl);
                }
            }, 300);
        }
    }

    checkForSettingsSaved();

    // -------------------------------------------------
    // Progress bar functions
    // -------------------------------------------------
    let progressInterval = null;
    
    function showProgress(title, message, total = 100) {
        const $overlay = $('#hvnly-progress-overlay');
        $('#hvnly-progress-title').text(title);
        $('#hvnly-progress-message').text(message);
        $('#hvnly-progress-total').text(total);
        $('#hvnly-progress-current').text('0');
        $('#hvnly-progress-percentage').text('0%');
        $('#hvnly-progress-bar-fill').css('width', '0%');
        $overlay.addClass('show');
    }
    
    function updateProgress(current, total, customMessage = null) {
        const percentage = Math.min(100, Math.round((current / total) * 100));
        $('#hvnly-progress-current').text(current);
        $('#hvnly-progress-percentage').text(percentage + '%');
        $('#hvnly-progress-bar-fill').css('width', percentage + '%');
        
        if (customMessage) {
            $('#hvnly-progress-message').text(customMessage);
        }
        
        // Update icon based on progress
        if (percentage >= 100) {
            $('#hvnly-progress-icon i').removeClass('fa-broom').addClass('fa-check-circle');
        } else if (percentage >= 75) {
            $('#hvnly-progress-icon i').removeClass('fa-broom').addClass('fa-fire');
        } else if (percentage >= 50) {
            $('#hvnly-progress-icon i').removeClass('fa-broom').addClass('fa-bolt');
        }
    }
    
    function hideProgress() {
        setTimeout(function() {
            const $overlay = $('#hvnly-progress-overlay');
            $overlay.removeClass('show');
            // Reset icon
            setTimeout(function() {
                $('#hvnly-progress-icon i').removeClass('fa-check-circle fa-fire fa-bolt').addClass('fa-broom');
            }, 300);
        }, 500);
    }
    
    function simulateProgress(total, duration, onComplete) {
        let current = 0;
        const increment = Math.ceil(total / 20);
        const intervalTime = duration / 20;
        
        if (progressInterval) clearInterval(progressInterval);
        
        progressInterval = setInterval(function() {
            current += increment;
            if (current >= total) {
                current = total;
                clearInterval(progressInterval);
                updateProgress(current, total, 'Finalizing...');
                if (onComplete) onComplete();
            } else {
                updateProgress(current, total);
            }
        }, intervalTime);
    }

    // -------------------------------------------------
    // Toast helpers
    // -------------------------------------------------
    function showToast(title, message, type = 'success', duration = 5000) {
        const toastId = 'toast-' + Date.now();
        
        let iconHtml = '';
        if (type === 'success') {
            iconHtml = '<i class="fas fa-check-circle"></i>';
        } else if (type === 'error') {
            iconHtml = '<i class="fas fa-exclamation-circle"></i>';
        } else if (type === 'warning') {
            iconHtml = '<i class="fas fa-exclamation-triangle"></i>';
        } else if (type === 'info') {
            iconHtml = '<i class="fas fa-info-circle"></i>';
        } else {
            iconHtml = '<i class="fas fa-info-circle"></i>';
        }
        
        const toastHTML = `
            <div class="hvnly-toast ${type}" id="${toastId}">
                <div class="hvnly-toast-icon">
                    ${iconHtml}
                </div>
                <div class="hvnly-toast-content">
                    <h4 class="hvnly-toast-title">${title}</h4>
                    <p class="hvnly-toast-message">${message}</p>
                </div>
                <button type="button" class="hvnly-toast-close">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        $('#hvnly-toast-container').prepend(toastHTML);
        const $toast = $('#' + toastId);
        
        setTimeout(() => {
            $toast.addClass('show');
        }, 100);
        
        $toast.find('.hvnly-toast-close').on('click', function() {
            hideToast($toast);
        });
        
        if (duration > 0) {
            setTimeout(() => {
                hideToast($toast);
            }, duration);
        }
        
        return $toast;
    }
    
    function hideToast($toast) {
        $toast.removeClass('show').addClass('hide');
        setTimeout(() => {
            $toast.remove();
        }, 400);
    }

    // -------------------------------------------------
    // Modal functions
    // -------------------------------------------------
    function showModal(title, body, buttons = []) {
        $('#hvnly-modal-title').html(title);
        $('#hvnly-modal-body').html(body);
        
        const $footer = $('#hvnly-modal-footer').empty();
        buttons.forEach(button => {
            const $btn = $(`
                <button type="button" class="hvnly-modal-button ${button.type || 'secondary'}" 
                        data-action="${button.action || ''}">
                    ${button.icon ? `<i class="${button.icon}"></i>` : ''}
                    ${button.text}
                </button>
            `);
            
            if (button.type === 'primary') {
                $btn.addClass('primary');
            } else {
                $btn.addClass('secondary');
            }
            
            $footer.append($btn);
        });
        
        $('#hvnly-modal-overlay').addClass('show');
        
        $('.hvnly-modal-button').off('click').on('click', function() {
            const action = $(this).data('action');
            hideModal();
            if (action && typeof window[action] === 'function') {
                window[action]();
            }
        });
    }
    
    function hideModal() {
        $('#hvnly-modal-overlay').removeClass('show');
    }

    // -------------------------------------------------
    // Confirm dialog
    // -------------------------------------------------
    function showConfirmDialog(title, message, confirmAction) {
        const body = `
            <div class="hvnly-confirm-icon">
                <div class="hvnly-modal-icon warning">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
            </div>
            <p class="hvnly-modal-message">${message}</p>
        `;
        
        const buttons = [
            { text: 'Cancel', type: 'secondary', icon: 'fas fa-times' },
            { text: 'Confirm', type: 'primary', action: confirmAction, icon: 'fas fa-check' }
        ];
        
        showModal(title, body, buttons);
    }

    // -------------------------------------------------
    // Cache-clear functions with progress bar
    // -------------------------------------------------
    window.clearAllCache = function() {
        const totalItems = getTotalCacheItems();
        if (totalItems === 0) {
            showToast('No Cache to Clear', 'All cache is already empty.', 'info', 3000);
            return;
        }
        performCacheClearWithProgress('all', $clearCacheBtn, totalItems, 'Clearing all cache items');
    }

    window.clearSearchCache = function() {
        const totalItems = getSearchCacheItems();
        if (totalItems === 0) {
            showToast('No Search Cache', 'Search cache is already empty.', 'info', 3000);
            return;
        }
        performCacheClearWithProgress('search', $clearSearchCacheBtn, totalItems, 'Clearing search cache');
    }

    window.clearSidebarCache = function() {
        const totalItems = getSidebarCacheItems();
        if (totalItems === 0) {
            showToast('No Sidebar Cache', 'Sidebar cache is already empty.', 'info', 3000);
            return;
        }
        performCacheClearWithProgress('sidebar', $clearSidebarCacheBtn, totalItems, 'Clearing sidebar cache');
    }

    window.clearTermsCache = function() {
        const totalItems = getTermsCacheItems();
        if (totalItems === 0) {
            showToast('No Terms Cache', 'Terms cache is already empty.', 'info', 3000);
            return;
        }
        performCacheClearWithProgress('terms', $clearTermsCacheBtn, totalItems, 'Clearing terms cache');
    }

    window.clearAllShortcodeCache = function() {
        const totalItems = getTotalCacheItems();
        if (totalItems === 0) {
            showToast('No Shortcode Cache', 'Shortcode cache is already empty.', 'info', 3000);
            return;
        }
        performCacheClearWithProgress('all_shortcode', $clearShortcodeCacheBtn, 50, 'Clearing all shortcode cache');
    }

    window.clearGridShortcodeCache = function() {
        const totalItems = getTotalCacheItems();
        if (totalItems === 0) {
            showToast('No Grid Shortcode Cache', 'Grid shortcode cache is already empty.', 'info', 3000);
            return;
        }
        performCacheClearWithProgress('hvnly_property_grid', $clearGridShortcodeBtn, 20, 'Clearing grid shortcode cache');
    }

    window.clearListShortcodeCache = function() {
        const totalItems = getTotalCacheItems();
        if (totalItems === 0) {
            showToast('No List Shortcode Cache', 'List shortcode cache is already empty.', 'info', 3000);
            return;
        }
        performCacheClearWithProgress('hvnly_property_list', $clearListShortcodeBtn, 20, 'Clearing list shortcode cache');
    }

    window.clearSearchShortcodeCache = function() {
        const totalItems = getTotalCacheItems();
        if (totalItems === 0) {
            showToast('No Search Shortcode Cache', 'Search shortcode cache is already empty.', 'info', 3000);
            return;
        }
        performCacheClearWithProgress('hvnly_property_search', $clearSearchShortcodeBtn, 20, 'Clearing search shortcode cache');
    }

    function performCacheClearWithProgress(type, $btn, totalItems, progressMessage) {
        const $allButtons = $('.action-buttons .button');
        
        // Disable all buttons
        $allButtons.prop('disabled', true).css('opacity', '0.6');
        $btn.text('Clearing...').css('cursor', 'wait');
        
        // Show progress overlay
        showProgress('Clearing Cache', progressMessage, totalItems);
        
        // Simulate progress while actual clearing happens
        simulateProgress(totalItems, 1500, function() {
            // Actual AJAX call after progress simulation
            $.ajax({
                url: hvnlyCacheAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: type === 'all_shortcode' ? 'hvnly_clear_shortcode_cache' : 'hvnly_clear_cache',
                    cache_type: type === 'all_shortcode' ? 'all' : type,
                    shortcode_type: type,
                    nonce: hvnlyCacheAdmin.nonce
                },
                success: function(res) {
                    if (res.success) {
                        updateProgress(totalItems, totalItems, 'Complete!');
                        setTimeout(function() {
                            hideProgress();
                            showToast('Cache Cleared', res.data || 'Cache cleared successfully.', 'success', 4000);
                            $btn.text('Cleared!').css('background', 'var(--hvnly-brand-success)').css('color', '#fff');
                            setTimeout(function() { 
                                resetAllButtons(); 
                                refreshStats(); 
                            }, 1500);
                        }, 500);
                    } else {
                        hideProgress();
                        showToast('Failed', res.data || 'Failed to clear cache.', 'error', 5000);
                        showError($btn, res.data);
                    }
                },
                error: function() {
                    hideProgress();
                    showToast('Error', hvnlyCacheAdmin.errorText || 'An error occurred.', 'error', 5000);
                    showError($btn, hvnlyCacheAdmin.errorText);
                },
                complete: function() {
                    setTimeout(function() {
                        $allButtons.prop('disabled', false).css('opacity', '');
                        $btn.css('cursor', '');
                    }, 800);
                }
            });
        });
    }

    function resetAllButtons() {
        $('.action-buttons .button').each(function() {
            const $btn = $(this);
            $btn.css('background', '').css('color', '');
            
            const id = $btn.attr('id');
            switch(id) {
                case 'hvnly-clear-cache':
                    $btn.text('Clear All Cache');
                    break;
                case 'hvnly-clear-search-cache':
                    $btn.text('Clear Main Search Cache');
                    break;
                case 'hvnly-clear-sidebar-cache':
                    $btn.text('Clear Sidebar Cache');
                    break;
                case 'hvnly-clear-terms-cache':
                    $btn.text('Clear Terms Cache');
                    break;
                case 'hvnly-clear-shortcode-cache':
                    $btn.text('Clear All Shortcode Cache');
                    break;
                case 'hvnly-clear-grid-shortcode':
                    $btn.text('Clear Grid Shortcode');
                    break;
                case 'hvnly-clear-list-shortcode':
                    $btn.text('Clear List Shortcode');
                    break;
                case 'hvnly-clear-search-shortcode':
                    $btn.text('Clear Search Shortcode');
                    break;
                case 'hvnly-refresh-stats':
                    $btn.text('Refresh Stats');
                    break;
                default:
                    break;
            }
        });
        
        // Re-enable buttons based on cache availability
        updateButtonStates();
    }

    // -------------------------------------------------
    // Stats refresh
    // -------------------------------------------------
    function refreshStats($btn = null) {
        if ($btn) {
            $btn.prop('disabled', true).css('opacity', '0.6').text('Refreshing...');
        }

        $.ajax({
            url: hvnlyCacheAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'hvnly_get_cache_stats',
                nonce: hvnlyCacheAdmin.nonce
            },
            success: function(res) {
                if (res.success) {
                    updateStatsDisplay(res.data.stats || {}, res.data.performance || {});
                    // Update button states after stats refresh
                    updateButtonStates();
                    if ($btn) {
                        $btn.text('Updated!').css('background', 'var(--hvnly-brand-success)').css('color', '#fff');
                        setTimeout(function() {
                            $btn.text('Refresh Stats').css('background', '').css('color', '').prop('disabled', false).css('opacity', '');
                        }, 1000);
                    }
                    showToast('Stats Updated', 'Cache statistics have been refreshed.', 'success', 3000);
                }
            },
            error: function() {
                if ($btn) {
                    $btn.text('Refresh Stats').prop('disabled', false).css('opacity', '');
                }
                showToast('Error', 'Failed to refresh statistics.', 'error', 3000);
            }
        });
    }

    // -------------------------------------------------
    // Stats UI update
    // -------------------------------------------------
    function updateStatsDisplay(stats, perf) {
        let hitRate = parseFloat(stats.cache_hit_rate) || 0;
        
        if (hitRate > 100) hitRate = 100;
        if (hitRate < 0) hitRate = 0;
        
        const statCards = $('.stat-card');
        
        if (statCards.length >= 1) {
            statCards.eq(0).find('.stat-value').text(stats.cache_size_human || '0 Bytes');
        }
        
        if (statCards.length >= 2) {
            statCards.eq(1).find('.stat-value').text(formatNumber(stats.search_cache_count || 0));
        }
        
        if (statCards.length >= 3) {
            statCards.eq(2).find('.stat-value').text(formatNumber(stats.term_cache_count || 0));
        }
        
        if (statCards.length >= 4) {
            statCards.eq(3).find('.stat-value').text(hitRate.toFixed(1) + '%');
        }
        
        if (statCards.length >= 5) {
            statCards.eq(4).find('.stat-value').text(formatNumber(stats.sidebar_cache_count || 0));
        }
        
        if (statCards.length >= 6) {
            statCards.eq(5).find('.stat-value').text(formatNumber(stats.total_cached_items || 0));
        }
    }

    function formatNumber(number) {
        return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function showError($el, msg) {
        $el.text(msg).css('background', 'var(--hvnly-brand-error)').css('color', '#fff');
        setTimeout(function() {
            $el.css('background', '').css('color', '');
            resetAllButtons();
        }, 3000);
    }

    // -------------------------------------------------
    // Initialize - Disable buttons and show loading state
    // -------------------------------------------------
    initializeButtonsAsLoading();
    
    // Load initial stats and enable buttons based on cache availability
    setTimeout(function() {
        refreshStats();
        setInterval(refreshStats, 30000);
        
        // Remove loading overlay after stats are loaded
        setTimeout(function() {
            removeLoadingOverlay();
            updateButtonStates();
        }, 1500);
    }, 500);
});