<?php

/**

 * Enterprise Dashboard Template for SensFRX

 *

 * Store owner friendly dashboard with enterprise look and feel

 * Uses sensfrx.ai brand colors and accessibility best practices

 */



if (!defined('ABSPATH')) {

    die('Direct access not permitted');

}



// Get property credentials

$options = get_option('sensfrx_options', SensFRX::default_options());

$property_id = isset($options['sensfrx_property_id']) ? $options['sensfrx_property_id'] : '';



// Check if we should show demo data

$show_demo = SensFRX_Demo_Data::should_show_demo_data();

$demo_stats = $show_demo ? SensFRX_Demo_Data::get_demo_stats() : null;

$demo_cases = $show_demo ? SensFRX_Demo_Data::get_demo_fraud_cases(3) : array();



// Get current tab

$current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'dashboard';

?>



<div class="sensfrx-enterprise-wrapper">

    <!-- Navigation Tabs -->

    <nav class="sensfrx-nav-tabs">

        <a href="?page=sensfrx_fpwoo&tab=dashboard" class="sensfrx-nav-tab <?php echo $current_tab === 'dashboard' ? 'active' : ''; ?>">

            Dashboard

        </a>

        <a href="?page=sensfrx_fpwoo&tab=validation-rules" class="sensfrx-nav-tab <?php echo $current_tab === 'validation-rules' ? 'active' : ''; ?>">

            Validation Rules

        </a>

        <a href="?page=sensfrx_fpwoo&tab=fraud" class="sensfrx-nav-tab <?php echo $current_tab === 'fraud' ? 'active' : ''; ?>">

            Fraud Intelligence

        </a>

        <a href="?page=sensfrx_fpwoo&tab=settings" class="sensfrx-nav-tab <?php echo $current_tab === 'settings' ? 'active' : ''; ?>">

            Settings

        </a>

        <a href="?page=sensfrx_fpwoo&tab=fraud-protection" class="sensfrx-nav-tab <?php echo $current_tab === 'fraud-protection' ? 'active' : ''; ?>">

            Fraud Protection

        </a>

        <a href="?page=sensfrx_fpwoo&tab=activity" class="sensfrx-nav-tab <?php echo $current_tab === 'activity' ? 'active' : ''; ?>">

            Activity Logs

        </a>

        <a href="?page=sensfrx_fpwoo&tab=review" class="sensfrx-nav-tab sensfrx-nav-tab-highlight <?php echo $current_tab === 'review' ? 'active' : ''; ?>">

            Fraud Review

            <span class="sensfrx-nav-badge">0</span>

        </a>

        <?php /* COMMENTED OUT - Email Customization UI - Will add partial customization later

        <a href="?page=sensfrx_fpwoo&tab=email-notifications" class="sensfrx-nav-tab <?php echo $current_tab === 'email-notifications' ? 'active' : ''; ?>">

            Email Notifications

        </a>

        */ ?>

    </nav>



    <div class="sensfrx-enterprise-dashboard">

        <!-- Dashboard Header -->

        <div class="sensfrx-dashboard-header">

        <div class="sensfrx-header-content">

            <h1 class="sensfrx-dashboard-title">Store Protection Overview</h1>

            <p class="sensfrx-dashboard-subtitle">See how we're protecting your business from fraud</p>

        </div>



        <div class="sensfrx-header-actions">

            <div class="sensfrx-time-filter">

                <label for="time-range">Time Period:</label>

                <select id="time-range" class="sensfrx-select">

                    <!-- <option value="today">Today</option>

                    <option value="7days" selected>Last 7 Days</option>

                    <option value="30days">Last 30 Days</option>

                    <option value="90days">Last 90 Days</option> -->

                </select>

            </div>

        </div>

    </div>



    <!-- Demo Data Banner -->

    <?php if ($show_demo): ?>

    <div id="demo-banner" style="background: linear-gradient(135deg, #EFF6FF 0%, #DBEAFE 100%); border-left: 4px solid #3B82F6; padding: 14px 20px; border-radius: 8px; margin: 20px 0; display: flex; align-items: center; gap: 12px; box-shadow: 0 2px 8px rgba(59, 130, 246, 0.15);">

        <!-- Preview Icon -->

        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" style="flex-shrink: 0;">

            <path d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" fill="#3B82F6"/>

            <path d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

        </svg>

        <div style="flex: 1;">

            <div style="font-size: 14px; font-weight: 700; color: #1E40AF; margin-bottom: 2px;">Preview Mode - Sample Data</div>

            <div style="font-size: 12px; color: #1E3A8A;">This is how your dashboard will look once you have transaction data. Real data will replace this automatically.</div>

        </div>

        <button onclick="disableDemoMode()" style="background: white; border: 2px solid #3B82F6; color: #3B82F6; padding: 8px 16px; border-radius: 6px; font-size: 12px; font-weight: 600; cursor: pointer; white-space: nowrap; transition: all 0.2s;" onmouseover="this.style.background='#3B82F6'; this.style.color='white'" onmouseout="this.style.background='white'; this.style.color='#3B82F6'">

            Exit Preview Mode

        </button>

    </div>

    <?php endif; ?>



    <!-- Custom Modal for Demo Mode Confirmation -->

    <div id="demo-mode-modal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.6); z-index: 99999; align-items: center; justify-content: center; backdrop-filter: blur(4px);">

        <div style="background: white; border-radius: 16px; max-width: 480px; width: 90%; margin: 20px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3); animation: modalSlideIn 0.3s ease-out; position: relative;">

            <!-- Header with Icon -->

            <div style="padding: 32px 32px 24px; text-align: center; border-bottom: 1px solid #E5E7EB;">

                <div style="width: 64px; height: 64px; margin: 0 auto 16px; background: linear-gradient(135deg, #DBEAFE 0%, #BFDBFE 100%); border-radius: 16px; display: flex; align-items: center; justify-content: center;">

                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none">

                        <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                </div>

                <h3 style="margin: 0 0 8px; font-size: 20px; font-weight: 700; color: #111827;">Switch to Real Data?</h3>

                <p style="margin: 0; font-size: 14px; color: #6B7280; line-height: 1.6;">This will hide the sample data and show your actual transaction metrics. You can re-enable preview mode anytime from Settings.</p>

            </div>



            <!-- Body with Details -->

            <div style="padding: 24px 32px;">

                <div style="background: #F9FAFB; border-radius: 8px; padding: 16px; margin-bottom: 20px;">

                    <div style="display: flex; align-items: start; gap: 12px; margin-bottom: 12px;">

                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" style="flex-shrink: 0; margin-top: 2px;">

                            <path d="M10 0C4.5 0 0 4.5 0 10s4.5 10 10 10 10-4.5 10-10S15.5 0 10 0zm1 15H9v-2h2v2zm0-4H9V5h2v6z" fill="#3B82F6"/>

                        </svg>

                        <div style="flex: 1;">

                            <div style="font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 4px;">What happens next:</div>

                            <ul style="margin: 0; padding-left: 18px; font-size: 13px; color: #6B7280; line-height: 1.8;">

                                <li>Sample data will be hidden</li>

                                <li>Real transaction metrics will appear</li>

                                <li>Empty states shown if no data yet</li>

                            </ul>

                        </div>

                    </div>

                </div>

            </div>



            <!-- Footer with Actions -->

            <div style="padding: 20px 32px 32px; display: flex; gap: 12px; justify-content: flex-end;">

                <button onclick="closeDemoModal()" style="padding: 12px 24px; background: white; border: 2px solid #E5E7EB; color: #6B7280; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.borderColor='#D1D5DB'; this.style.background='#F9FAFB'" onmouseout="this.style.borderColor='#E5E7EB'; this.style.background='white'">

                    Cancel

                </button>

                <button onclick="confirmDisableDemo()" style="padding: 12px 24px; background: linear-gradient(135deg, #3B82F6 0%, #1E40AF 100%); border: none; color: white; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3); transition: all 0.2s;" onmouseover="this.style.transform='translateY(-1px)'; this.style.boxShadow='0 4px 12px rgba(59, 130, 246, 0.4)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(59, 130, 246, 0.3)'">

                    Switch to Real Data →

                </button>

            </div>

        </div>

    </div>



    <style>

    @keyframes modalSlideIn {

        from {

            opacity: 0;

            transform: translateY(-20px) scale(0.95);

        }

        to {

            opacity: 1;

            transform: translateY(0) scale(1);

        }

    }

    </style>



    <!-- Getting Started Sidebar (shown for new users) -->

    <?php

    $getting_started_dismissed = get_option('sensfrx_getting_started_dismissed', false);

    $checklist_items = get_option('sensfrx_checklist_items', [

        'connect_api' => false,

        'review_protections' => false,

        'configure_rules' => false,

        'test_order' => false,

        'review_fraud_case' => false

    ]);



    // Calculate completion percentage

    $completed_count = count(array_filter($checklist_items));

    $total_count = count($checklist_items);

    $completion_percentage = $total_count > 0 ? round(($completed_count / $total_count) * 100) : 0;



    if (!$getting_started_dismissed):

    ?>

    <!-- Chat Widget Toggle Button (floating, bottom-right) -->

    <button id="getting-started-toggle" onclick="toggleGettingStarted()" style="position: fixed; right: 24px; bottom: 24px; z-index: 9999; background: linear-gradient(135deg, #3B82F6 0%, #1E40AF 100%); color: white; border: none; border-radius: 50%; width: 56px; height: 56px; cursor: pointer; box-shadow: 0 4px 16px rgba(59, 130, 246, 0.5); display: flex; align-items: center; justify-content: center; transition: all 0.3s;" onmouseover="this.style.transform='scale(1.1)'; this.style.boxShadow='0 6px 20px rgba(59, 130, 246, 0.6)'" onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 4px 16px rgba(59, 130, 246, 0.5)'">

        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

            <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>

        </svg>

    </button>



    <!-- Chat Widget Panel (right side, compact) -->

    <div id="getting-started-sidebar" style="position: fixed; right: 24px; bottom: 90px; width: 360px; max-height: 600px; background: white; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.15); z-index: 9998; overflow: hidden; display: none;">

        <!-- Compact Header -->

        <div style="background: linear-gradient(135deg, #3B82F6 0%, #1E40AF 100%); padding: 16px; display: flex; justify-content: space-between; align-items: center;">

            <div style="flex: 1;">

                <h2 style="margin: 0; font-size: 16px; font-weight: 700; color: white;">Getting Started</h2>

                <div style="display: flex; align-items: center; gap: 8px; margin-top: 8px;">

                    <div style="flex: 1; background: rgba(255,255,255,0.2); height: 4px; border-radius: 2px; overflow: hidden;">

                        <div id="checklist-progress-bar" style="background: white; height: 100%; width: <?php echo esc_attr( $completion_percentage ); ?>%; transition: width 0.3s ease;"></div>

                    </div>

                    <span id="checklist-percentage" style="font-size: 11px; font-weight: 700; color: white; min-width: 30px;"><?php echo esc_html( $completion_percentage ); ?>%</span>

                </div>

            </div>



            <button onclick="toggleGettingStarted()" style="background: rgba(255,255,255,0.1); border: none; color: white; cursor: pointer; padding: 6px; border-radius: 4px; margin-left: 12px; transition: background 0.2s; flex-shrink: 0;" onmouseover="this.style.background='rgba(255,255,255,0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'">

                <svg width="16" height="16" viewBox="0 0 20 20" fill="none">

                    <path d="M15 5L5 15M5 5l10 10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>

                </svg>

            </button>

        </div>



        <!-- Scrollable Content -->

        <div style="max-height: 500px; overflow-y: auto; padding: 16px;">



        <!-- Checklist Items -->

        <div style="display: grid; gap: 12px;">

            <!-- Item 1: Connect API -->

            <div class="checklist-item" style="background: #F9FAFB; border-left: 3px solid <?php echo $checklist_items['connect_api'] ? '#10B981' : '#3B82F6'; ?>; border-radius: 6px; padding: 12px; transition: all 0.2s;">

                <label style="display: flex; align-items: start; gap: 10px; cursor: pointer;">

                    <input type="checkbox"

                           class="checklist-checkbox"

                           data-item="connect_api"

                           <?php echo $checklist_items['connect_api'] ? 'checked' : ''; ?>

                           style="width: 18px; height: 18px; margin-top: 1px; cursor: pointer; accent-color: #3B82F6;">

                    <div style="flex: 1;">

                        <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 4px;">

                            <h4 style="margin: 0; font-size: 13px; font-weight: 600; color: #111827;">Connect Your Store</h4>

                            <span style="background: #DBEAFE; color: #1E40AF; padding: 1px 6px; border-radius: 8px; font-size: 9px; font-weight: 700;">REQUIRED</span>

                        </div>

                        <p style="margin: 0 0 6px; font-size: 12px; color: #6B7280; line-height: 1.4;">Enter API credentials in Settings</p>

                        <a href="?page=sensfrx_fpwoo&tab=settings" style="display: inline-flex; align-items: center; gap: 3px; color: #3B82F6; text-decoration: none; font-size: 11px; font-weight: 600;">

                            Go to Settings →

                        </a>

                    </div>

                </label>

            </div>



            <!-- Item 2: Review Protection Settings -->

            <div class="checklist-item" style="background: #F9FAFB; border-left: 3px solid <?php echo $checklist_items['review_protections'] ? '#10B981' : '#E5E7EB'; ?>; border-radius: 6px; padding: 12px; transition: all 0.2s;">

                <label style="display: flex; align-items: start; gap: 10px; cursor: pointer;">

                    <input type="checkbox"

                           class="checklist-checkbox"

                           data-item="review_protections"

                           <?php echo $checklist_items['review_protections'] ? 'checked' : ''; ?>

                           style="width: 18px; height: 18px; margin-top: 1px; cursor: pointer; accent-color: #3B82F6;">

                    <div style="flex: 1;">

                        <h4 style="margin: 0 0 4px; font-size: 13px; font-weight: 600; color: #111827;">Review Smart Protection Policies</h4>

                        <p style="margin: 0; font-size: 12px; color: #6B7280; line-height: 1.4;">Configure automatic fraud detection rules to block suspicious orders in real-time</p>

                        <a href="?page=sensfrx_fpwoo&tab=validation-rules" style="display: inline-flex; align-items: center; gap: 4px; color: #3B82F6; text-decoration: none; font-size: 13px; font-weight: 600; margin-top: 6px;">

                            View Validation Rules

                            <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">

                                <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"/>

                            </svg>

                        </a>

                    </div>

                </label>

            </div>



            <!-- Item 3: Configure Custom Rules -->

            <div class="checklist-item" style="background: #F9FAFB; border-left: 3px solid <?php echo $checklist_items['configure_rules'] ? '#10B981' : '#E5E7EB'; ?>; border-radius: 6px; padding: 12px; transition: all 0.2s;">

                <label style="display: flex; align-items: start; gap: 10px; cursor: pointer;">

                    <input type="checkbox"

                           class="checklist-checkbox"

                           data-item="configure_rules"

                           <?php echo $checklist_items['configure_rules'] ? 'checked' : ''; ?>

                           style="width: 18px; height: 18px; margin-top: 1px; cursor: pointer; accent-color: #3B82F6;">

                    <div style="flex: 1;">

                        <h4 style="margin: 0 0 4px; font-size: 13px; font-weight: 600; color: #111827;">Set Up Custom Blocking Rules</h4>

                        <p style="margin: 0; font-size: 12px; color: #6B7280; line-height: 1.4;">Define specific conditions to block high-risk transactions based on your business needs</p>

                        <a href="?page=sensfrx_fpwoo&tab=validation-rules" style="display: inline-flex; align-items: center; gap: 4px; color: #3B82F6; text-decoration: none; font-size: 13px; font-weight: 600; margin-top: 6px;">

                            Configure Rules

                            <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">

                                <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"/>

                            </svg>

                        </a>

                    </div>

                </label>

            </div>



            <!-- Item 4: Test with Sample Order -->

            <div class="checklist-item" style="background: #F9FAFB; border-left: 3px solid <?php echo $checklist_items['test_order'] ? '#10B981' : '#E5E7EB'; ?>; border-radius: 6px; padding: 12px; transition: all 0.2s;">

                <label style="display: flex; align-items: start; gap: 10px; cursor: pointer;">

                    <input type="checkbox"

                           class="checklist-checkbox"

                           data-item="test_order"

                           <?php echo $checklist_items['test_order'] ? 'checked' : ''; ?>

                           style="width: 18px; height: 18px; margin-top: 1px; cursor: pointer; accent-color: #3B82F6;">

                    <div style="flex: 1;">

                        <h4 style="margin: 0 0 4px; font-size: 13px; font-weight: 600; color: #111827;">Process a Test Order</h4>

                        <p style="margin: 0; font-size: 12px; color: #6B7280; line-height: 1.4;">Create a test transaction to verify fraud detection is working correctly for your store</p>

                    </div>

                </label>

            </div>



            <!-- Item 5: Review Your First Fraud Case -->

            <div class="checklist-item" style="background: #F9FAFB; border-left: 3px solid <?php echo $checklist_items['review_fraud_case'] ? '#10B981' : '#E5E7EB'; ?>; border-radius: 6px; padding: 12px; transition: all 0.2s;">

                <label style="display: flex; align-items: start; gap: 10px; cursor: pointer;">

                    <input type="checkbox"

                           class="checklist-checkbox"

                           data-item="review_fraud_case"

                           <?php echo $checklist_items['review_fraud_case'] ? 'checked' : ''; ?>

                           style="width: 18px; height: 18px; margin-top: 1px; cursor: pointer; accent-color: #3B82F6;">

                    <div style="flex: 1;">

                        <h4 style="margin: 0 0 4px; font-size: 13px; font-weight: 600; color: #111827;">Review Flagged Transactions</h4>

                        <p style="margin: 0; font-size: 12px; color: #6B7280; line-height: 1.4;">Learn how to review suspicious orders and take action to approve or block them</p>

                        <a href="?page=sensfrx_fpwoo&tab=review" style="display: inline-flex; align-items: center; gap: 4px; color: #3B82F6; text-decoration: none; font-size: 13px; font-weight: 600; margin-top: 6px;">

                            Go to Fraud Review

                            <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">

                                <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"/>

                            </svg>

                        </a>

                    </div>

                </label>

            </div>

        </div>



        <!-- Help Footer -->

        <div style="margin-top: 20px; padding-top: 16px; border-top: 1px solid #E5E7EB;">

            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 12px;">

                <svg width="20" height="20" viewBox="0 0 20 20" fill="none">

                    <circle cx="10" cy="10" r="9" stroke="#3B82F6" stroke-width="2"/>

                    <path d="M10 6V10M10 14H10.01" stroke="#3B82F6" stroke-width="2" stroke-linecap="round"/>

                </svg>

                <p style="margin: 0; font-size: 12px; color: #6B7280; line-height: 1.4;">

                    Need help? Visit our <a href="https://docs.sensfrx.ai" target="_blank" style="color: #3B82F6; text-decoration: none; font-weight: 600;">documentation</a> or email <a href="mailto:support@sensfrx.ai" style="color: #3B82F6; text-decoration: none; font-weight: 600;">support@sensfrx.ai</a>

                </p>

            </div>

            <a href="https://discord.gg/sensfrx" target="_blank" style="display: inline-flex; align-items: center; gap: 8px; background: #5865F2; color: white; padding: 10px 16px; border-radius: 6px; text-decoration: none; font-size: 13px; font-weight: 600; transition: background 0.2s;" onmouseover="this.style.background='#4752C4'" onmouseout="this.style.background='#5865F2'">

                <svg width="20" height="20" viewBox="0 0 24 24" fill="white">

                    <path d="M19.27 5.33C17.94 4.71 16.5 4.26 15 4a.09.09 0 0 0-.07.03c-.18.33-.39.76-.53 1.09a16.09 16.09 0 0 0-4.8 0c-.14-.34-.35-.76-.54-1.09c-.01-.02-.04-.03-.07-.03c-1.5.26-2.93.71-4.27 1.33c-.01 0-.02.01-.03.02c-2.72 4.07-3.47 8.03-3.1 11.95c0 .02.01.04.03.05c1.8 1.32 3.53 2.12 5.24 2.65c.03.01.06 0 .07-.02c.4-.55.76-1.13 1.07-1.74c.02-.04 0-.08-.04-.09c-.57-.22-1.11-.48-1.64-.78c-.04-.02-.04-.08-.01-.11c.11-.08.22-.17.33-.25c.02-.02.05-.02.07-.01c3.44 1.57 7.15 1.57 10.55 0c.02-.01.05-.01.07.01c.11.09.22.17.33.26c.04.03.04.09-.01.11c-.52.31-1.07.56-1.64.78c-.04.01-.05.06-.04.09c.32.61.68 1.19 1.07 1.74c.03.01.06.02.09.01c1.72-.53 3.45-1.33 5.25-2.65c.02-.01.03-.03.03-.05c.44-4.53-.73-8.46-3.1-11.95c-.01-.01-.02-.02-.04-.02zM8.52 14.91c-1.03 0-1.89-.95-1.89-2.12s.84-2.12 1.89-2.12c1.06 0 1.9.96 1.89 2.12c0 1.17-.84 2.12-1.89 2.12zm6.97 0c-1.03 0-1.89-.95-1.89-2.12s.84-2.12 1.89-2.12c1.06 0 1.9.96 1.89 2.12c0 1.17-.83 2.12-1.89 2.12z"/>

                </svg>

                Join Discord for Support

            </a>



            <!-- Dismiss Button -->

            <button onclick="dismissGettingStarted()" style="width: 100%; margin-top: 16px; padding: 12px; background: #F3F4F6; color: #6B7280; border: none; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#E5E7EB'" onmouseout="this.style.background='#F3F4F6'">

                Dismiss Guide

            </button>

        </div>

        </div> <!-- Close sidebar content -->

    </div> <!-- Close sidebar panel -->

    <?php endif; ?>



    <!-- Critical Order Widgets -->

    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 24px; margin-bottom: 32px;">



        <!-- Widget 1: Revenue Protected -->

        <div style="background: linear-gradient(135deg, #3B82F6 0%, #1E40AF 100%); border-radius: 12px; padding: 28px; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3); position: relative; overflow: hidden;">

            <!-- Background Pattern -->

            <div style="position: absolute; top: 0; right: 0; opacity: 0.1;">

                <svg width="200" height="200" viewBox="0 0 200 200">

                    <circle cx="150" cy="50" r="80" fill="white"/>

                    <circle cx="180" cy="150" r="60" fill="white"/>

                </svg>

            </div>



            <div style="position: relative; z-index: 1;">

                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">

                    <div style="width: 48px; height: 48px; background: rgba(255,255,255,0.2); border-radius: 12px; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(10px);">

                        <svg width="28" height="28" viewBox="0 0 24 24" fill="none">

                            <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                        </svg>

                    </div>

                    <div>

                        <div style="color: rgba(255,255,255,0.9); font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">Revenue Protected</div>

                        <div id="revenue-protected-period" style="color: rgba(255,255,255,0.7); font-size: 11px; margin-top: 2px;">Last 7 Days</div>

                    </div>

                </div>



                <div style="margin-bottom: 12px;">

                    <div id="revenue-protected-amount" style="font-size: 42px; font-weight: 800; color: white; line-height: 1; margin-bottom: 8px;">

                        <span class="sensfrx-loading-spinner" style="width: 24px; height: 24px; border: 3px solid rgba(255,255,255,0.3); border-top-color: white;"></span>

                    </div>

                    <div id="revenue-protected-trend" style="color: rgba(255,255,255,0.9); font-size: 14px; font-weight: 600;"></div>

                </div>



                <div style="background: rgba(255,255,255,0.15); backdrop-filter: blur(10px); padding: 12px 16px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.2);">

                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">

                        <span style="color: rgba(255,255,255,0.9); font-size: 12px; font-weight: 600;">Blocked Fraudulent Orders</span>

                        <span id="blocked-orders-count" style="color: white; font-size: 16px; font-weight: 700;">-</span>

                    </div>

                    <div style="display: flex; justify-content: space-between; align-items: center;">

                        <span style="color: rgba(255,255,255,0.9); font-size: 12px; font-weight: 600;">Chargebacks Prevented</span>

                        <span id="chargebacks-prevented" style="color: white; font-size: 16px; font-weight: 700;">-</span>

                    </div>

                </div>

            </div>

        </div>



        <!-- Widget 2: Orders Needing Review -->

        <div id="pending-orders-widget" style="background: white; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); border: 2px solid #E5E7EB; overflow: hidden;">

            <!-- Header -->

            <div id="pending-orders-header" style="background: #F9FAFB; padding: 20px 24px; border-bottom: 1px solid #E5E7EB;">

                <div style="display: flex; justify-content: space-between; align-items: center;">

                    <div style="display: flex; align-items: center; gap: 12px;">

                        <div id="pending-orders-icon" style="width: 40px; height: 40px; background: #6B7280; border-radius: 10px; display: flex; align-items: center; justify-content: center;">

                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                            </svg>

                        </div>

                        <div>

                            <h3 id="pending-orders-title" style="margin: 0; font-size: 18px; font-weight: 700; color: #374151;">Review Queue</h3>

                            <p id="pending-orders-subtitle" style="margin: 4px 0 0; font-size: 13px; color: #6B7280;">No orders need your attention</p>

                        </div>

                    </div>

                    <div style="text-align: right;">

                        <div id="pending-orders-value" style="font-size: 24px; font-weight: 800; color: #6B7280; line-height: 1;">-</div>

                        <div style="font-size: 11px; color: #6B7280; font-weight: 600; margin-top: 4px;">PENDING VALUE</div>

                    </div>

                </div>

            </div>



            <!-- Orders List -->

            <div id="pending-orders-list" style="padding: 16px 24px; max-height: 400px; overflow-y: auto;">

                <div style="text-align: center; padding: 40px 20px; color: #9CA3AF;">

                    <div class="sensfrx-loading-spinner" style="margin: 0 auto 16px;"></div>

                    <p style="margin: 0; font-size: 14px;">Loading pending orders...</p>

                </div>

            </div>

        </div>

    </div>



    <!-- Key Metrics Grid -->

    <div class="sensfrx-metrics-grid">

        <!-- Total Logins -->

        <div class="sensfrx-metric-card">

            <div class="sensfrx-metric-icon sensfrx-icon-login">

                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">

                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z" fill="currentColor"/>

                </svg>

            </div>

            <div class="sensfrx-metric-content">

                <div class="sensfrx-metric-label">Customer Logins</div>

                <div class="sensfrx-metric-value" id="metric-logins">

                    <span class="sensfrx-loading-spinner"></span>

                </div>

                <div class="sensfrx-metric-change" id="metric-logins-change"></div>

            </div>

        </div>



        <!-- Total Transactions -->

        <div class="sensfrx-metric-card">

            <div class="sensfrx-metric-icon sensfrx-icon-transaction">

                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">

                    <path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z" fill="currentColor"/>

                </svg>

            </div>

            <div class="sensfrx-metric-content">

                <div class="sensfrx-metric-label">Orders Protected</div>

                <div class="sensfrx-metric-value" id="metric-transactions">

                    <span class="sensfrx-loading-spinner"></span>

                </div>

                <div class="sensfrx-metric-change" id="metric-transactions-change"></div>

            </div>

        </div>



        <!-- New Registrations -->

        <div class="sensfrx-metric-card">

            <div class="sensfrx-metric-icon sensfrx-icon-registration">

                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">

                    <path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"/>

                </svg>

            </div>

            <div class="sensfrx-metric-content">

                <div class="sensfrx-metric-label">New Customer Signups</div>

                <div class="sensfrx-metric-value" id="metric-registrations">

                    <span class="sensfrx-loading-spinner"></span>

                </div>

                <div class="sensfrx-metric-change" id="metric-registrations-change"></div>

            </div>

        </div>



        <!-- Bot Activity -->

        <div class="sensfrx-metric-card">

            <div class="sensfrx-metric-icon sensfrx-icon-bot">

                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">

                    <path d="M20 9V7c0-1.1-.9-2-2-2h-3c0-1.66-1.34-3-3-3S9 3.34 9 5H6c-1.1 0-2 .9-2 2v2c-1.66 0-3 1.34-3 3s1.34 3 3 3v4c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-4c1.66 0 3-1.34 3-3s-1.34-3-3-3zM9 13c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm3-8c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm3 8c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" fill="currentColor"/>

                </svg>

            </div>

            <div class="sensfrx-metric-content">

                <div class="sensfrx-metric-label">Suspicious Activity Stopped</div>

                <div class="sensfrx-metric-value" id="metric-bots">

                    <span class="sensfrx-loading-spinner"></span>

                </div>

                <div class="sensfrx-metric-change" id="metric-bots-change"></div>

            </div>

        </div>

    </div>



    <!-- Main Content Grid -->

    <div class="sensfrx-content-grid">

        <!-- Your Protection Plan (LEFT) -->

        <div class="sensfrx-card sensfrx-plan-card">

            <div class="sensfrx-card-header">

                <h2 class="sensfrx-card-title">Your Protection Plan</h2>

            </div>

            <div class="sensfrx-card-body">

                <div class="sensfrx-plan-info">

                    <div class="sensfrx-plan-badge">

                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none">

                            <path d="M10 0L12 7H20L14 12L16 20L10 15L4 20L6 12L0 7H8L10 0Z" fill="#f59e0b"/>

                        </svg>

                        <span id="plan-name">Loading...</span>

                    </div>



                    <!-- API Error Display -->

                    <div id="api-error-message" style="display: none; padding: 16px; background: #fee2e2; border-left: 4px solid #ef4444; border-radius: 8px; margin-top: 16px;">

                        <h4 style="margin: 0 0 8px; font-size: 14px; font-weight: 600; color: #991b1b;">

                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style="display: inline-block; vertical-align: middle; margin-right: 4px;">

                                <path d="M8 0L0 8L8 16L16 8L8 0Z" fill="#ef4444"/>

                                <path d="M7 4H9V9H7V4Z M7 11H9V13H7V11Z" fill="white"/>

                            </svg>

                            <span id="error-title">Connection Issue</span>

                        </h4>

                        <p id="error-description" style="margin: 0 0 12px; font-size: 13px; color: #7f1d1d; line-height: 1.5;"></p>

                        <div id="error-solution" style="padding: 12px; background: white; border-radius: 4px;">

                            <strong style="font-size: 13px; color: #991b1b;">How to fix:</strong>

                            <ol id="error-steps" style="margin: 8px 0 0; padding-left: 20px; font-size: 13px; color: #7f1d1d;"></ol>

                        </div>

                        <a href="https://sensfrx.ai/support" target="_blank" style="display: inline-block; margin-top: 12px; padding: 8px 16px; background: #ef4444; color: white; text-decoration: none; border-radius: 4px; font-size: 13px; font-weight: 500;">

                            Contact Support

                        </a>

                    </div>



                    <!-- Credit Usage Section (hidden for FREE users) -->

                    <div class="sensfrx-credit-usage" id="credit-usage-section">

                        <div class="sensfrx-usage-header">

                            <span class="sensfrx-usage-label">Monthly Credits</span>

                            <span class="sensfrx-usage-value"><span id="credits-used">0</span> / <span id="credits-total">500</span></span>

                        </div>

                        <div class="sensfrx-progress-bar">

                            <div class="sensfrx-progress-fill" id="credits-progress" style="width: 0%"></div>

                        </div>

                        <p class="sensfrx-usage-note">You have <strong><span id="credits-remaining">500</span> credits</strong> remaining this month</p>

                    </div>



                    <!-- FREE User Credit Usage (shown for FREE users) -->

                    <div class="sensfrx-free-usage" id="free-credit-usage" style="display: none;">

                        <div class="sensfrx-usage-header">

                            <span class="sensfrx-usage-label">Free Credits Used</span>

                            <span class="sensfrx-usage-value"><span id="free-credits-used">0</span> / <span id="free-credits-total">100</span></span>

                        </div>

                        <div class="sensfrx-progress-bar">

                            <div class="sensfrx-progress-fill" id="free-credits-progress" style="width: 0%"></div>

                        </div>

                        <p class="sensfrx-usage-note" style="margin-bottom: 16px;">You have <strong><span id="free-credits-remaining">100</span> free credits</strong> remaining</p>



                        <!-- Upgrade prompt -->

                        <div style="padding: 16px; background: #fef3c7; border-radius: 8px; margin-bottom: 16px;">

                            <h3 style="margin: 0 0 8px; font-size: 16px; color: #92400e;">Unlock Premium Protection</h3>

                            <p style="margin: 0; font-size: 14px; color: #78350f; line-height: 1.5;">

                                Get advanced fraud detection, unlimited checks, and priority support.

                            </p>

                        </div>

                        <div style="display: flex; flex-direction: column; gap: 8px; font-size: 14px;">

                            <div style="display: flex; align-items: center; gap: 8px;">

                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                                    <path d="M8 0L10 5L16 6L12 10L13 16L8 13L3 16L4 10L0 6L6 5L8 0Z" fill="#10b981"/>

                                </svg>

                                <span>Unlimited fraud checks per month</span>

                            </div>

                            <div style="display: flex; align-items: center; gap: 8px;">

                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                                    <path d="M8 0L10 5L16 6L12 10L13 16L8 13L3 16L4 10L0 6L6 5L8 0Z" fill="#10b981"/>

                                </svg>

                                <span>Advanced risk scoring & analytics</span>

                            </div>

                            <div style="display: flex; align-items: center; gap: 8px;">

                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                                    <path d="M8 0L10 5L16 6L12 10L13 16L8 13L3 16L4 10L0 6L6 5L8 0Z" fill="#10b981"/>

                                </svg>

                                <span>Priority email support</span>

                            </div>

                        </div>

                    </div>



                    <!-- Plan Details Section -->

                    <div class="sensfrx-plan-details" id="plan-details-section" style="margin-top: 24px; padding: 16px; background: #f9fafb; border-radius: 8px; display: none;">

                        <h3 style="margin: 0 0 12px; font-size: 14px; font-weight: 600; color: #374151;">Plan Details</h3>



                        <!-- Plan Dates -->

                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px;">

                            <div>

                                <div style="font-size: 12px; color: #6b7280; margin-bottom: 4px;">Start Date</div>

                                <div style="font-size: 14px; font-weight: 500; color: #111827;" id="plan-start-date">-</div>

                            </div>

                            <div>

                                <div style="font-size: 12px; color: #6b7280; margin-bottom: 4px;">Renewal Date</div>

                                <div style="font-size: 14px; font-weight: 500; color: #111827;" id="plan-renewal-date">-</div>

                            </div>

                            <div>

                                <div style="font-size: 12px; color: #6b7280; margin-bottom: 4px;">Expiration Date</div>

                                <div style="font-size: 14px; font-weight: 500; color: #111827;" id="plan-exp-date">-</div>

                            </div>

                            <div>

                                <div style="font-size: 12px; color: #6b7280; margin-bottom: 4px;">Users Allowed</div>

                                <div style="font-size: 14px; font-weight: 500; color: #111827;" id="plan-users">-</div>

                            </div>

                        </div>



                        <!-- Plan Limits with Upgrade Hints -->

                        <div style="border-top: 1px solid #e5e7eb; padding-top: 12px;">

                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">

                                <div style="font-size: 12px; font-weight: 600; color: #374151;">Current Limits</div>

                                <div id="upgrade-hint-free" style="display: none; font-size: 11px; color: #059669; font-weight: 500; cursor: pointer;" onclick="document.getElementById('upgrade-btn').click()">

                                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" style="display: inline-block; vertical-align: middle; margin-right: 2px;">

                                        <path d="M6 0L7.5 4L12 4.5L9 7.5L9.75 12L6 9.75L2.25 12L3 7.5L0 4.5L4.5 4L6 0Z" fill="#059669"/>

                                    </svg>

                                    Remove limits

                                </div>

                            </div>

                            <div style="display: flex; flex-direction: column; gap: 8px; font-size: 13px;">

                                <!-- Data Visibility -->

                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px; background: white; border: 1px solid #e5e7eb; border-radius: 6px;">

                                    <div style="display: flex; align-items: center; gap: 8px;">

                                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="limit-icon-free" style="display: none;">

                                            <rect x="2" y="6" width="12" height="8" rx="1" fill="#d1d5db"/>

                                            <circle cx="8" cy="10" r="1.5" fill="#6b7280"/>

                                            <path d="M6 6V4C6 2.9 6.9 2 8 2C9.1 2 10 2.9 10 4V6" stroke="#6b7280" stroke-width="1.5"/>

                                        </svg>

                                        <span style="color: #6b7280;">Data Visibility</span>

                                    </div>

                                    <span style="color: #111827; font-weight: 600; font-size: 14px;" id="plan-visibility">-</span>

                                </div>



                                <!-- Data Retention -->

                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px; background: white; border: 1px solid #e5e7eb; border-radius: 6px;">

                                    <div style="display: flex; align-items: center; gap: 8px;">

                                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="limit-icon-free" style="display: none;">

                                            <rect x="2" y="6" width="12" height="8" rx="1" fill="#d1d5db"/>

                                            <circle cx="8" cy="10" r="1.5" fill="#6b7280"/>

                                            <path d="M6 6V4C6 2.9 6.9 2 8 2C9.1 2 10 2.9 10 4V6" stroke="#6b7280" stroke-width="1.5"/>

                                        </svg>

                                        <span style="color: #6b7280;">Data Retention</span>

                                    </div>

                                    <span style="color: #111827; font-weight: 600; font-size: 14px;" id="plan-retention">-</span>

                                </div>



                                <!-- Custom Validation -->

                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px; background: white; border: 1px solid #e5e7eb; border-radius: 6px;">

                                    <div style="display: flex; align-items: center; gap: 8px;">

                                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="limit-icon-free" style="display: none;">

                                            <rect x="2" y="6" width="12" height="8" rx="1" fill="#d1d5db"/>

                                            <circle cx="8" cy="10" r="1.5" fill="#6b7280"/>

                                            <path d="M6 6V4C6 2.9 6.9 2 8 2C9.1 2 10 2.9 10 4V6" stroke="#6b7280" stroke-width="1.5"/>

                                        </svg>

                                        <span style="color: #6b7280;">Custom Rules</span>

                                    </div>

                                    <span style="color: #111827; font-weight: 600; font-size: 14px;" id="plan-custom-validation">-</span>

                                </div>



                                <!-- Blacklist/Whitelist -->

                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px; background: white; border: 1px solid #e5e7eb; border-radius: 6px;">

                                    <div style="display: flex; align-items: center; gap: 8px;">

                                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="limit-icon-free" style="display: none;">

                                            <rect x="2" y="6" width="12" height="8" rx="1" fill="#d1d5db"/>

                                            <circle cx="8" cy="10" r="1.5" fill="#6b7280"/>

                                            <path d="M6 6V4C6 2.9 6.9 2 8 2C9.1 2 10 2.9 10 4V6" stroke="#6b7280" stroke-width="1.5"/>

                                        </svg>

                                        <span style="color: #6b7280;">Block/Allow Lists</span>

                                    </div>

                                    <span style="color: #111827; font-weight: 600; font-size: 14px;" id="plan-blacklist-limit">-</span>

                                </div>

                            </div>



                            <!-- Upgrade Teaser for FREE users -->

                            <div id="limits-upgrade-teaser" style="display: none; margin-top: 12px; padding: 10px; background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%); border-radius: 6px; border: 1px solid #10b981;">

                                <div style="display: flex; align-items: start; gap: 8px;">

                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style="flex-shrink: 0; margin-top: 2px;">

                                        <path d="M8 0L10 5L16 6L12 10L13 16L8 13L3 16L4 10L0 6L6 5L8 0Z" fill="#059669"/>

                                    </svg>

                                    <div style="flex: 1;">

                                        <div style="font-size: 12px; font-weight: 600; color: #065f46; margin-bottom: 4px;">Unlock More with Pro</div>

                                        <div style="font-size: 11px; color: #047857; line-height: 1.4;">

                                            <strong>See deeper insights</strong>, keep your data longer, create custom fraud rules, and build comprehensive blocklists to stop sophisticated attacks

                                        </div>

                                    </div>

                                </div>

                            </div>

                        </div>

                    </div>



                    <!-- Action Buttons -->

                    <div class="sensfrx-quick-actions">

                        <a href="?page=sensfrx_fpwoo&tab=settings" class="sensfrx-btn sensfrx-btn-secondary" id="view-usage-btn">View Usage Details</a>

                        <a href="https://client.sensfrx.ai/account/upgrade-plan" target="_blank" class="sensfrx-btn sensfrx-btn-primary" id="upgrade-btn">Upgrade Plan</a>

                    </div>

                </div>

            </div>

        </div>



        <!-- Right Column Container (Fraud Score + Activity) -->

        <div class="sensfrx-right-column">

            <!-- Fraud Risk Score (RIGHT) -->

            <div class="sensfrx-card sensfrx-fraudometer-card">

            <div class="sensfrx-card-header">

                <h2 class="sensfrx-card-title">Fraud Risk Score</h2>

                <span class="sensfrx-info-badge" title="Your overall fraud risk based on recent activity">?</span>

            </div>

            <div class="sensfrx-card-body">

                <div class="sensfrx-fraudometer">

                    <div class="sensfrx-gauge-container">

                        <svg class="sensfrx-gauge" viewBox="0 0 200 110">

                            <defs>

                                <linearGradient id="gaugeGradient" x1="0%" y1="0%" x2="100%" y2="0%">

                                    <stop offset="0%" style="stop-color:#10b981;stop-opacity:1" />

                                    <stop offset="50%" style="stop-color:#f59e0b;stop-opacity:1" />

                                    <stop offset="100%" style="stop-color:#ef4444;stop-opacity:1" />

                                </linearGradient>

                            </defs>

                            <path id="gaugeTrack" d="M 20 100 A 80 80 0 0 1 180 100"

                                  stroke="#e5e7eb" stroke-width="12" fill="none" stroke-linecap="round"/>

                            <path id="gaugeProgress" d="M 20 100 A 80 80 0 0 1 180 100"

                                  stroke="url(#gaugeGradient)" stroke-width="12" fill="none"

                                  stroke-linecap="round" stroke-dasharray="251.2" stroke-dashoffset="188.4"/>

                            <circle id="gaugeIndicator" cx="50" cy="75" r="6" fill="#0066cc"/>

                        </svg>

                        <div class="sensfrx-gauge-score">

                            <span class="sensfrx-score-value" id="fraud-score"><span class="sensfrx-loading-spinner"></span></span>

                            <span class="sensfrx-score-label">out of 100</span>

                        </div>

                    </div>

                    <div class="sensfrx-risk-legend">

                        <div class="sensfrx-legend-item">

                            <span class="sensfrx-legend-dot sensfrx-risk-low"></span>

                            <span>Low Risk (0-33)</span>

                        </div>

                        <div class="sensfrx-legend-item">

                            <span class="sensfrx-legend-dot sensfrx-risk-medium"></span>

                            <span>Medium Risk (34-66)</span>

                        </div>

                        <div class="sensfrx-legend-item">

                            <span class="sensfrx-legend-dot sensfrx-risk-high"></span>

                            <span>High Risk (67-100)</span>

                        </div>

                    </div>

                    <div class="sensfrx-risk-status">

                        <div class="sensfrx-status-badge sensfrx-status-low">

                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                                <path d="M8 0L10.4 5.6L16 8L10.4 10.4L8 16L5.6 10.4L0 8L5.6 5.6L8 0Z" fill="currentColor"/>

                            </svg>

                            Your store is well protected

                        </div>

                    </div>

                </div>

            </div>

        </div>



        <!-- Recent Suspicious Activity (moved below Fraud Risk Score) -->

        <div class="sensfrx-card sensfrx-activity-card">

            <div class="sensfrx-card-header">

                <h2 class="sensfrx-card-title">Recent Suspicious Activity</h2>

                <a href="?page=sensfrx_fpwoo&tab=fraud" class="sensfrx-link-view-all">View All Cases →</a>

            </div>

            <div class="sensfrx-card-body">

                <div id="recent-fraud-cases">

                    <!-- Empty state -->

                    <div class="sensfrx-empty-state" style="display: none;">

                        <svg width="64" height="64" viewBox="0 0 64 64" fill="none" class="sensfrx-empty-icon">

                            <path d="M32 4C16.536 4 4 16.536 4 32s12.536 28 28 28 28-12.536 28-28S47.464 4 32 4zm0 52c-13.234 0-24-10.766-24-24S18.766 8 32 8s24 10.766 24 24-10.766 24-24 24z" fill="#d1d5db"/>

                            <path d="M32 16c-8.837 0-16 7.163-16 16s7.163 16 16 16 16-7.163 16-16-7.163-16-16-16zm0 28c-6.627 0-12-5.373-12-12s5.373-12 12-12 12 5.373 12 12-5.373 12-12 12z" fill="#d1d5db"/>

                            <circle cx="32" cy="32" r="4" fill="#d1d5db"/>

                        </svg>

                        <h3 class="sensfrx-empty-title">Great News! No Suspicious Activity</h3>

                        <p class="sensfrx-empty-description">Your store is secure. We're monitoring all activity and will alert you if we detect anything unusual.</p>

                        <div class="sensfrx-empty-actions">

                            <a href="?page=sensfrx_fpwoo&tab=settings" class="sensfrx-btn sensfrx-btn-secondary">Review Protection Settings</a>

                        </div>

                    </div>



                    <!-- Example of populated state (hidden by default, shown when data exists) -->

                    <div class="sensfrx-fraud-list" style="display: none;">

                       

                    </div>

                </div>

            </div>

        </div>



        </div><!-- End .sensfrx-right-column -->



    </div>



    <!-- Footer removed as requested -->

    </div>

