<?php
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Enqueue credit analytics scripts
wp_enqueue_script(
    'aysa-credit-analytics',
    AYSA_PLUGIN_URL . 'assets/js/aysa-credit-analytics.js',
    array('jquery'),
    AYSA_VERSION,
    true
);

// Localize the script with AJAX data
wp_localize_script('aysa-credit-analytics', 'aysa_credit_analytics', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('aysa_credit_analytics_nonce'),
    'api_base_url' => AYSA_API_BASE_URL,
    'project_id' => class_exists('Aysa_Wallet_Manager') ? intval(Aysa_Wallet_Manager::get_instance()->get_project_id()) : intval(get_option('aysa_project_id', 0))
));

// Enqueue Chart.js for credit analytics
wp_enqueue_script(
    'chartjs',
    AYSA_PLUGIN_URL . 'assets/js/vendor/chartjs-stub.js',
    array(),
    AYSA_VERSION,
    true
);

// Enqueue credit analytics CSS
wp_enqueue_style(
    'aysa-credit-analytics',
    AYSA_PLUGIN_URL . 'admin/css/aysa-credit-analytics.css',
    array(),
    AYSA_VERSION
);
?>

<style>
/* Uninstall options styles */
.aysa-uninstall-warning {
    background-color: #f3f4f6;
    border-left: 4px solid #2563eb;
    padding: 15px;
    border-radius: 4px;
    margin: 15px 0;
}

.aysa-warning-text {
    color: #374151 !important;
    font-weight: 500;
    margin-top: 8px;
    line-height: 1.5;
}

.aysa-warning-text strong {
    color: #1f2937;
    font-size: 14px;
}

.aysa-uninstall-warning .aysa-checkbox-label {
    font-weight: 600;
    color: #1f2937;
}

.aysa-uninstall-warning input[type="checkbox"]:checked + .aysa-checkbox-checkmark::after {
    border-color: #2563eb !important;
}

/* Horizontal Tab Navigation Styles */
.aysa-tabs-container {
    margin-top: 20px;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aysa-tabs-nav {
    display: flex;
    background: #f8f9fa;
    border-radius: 8px 8px 0 0;
    border-bottom: 1px solid #e9ecef;
    overflow-x: auto;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
    gap: 0;
}

.aysa-tabs-nav::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
}

.aysa-tab-button {
    background: none;
    border: none;
    padding: 16px 24px;
    font-size: 14px;
    font-weight: 500;
    color: #6c757d;
    cursor: pointer;
    transition: all 0.2s ease;
    white-space: nowrap;
    border-bottom: 3px solid transparent;
    position: relative;
    min-width: 140px;
    text-align: center;
    margin: 0;
    border-radius: 0;
}

.aysa-tab-button:hover {
    background-color: #e9ecef;
    color: #495057;
}

.aysa-tab-button.active {
    background-color: #ffffff;
    color: #2563eb;
    border-bottom-color: #2563eb;
    font-weight: 600;
    box-shadow: 0 2px 4px rgba(37, 99, 235, 0.1);
}

.aysa-tab-button.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    right: 0;
    height: 1px;
    background-color: #ffffff;
}

.aysa-tabs-content {
    background: #ffffff;
    border-radius: 0 0 8px 8px;
    min-height: 500px;
    padding: 0;
}

.aysa-tab-content {
    display: none;
    padding: 30px;
}