</div>



<script>

// Demo data from PHP

const showDemoData = <?php echo $show_demo ? 'true' : 'false'; ?>;

const demoStats = <?php echo $show_demo ? json_encode($demo_stats) : 'null'; ?>;

const demoCases = <?php echo $show_demo ? json_encode($demo_cases) : '[]'; ?>;



// Load real dashboard data from SensFRX API

document.addEventListener('DOMContentLoaded', function() {

    const restUrl = '<?php echo esc_url(rest_url('sensfrx-fraud-prevention-for-woocommerce/')); ?>';

    const nonce = '<?php echo esc_js( wp_create_nonce('wp_rest') ); ?>';



    // Get time period from dropdown

    const timeRange = document.getElementById('time-range');

    const selectedPeriod = timeRange ? timeRange.value : '7days';



    // Load demo data first if enabled

    if (showDemoData) {

        loadDemoData();

    }



    // Always fetch license/plan info (this is real data, not demo)

    // This also handles setting placeholders if NOT in demo mode

    fetchDashboardData(restUrl, nonce, selectedPeriod);



    // Load critical order widgets (only if NOT in demo mode)

    if (!showDemoData) {

        loadRevenueProtected(restUrl, nonce);

        loadPendingOrders(restUrl, nonce);

    }



    // Update data when time period changes

    if (timeRange) {

        timeRange.addEventListener('change', function() {

            const selectedPeriod = timeRange ? timeRange.value : '7days';

            fetchDashboardData(restUrl, nonce, selectedPeriod);

            loadRevenueProtected(restUrl, nonce);

        });

    }



    // Initialize Getting Started checklist

    initializeChecklist(restUrl, nonce);



    // Refresh pending orders every 30 seconds

    setInterval(function() {

        loadPendingOrders(restUrl, nonce);

    }, 30000);

});



const PLAN_DAYS = {

    "7": ["any"],  // always show

    "15": ["Pro", "Growth", "Business", "Enterprise", 

           "Lifetime Access to Tier 1", 

           "Lifetime Access to Tier 2", 

           "Lifetime Access to Tier 3"],

    "30": ["Growth", "Business", "Enterprise", 

           "Lifetime Access to Tier 2", 

           "Lifetime Access to Tier 3"],

    "60": ["Business", "Enterprise", "Lifetime Access to Tier 3"],

    "120": ["Enterprise"]

};





function renderTimeFilterOptions(plan) {

    const $ = jQuery;

    const select = $('#time-range');

    select.empty();



    // Always available

    select.append(`<option value="today">Today</option>`);

    select.append(`<option value="7days">Last 7 Days</option>`);



    const rules = {

        "15days": ["Pro", "Growth", "Business", "Enterprise",

            "Lifetime Access to Tier 1", 

            "Lifetime Access to Tier 2", 

            "Lifetime Access to Tier 3"

        ],

        "30days": ["Growth", "Business", "Enterprise",

            "Lifetime Access to Tier 2", 

            "Lifetime Access to Tier 3"

        ],

        "60days": ["Business", "Enterprise",

            "Lifetime Access to Tier 3"

        ],

        "120days": ["Enterprise"]

    };



    for (const value in rules) {

        if (rules[value].includes(plan)) {

            const label = `Last ${value.replace('days', '')} Days`;

            select.append(`<option value="${value}">${label}</option>`);

        }

    }



    // Default

    // select.val("7days");

    const currentValue = select.data('current') || '7days';

    select.val(currentValue);



}