.aysa-tab-content.active {
    display: block;
    animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

/* Responsive design for mobile */
@media (max-width: 768px) {
    .aysa-tabs-nav {
        flex-wrap: nowrap;
        overflow-x: auto;
    }
    
    .aysa-tab-button {
        min-width: 120px;
        padding: 12px 16px;
        font-size: 13px;
    }
    
    .aysa-tab-content {
        padding: 20px;
    }
}

/* Base Styles */
.aysa-dashboard-wrapper {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    color: #333;
    background-color: #f8f9fa;
    padding: 20px;
    width: 100%;
    min-height: 100vh;
    box-sizing: border-box;
}

.aysa-dashboard-container {
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Header Styles */
.aysa-dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-dashboard-title h1 {
    font-size: 22px;
    margin: 0 0 5px;
    font-weight: 500;
    color: #333;
}

.aysa-dashboard-title p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.aysa-dashboard-user {
    display: flex;
    align-items: center;
    gap: 15px;
}

.aysa-btn-text {
    background: none;
    color: #1a73e8;
    padding: 0;
    border: none;
    font-size: 14px;
    cursor: pointer;
}

.aysa-btn-text:hover {
    text-decoration: underline;
}

/* Panel Styles */
.aysa-panel {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    border: 1px solid #e0e0e0;
}

.aysa-section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px;
    color: #202124;
}

/* Info Box */
.aysa-info-box {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
    border: 1px solid #e0e0e0;
}

.aysa-info-box h3 {
    font-size: 14px;
    font-weight: 500;
    margin: 0 0 10px;
    color: #202124;
}

.aysa-info-box p {
    margin: 0;
    color: #5f6368;
    font-size: 13px;
}

/* Secret Key Display */
.aysa-secret-key-display {
    margin: 20px 0;
}

.aysa-secret-key-container {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.aysa-secret-key-container input {
    flex: 1;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-family: monospace;
    font-size: 14px;
    background-color: #f9f9f9;
}

.aysa-secret-key-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

/* Authentication Management Styles */
.aysa-auth-status {
    margin: 20px 0;
}

.aysa-auth-success {
    background: #d1f2eb;
    border: 1px solid #1abc9c;
    border-radius: 6px;
    padding: 15px;
}

.aysa-auth-warning {
    background: #fdf2e9;
    border: 1px solid #e67e22;
    border-radius: 6px;
    padding: 15px;
}

.aysa-auth-error,
.aysa-error {
    background: #fadbd8;
    border: 1px solid #e74c3c;
    border-radius: 6px;
    padding: 15px;
    color: #e74c3c;
}

.aysa-auth-info h4 {
    margin: 0 0 10px 0;
    font-size: 16px;
}

.aysa-auth-info p {
    margin: 5px 0;
    font-size: 14px;
}

.aysa-loading {
    text-align: center;
    padding: 20px;
    color: #666;
    font-style: italic;
}

/* Authentication Stats */
.aysa-auth-stats {
    margin-top: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.aysa-auth-stats h4 {
    margin: 0 0 15px 0;
    color: #333;
}

.aysa-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
}

.aysa-stat-item {
    text-align: center;
    padding: 15px;
    background: white;
    border-radius: 4px;
    border: 1px solid #dee2e6;
}

.aysa-stat-value {
    display: block;
    font-size: 24px;
    font-weight: bold;
    color: #0073aa;
    margin-bottom: 5px;
}

.aysa-stat-label {
    display: block;
    font-size: 12px;
    color: #666;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.aysa-btn-danger {
    background-color: #dc3545;
    color: white;
    border: 1px solid #dc3545;
}

.aysa-btn-danger:hover {
    background-color: #c82333;
    border-color: #bd2130;
}

/* Responsive Design */
@media (max-width: 768px) {
    .aysa-secret-key-container {
        flex-direction: column;
        align-items: stretch;
    }
    
    .aysa-secret-key-actions {
        justify-content: center;
    }
    
    .aysa-stats-grid {
        grid-template-columns: 1fr;
    }
}

/* Form Styles */
.aysa-settings-form {
    max-width: 600px;
}

.aysa-form-group {
    margin-bottom: 20px;
}

.aysa-form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #202124;
}

.aysa-select {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background-color: white;
    color: #202124;
    font-size: 14px;
}

.aysa-input {
    width: 100%;
    max-width: 250px;
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background-color: white;
    color: #202124;
    font-size: 14px;
}

.aysa-field-description {
    font-size: 12px;
    color: #5f6368;
    margin-top: 4px;
    margin-bottom: 0;
}

.aysa-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.aysa-checkbox {
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-checkbox input[type="checkbox"] {
    width: 16px;
    height: 16px;
}

.aysa-checkbox label {
    margin: 0;
    font-weight: normal;
}

.aysa-form-actions {
    margin-top: 30px;
}

/* Button Styles */
.aysa-btn {
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    border: none;
}

.aysa-btn-primary {
    background-color: #1a73e8;
    color: white;
}

.aysa-btn-secondary {
    background-color: #f8f9fa;
    color: #5f6368;
    border: 1px solid #e0e0e0;
}

.aysa-btn-warning {
    background-color: #ff9800;
    color: white;
    border: 1px solid #ff9800;
}

.aysa-btn-warning:hover {
    background-color: #f57c00;
}

.aysa-btn-small {
    padding: 4px 8px;
    font-size: 12px;
}

/* Automation Feature Styles */
.aysa-automation-features {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.aysa-feature-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    background: white;
}

.aysa-feature-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.aysa-feature-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.aysa-status-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-status-suggest {
    background-color: #fff3cd;
    color: #856404;
}

.aysa-status-automate {
    background-color: #d4edda;
    color: #155724;
}

.aysa-status-disabled {
    background-color: #f8f9fa;
    color: #6c757d;
}

.aysa-feature-content p {
    margin: 0 0 15px 0;
    color: #5f6368;
    font-size: 14px;
}

.aysa-feature-controls {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-bottom: 15px;
}

.aysa-toggle {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
}

.aysa-toggle input[type="checkbox"] {
    position: relative;
    width: 44px;
    height: 24px;
    appearance: none;
    background-color: #ccc;
    border-radius: 12px;
    transition: background-color 0.3s;
}

.aysa-toggle input[type="checkbox"]:checked {
    background-color: #1a73e8;
}

.aysa-toggle input[type="checkbox"]:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.aysa-toggle input[type="checkbox"]::before {
    content: '';
    position: absolute;
    top: 2px;
    left: 2px;
    width: 20px;
    height: 20px;
    background-color: white;
    border-radius: 50%;
    transition: transform 0.3s;
}

.aysa-toggle input[type="checkbox"]:checked::before {
    transform: translateX(20px);
}

.aysa-toggle-label {
    font-size: 14px;
    font-weight: 500;
}

.aysa-feature-stats {
    display: flex;
    gap: 20px;
    font-size: 12px;
    color: #5f6368;
}

.aysa-stat strong {
    color: #202124;
}

/* Range Input Styles */
.aysa-range {
    width: 100%;
    height: 6px;
    border-radius: 3px;
    background: #e0e0e0;
    outline: none;
    appearance: none;
}

.aysa-range::-webkit-slider-thumb {
    appearance: none;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: #1a73e8;
    cursor: pointer;
}

.aysa-range::-moz-range-thumb {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: #1a73e8;
    cursor: pointer;
    border: none;
}

.aysa-range-display {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 5px;
}

.aysa-range-value {
    font-weight: 600;
    color: #1a73e8;
}

.aysa-range-label {
    font-size: 12px;
    color: #5f6368;
}

/* Modal Styles */
.aysa-modal {
    position: fixed;
    z-index: 10000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    display: none;
}

.aysa-modal.show {
    display: block;
}

.aysa-modal-content {
    background-color: white;
    margin: 5% auto;
    padding: 0;
    border-radius: 8px;
    width: 90%;
    max-width: 500px;
    max-height: 80vh;
}

.aysa-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

.aysa-modal-close {
    font-size: 24px;
    font-weight: bold;
    cursor: pointer;
    color: #aaa;
}

.aysa-modal-close:hover {
    color: #000;
}

.aysa-modal-body {
    padding: 20px;
    max-height: 60vh;
    overflow-y: auto;
}

.aysa-modal .aysa-form-group {
    margin-bottom: 15px;
}

.aysa-modal .aysa-form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 600;
    color: #333;
}

.aysa-modal .aysa-form-group select, 
.aysa-modal .aysa-form-group textarea, 
.aysa-modal .aysa-form-group input[type="text"] {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    box-sizing: border-box;
}

.aysa-modal .aysa-form-group textarea {
    resize: vertical;
    min-height: 100px;
}

.aysa-modal .aysa-form-actions {
    padding-top: 15px;
    border-top: 1px solid #eee;
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 20px;
}

.aysa-notice {
    padding: 10px 15px;
    margin: 15px 0;
    border-radius: 4px;
    font-size: 14px;
}

.aysa-notice-success {
    background-color: #e8f5e9;
    color: #2e7d32;
    border-left: 4px solid #2e7d32;
}

.aysa-notice-error {
    background-color: #ffebee;
    color: #c62828;
    border-left: 4px solid #c62828;
}

.aysa-notice-warning {
    background-color: #fff3cd;
    color: #856404;
    border-left: 4px solid #ffc107;
}

/* Responsive Adjustments */
@media screen and (max-width: 768px) {
    .aysa-dashboard-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .aysa-dashboard-user {
        flex-wrap: wrap;
    }
    
    .aysa-secret-key-container {
        flex-direction: column;
    }
    
    .aysa-secret-key-container input {
        width: 100%;
    }
    
    .aysa-modal-content {
        width: 95%;
        margin: 2% auto;
    }
}

/* Credit Analytics Styles */
.aysa-credit-analytics {
    background: #ffffff;
    border-radius: 8px;
    padding: 20px;
    margin-top: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aysa-credit-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.aysa-credit-stat {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    border: 1px solid #e9ecef;
}

.aysa-credit-stat h3 {
    margin: 0 0 10px 0;
    font-size: 24px;
    font-weight: 600;
    color: #2563eb;
}

.aysa-credit-stat p {
    margin: 0;
    color: #6c757d;
    font-size: 14px;
}

.aysa-credit-chart {
    margin: 30px 0;
    height: 300px;
}

.aysa-transaction-table {
    margin-top: 30px;
}

.aysa-transaction-table table {
    width: 100%;
    border-collapse: collapse;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aysa-transaction-table th,
.aysa-transaction-table td {
    padding: 12px 15px;
    text-align: left;
    border-bottom: 1px solid #e9ecef;
}

.aysa-transaction-table th {
    background: #f8f9fa;
    font-weight: 600;
    color: #495057;
}

.aysa-transaction-table tr:hover {
    background: #f8f9fa;
}

.badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.badge-success { background: #d1f2eb; color: #0f5132; }
.badge-info { background: #d1ecf1; color: #0c5460; }
.badge-warning { background: #fff3cd; color: #856404; }
.badge-primary { background: #cce7ff; color: #004085; }
.badge-secondary { background: #e2e3e5; color: #383d41; }
.badge-dark { background: #d6d8db; color: #1b1e21; }

.text-success { color: #28a745 !important; }
.text-danger { color: #dc3545 !important; }
.text-primary { color: #007bff !important; }
.text-muted { color: #6c757d !important; }
.font-weight-bold { font-weight: 600 !important; }

</style>

<?php
$current_tab = isset($_GET['tab']) ? sanitize_key((string) $_GET['tab']) : 'general';
$allowed_tabs = array('general', 'authentication', 'api', 'credits', 'notifications', 'advanced');
if (!in_array($current_tab, $allowed_tabs, true)) {
    $current_tab = 'general';
}

$current_api_environment = class_exists('Aysa_API_Config')
    ? (string) Aysa_API_Config::get_environment()
    : 'production';
$current_api_base_url = class_exists('Aysa_API_Config')
    ? (string) Aysa_API_Config::get_api_base_url()
    : (defined('AYSA_API_BASE_URL') ? (string) AYSA_API_BASE_URL : '');
?>
<div class="aysa-dashboard-wrapper">
    <div class="aysa-dashboard-container">
        <!-- Header -->
        <div class="aysa-dashboard-header">
            <div class="aysa-dashboard-title">
                <h1>AYSA Settings</h1>
                <p>Configure your AYSA plugin settings and manage your account</p>
            </div>
            <div class="aysa-dashboard-user">
                <?php
                // Use the credits component from dashboard
                if (class_exists('Aysa_Credits_Component')) {
                    Aysa_Credits_Component::display();
                } else {
                    echo '<div class="aysa-credits-component"><span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span></div>';
                }
                ?>
                <button class="aysa-buy-btn" onclick="window.open('https://aysa.ai/pricing', '_blank')">
                    Buy Credits
                </button>
            </div>
        </div>

        <!-- Tabs Container -->
        <div class="aysa-tabs-container">
            <!-- Tab Navigation -->
            <div class="aysa-tabs-nav">
                <button class="aysa-tab-button <?php echo $current_tab === 'general' ? 'active' : ''; ?>" data-tab="general">
                    <i class="dashicons dashicons-admin-generic"></i>
                    General Settings
                </button>
                <button class="aysa-tab-button <?php echo $current_tab === 'authentication' ? 'active' : ''; ?>" data-tab="authentication">
                    <i class="dashicons dashicons-lock"></i>
                    Authentication
                </button>
                <button class="aysa-tab-button <?php echo $current_tab === 'api' ? 'active' : ''; ?>" data-tab="api">
                    <i class="dashicons dashicons-rest-api"></i>
                    API Configuration
                </button>
                <button class="aysa-tab-button <?php echo $current_tab === 'credits' ? 'active' : ''; ?>" data-tab="credits">
                    <i class="dashicons dashicons-chart-area"></i>
                    Credit Usage
                </button>
                <button class="aysa-tab-button <?php echo $current_tab === 'notifications' ? 'active' : ''; ?>" data-tab="notifications">
                    <i class="dashicons dashicons-bell"></i>
                    Notifications
                </button>
                <button class="aysa-tab-button <?php echo $current_tab === 'advanced' ? 'active' : ''; ?>" data-tab="advanced">
                    <i class="dashicons dashicons-admin-tools"></i>
                    Advanced
                </button>
            </div>

            <!-- Tab Content -->
            <div class="aysa-tabs-content">
                <!-- General Settings Tab -->
                <div id="general" class="aysa-tab-content <?php echo $current_tab === 'general' ? 'active' : ''; ?>">
                    <h2>General Settings</h2>
                    <div class="aysa-panel">
                        <h3 class="aysa-section-title">Plugin Configuration</h3>
                        <p>Configure basic plugin settings and preferences.</p>
                        
                        <div class="aysa-info-box">
                            <h3>Plugin Information</h3>
                            <p><strong>Version:</strong> <?php echo defined('AYSA_VERSION') ? AYSA_VERSION : '1.0.0'; ?></p>
                            <p><strong>Status:</strong> <span style="color: #28a745;">✓ Active</span></p>
                        </div>
                    </div>
                </div>

                <!-- Authentication Tab -->
                <div id="authentication" class="aysa-tab-content <?php echo $current_tab === 'authentication' ? 'active' : ''; ?>">
                    <h2>Authentication</h2>
                    <div class="aysa-panel">
                        <h3 class="aysa-section-title">AYSA Authentication</h3>
                        <p>Manage your AYSA account authentication and API access.</p>
                        
                        <!-- Auth Status Container -->
                        <div id="aysa-auth-status-container" class="aysa-auth-status">
                            <div class="aysa-info-box">
                                <h3>Loading Authentication Status...</h3>
                                <p>Please wait while we check your authentication status.</p>
                            </div>
                        </div>

                        <!-- Secret Key Management -->
                        <div class="aysa-secret-key-display">
                            <h3 class="aysa-section-title">Secret Key Management</h3>
                            <div class="aysa-secret-key-container">
                                <input type="text" id="aysa-secret-key" placeholder="Enter your AYSA secret key" readonly>
                                <button class="aysa-btn-text" onclick="toggleSecretKeyVisibility()">Show/Hide</button>
                                <button class="aysa-btn-text" onclick="copySecretKey()">Copy</button>
                            </div>
                            <div class="aysa-secret-key-actions">
                                <button class="aysa-btn-text" onclick="window.open('admin.php?page=aysa-login', '_self')">Login with Secret Key</button>
                                <button class="aysa-btn-text" onclick="logoutFromDomain()">Logout</button>
                            </div>
                        </div>

                        <!-- Authentication Statistics -->
                        <div id="aysa-auth-stats" class="aysa-auth-stats" style="display: none; margin-top: 20px;">
                            <h3 class="aysa-section-title">Authentication Statistics</h3>
                            <div class="aysa-info-box">
                                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
                                    <div>
                                        <strong>Total Users:</strong> <span id="total-users">0</span>
                                    </div>
                                    <div>
                                        <strong>Total Domains:</strong> <span id="total-domains">0</span>
                                    </div>
                                    <div>
                                        <strong>Recent Activity:</strong> <span id="recent-activity">0</span>
                                    </div>
                                    <div>
                                        <strong>Current Status:</strong> <span id="current-user-status">Active</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- API Configuration Tab -->
                <div id="api" class="aysa-tab-content <?php echo $current_tab === 'api' ? 'active' : ''; ?>">
                    <h2>API Configuration</h2>
                    <div class="aysa-panel">
                        <h3 class="aysa-section-title">Connected Services</h3>
                        <p>AYSA manages secure service connections automatically. This section is informational only.</p>
                        
                        <div class="aysa-info-box">
                            <h3>Current Connection</h3>
                            <p><strong>Environment:</strong> <span id="current-environment"><?php echo esc_html(ucfirst($current_api_environment)); ?></span></p>
                            <p><strong>Base URL:</strong> <span id="current-base-url"><?php echo esc_html($current_api_base_url); ?></span></p>
                            <p><strong>Status:</strong> Managed by AYSA live infrastructure.</p>
                        </div>

                        <div class="aysa-info-box" style="margin-top: 20px;">
                            <h3>Off-Page Marketplace</h3>
                            <p>Marketplace access is handled server-side by AYSA. You do not need to paste API credentials here.</p>
                            <div style="margin-top: 16px; display: grid; gap: 10px; max-width: 720px;">
                                <div style="display:flex; justify-content:space-between; gap:16px; flex-wrap:wrap;">
                                    <span><strong>Connection:</strong> Managed by AYSA</span>
                                    <span><strong>Scope:</strong> Offers, orders, and wallet sync</span>
                                </div>
                                <span id="marketplace-credentials-status" style="color: #475569; font-size: 13px;">If marketplace data stops loading, contact AYSA support instead of changing credentials locally.</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Credit Usage Tab -->
                <div id="credits" class="aysa-tab-content <?php echo $current_tab === 'credits' ? 'active' : ''; ?>">
                    <h2>Credit Usage Analytics</h2>
                    
                    <!-- Credit Statistics -->
                    <div class="aysa-credit-analytics">
                        <div class="aysa-credit-stats">
                            <div class="aysa-credit-stat">
                                <h3 id="current-credits-stat">Loading...</h3>
                                <p>Current Credits</p>
                            </div>
                            <div class="aysa-credit-stat">
                                <h3 id="total-credits-used">Loading...</h3>
                                <p>Total Credits Used</p>
                            </div>
                            <div class="aysa-credit-stat">
                                <h3 id="credits-this-month">Loading...</h3>
                                <p>Credits This Month</p>
                            </div>
                            <div class="aysa-credit-stat">
                                <h3 id="average-daily-usage">Loading...</h3>
                                <p>Average Daily Usage</p>
                            </div>
                        </div>

                        <!-- Credit Breakdown Chart -->
                        <div class="aysa-credit-chart">
                            <h3>Credit Usage Breakdown</h3>
                            <canvas id="credit-breakdown-chart" width="400" height="300"></canvas>
                            <div id="credit-breakdown-legend"></div>
                        </div>

                        <!-- Transaction History -->
                        <div class="aysa-transaction-table aysa-table-responsive">
                            <h3>Transaction History</h3>
                            <table>
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Type</th>
                                        <th>Amount</th>
                                        <th>Balance After</th>
                                    </tr>
                                </thead>
                                <tbody id="transaction-history-tbody">
                                    <tr>
                                        <td colspan="4" class="text-center text-muted">Loading transaction history...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Notifications Tab -->
                <div id="notifications" class="aysa-tab-content <?php echo $current_tab === 'notifications' ? 'active' : ''; ?>">
                    <h2>Notifications</h2>
                    <div class="aysa-panel">
                        <h3 class="aysa-section-title">AYSA Notification Center</h3>
                        <p>Review recent AYSA updates directly from the plugin, including billing, referrals, issue reports and follow-up messages.</p>

                        <div class="aysa-info-box" style="display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap;">
                            <div>
                                <h3 style="margin-bottom:6px;">Unread notifications</h3>
                                <p style="font-size:26px;font-weight:700;color:#b91c1c;margin:0;" id="aysa-plugin-notifications-unread">0</p>
                            </div>
                            <div style="display:flex;gap:10px;flex-wrap:wrap;">
                                <button type="button" class="aysa-btn aysa-btn-secondary" id="aysa-plugin-notifications-refresh">Refresh</button>
                                <button type="button" class="aysa-btn aysa-btn-primary" id="aysa-plugin-notifications-read-all">Mark all as read</button>
                            </div>
                        </div>

                        <div id="aysa-plugin-notifications-status" class="aysa-field-description" style="margin-top:14px;">Notifications will load from your AYSA account.</div>

                        <div id="aysa-plugin-notifications-list" style="margin-top:20px;display:grid;gap:12px;">
                            <div class="aysa-info-box">
                                <p style="margin:0;">Open this tab to load your latest notifications.</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Advanced Tab -->
                <div id="advanced" class="aysa-tab-content <?php echo $current_tab === 'advanced' ? 'active' : ''; ?>">
                    <h2>Advanced Settings</h2>
                    <div class="aysa-panel">
                        <h3 class="aysa-section-title">Plugin Management</h3>
                        <p>Advanced configuration options and plugin management.</p>
                        
                        <div class="aysa-info-box">
                            <h3>Maintenance</h3>
                            <p>Advanced cleanup and uninstall controls are intentionally hidden in client mode.</p>
                        </div>

                        <div class="aysa-uninstall-warning">
                            <p class="aysa-warning-text">
                                If you need to disconnect AYSA, remove project data, or prepare a clean reinstall, contact support first so the website, project mapping, and credits stay aligned.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Plain JavaScript implementation - no jQuery dependency
document.addEventListener('DOMContentLoaded', function() {
    console.log('Settings page initialized with plain JavaScript');
    
    // WordPress admin URL for AJAX
    var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    var aysaAutomationNonce = '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>';
    var aysaNotificationsNonce = '<?php echo wp_create_nonce('aysa_notifications_nonce'); ?>';

    // Tab switching functionality
    function initializeTabs() {
        const tabButtons = document.querySelectorAll('.aysa-tab-button');
        const tabContents = document.querySelectorAll('.aysa-tab-content');
        
        tabButtons.forEach(function(button) {
            button.addEventListener('click', function() {
                const targetTab = this.getAttribute('data-tab');
                
                // Remove active class from all tabs and content
                tabButtons.forEach(btn => btn.classList.remove('active'));
                tabContents.forEach(content => content.classList.remove('active'));
                
                // Add active class to clicked tab and corresponding content
                this.classList.add('active');
                const targetContent = document.getElementById(targetTab);
                if (targetContent) {
                    targetContent.classList.add('active');
                }

                const nextUrl = new URL(window.location.href);
                nextUrl.searchParams.set('tab', targetTab);
                window.history.replaceState({}, '', nextUrl.toString());
                
                // Initialize credit analytics when credit usage tab is shown
                if (targetTab === 'credits' && typeof initCreditAnalytics === 'function') {
                    console.log('Credit Usage tab activated - initializing analytics...');
                    setTimeout(function() {
                        initCreditAnalytics();
                    }, 100);
                }

                if (targetTab === 'notifications') {
                    loadPluginNotifications();
                }
            });
        });
    }

    // Authentication Management Functions
    function loadAuthStatus() {
        if (typeof AysaAPI !== 'undefined') {
            AysaAPI.checkAuthStatus()
                .then(function(authStatus) {
                    displayAuthStatus(authStatus);
                })
                .catch(function(error) {
                    console.error('Failed to load auth status:', error);
                    const container = document.getElementById('aysa-auth-status-container');
                    if (container) {
                        container.innerHTML = '<div class="aysa-error">Failed to load authentication status</div>';
                    }
                });
        }
    }

    function displayAuthStatus(authStatus) {
        const container = document.getElementById('aysa-auth-status-container');
        
        // Check if container exists before trying to set innerHTML
        if (!container) {
            console.warn('Auth status container not found, skipping display');
            return;
        }
        
        if (authStatus.authenticated) {
            container.innerHTML = `
                <div class="aysa-auth-success">
                    <div class="aysa-auth-info">
                        <h4>🔐 Authentication Active</h4>
                        <p><strong>WordPress User ID:</strong> ${authStatus.wp_user_id}</p>
                        <p><strong>Aysa User ID:</strong> ${authStatus.aysa_user_id}</p>
                        <p><strong>Source:</strong> Database (30-day persistence)</p>
                        <p><strong>Domain:</strong> ${authStatus.domain || window.location.hostname}</p>
                        <p><strong>Expires:</strong> ${authStatus.expires_at ? new Date(authStatus.expires_at).toLocaleDateString() : 'Unknown'}</p>
                    </div>
                </div>
            `;
            
            // Update secret key field if available
            const secretKeyField = document.getElementById('aysa-secret-key');
            if (secretKeyField && authStatus.secret_key) {
                secretKeyField.value = authStatus.secret_key;
            }
            
            // Load stats if available
            loadAuthStats();
        } else {
            let errorMessage = '⚠️ Not Authenticated';
            let detailMessage = 'Please log in with your secret key to access Aysa.ai features.';
            
            if (authStatus.source === 'no_wp_user') {
                errorMessage = '❌ WordPress Login Required';
                detailMessage = 'You must be logged into WordPress to use Aysa.ai authentication.';
            }
            
            container.innerHTML = `
                <div class="aysa-auth-warning">
                    <div class="aysa-auth-info">
                        <h4>${errorMessage}</h4>
                        <p>${detailMessage}</p>
                        <p><a href="admin.php?page=aysa-login">Go to Login Page</a></p>
                    </div>
                </div>
            `;
        }
    }

    function loadAuthStats() {
        // Make AJAX call to get authentication stats using fetch
        const formData = new FormData();
        formData.append('action', 'aysa_get_auth_stats');
        formData.append('nonce', typeof aysa_ajax !== 'undefined' ? aysa_ajax.nonce : '');
        
        fetch(typeof aysa_ajax !== 'undefined' ? aysa_ajax.ajax_url : '/wp-admin/admin-ajax.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                // Add null checks for all elements before setting textContent
                const totalUsersElement = document.getElementById('total-users');
                const totalDomainsElement = document.getElementById('total-domains');
                const recentActivityElement = document.getElementById('recent-activity');
                const currentUserStatusElement = document.getElementById('current-user-status');
                const authStatsElement = document.getElementById('aysa-auth-stats');
                
                if (totalUsersElement) {
                    totalUsersElement.textContent = data.data.total_users || '0';
                }
                if (totalDomainsElement) {
                    totalDomainsElement.textContent = data.data.total_domains || '0';
                }
                if (recentActivityElement) {
                    recentActivityElement.textContent = data.data.recent_activity || '0';
                }
                if (currentUserStatusElement) {
                    currentUserStatusElement.textContent = 'Active';
                }
                if (authStatsElement) {
                    authStatsElement.style.display = 'block';
                }
            }
        })
        .catch(error => {
            console.error('Failed to load auth stats:', error);
        });
    }

    // Utility Functions
    function logoutFromDomain() {
        if (confirm('Are you sure you want to logout? You will need to enter your secret key again.')) {
            if (typeof AysaAPI !== 'undefined') {
                AysaAPI.logout()
                    .then(function() {
                        // Refresh the page to show logged out state
                        window.location.reload();
                    })
                    .catch(function(error) {
                        console.error('Logout failed:', error);
                        alert('Logout failed. Please try again.');
                    });
            }
        }
    }

    function toggleSecretKeyVisibility() {
        const secretKeyInput = document.getElementById('aysa-secret-key');
        if (secretKeyInput) {
            if (secretKeyInput.type === 'password') {
                secretKeyInput.type = 'text';
            } else {
                secretKeyInput.type = 'password';
            }
        }
    }

    function copySecretKey() {
        const secretKeyInput = document.getElementById('aysa-secret-key');
        if (secretKeyInput && secretKeyInput.value) {
            secretKeyInput.select();
            secretKeyInput.setSelectionRange(0, 99999); // For mobile devices
            document.execCommand('copy');
            alert('Secret key copied to clipboard!');
        } else {
            alert('No secret key available to copy.');
        }
    }

    // API Environment Configuration
    function initializeApiControls() {
        const marketplaceStatus = document.getElementById('marketplace-credentials-status');
        
        if (marketplaceStatus) {
            marketplaceStatus.textContent = 'Marketplace and API connections are managed by AYSA live infrastructure.';
        }
    }

    // Advanced Settings
    function initializeAdvancedSettings() {
        const saveAdvancedBtn = document.getElementById('save-advanced-settings');
        
        if (saveAdvancedBtn) {
            saveAdvancedBtn.addEventListener('click', function() {
                const deleteData = document.getElementById('aysa-delete-data').checked;
                
                const formData = new FormData();
                formData.append('action', 'aysa_save_settings');
                formData.append('nonce', '<?php echo wp_create_nonce('aysa_settings_nonce'); ?>');
                formData.append('settings[delete_tables_on_uninstall]', deleteData ? '1' : '0');
                
                fetch(ajaxurl, {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Uninstall preference saved successfully.');
                    } else {
                        alert('Error saving uninstall preference: ' + ((data && data.data && data.data.message) ? data.data.message : 'Unknown error'));
                    }
                })
                .catch(error => {
                    alert('Error saving uninstall preference. Please try again.');
                    console.error('Advanced settings save error:', error);
                });
            });
        }
    }

    function escapeHtml(value) {
        return String(value || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function formatNotificationDate(value) {
        if (!value) {
            return '';
        }

        try {
            return new Date(value).toLocaleString();
        } catch (error) {
            return value;
        }
    }

    function renderPluginNotifications(items) {
        const list = document.getElementById('aysa-plugin-notifications-list');
        if (!list) {
            return;
        }

        if (!Array.isArray(items) || items.length === 0) {
            list.innerHTML = `
                <div class="aysa-info-box">
                    <p style="margin:0;">No notifications yet. Your next AYSA updates will appear here.</p>
                </div>
            `;
            return;
        }

        list.innerHTML = items.map(function(item) {
            const isUnread = !item.read_at;
            const actionButton = item.action_url
                ? `<a href="${escapeHtml(item.action_url)}" class="button button-secondary" target="_blank" rel="noopener">Open</a>`
                : '';

            return `
                <div class="aysa-info-box" style="border-left:4px solid ${isUnread ? '#b91c1c' : '#cbd5e1'};">
                    <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:14px;flex-wrap:wrap;">
                        <div style="flex:1;min-width:280px;">
                            <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:6px;">
                                <strong style="font-size:15px;">${escapeHtml(item.title)}</strong>
                                <span style="font-size:12px;padding:4px 8px;border-radius:999px;background:#f1f5f9;color:#334155;text-transform:capitalize;">${escapeHtml(item.category || 'product')}</span>
                                ${isUnread ? '<span style="font-size:12px;padding:4px 8px;border-radius:999px;background:#fee2e2;color:#991b1b;">Unread</span>' : ''}
                            </div>
                            <p style="margin:0 0 8px 0;color:#334155;">${escapeHtml(item.body)}</p>
                            <p style="margin:0;color:#64748b;font-size:12px;">${escapeHtml(formatNotificationDate(item.created_at))}</p>
                        </div>
                        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                            ${actionButton}
                            ${isUnread ? `<button type="button" class="button button-primary aysa-plugin-notification-read-btn" data-id="${escapeHtml(item.id)}">Mark as read</button>` : ''}
                        </div>
                    </div>
                </div>
            `;
        }).join('');

        list.querySelectorAll('.aysa-plugin-notification-read-btn').forEach(function(button) {
            button.addEventListener('click', function() {
                markPluginNotificationRead(this.getAttribute('data-id'));
            });
        });
    }

    function updatePluginNotificationsStatus(message, isError) {
        const status = document.getElementById('aysa-plugin-notifications-status');
        if (!status) {
            return;
        }

        status.textContent = message;
        status.style.color = isError ? '#b91c1c' : '#475569';
    }

    function updatePluginUnreadCount(count) {
        const unread = document.getElementById('aysa-plugin-notifications-unread');
        if (unread) {
            unread.textContent = String(count || 0);
        }
    }

    function loadPluginNotifications() {
        updatePluginNotificationsStatus('Loading notifications...', false);

        const formData = new FormData();
        formData.append('action', 'aysa_notifications_fetch');
        formData.append('nonce', aysaNotificationsNonce);

        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                updatePluginUnreadCount(data.data.unread_count || 0);
                renderPluginNotifications(data.data.notifications || []);
                updatePluginNotificationsStatus('Notifications synced with your AYSA account.', false);
                return;
            }

            renderPluginNotifications([]);
            updatePluginUnreadCount(0);
            updatePluginNotificationsStatus((data && data.data && data.data.message) ? data.data.message : 'Failed to load notifications.', true);
        })
        .catch(error => {
            console.error('Failed to load plugin notifications:', error);
            renderPluginNotifications([]);
            updatePluginUnreadCount(0);
            updatePluginNotificationsStatus('Failed to load notifications.', true);
        });
    }

    function markPluginNotificationRead(notificationId) {
        const formData = new FormData();
        formData.append('action', 'aysa_notifications_mark_read');
        formData.append('nonce', aysaNotificationsNonce);
        formData.append('notification_id', notificationId);

        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updatePluginUnreadCount((data.data && data.data.unread_count) ? data.data.unread_count : 0);
                loadPluginNotifications();
                return;
            }

            updatePluginNotificationsStatus((data && data.data && data.data.message) ? data.data.message : 'Failed to update notification.', true);
        })
        .catch(error => {
            console.error('Failed to mark notification as read:', error);
            updatePluginNotificationsStatus('Failed to update notification.', true);
        });
    }

    function markAllPluginNotificationsRead() {
        const formData = new FormData();
        formData.append('action', 'aysa_notifications_mark_all_read');
        formData.append('nonce', aysaNotificationsNonce);

        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updatePluginUnreadCount(0);
                loadPluginNotifications();
                return;
            }

            updatePluginNotificationsStatus((data && data.data && data.data.message) ? data.data.message : 'Failed to mark all notifications as read.', true);
        })
        .catch(error => {
            console.error('Failed to mark all notifications as read:', error);
            updatePluginNotificationsStatus('Failed to mark all notifications as read.', true);
        });
    }

    // Range Input Updates
    function initializeRangeInputs() {
        const rangeInputs = document.querySelectorAll('.aysa-range');
        rangeInputs.forEach(function(range) {
            const updateDisplay = function() {
                const valueSpan = range.parentNode.querySelector('.aysa-range-value');
                if (valueSpan) {
                    valueSpan.textContent = Math.round(range.value * 100) + '%';
                }
            };
            
            range.addEventListener('input', updateDisplay);
            updateDisplay(); // Set initial value
        });
    }

    // Initialize everything
    function initializeSettingsPage() {
        console.log('Initializing settings page...');
        
        // Initialize tabs
        initializeTabs();
        
        // Initialize API controls
        initializeApiControls();
        
        // Initialize advanced settings
        initializeAdvancedSettings();

        const refreshNotificationsBtn = document.getElementById('aysa-plugin-notifications-refresh');
        if (refreshNotificationsBtn) {
            refreshNotificationsBtn.addEventListener('click', loadPluginNotifications);
        }

        const markAllNotificationsBtn = document.getElementById('aysa-plugin-notifications-read-all');
        if (markAllNotificationsBtn) {
            markAllNotificationsBtn.addEventListener('click', markAllPluginNotificationsRead);
        }
        
        // Initialize range inputs
        initializeRangeInputs();
        
        // Load authentication status
        loadAuthStatus();
        
        // Load credit data
        loadCreditData();
        
        // Initialize credit analytics if credit usage tab is active
        const creditsTab = document.getElementById('credits');
        if (creditsTab && creditsTab.classList.contains('active') && typeof initCreditAnalytics === 'function') {
            console.log('Credit Usage tab is active on page load - initializing analytics...');
            setTimeout(function() {
                initCreditAnalytics();
            }, 500);
        }

        const notificationsTab = document.getElementById('notifications');
        if (notificationsTab && notificationsTab.classList.contains('active')) {
            loadPluginNotifications();
        }
    }

    // Load credit data
    function loadCreditData() {
        console.log('Loading credit data...');
        
        // Load current credits
        loadCurrentCredits();
        
        // Load credit summary
        loadCreditSummary();
        
        // Load transaction history
        loadTransactionHistory();
    }

    // Load current credits
    function loadCurrentCredits() {
        if (typeof aysa_credit_analytics === 'undefined' || !aysa_credit_analytics.nonce || !aysa_credit_analytics.ajax_url) {
            return;
        }
        const formData = new FormData();
        formData.append('action', 'aysa_get_credit_balance');
        formData.append('nonce', aysa_credit_analytics.nonce);
        
        fetch(aysa_credit_analytics.ajax_url, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                const balance = data.data.totalCredits || data.data.currentBalance || 0;
                updateCreditDisplay(balance);
            } else {
                console.error('Failed to load credit balance:', data);
                updateCreditDisplay(0);
            }
        })
        .catch(error => {
            console.error('Error loading credit balance:', error);
            updateCreditDisplay(0);
        });
    }

    // Load credit summary
    function loadCreditSummary() {
        if (typeof aysa_credit_analytics === 'undefined' || !aysa_credit_analytics.nonce || !aysa_credit_analytics.ajax_url) {
            return;
        }
        const formData = new FormData();
        formData.append('action', 'aysa_get_credit_summary');
        formData.append('nonce', aysa_credit_analytics.nonce);
        
        fetch(aysa_credit_analytics.ajax_url, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                const totalUsed = data.data.totalCreditsUsed || data.data.totalSpent || 0;
                const thisMonth = data.data.creditsThisMonth || 0;
                const avgDaily = data.data.averageDailyUsage || 0;
                
                document.getElementById('total-credits-used').textContent = totalUsed;
                document.getElementById('credits-this-month').textContent = thisMonth;
                document.getElementById('average-daily-usage').textContent = avgDaily;
            } else {
                console.error('Failed to load credit summary:', data);
            }
        })
        .catch(error => {
            console.error('Error loading credit summary:', error);
        });
    }

    // Load transaction history with correct balance calculations
    function loadTransactionHistory() {
        if (typeof aysa_credit_analytics === 'undefined' || !aysa_credit_analytics.nonce || !aysa_credit_analytics.ajax_url) {
            return;
        }
        const formData = new FormData();
        formData.append('action', 'aysa_get_credit_history');
        formData.append('nonce', aysa_credit_analytics.nonce);
        
        fetch(aysa_credit_analytics.ajax_url, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            const records = data && data.success && data.data
                ? (Array.isArray(data.data.transactions) ? data.data.transactions : (Array.isArray(data.data.records) ? data.data.records : []))
                : [];
            if (data.success) {
                renderTransactionHistory(records, data.data.currentBalance || 0);
            } else {
                console.error('Failed to load transaction history:', data);
                document.getElementById('transaction-history-tbody').innerHTML = 
                    '<tr><td colspan="4" class="text-center text-muted">No transaction data available</td></tr>';
                // Show "No Credit Data" section when there's an error
                showEmptyChart();
            }
        })
        .catch(error => {
            console.error('Error loading transaction history:', error);
            document.getElementById('transaction-history-tbody').innerHTML = 
                '<tr><td colspan="4" class="text-center text-muted">Error loading transaction history</td></tr>';
            // Show "No Credit Data" section when there's an error
            showEmptyChart();
        });
    }

    // Show empty chart state
    function showEmptyChart() {
        const legendContainer = document.getElementById('credit-breakdown-legend');
        if (legendContainer) {
            legendContainer.innerHTML = `
                <div class="aysa-empty-state">
                    <div class="aysa-empty-state-icon">📊</div>
                    <h5>No Credit Data</h5>
                    <p>No credit breakdown data available.</p>
                </div>
            `;
        }
    }

    // Render transaction history with correct balance calculations
    function renderTransactionHistory(transactions, currentBalance) {
        const tbody = document.getElementById('transaction-history-tbody');
        if (!tbody) return;

        if (!transactions || transactions.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">No transactions found</td></tr>';
            // Show "No Credit Data" section when there are no transactions
            showEmptyChart();
            return;
        }
        
        // Hide "No Credit Data" section when we have transaction data
        const emptyChartElement = document.querySelector('#credit-breakdown-legend .aysa-empty-state');
        if (emptyChartElement) {
            emptyChartElement.style.display = 'none';
        }

        // Sort transactions by date (oldest first for proper balance calculation)
        const sortedTransactions = transactions.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
        
        // Calculate running balance starting from the first transaction
        let runningBalance = currentBalance;
        const transactionsWithBalance = sortedTransactions.map(transaction => {
            const amount = transaction.creditsUsed || 0;
            
            // Add the transaction amount to get the balance after this transaction
            runningBalance = runningBalance + amount;
            
            return {
                ...transaction,
                balanceAfter: runningBalance
            };
        });

        let html = '';
        transactionsWithBalance.forEach(transaction => {
            const date = formatTransactionDate(transaction.createdAt);
            const type = getTransactionTypeDisplay(transaction.category);
            const amount = formatTransactionAmount(transaction.creditsUsed || 0);
            const balanceAfter = transaction.balanceAfter;
            
            html += `
                <tr>
                    <td>${date}</td>
                    <td><span class="badge badge-${getTransactionTypeClass(transaction.category)}">${type}</span></td>
                    <td class="${transaction.creditsUsed < 0 ? 'text-danger' : 'text-success'}">${amount}</td>
                    <td class="text-primary font-weight-bold">${balanceAfter.toLocaleString()}</td>
                </tr>
            `;
        });

        tbody.innerHTML = html;
    }

    // Update credit display
    function updateCreditDisplay(balance) {
        // Update all credit displays
        const creditElements = document.querySelectorAll('#current-credits-stat, .aysa-credits-amount');
        creditElements.forEach(element => {
            if (element) {
                element.textContent = Math.floor(balance);
            }
        });
    }

    // Helper functions for transaction formatting
    function formatTransactionDate(dateString) {
        if (!dateString) return 'Unknown Date';
        try {
            const date = new Date(dateString);
            return date.toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        } catch (error) {
            return 'Invalid Date';
        }
    }

    function formatTransactionAmount(amount) {
        if (amount === 0) return '0';
        return amount > 0 ? `+${amount}` : `${amount}`;
    }

    function getTransactionTypeDisplay(category) {
        const typeMap = {
            'keyword_analysis': 'KEYWORD ANALYSIS',
            'keyword_management': 'KEYWORD MANAGEMENT',
            'domain_authority': 'DOMAIN AUTHORITY',
            'competitor_analysis': 'COMPETITOR ANALYSIS',
            'credit_purchase': 'CREDIT PURCHASE',
            'credit_refund': 'CREDIT REFUND',
            'api_usage': 'API USAGE'
        };
        return typeMap[category] || category.toUpperCase().replace(/_/g, ' ');
    }

    function getTransactionTypeClass(category) {
        const classMap = {
            'keyword_analysis': 'primary',
            'keyword_management': 'secondary',
            'domain_authority': 'info',
            'competitor_analysis': 'warning',
            'credit_purchase': 'success',
            'credit_refund': 'success',
            'api_usage': 'dark'
        };
        return classMap[category] || 'secondary';
    }

    // Make functions globally available for onclick handlers
    window.logoutFromDomain = logoutFromDomain;
    window.toggleSecretKeyVisibility = toggleSecretKeyVisibility;
    window.copySecretKey = copySecretKey;

    // Start initialization
    initializeSettingsPage();
});
</script>