function fetchDashboardData(restUrl, nonce, selectedPeriod) {



    // Fetch license info for plan details

    fetch(restUrl + 'get_license_info', {

        method: 'GET',

        headers: {

            'X-WP-Nonce': nonce,

            'Content-Type': 'application/json'

        }

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success' && data.data) {

            updatePlanInfo(data.data);

            const timeRange = document.getElementById('time-range');

            if (timeRange) {

                jQuery('#time-range').data('current', timeRange.value);

            }

            renderTimeFilterOptions(data.data.plan);

            loadRevenueProtected(restUrl, nonce);

            const periodLabel = selectedPeriod === '7days' ? 'Last 7 Days' :

                               selectedPeriod === '15days' ? 'Last 15 Days' :

                               selectedPeriod === '30days' ? 'Last 30 Days' :

                               selectedPeriod === '60days' ? 'Last 60 Days' :

                               selectedPeriod === '90days' ? 'Last 90 Days' : 

                               selectedPeriod === '120days' ? 'Last 120 Days' : 'Today';



            const headerLabel = document.getElementById('revenue-protected-period');

            if (headerLabel) {

                headerLabel.textContent = periodLabel;

            }

            hideApiError();

        } else {

            showApiError(data);

        }

    })

    .catch(error => {



        showApiError({

            status: 'error',

            message: 'Network error',

            error: error.message

        });

    });



    // Fetch review count for fraud review badge

    fetch(restUrl + 'get_sensfrx_review_count', {

        method: 'GET',

        headers: {

            'X-WP-Nonce': nonce,

            'Content-Type': 'application/json'

        }

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success') {

            const badge = document.querySelector('.sensfrx-nav-badge');

            if (badge) {

                badge.textContent = data.reviewCount || 0;

            }

        }

    })

    .catch(error => console.error('Error fetching review count:', error));



    // NOTE: get_fraud_stats endpoint removed - metrics now set to placeholder values if no demo

    // Set fraud risk score to 0 (placeholder)

    if (!showDemoData) {

        // Stats 

        fetch(restUrl + 'get_sensfrx_stats?selectedPeriod='+ encodeURIComponent(selectedPeriod), {

            method: 'GET',

            headers: {

                'X-WP-Nonce': nonce,

                'Content-Type': 'application/json'

            }

        })

        .then(response => response.json())

        .then(data => {

            if (data.status === 'success') {

                // Extract response arrays

                const ato = data.atoArray || {};

                const trans = data.transArray || {};

                const reg = data.regArray || {};

                const bot = data.botArray || {};



                // Helper: format trending value

                function formatTrend(changeValue) {

                    if (changeValue > 0) {

                        return `<span class="sensfrx-trend-up">+${changeValue}%</span>`;

                    }

                    if (changeValue < 0) {

                        return `<span class="sensfrx-trend-down">${changeValue}%</span>`;

                    }

                    return `<span class="sensfrx-trend-neutral">0%</span>`;

                }



                // =======================

                // ATO / Logins

                // =======================

                document.getElementById('metric-logins').innerHTML =

                    `<strong>${ato.t_count ?? '-'}</strong>`;



                document.getElementById('metric-logins-change').innerHTML =

                    formatTrend(ato.t_change);



                // =======================

                // Transactions

                // =======================

                document.getElementById('metric-transactions').innerHTML =

                    `<strong>${trans.t_count ?? '-'}</strong>`;



                document.getElementById('metric-transactions-change').innerHTML =

                    formatTrend(trans.t_change);



                // =======================

                // Registrations

                // =======================

                document.getElementById('metric-registrations').innerHTML =

                    `<strong>${reg.t_count ?? '-'}</strong>`;



                document.getElementById('metric-registrations-change').innerHTML =

                    formatTrend(reg.t_change);



                // =======================

                // Bots

                // =======================

                document.getElementById('metric-bots').innerHTML =

                    `<strong>${bot.t_count ?? '-'}</strong>`;



                document.getElementById('metric-bots-change').innerHTML =

                    formatTrend(bot.t_change);



            } else {

                showApiError({

                    status: 'error',

                    message: 'API error',

                    error: data.message

                });

            }

        })

        .catch(error => {

            // updateFraudScore(0);

            showApiError({

                status: 'error',

                message: 'Network error',

                error: error.message

            });

        });



        // Fraud Risk Score

        fetch(restUrl + 'get_fraud_rate', {

            method: 'GET',

            headers: {

                'X-WP-Nonce': nonce,

                'Content-Type': 'application/json'

            }

        })

        .then(response => response.json())

        .then(data => {

            if (data.status === 'success') {

                updateFraudScore(data.data.fraud_rate);

            } else {

                updateFraudScore(0);

                showApiError({

                    status: 'error',

                    message: 'API error',

                    error: data.message

                });

            }

        })

        .catch(error => {

            updateFraudScore(0);

            showApiError({

                status: 'error',

                message: 'Network error',

                error: error.message

            });

        });



        // Recent Alert 

        fetch(restUrl + 'get_sensfrx_recent_activity_options', {

            method: 'GET',

            headers: {

                'X-WP-Nonce': nonce,

                'Content-Type': 'application/json'

            }

        })

        .then(response => response.json())

        .then(data => {

            if (data.status === 'success') {

                const alerts = data.sensfrx_recent_activity || [];

                const recentAlertsLength = alerts.length;

                if (recentAlertsLength > 0) {

                    document.querySelector('.sensfrx-empty-state').style.display = 'none';

                    document.querySelector('.sensfrx-fraud-list').style.display = 'block';



                    // 🔥 Clear old rows

                    const fraudList = document.querySelector(".sensfrx-fraud-list");

                    fraudList.innerHTML = "";



                    alerts.slice(0, 5).forEach(alert => {

                        let { uID: uid, ue, un, et, events } = alert;



                        // Clean event list

                        let eventArray = events

                            .split(",")

                            .map(e => e.trim())

                            .filter(e => e !== "" && !e.includes("Change in ,"));

                        events = eventArray.join(", ");



                        // Format datetime

                        let dateObject = new Date(et);

                        let day = dateObject.getDate();

                        let month = dateObject.toLocaleString('default', { month: 'short' });

                        let year = dateObject.getFullYear();



                        let hours = dateObject.getHours();

                        let minutes = dateObject.getMinutes();

                        let ampm = hours >= 12 ? 'pm' : 'am';



                        hours = hours % 12 || 12;

                        minutes = minutes < 10 ? '0' + minutes : minutes;



                        let formattedDateTime = `${day} ${month} ${year}, ${hours}:${minutes} ${ampm}`;



                        let registerDiv = document.createElement("div");

                        registerDiv.innerHTML = `

                            <div class="sensfrx-fraud-item">

                                <div class="sensfrx-fraud-icon sensfrx-risk-high-bg">!</div>

                                <div class="sensfrx-fraud-content">

                                    <div class="sensfrx-fraud-title">${events}</div>

                                    <div class="sensfrx-fraud-meta">Email: ${ue} • ${formattedDateTime}</div>

                                </div>

                                <div class="sensfrx-fraud-action">

                                    <span class="sensfrx-badge sensfrx-badge-danger">Blocked</span>

                                </div>

                            </div>

                        `;



                        document.querySelector(".sensfrx-fraud-list").appendChild(registerDiv);

                    });



                } else {

                    document.querySelector('.sensfrx-empty-state').style.display = 'block';

                    document.querySelector('.sensfrx-fraud-list').style.display = 'none';

                }

            } else {

                showApiError({

                    status: 'error',

                    message: 'API error',

                    error: data.message

                });

            }

        })

        .catch(error => {

            showApiError({

                status: 'error',

                message: 'Network error',

                error: error.message

            });

        });



    }

}



// Add subtle DEMO watermark to a card

function addDemoWatermark(cardSelector) {

    const card = document.querySelector(cardSelector);

    if (card && !card.querySelector('.demo-watermark')) {

        // Check if card already has position relative/absolute

        const position = window.getComputedStyle(card).position;

        if (position === 'static') {

            card.style.position = 'relative';

        }



        const watermark = document.createElement('div');

        watermark.className = 'demo-watermark';

        watermark.innerHTML = 'DEMO';

        watermark.style.cssText = `

            position: absolute;

            top: 8px;

            right: 8px;

            background: rgba(59, 130, 246, 0.08);

            color: rgba(59, 130, 246, 0.4);

            font-size: 9px;

            font-weight: 700;

            letter-spacing: 0.5px;

            padding: 3px 8px;

            border-radius: 4px;

            pointer-events: none;

            user-select: none;

            z-index: 1;

        `;

        card.appendChild(watermark);

    }

}



// Load demo data into dashboard

function loadDemoData() {



    if (!demoStats) {

        console.error('No demo stats available');

        return;

    }



    // Add DEMO watermarks to cards showing demo data

    const metricCards = document.querySelectorAll('.sensfrx-metric-card');

    metricCards.forEach(card => {

        if (card && !card.querySelector('.demo-watermark')) {

            const position = window.getComputedStyle(card).position;

            if (position === 'static') {

                card.style.position = 'relative';

            }

            const watermark = document.createElement('div');

            watermark.className = 'demo-watermark';

            watermark.innerHTML = 'DEMO';

            watermark.style.cssText = `

                position: absolute;

                top: 12px;

                right: 12px;

                background: rgba(59, 130, 246, 0.08);

                color: rgba(59, 130, 246, 0.4);

                font-size: 9px;

                font-weight: 700;

                letter-spacing: 0.5px;

                padding: 3px 8px;

                border-radius: 4px;

                pointer-events: none;

                user-select: none;

                z-index: 1;

            `;

            card.appendChild(watermark);

        }

    });



    // Update metrics with demo data



    const loginElement = document.getElementById('metric-logins');

    const loginChangeElement = document.getElementById('metric-logins-change');



    if (loginElement) {

        loginElement.innerHTML = '<strong>' + demoStats.total_logins.current + '</strong>';

    }

    if (loginChangeElement) {

        loginChangeElement.innerHTML = '<span class="sensfrx-trend-up">' + demoStats.total_logins.change + '</span> vs last month';

    }



    const txElement = document.getElementById('metric-transactions');

    const txChangeElement = document.getElementById('metric-transactions-change');



    if (txElement) {

        txElement.innerHTML = '<strong>' + demoStats.total_transactions.current + '</strong>';

    }

    if (txChangeElement) {

        txChangeElement.innerHTML = '<span class="sensfrx-trend-up">' + demoStats.total_transactions.change + '</span> vs last month';

    }



    const regElement = document.getElementById('metric-registrations');

    const regChangeElement = document.getElementById('metric-registrations-change');



    if (regElement) {

        regElement.innerHTML = '<strong>' + demoStats.total_registrations.current + '</strong>';

    }

    if (regChangeElement) {

        regChangeElement.innerHTML = '<span class="sensfrx-trend-up">' + demoStats.total_registrations.change + '</span> vs last month';

    }



    const botsElement = document.getElementById('metric-bots');

    const botsChangeElement = document.getElementById('metric-bots-change');



    if (botsElement) {

        botsElement.innerHTML = '<strong>' + demoStats.suspicious_activity.current + '</strong>';

    }

    if (botsChangeElement) {

        botsChangeElement.innerHTML = '<span class="sensfrx-trend-down">' + demoStats.suspicious_activity.change + '</span> vs last month';

    }



    // Update fraud score

    updateFraudScore(demoStats.risk_score.average);



    // Update Revenue Protected widget

    const revenueElement = document.getElementById('revenue-protected-amount');

    const blockedOrdersElement = document.getElementById('blocked-orders-count');

    const chargebacksElement = document.getElementById('chargebacks-prevented');

    const revenueTrendElement = document.getElementById('revenue-protected-trend');



    if (revenueElement) {

        revenueElement.innerHTML = '<span style="font-size: 32px; font-weight: 800;">' + demoStats.fraud_prevented.amount + '</span>';

    }

    if (blockedOrdersElement) {

        blockedOrdersElement.textContent = demoStats.fraud_prevented.count;

    }

    if (chargebacksElement) {

        chargebacksElement.textContent = demoStats.fraud_prevented.count;

    }

    if (revenueTrendElement) {

        revenueTrendElement.textContent = 'Last 7 Days';

    }



    // Add DEMO watermark to Revenue Protected widget

    addDemoWatermark('.sensfrx-revenue-card');



    // Add DEMO watermark to Fraud Risk Score card

    addDemoWatermark('.sensfrx-fraud-score-card');



    // Update Review Queue with demo cases

    if (demoCases && demoCases.length > 0) {

        const pendingContainer = document.querySelector('.sensfrx-pending-orders');

        if (pendingContainer) {

            let casesHTML = '';

            demoCases.forEach(function(fraudCase) {

                const riskColor = fraudCase.risk_level === 'high' ? '#ef4444' :

                                 fraudCase.risk_level === 'medium' ? '#f59e0b' : '#10b981';



                casesHTML += `

                    <div style="padding: 16px; border-bottom: 1px solid rgba(255,255,255,0.1); transition: background 0.2s; cursor: pointer;" onmouseover="this.style.background='rgba(255,255,255,0.05)'" onmouseout="this.style.background='transparent'">

                        <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 8px;">

                            <div>

                                <div style="font-size: 14px; font-weight: 600; color: white; margin-bottom: 4px;">${fraudCase.customer}</div>

                                <div style="font-size: 12px; color: rgba(255,255,255,0.7);">${fraudCase.email}</div>

                            </div>

                            <div style="text-align: right;">

                                <div style="font-size: 16px; font-weight: 700; color: white;">${fraudCase.amount}</div>

                                <div style="font-size: 11px; color: rgba(255,255,255,0.6);">${fraudCase.time}</div>

                            </div>

                        </div>

                        <div style="display: flex; align-items: center; gap: 12px; margin-top: 12px;">

                            <div style="background: ${riskColor}; color: white; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 700; text-transform: uppercase;">

                                Score: ${fraudCase.risk_score}

                            </div>

                            <div style="font-size: 12px; color: rgba(255,255,255,0.8);">${fraudCase.reason}</div>

                        </div>

                    </div>

                `;

            });

            pendingContainer.innerHTML = casesHTML;

        }



        // Add DEMO watermark to Review Queue widget

        addDemoWatermark('.sensfrx-pending-card');

    }



}



function updateFraudScore(score) {

    const scoreElement = document.getElementById('fraud-score');

    const gaugeProgress = document.getElementById('gaugeProgress');

    const gaugeIndicator = document.getElementById('gaugeIndicator');



    if (scoreElement) {

        scoreElement.textContent = Math.round(score);

    }



    // Update gauge visualization

    if (gaugeProgress && gaugeIndicator) {

        // Gauge is a semi-circle from 0-100

        // Arc path: M 20 100 A 80 80 0 0 1 180 100

        // This creates a semi-circle from left (180°) to right (0°)

        const percentage = score / 100;

        const dashOffset = 251.2 - (251.2 * percentage);

        gaugeProgress.style.strokeDashoffset = dashOffset;



        // Move indicator dot along the arc

        // The arc starts at 180° (left) and goes to 0° (right)

        // So angle should be: 180° - (percentage * 180°)

        const angle = 180 - (180 * percentage); // Start from left (180°) and move right

        const radians = (angle * Math.PI) / 180; // Convert to radians

        const centerX = 100;

        const centerY = 100;

        const radius = 80;



        // Calculate position on arc

        // For angle=180° (0% score): x=20, y=100 (left side)

        // For angle=0° (100% score): x=180, y=100 (right side)

        const indicatorX = centerX + radius * Math.cos(radians);

        const indicatorY = centerY - radius * Math.sin(radians); // Negative because SVG Y increases downward



        gaugeIndicator.setAttribute('cx', indicatorX);

        gaugeIndicator.setAttribute('cy', indicatorY);

    }

}



function showApiError(errorData) {

    const errorBox = document.getElementById('api-error-message');

    const errorTitle = document.getElementById('error-title');

    const errorDescription = document.getElementById('error-description');

    const errorSteps = document.getElementById('error-steps');



    // Hide plan sections when showing error

    const creditUsageSection = document.getElementById('credit-usage-section');

    const freeCreditUsage = document.getElementById('free-credit-usage');

    if (creditUsageSection) creditUsageSection.style.display = 'none';

    if (freeCreditUsage) freeCreditUsage.style.display = 'none';



    // Determine error type and provide specific guidance

    let title = 'Connection Issue';

    let description = '';

    let steps = [];



    const message = errorData.message || errorData.error || 'Unknown error';

    const details = errorData.details || '';

    

    if (message.toLowerCase().includes('not configured')) {

        title = 'Store Not Connected';

        description = 'Your SensFRX credentials have not been configured yet.';

        steps = [

            'Go to <a href="?page=sensfrx_fpwoo&tab=settings">Settings</a>',

            'Get your credentials from <a href="https://status.sensfrx.com" target="_blank">SensFRX Dashboard</a>',

            'Add your Property ID and Property Secret',

            'Save and this dashboard will automatically connect'

        ];

    } else if (message.toLowerCase().includes('unknown domain')) {

        title = 'Domain Not Registered';

        description = 'Your WordPress domain is not registered with SensFRX yet. This is a quick one-time setup.';

        steps = [

            'Go to your SensFRX dashboard at <a href="https://status.sensfrx.com" target="_blank">status.sensfrx.com</a>',

            'Navigate to Settings → Domains',

            'Add this domain: <strong>' + window.location.hostname + '</strong>',

            'Save and refresh this page'

        ];

    } else if (message.toLowerCase().includes('not authorized') || message.toLowerCase().includes('unauthorized') || message.toLowerCase().includes('invalid property') || message.toLowerCase().includes('invalid secret')) {

        title = 'Invalid Credentials';

        description = message + (details ? ' ' + details : '');

        steps = [

            'Go to <a href="?page=sensfrx_fpwoo&tab=settings">Settings</a>',

            'Verify your Property ID and Property Secret are correct',

            'Get correct credentials from <a href="https://status.sensfrx.com" target="_blank">your SensFRX dashboard</a>',

            'Save and refresh this page'

        ];

    } else if (message.toLowerCase().includes('license') || message.toLowerCase().includes('plan') || message.toLowerCase().includes('subscription')) {

        title = 'License Issue';

        description = message;

        steps = [

            'Check your SensFRX plan status at <a href="https://status.sensfrx.com" target="_blank">status.sensfrx.com</a>',

            'Verify your subscription is active',

            'Contact support if you believe this is an error',

            'Refresh this page after resolving the issue'

        ];

    } else if (message.toLowerCase().includes('network')) {

        title = 'Network Error';

        description = message + (details ? ' ' + details : '');

        steps = [

            'Check your internet connection',

            'Verify WordPress can make external HTTP requests',

            'Check if your hosting has firewall rules blocking sensfrx.ai',

            'Try again in a few moments'

        ];

    } else if (message.toLowerCase().includes('unable to verify')) {

        title = 'Connection Issue';

        description = message;

        steps = [

            'Check the browser console for detailed error information',

            'Verify your credentials are correct in <a href="?page=sensfrx_fpwoo&tab=settings">Settings</a>',

            'Check your SensFRX plan status at <a href="https://status.sensfrx.com" target="_blank">status.sensfrx.com</a>',

            'Contact support if the issue persists'

        ];

    } else {

        title = 'Connection Issue';

        description = message + (details ? '<br>' + details : '');

        steps = [

            'Check the browser console for detailed error information',

            'Verify your credentials in <a href="?page=sensfrx_fpwoo&tab=settings">Settings</a>',

            'Ensure your internet connection is stable',

            'Contact support with console error details if the issue persists'

        ];

    }



    errorTitle.textContent = title;

    errorDescription.innerHTML = description;

    errorSteps.innerHTML = steps.map(step => '<li>' + step + '</li>').join('');

    errorBox.style.display = 'block';



    // Update plan name to show error state

    document.getElementById('plan-name').textContent = 'Not Connected';

}



function hideApiError() {

    const errorBox = document.getElementById('api-error-message');

    if (errorBox) errorBox.style.display = 'none';

}



function updatePlanInfo(licenseData) {



    // Extract plan name - try multiple possible field names

    const planName = document.getElementById('plan-name');

    const planNameText = licenseData.planName ||

                         licenseData.plan_name ||

                         licenseData.plan ||

                         licenseData.license_type ||

                         'Unknown Plan';



    if (planName) {

        planName.textContent = planNameText;

    }



    // Extract credit information - try multiple possible structures

    let creditsUsedVal = 0;

    let creditsTotalVal = 0;



    // Check if credits is an object with used/total properties

    if (licenseData.credits && typeof licenseData.credits === 'object') {

        creditsUsedVal = parseInt(licenseData.credits.used || licenseData.credits.consumed || 0);

        creditsTotalVal = parseInt(licenseData.credits.total || licenseData.credits.limit || licenseData.credits.quota || 0);

    }

    // Check if credits is a number (total) and available_credit exists

    else if (typeof licenseData.credits === 'number' && licenseData.available_credit !== undefined) {

        creditsTotalVal = parseInt(licenseData.credits || 0);

        const availableCredits = parseInt(licenseData.available_credit || 0);

        creditsUsedVal = creditsTotalVal - availableCredits;

    }

    // Fallback to other possible field names

    else if (licenseData.credit_used !== undefined && licenseData.credit_limit !== undefined) {

        creditsUsedVal = parseInt(licenseData.credit_used || 0);

        creditsTotalVal = parseInt(licenseData.credit_limit || 0);

    } else if (licenseData.used_credits !== undefined && licenseData.total_credits !== undefined) {

        creditsUsedVal = parseInt(licenseData.used_credits || 0);

        creditsTotalVal = parseInt(licenseData.total_credits || 0);

    }



    // Update plan details section with API data

    const planDetailsSection = document.getElementById('plan-details-section');

    if (planDetailsSection) {

        planDetailsSection.style.display = 'block';



        // Update dates

        const formatDate = (dateStr) => {

            if (!dateStr) return '-';

            const date = new Date(dateStr);

            return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });

        };



        const startDate = document.getElementById('plan-start-date');

        const renewalDate = document.getElementById('plan-renewal-date');

        const expDate = document.getElementById('plan-exp-date');

        const planUsers = document.getElementById('plan-users');



        if (startDate) startDate.textContent = formatDate(licenseData.start_date);

        if (renewalDate) renewalDate.textContent = formatDate(licenseData.renewal);

        if (expDate) expDate.textContent = formatDate(licenseData.exp_date);

        if (planUsers) planUsers.textContent = licenseData.users || '-';



        // Update plan limits

        const visibility = document.getElementById('plan-visibility');

        const retention = document.getElementById('plan-retention');

        const customValidation = document.getElementById('plan-custom-validation');

        const blacklistLimit = document.getElementById('plan-blacklist-limit');



        if (visibility) visibility.textContent = licenseData.visibility_limit || '-';

        if (retention) retention.textContent = licenseData.retention_limit || '-';

        if (customValidation) customValidation.textContent = licenseData.custom_validation_limit || '-';

        if (blacklistLimit) blacklistLimit.textContent = licenseData.blacklist_whitelist_limit || '-';

    }



    // Check if user is on FREE plan - only check plan name, not credit values

    const isFreeUser = planNameText.toLowerCase().includes('free') ||

                       planNameText.toLowerCase().includes('trial') ||

                       planNameText.toLowerCase().includes('starter');



    const creditUsageSection = document.getElementById('credit-usage-section');

    const freeCreditUsage = document.getElementById('free-credit-usage');

    const viewUsageBtn = document.getElementById('view-usage-btn');

    const upgradeBtn = document.getElementById('upgrade-btn');



    if (isFreeUser) {

        // Show FREE user credit usage with upgrade prompt

        if (creditUsageSection) creditUsageSection.style.display = 'none';

        if (freeCreditUsage) freeCreditUsage.style.display = 'block';



        // Show visual upgrade hints for plan limits

        const upgradeHint = document.getElementById('upgrade-hint-free');

        const upgradeTeaser = document.getElementById('limits-upgrade-teaser');

        const lockIcons = document.querySelectorAll('.limit-icon-free');



        if (upgradeHint) upgradeHint.style.display = 'block';

        if (upgradeTeaser) upgradeTeaser.style.display = 'block';

        lockIcons.forEach(icon => icon.style.display = 'block');



        // Update FREE user credits display

        const freeCreditsUsed = document.getElementById('free-credits-used');

        const freeCreditsTotal = document.getElementById('free-credits-total');

        const freeCreditsRemaining = document.getElementById('free-credits-remaining');

        const freeCreditsProgress = document.getElementById('free-credits-progress');



        const remaining = creditsTotalVal - creditsUsedVal;

        const percentage = creditsTotalVal > 0 ? (creditsUsedVal / creditsTotalVal) * 100 : 0;



        if (freeCreditsUsed) freeCreditsUsed.textContent = creditsUsedVal.toLocaleString();

        if (freeCreditsTotal) freeCreditsTotal.textContent = creditsTotalVal.toLocaleString();

        if (freeCreditsRemaining) freeCreditsRemaining.textContent = remaining.toLocaleString();

        if (freeCreditsProgress) freeCreditsProgress.style.width = percentage + '%';



        // Update button text for FREE users

        if (viewUsageBtn) {

            viewUsageBtn.textContent = 'Compare Plans';

            viewUsageBtn.href = 'https://sensfrx.ai/pricing';

            viewUsageBtn.target = '_blank';

        }

        if (upgradeBtn) {

            upgradeBtn.textContent = 'Upgrade Now';

        }

    } else {

        // Show credit usage for PAID users (Professional, Enterprise, etc.)

        if (creditUsageSection) creditUsageSection.style.display = 'block';

        if (freeCreditUsage) freeCreditUsage.style.display = 'none';



        // Hide upgrade hints for paid users

        const upgradeHint = document.getElementById('upgrade-hint-free');

        const upgradeTeaser = document.getElementById('limits-upgrade-teaser');

        const lockIcons = document.querySelectorAll('.limit-icon-free');



        if (upgradeHint) upgradeHint.style.display = 'none';

        if (upgradeTeaser) upgradeTeaser.style.display = 'none';

        lockIcons.forEach(icon => icon.style.display = 'none');



        // Update credits display

        const creditsUsed = document.getElementById('credits-used');

        const creditsTotal = document.getElementById('credits-total');

        const creditsRemaining = document.getElementById('credits-remaining');

        const creditsProgress = document.getElementById('credits-progress');



        const remaining = creditsTotalVal - creditsUsedVal;

        const percentage = creditsTotalVal > 0 ? (creditsUsedVal / creditsTotalVal) * 100 : 0;



        if (creditsUsed) creditsUsed.textContent = creditsUsedVal.toLocaleString();

        if (creditsTotal) creditsTotal.textContent = creditsTotalVal.toLocaleString();

        if (creditsRemaining) creditsRemaining.textContent = remaining.toLocaleString();

        if (creditsProgress) creditsProgress.style.width = percentage + '%';



        // Update button text for PAID users

        if (viewUsageBtn) {

            viewUsageBtn.textContent = 'View Usage Details';

            viewUsageBtn.href = '?page=sensfrx_fpwoo&tab=settings';

            viewUsageBtn.removeAttribute('target');

        }

        if (upgradeBtn) {

            upgradeBtn.textContent = 'Upgrade Plan';

        }

    }

}



// Load Revenue Protected Widget

function loadRevenueProtected(restUrl, nonce) {

    const timeRange = document.getElementById('time-range');

    const selectedPeriod = timeRange ? timeRange.value : '7days';



    // Calculate date range

    const today = new Date();

    let fromDate, toDate;

    toDate = today.toISOString().split('T')[0];



    if (selectedPeriod === 'today') {

        fromDate = toDate;

    } else if (selectedPeriod === '7days') {

        const sevenDaysAgo = new Date(today);

        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

        fromDate = sevenDaysAgo.toISOString().split('T')[0];

    } else if (selectedPeriod === '15days') {

        const fifteenDaysAgo = new Date(today);

        fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 15);

        fromDate = fifteenDaysAgo.toISOString().split('T')[0];

    } else if (selectedPeriod === '30days') {

        const thirtyDaysAgo = new Date(today);

        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

        fromDate = thirtyDaysAgo.toISOString().split('T')[0];

    } else if (selectedPeriod === '60days') {

        const sixtyDaysAgo = new Date(today);

        sixtyDaysAgo.setDate(sixtyDaysAgo.getDate() - 60);

        fromDate = sixtyDaysAgo.toISOString().split('T')[0];

    } else if (selectedPeriod === '90days') {

        const ninetyDaysAgo = new Date(today);

        ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90);

        fromDate = ninetyDaysAgo.toISOString().split('T')[0];

    } else if (selectedPeriod === '120days') {

        const onetwentyDaysAgo = new Date(today);

        onetwentyDaysAgo.setDate(onetwentyDaysAgo.getDate() - 120);

        fromDate = onetwentyDaysAgo.toISOString().split('T')[0];

    } else {

        fromDate = toDate;

    }

    // Fetch fraud cases to calculate revenue protected

    fetch(restUrl + 'fraud-cases-list?date_range='+ encodeURIComponent(selectedPeriod), {

        method: 'GET',

        headers: {

            'X-WP-Nonce': nonce,

            'Content-Type': 'application/json'

        }

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success' && data.data) {

            const cases = data.data;

            let totalRevenue = 0;

            let blockedCount = 0;

            let chargebacksPrevented = 0;



            cases.forEach(fraudCase => {

                const status = (fraudCase.status || '').toLowerCase();

                // Use amount first since that's what the API reliably returns

                const orderTotal = parseFloat(fraudCase.amount || fraudCase.order_total || 0);



                // Count blocked/rejected orders

                if (status === 'deny') {

                    totalRevenue += orderTotal;

                    blockedCount++;

                    chargebacksPrevented++; // Assume 1:1 for now

                }

            });



            // Format currency

            const currencySymbol = '<?php echo esc_js( html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,  "UTF-8") ); ?>';

            const formattedRevenue = currencySymbol + totalRevenue.toLocaleString('en-US', {

                minimumFractionDigits: 2,

                maximumFractionDigits: 2

            });



            // Update UI

            document.getElementById('revenue-protected-amount').innerHTML = formattedRevenue;

            document.getElementById('blocked-orders-count').textContent = blockedCount;

            document.getElementById('chargebacks-prevented').textContent = chargebacksPrevented;



            // Show trend (placeholder for now - could compare to previous period)

            const periodLabel = selectedPeriod === '7days' ? 'Last 7 Days' :

                               selectedPeriod === '15days' ? 'Last 15 Days' :

                               selectedPeriod === '30days' ? 'Last 30 Days' :

                               selectedPeriod === '60days' ? 'Last 60 Days' :

                               selectedPeriod === '90days' ? 'Last 90 Days' : 

                               selectedPeriod === '120days' ? 'Last 120 Days' : 'Today';

            document.getElementById('revenue-protected-trend').textContent = periodLabel;



            // Update the small header text too

            const headerLabel = document.getElementById('revenue-protected-period');

            if (headerLabel) {

                headerLabel.textContent = periodLabel;

            }

        }

    })

    .catch(error => {

        document.getElementById('revenue-protected-amount').innerHTML = '<span style="font-size: 20px;">Error loading data</span>';

    });

}



// Load Pending Orders Widget

function loadPendingOrders(restUrl, nonce) {

    fetch(restUrl + 'review-queue?filter=challenge&type=trans', {

        method: 'GET',

        headers: {

            'X-WP-Nonce': nonce,

            'Content-Type': 'application/json'

        }

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success' && data.data) {

            const pendingOrders = data.data;

            const container = document.getElementById('pending-orders-list');



            // Calculate total pending value

            let totalPending = 0;

            pendingOrders.forEach(order => {

                totalPending += parseFloat(order.order_total || order.amount || 0);

            });



            const currencySymbol = '<?php echo esc_js( html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, "UTF-8") ); ?>';

            document.getElementById('pending-orders-value').innerHTML =

                currencySymbol + totalPending.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });



            if (pendingOrders.length === 0) {

                // Update widget to neutral/passive state when no orders

                document.getElementById('pending-orders-widget').style.borderColor = '#E5E7EB';

                document.getElementById('pending-orders-header').style.background = '#F9FAFB';

                document.getElementById('pending-orders-header').style.borderColor = '#E5E7EB';

                document.getElementById('pending-orders-icon').style.background = '#6B7280';

                document.getElementById('pending-orders-title').style.color = '#374151';

                document.getElementById('pending-orders-title').textContent = 'Review Queue';

                document.getElementById('pending-orders-subtitle').style.color = '#6B7280';

                document.getElementById('pending-orders-subtitle').textContent = 'No orders need your attention';

                document.getElementById('pending-orders-value').style.color = '#6B7280';



                // Update icon to checkmark

                document.getElementById('pending-orders-icon').innerHTML = `

                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                        <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                `;



                container.innerHTML = `

                    <div style="text-align: center; padding: 60px 20px;">

                        <div style="width: 80px; height: 80px; background: linear-gradient(135deg, #D1FAE5 0%, #A7F3D0 100%); border-radius: 50%; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center;">

                            <svg width="40" height="40" viewBox="0 0 24 24" fill="none">

                                <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="#10B981" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                            </svg>

                        </div>

                        <h3 style="margin: 0 0 8px; font-size: 18px; font-weight: 700; color: #065F46;">All Clear!</h3>

                        <p style="margin: 0; color: #6B7280; font-size: 14px;">No orders are currently waiting for your review</p>

                    </div>

                `;

            } else {

                // Update widget to warning/amber state when there are orders

                document.getElementById('pending-orders-widget').style.borderColor = '#F59E0B';

                document.getElementById('pending-orders-header').style.background = 'linear-gradient(135deg, #FEF3C7 0%, #FDE68A 100%)';

                document.getElementById('pending-orders-header').style.borderColor = '#FDE68A';

                document.getElementById('pending-orders-icon').style.background = '#F59E0B';

                document.getElementById('pending-orders-title').style.color = '#92400E';

                document.getElementById('pending-orders-title').textContent = 'Orders Awaiting Your Decision';

                document.getElementById('pending-orders-subtitle').style.color = '#78350F';

                document.getElementById('pending-orders-subtitle').textContent = 'Take action to release revenue or prevent fraud';

                document.getElementById('pending-orders-value').style.color = '#D97706';



                // Update icon to warning

                document.getElementById('pending-orders-icon').innerHTML = `

                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                        <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                `;



                let html = '';

                pendingOrders.slice(0, 5).forEach(order => { // Show max 5

                    const riskScore = parseInt(order.risk_score || 0);

                    const riskColor = riskScore >= 70 ? '#EF4444' : riskScore >= 40 ? '#F59E0B' : '#10B981';

                    const riskLabel = riskScore >= 70 ? 'HIGH RISK' : riskScore >= 40 ? 'MEDIUM' : 'LOW RISK';

                    const orderValue = parseFloat(order.order_total || order.amount || 0);



                    html += `

                        <div style="border: 2px solid #E5E7EB; border-radius: 10px; padding: 16px; margin-bottom: 12px; transition: all 0.2s;" onmouseenter="this.style.borderColor='#3B82F6'; this.style.boxShadow='0 4px 12px rgba(59, 130, 246, 0.15)';" onmouseleave="this.style.borderColor='#E5E7EB'; this.style.boxShadow='';">

                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">

                                <div style="flex: 1;">

                                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 6px;">

                                        <span style="font-size: 16px; font-weight: 700; color: #111827;">Order #${order.order_id || 'N/A'}</span>

                                        <span style="background: ${riskColor}; color: white; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 700;">${riskLabel} ${riskScore}</span>

                                    </div>

                                    <div style="font-size: 13px; color: #6B7280; margin-bottom: 4px;">

                                        <strong>${order.email || order.user || 'Unknown Customer'}</strong>

                                    </div>

                                    <div style="font-size: 12px; color: #9CA3AF;">

                                        ${order.timestamp || ''} • ${order.ip_address || 'N/A'}

                                    </div>

                                </div>

                                <div style="text-align: right;">

                                    <div style="font-size: 20px; font-weight: 700; color: #111827;">${currencySymbol}${orderValue.toFixed(2)}</div>

                                    <div style="font-size: 11px; color: #6B7280; font-weight: 600; margin-top: 2px;">ORDER VALUE</div>

                                </div>

                            </div>

                            <div style="display: flex; gap: 8px; justify-content: flex-end;">

                                <button onclick="handleOrderAction('${order.order_id}', '${order.id}', 'approve', this)" style="padding: 8px 16px; background: linear-gradient(135deg, #10B981 0%, #059669 100%); color: white; border: none; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;">

                                    Approve Order

                                </button>

                                <button onclick="handleOrderAction('${order.order_id}', '${order.id}', 'reject', this)" style="padding: 8px 16px; background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%); color: white; border: none; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;">

                                    Block Order

                                </button>

                            </div>

                        </div>

                    `;

                });



                if (pendingOrders.length > 5) {

                    html += `

                        <div style="text-align: center; padding-top: 12px;">

                            <a href="?page=sensfrx_fpwoo&tab=review" style="display: inline-flex; align-items: center; gap: 6px; color: #3B82F6; text-decoration: none; font-size: 14px; font-weight: 600;">

                                View All ${pendingOrders.length} Pending Orders

                                <svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor">

                                    <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"/>

                                </svg>

                            </a>

                        </div>

                    `;

                }



                container.innerHTML = html;

            }

        }

    })

    .catch(error => {



        document.getElementById('pending-orders-list').innerHTML = `

            <div style="text-align: center; padding: 40px 20px; color: #EF4444;">

                <p style="margin: 0; font-size: 14px;">Error loading pending orders</p>

            </div>

        `;

    });

}



// Handle quick approve/block actions

function handleOrderAction(orderId, transaction_id, action, button) {

    if (!confirm('Are you sure you want to ' + action + ' order #' + orderId + '?')) {

        return;

    }



    const restUrl = '<?php echo esc_url(rest_url('sensfrx-fraud-prevention-for-woocommerce/')); ?>';

    const nonce = '<?php echo esc_js( wp_create_nonce('wp_rest') ); ?>';



    // Disable button and show loading

    const originalText = button.textContent;

    button.disabled = true;

    button.textContent = action === 'approve' ? 'Approving...' : 'Blocking...';



    fetch(restUrl + 'post_sensfrx_trans_review', {

        method: 'POST',

        headers: {

            'X-WP-Nonce': nonce,

            'Content-Type': 'application/json'

        },

        body: JSON.stringify({

            orderID: orderId,

            transAction: action,

            transID: transaction_id,

            type: 'trans'

        })

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success') {

            alert('Order #' + orderId + ' has been ' + (action === 'approve' ? 'approved' : 'blocked') + ' successfully!');

            // Reload pending orders

            loadPendingOrders(restUrl, nonce);

            loadRevenueProtected(restUrl, nonce);

        } else {

            alert('Error: ' + (data.message || 'Failed to process action'));

            button.disabled = false;

            button.textContent = originalText;

        }

    })

    .catch(error => {



        alert('Error: Failed to process action');

        button.disabled = false;

        button.textContent = originalText;

    });

}



// Getting Started Checklist Functions

function initializeChecklist(restUrl, nonce) {

    const checkboxes = document.querySelectorAll('.checklist-checkbox');



    checkboxes.forEach(checkbox => {

        checkbox.addEventListener('change', function() {

            updateChecklistItem(this.dataset.item, this.checked, restUrl, nonce);

        });

    });

}



function updateChecklistItem(itemName, isChecked, restUrl, nonce) {

    fetch(restUrl + 'update-checklist', {

        method: 'POST',

        headers: {

            'X-WP-Nonce': nonce,

            'Content-Type': 'application/json'

        },

        body: JSON.stringify({

            item: itemName,

            checked: isChecked

        })

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success') {

            // Update progress bar

            const percentage = data.completion_percentage || 0;

            document.getElementById('checklist-percentage').textContent = percentage + '% Complete';

            document.getElementById('checklist-progress-bar').style.width = percentage + '%';



            // Update border color of the item

            const item = document.querySelector(`[data-item="${itemName}"]`).closest('.checklist-item');

            if (item) {

                item.style.borderColor = isChecked ? '#10B981' : '#E5E7EB';

            }



            // Show success animation

            if (isChecked) {

                item.style.transform = 'scale(0.98)';

                setTimeout(() => {

                    item.style.transform = 'scale(1)';

                }, 150);

            }

        }

    })

    .catch(error => {

        // Silently fail - user can try again

    });

}



// Toggle chat widget visibility

function toggleGettingStarted() {

    const widget = document.getElementById('getting-started-sidebar');

    const currentDisplay = window.getComputedStyle(widget).display;



    if (currentDisplay === 'none') {

        // Show widget with slide-up animation

        widget.style.display = 'block';

        widget.style.opacity = '0';

        widget.style.transform = 'translateY(20px)';



        setTimeout(() => {

            widget.style.transition = 'all 0.3s ease';

            widget.style.opacity = '1';

            widget.style.transform = 'translateY(0)';

        }, 10);

    } else {

        // Hide widget with slide-down animation

        widget.style.opacity = '0';

        widget.style.transform = 'translateY(20px)';



        setTimeout(() => {

            widget.style.display = 'none';

        }, 300);

    }

}



function dismissGettingStarted() {

    if (!confirm('Are you sure you want to hide the Getting Started guide? You can always access help from the Settings page.')) {

        return;

    }



    const restUrl = '<?php echo esc_url(rest_url('sensfrx-fraud-prevention-for-woocommerce/')); ?>';

    const nonce = '<?php echo esc_js( wp_create_nonce('wp_rest') ); ?>';



    fetch(restUrl + 'dismiss-getting-started', {

        method: 'POST',

        headers: {

            'X-WP-Nonce': nonce,

            'Content-Type': 'application/json'

        }

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success') {

            // Fade out sidebar and button

            const sidebar = document.getElementById('getting-started-sidebar');

            const toggleBtn = document.getElementById('getting-started-toggle');



            sidebar.style.opacity = '0';

            toggleBtn.style.opacity = '0';

            sidebar.style.transition = 'opacity 0.3s ease';

            toggleBtn.style.transition = 'opacity 0.3s ease';



            setTimeout(() => {

                sidebar.style.display = 'none';

                toggleBtn.style.display = 'none';

            }, 300);

        }

    })

    .catch(error => {

        alert('Error dismissing guide. Please try again.');

    });

}



/**

 * Show custom modal for demo mode confirmation

 */

function disableDemoMode() {

    const modal = document.getElementById('demo-mode-modal');

    if (modal) {

        modal.style.display = 'flex';

        // Prevent body scroll when modal is open

        document.body.style.overflow = 'hidden';

    }

}



/**

 * Close demo mode modal

 */

function closeDemoModal() {

    const modal = document.getElementById('demo-mode-modal');

    if (modal) {

        modal.style.display = 'none';

        // Restore body scroll

        document.body.style.overflow = '';

    }

}



/**

 * Confirm and disable demo mode

 */

function confirmDisableDemo() {

    // Set demo mode to disabled

    fetch(ajaxurl, {

        method: 'POST',

        headers: {

            'Content-Type': 'application/x-www-form-urlencoded',

        },

        body: new URLSearchParams({

            'action': 'sensfrx_set_demo_mode',

            'mode': 'disabled',

            'nonce': '<?php echo esc_js( wp_create_nonce('sensfrx_demo_mode') ); ?>'

        })

    })

    .then(response => response.json())

    .then(data => {

        if (data.success) {

            // Reload page to show real data

            window.location.reload();

        } else {

            closeDemoModal();

            alert('Error disabling demo mode. Please try again.');

        }

    })

    .catch(error => {

        console.error('Error disabling demo mode:', error);

        closeDemoModal();

        alert('Error disabling demo mode. Please try again.');

    });

}



// Close modal when clicking outside

document.addEventListener('DOMContentLoaded', function() {

    const modal = document.getElementById('demo-mode-modal');

    if (modal) {

        modal.addEventListener('click', function(e) {

            if (e.target === modal) {

                closeDemoModal();

            }

        });

    }

});

</script>

