

<?php $__env->startSection('title', 'Algorithm Control Panel'); ?>

<?php $__env->startSection('content'); ?>
    <!-- Algorithm Control Panel -->
    <div class="algorithm-control-panel">
        <!-- Page Header -->
        <div class="page-header">
            <div class="header-content">
                <h1>🤖 Smart Algorithm Control</h1>
                <p class="header-subtitle">Complete control over CLX AI recommendation system</p>
            </div>
            <div class="header-actions">
                <button onclick="saveAlgorithmConfig()" class="btn-primary">
                    💾 Save Configuration
                </button>
                <button onclick="runABTest()" class="btn-secondary">
                    🧪 Run A/B Test
                </button>
                <button onclick="resetToDefaults()" class="btn-warning">
                    🔄 Reset Defaults
                </button>
                <button onclick="emergencyStop()" class="btn-danger">
                    🚨 Emergency Stop
                </button>
            </div>
        </div>

        <!-- Real-time Status Section -->
        <div class="status-section">
            <div class="status-grid">
                <div class="status-card">
                    <div class="status-icon">🎯</div>
                    <div class="status-value" id="accuracy-score">92.5%</div>
                    <div class="status-label">Recommendation Accuracy</div>
                </div>
                <div class="status-card">
                    <div class="status-icon">👥</div>
                    <div class="status-value" id="conversion-rate">8.7%</div>
                    <div class="status-label">VIP Conversion Rate</div>
                </div>
                <div class="status-card">
                    <div class="status-icon">💰</div>
                    <div class="status-value" id="revenue-impact">$12,450</div>
                    <div class="status-label">Monthly Revenue Impact</div>
                </div>
                <div class="status-card">
                    <div class="status-icon">⚡</div>
                    <div class="status-value" id="active-users">1,234</div>
                    <div class="status-label">Active Users</div>
                </div>
            </div>
        </div>

        <!-- Main Control Grid -->
        <div class="control-grid">
            <!-- Weight Distribution Controls -->
            <div class="control-card">
                <div class="card-header">
                    <h3>🎯 Weight Distribution</h3>
                    <div class="card-subtitle">Control how much each factor influences recommendations</div>
                </div>
                <div class="control-content">
                    <div class="weight-controls">
                        <!-- Location Relevance -->
                        <div class="weight-control-group">
                            <div class="control-label">
                                <span class="control-icon">📍</span>
                                <span>Location Relevance</span>
                                <span class="weight-value" id="location-value">80%</span>
                            </div>
                            <input type="range" min="0" max="100" value="80" id="location-weight" 
                                   oninput="updateWeight('location', this.value)" class="weight-slider">
                            <div class="weight-description">How much geographic proximity affects recommendations</div>
                        </div>

                        <!-- Search History -->
                        <div class="weight-control-group">
                            <div class="control-label">
                                <span class="control-icon">🔍</span>
                                <span>Search History</span>
                                <span class="weight-value" id="search-value">60%</span>
                            </div>
                            <input type="range" min="0" max="100" value="60" id="search-weight" 
                                   oninput="updateWeight('search', this.value)" class="weight-slider">
                            <div class="weight-description">How much past behavior influences recommendations</div>
                        </div>

                        <!-- User Profile -->
                        <div class="weight-control-group">
                            <div class="control-label">
                                <span class="control-icon">👤</span>
                                <span>User Profile</span>
                                <span class="weight-value" id="profile-value">70%</span>
                            </div>
                            <input type="range" min="0" max="100" value="70" id="profile-weight" 
                                   oninput="updateWeight('profile', this.value)" class="weight-slider">
                            <div class="weight-description">How much user demographics affect recommendations</div>
                        </div>

                        <!-- Ad Performance -->
                        <div class="weight-control-group">
                            <div class="control-label">
                                <span class="control-icon">📊</span>
                                <span>Ad Performance</span>
                                <span class="weight-value" id="performance-value">90%</span>
                            </div>
                            <input type="range" min="0" max="100" value="90" id="performance-weight" 
                                   oninput="updateWeight('performance', this.value)" class="weight-slider">
                            <div class="weight-description">How much ad engagement history matters</div>
                        </div>

                        <!-- Freshness Factor -->
                        <div class="weight-control-group">
                            <div class="control-label">
                                <span class="control-icon">⏰</span>
                                <span>Freshness Factor</span>
                                <span class="weight-value" id="freshness-value">40%</span>
                            </div>
                            <input type="range" min="0" max="100" value="40" id="freshness-weight" 
                                   oninput="updateWeight('freshness', this.value)" class="weight-slider">
                            <div class="weight-description">How much new content is prioritized</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- VIP Priority Controls -->
            <div class="control-card">
                <div class="card-header">
                    <h3>👑 VIP Member Priority</h3>
                    <div class="card-subtitle">Set algorithm benefits for different VIP tiers</div>
                </div>
                <div class="control-content">
                    <div class="vip-controls">
                        <!-- Platinum VIP -->
                        <div class="vip-control-group">
                            <div class="control-label">
                                <span class="vip-badge platinum">🏆</span>
                                <span>Platinum VIP Boost</span>
                                <span class="weight-value" id="platinum-value">100%</span>
                            </div>
                            <input type="range" min="0" max="100" value="100" id="platinum-weight" 
                                   oninput="console.log('Platinum slider changed:', this.value); updateVIPWeight('platinum', this.value)" class="weight-slider">
                            <div class="vip-description">Maximum algorithm priority for Platinum members</div>
                        </div>

                        <!-- Gold VIP -->
                        <div class="vip-control-group">
                            <div class="control-label">
                                <span class="vip-badge gold">🥇</span>
                                <span>Gold VIP Boost</span>
                                <span class="weight-value" id="gold-value">75%</span>
                            </div>
                            <input type="range" min="0" max="100" value="75" id="gold-weight" 
                                   oninput="console.log('Gold slider changed:', this.value); updateVIPWeight('gold', this.value)" class="weight-slider">
                            <div class="vip-description">High algorithm priority for Gold members</div>
                        </div>

                        <!-- Silver VIP -->
                        <div class="vip-control-group">
                            <div class="control-label">
                                <span class="vip-badge silver">🥈</span>
                                <span>Silver VIP Boost</span>
                                <span class="weight-value" id="silver-value">50%</span>
                            </div>
                            <input type="range" min="0" max="100" value="50" id="silver-weight" 
                                   oninput="console.log('Silver slider changed:', this.value); updateVIPWeight('silver', this.value)" class="weight-slider">
                            <div class="vip-description">Moderate algorithm priority for Silver members</div>
                        </div>

                        <!-- Free Users -->
                        <div class="vip-control-group">
                            <div class="control-label">
                                <span class="vip-badge free">🆓</span>
                                <span>Free User Weight</span>
                                <span class="weight-value" id="free-value">20%</span>
                            </div>
                            <input type="range" min="0" max="100" value="20" id="free-weight" 
                                   oninput="console.log('Free slider changed:', this.value); updateVIPWeight('free', this.value)" class="weight-slider">
                            <div class="vip-description">Baseline algorithm priority for free users</div>
                        </div>

                        <!-- VIP Priority Toggle -->
                        <div class="priority-toggle">
                            <label class="toggle-switch">
                                <input type="checkbox" id="priority-ranking" checked onchange="togglePriorityRanking()">
                                <span class="toggle-slider"></span>
                            </label>
                            <div class="toggle-label">
                                <span>Enable VIP Priority Ranking</span>
                                <span class="toggle-description">Give VIP members algorithmic advantages</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Ad Package Boosts Controls -->
            <div class="control-card">
                <div class="card-header">
                    <h3>📦 Ad Package Boosts</h3>
                    <div class="card-subtitle">Set algorithm boosts for specific ad packages</div>
                </div>
                <div class="control-content">
                    <div class="package-controls">
                        <div class="loading-placeholder">
                            <span>Loading packages...</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Advanced Algorithm Settings -->
            <div class="control-card">
                <div class="card-header">
                    <h3>🎛️ Advanced Controls</h3>
                    <div class="card-subtitle">Fine-tune algorithm behavior and learning</div>
                </div>
                <div class="control-content">
                    <div class="advanced-controls">
                        <!-- Learning Rate -->
                        <div class="control-group">
                            <label class="control-label">Learning Rate</label>
                            <div class="control-input-group">
                                <input type="range" min="0.1" max="1.0" step="0.1" value="0.7" id="learning-rate" 
                                       oninput="updateAdvancedSetting('learning_rate', this.value)" class="advanced-slider">
                                <span class="control-value" id="learning-rate-value">0.7</span>
                            </div>
                            <div class="control-description">How quickly the algorithm adapts to new data</div>
                        </div>

                        <!-- Memory Window -->
                        <div class="control-group">
                            <label class="control-label">Memory Window (days)</label>
                            <div class="control-input-group">
                                <input type="number" min="1" max="365" value="30" id="memory-window" 
                                       onchange="updateAdvancedSetting('memory_window', this.value)" class="advanced-input">
                            </div>
                            <div class="control-description">How much historical data the algorithm considers</div>
                        </div>

                        <!-- Personalization Toggle -->
                        <div class="control-group">
                            <label class="control-label">Personalization</label>
                            <div class="control-input-group">
                                <select id="personalization" onchange="updateAdvancedSetting('personalization', this.value)" class="advanced-select">
                                    <option value="on">ON</option>
                                    <option value="off">OFF</option>
                                </select>
                            </div>
                            <div class="control-description">Enable/disable personalized recommendations</div>
                        </div>

                        <!-- Diversity Factor -->
                        <div class="control-group">
                            <label class="control-label">Diversity Factor</label>
                            <div class="control-input-group">
                                <input type="range" min="0" max="100" value="40" id="diversity-factor" 
                                       oninput="updateAdvancedSetting('diversity_factor', this.value)" class="advanced-slider">
                                <span class="control-value" id="diversity-value">40%</span>
                            </div>
                            <div class="control-description">Balance between relevance and content variety</div>
                        </div>

                        <!-- Algorithm Status -->
                        <div class="control-group">
                            <label class="control-label">Algorithm Status</label>
                            <div class="status-indicator" id="algorithm-status">
                                <span class="status-dot active"></span>
                                <span class="status-text">Active</span>
                            </div>
                            <div class="control-description">Current algorithm operational status</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Algorithm Actions -->
            <div class="control-card">
                <div class="card-header">
                    <h3>🚀 Algorithm Actions</h3>
                    <div class="card-subtitle">Perform administrative actions on the algorithm</div>
                </div>
                <div class="control-content">
                    <div class="action-controls">
                        <!-- Save Configuration -->
                        <div class="action-group">
                            <button onclick="saveAlgorithmConfig()" class="action-btn primary">
                                <span class="action-icon">💾</span>
                                <span>Save Configuration</span>
                            </button>
                            <div class="action-description">Save all current algorithm settings</div>
                        </div>

                        <!-- Run A/B Test -->
                        <div class="action-group">
                            <button onclick="runABTest()" class="action-btn secondary">
                                <span class="action-icon">🧪</span>
                                <span>Run A/B Test</span>
                            </button>
                            <div class="action-description">Test different algorithm configurations</div>
                        </div>

                        <!-- Reset Defaults -->
                        <div class="action-group">
                            <button onclick="resetToDefaults()" class="action-btn warning">
                                <span class="action-icon">🔄</span>
                                <span>Reset Defaults</span>
                            </button>
                            <div class="action-description">Restore factory default settings</div>
                        </div>

                        <!-- Emergency Stop -->
                        <div class="action-group">
                            <button onclick="emergencyStop()" class="action-btn danger">
                                <span class="action-icon">🚨</span>
                                <span>Emergency Stop</span>
                            </button>
                            <div class="action-description">Temporarily disable algorithm</div>
                        </div>

                        <!-- Export Data -->
                        <div class="action-group">
                            <button onclick="exportAlgorithmData()" class="action-btn info">
                                <span class="action-icon">📊</span>
                                <span>Export Data</span>
                            </button>
                            <div class="action-description">Export algorithm performance data</div>
                        </div>

                        <!-- Clear Cache -->
                        <div class="action-group">
                            <button onclick="clearAlgorithmCache()" class="action-btn neutral">
                                <span class="action-icon">🧹</span>
                                <span>Clear Cache</span>
                            </button>
                            <div class="action-description">Clear algorithm cache and temporary data</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Performance Monitoring -->
            <div class="control-card">
                <div class="card-header">
                    <h3>📈 Performance Monitoring</h3>
                    <div class="card-subtitle">Real-time algorithm performance metrics</div>
                </div>
                <div class="control-content">
                    <div class="performance-metrics">
                        <!-- Processing Queue -->
                        <div class="metric-card">
                            <div class="metric-header">
                                <span class="metric-icon">⚡</span>
                                <span class="metric-title">Processing Queue</span>
                            </div>
                            <div class="metric-value" id="processing-queue">150</div>
                            <div class="metric-subtitle">Active processing tasks</div>
                        </div>

                        <!-- Cache Hit Rate -->
                        <div class="metric-card">
                            <div class="metric-header">
                                <span class="metric-icon">💾</span>
                                <span class="metric-title">Cache Hit Rate</span>
                            </div>
                            <div class="metric-value" id="cache-hit-rate">85.5%</div>
                            <div class="metric-subtitle">Cache efficiency</div>
                        </div>

                        <!-- API Response Time -->
                        <div class="metric-card">
                            <div class="metric-header">
                                <span class="metric-icon">⏱️</span>
                                <span class="metric-title">API Response Time</span>
                            </div>
                            <div class="metric-value" id="api-response-time">245ms</div>
                            <div class="metric-subtitle">Average response time</div>
                        </div>

                        <!-- Last Updated -->
                        <div class="metric-card">
                            <div class="metric-header">
                                <span class="metric-icon">🕒</span>
                                <span class="metric-title">Last Updated</span>
                            </div>
                            <div class="metric-value" id="last-updated"><?php echo e(now()->toDateTimeString()); ?></div>
                            <div class="metric-subtitle">Last configuration update</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Algorithm Insights -->
            <div class="control-card">
                <div class="card-header">
                    <h3>💡 Algorithm Insights</h3>
                    <div class="card-subtitle">AI-generated insights and recommendations</div>
                </div>
                <div class="control-content">
                    <div class="insights-container">
                        <div class="insight-item">
                            <div class="insight-header">
                                <span class="insight-icon">🎯</span>
                                <span class="insight-title">Optimization Suggestion</span>
                            </div>
                            <div class="insight-content">
                                Consider increasing the freshness factor to 50% to improve content variety and user engagement.
                            </div>
                            <div class="insight-actions">
                                <button onclick="applySuggestion('freshness', 50)" class="insight-btn">Apply</button>
                                <button onclick="dismissSuggestion(this)" class="insight-btn secondary">Dismiss</button>
                            </div>
                        </div>

                        <div class="insight-item">
                            <div class="insight-header">
                                <span class="insight-icon">📊</span>
                                <span class="insight-title">Performance Alert</span>
                            </div>
                            <div class="insight-content">
                                VIP conversion rate has increased by 15% this month. Consider reviewing Platinum member benefits.
                            </div>
                            <div class="insight-actions">
                                <button onclick="reviewVIPBenefits()" class="insight-btn">Review</button>
                                <button onclick="dismissSuggestion(this)" class="insight-btn secondary">Dismiss</button>
                            </div>
                        </div>

                        <div class="insight-item">
                            <div class="insight-header">
                                <span class="insight-icon">⚠️</span>
                                <span class="insight-title">System Alert</span>
                            </div>
                            <div class="insight-content">
                                Cache hit rate is below optimal. Consider increasing cache size or reviewing cache strategy.
                            </div>
                            <div class="insight-actions">
                                <button onclick="optimizeCache()" class="insight-btn">Optimize</button>
                                <button onclick="dismissSuggestion(this)" class="insight-btn secondary">Dismiss</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Algorithm Control JavaScript -->
    <script>
        let algorithmConfig = {
            weights: {},
            advanced: {},
            vipSettings: {}
        };

        // Initialize algorithm control panel
        document.addEventListener('DOMContentLoaded', function() {
            loadAlgorithmConfig();
            loadUserPlans(); // Load user plans to generate dynamic VIP controls
            loadAdPackages(); // Load ad packages to generate dynamic package controls
            updateRealTimeStatus();
            setInterval(updateRealTimeStatus, 30000); // Update every 30 seconds
        });

        // Load current algorithm configuration
        async function loadAlgorithmConfig() {
            try {
                console.log('Loading algorithm config...');
                
                const response = await fetch('/admin/algorithm/config');
                console.log('Response status:', response.status);
                
                const contentType = response.headers.get('content-type');
                console.log('Content type:', contentType);
                
                if (contentType && contentType.includes('application/json')) {
                    const data = await response.json();
                    console.log('Response data:', data);

                    if (data.success) {
                        algorithmConfig = data.data;
                        console.log('Loaded config from server:', algorithmConfig);
                        updateUIFromConfig();
                    } else {
                        console.error('Failed to load config:', data.message);
                    }
                } else {
                    // Server returned HTML instead of JSON
                    const htmlResponse = await response.text();
                    console.log('Server returned HTML instead of JSON:', htmlResponse);
                }
            } catch (error) {
                console.error('Error loading algorithm config:', error);
            }
        }

        // Load user plans for dynamic VIP configuration
        async function loadUserPlans() {
            try {
                console.log('Loading user plans...');
                
                const response = await fetch('/admin/algorithm/user-plans');
                console.log('User plans response status:', response.status);
                
                const contentType = response.headers.get('content-type');
                console.log('Content type:', contentType);
                
                if (contentType && contentType.includes('application/json')) {
                    const data = await response.json();
                    console.log('User plans data:', data);

                    if (data.success) {
                        generateVIPControls(data.data);
                    } else {
                        console.error('Failed to load user plans:', data.message);
                        // Fallback to hardcoded VIP controls
                        generateDefaultVIPControls();
                    }
                } else {
                    // Server returned HTML instead of JSON
                    const htmlResponse = await response.text();
                    console.log('Server returned HTML instead of JSON:', htmlResponse);
                    // Fallback to hardcoded VIP controls
                    generateDefaultVIPControls();
                }
            } catch (error) {
                console.error('Error loading user plans:', error);
                // Fallback to hardcoded VIP controls
                generateDefaultVIPControls();
            }
        }

        // Generate VIP controls dynamically based on user plans
        function generateVIPControls(plans) {
            const vipContainer = document.querySelector('.vip-controls');
            if (!vipContainer) return;

            // Clear existing VIP controls
            vipContainer.innerHTML = '';

            // Sort plans by price (highest first)
            plans.sort((a, b) => b.price - a.price);

            plans.forEach((plan, index) => {
                const planId = plan.id;
                const planName = plan.name;
                const currentBoost = plan.algorithm_boost || 50;

                // Initialize config with current values so they are saved even if untouched
                if (!algorithmConfig.vipSettings) algorithmConfig.vipSettings = {};
                algorithmConfig.vipSettings[`plan_${planId}_boost`] = currentBoost;

                // Create VIP control group
                const vipControlGroup = document.createElement('div');
                vipControlGroup.className = 'vip-control-group';
                vipControlGroup.id = `vip-control-${planId}`;

                vipControlGroup.innerHTML = `
                    <div class="control-label">
                        <span class="vip-badge ${getPlanBadgeClass(planName)}">${getPlanIcon(planName)}</span>
                        <span>${planName} Boost</span>
                        <span class="weight-value" id="plan-${planId}-value">${currentBoost}%</span>
                    </div>
                    <input type="range" min="0" max="100" value="${currentBoost}" id="plan-${planId}-weight" 
                           oninput="updatePlanWeight(${planId}, this.value)" class="weight-slider">
                    <div class="vip-description">Algorithm boost for ${planName} members</div>
                `;

                vipContainer.appendChild(vipControlGroup);
            });

            // Add priority toggle if we have plans
            if (plans.length > 0) {
                const priorityToggle = document.createElement('div');
                priorityToggle.className = 'priority-toggle';
                priorityToggle.innerHTML = `
                    <label class="toggle-switch">
                        <input type="checkbox" id="priority-ranking" checked onchange="togglePriorityRanking()">
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="toggle-label">
                        <span>Enable VIP Priority Ranking</span>
                        <span class="toggle-description">Give VIP members algorithmic advantages</span>
                    </div>
                `;
                vipContainer.appendChild(priorityToggle);
            }
        }

        // Load ad packages for dynamic configuration
        async function loadAdPackages() {
            try {
                console.log('Loading ad packages...');
                
                const response = await fetch('/admin/algorithm/ad-packages');
                console.log('Ad packages response status:', response.status);
                
                const contentType = response.headers.get('content-type');
                
                if (contentType && contentType.includes('application/json')) {
                    const data = await response.json();
                    if (data.success) {
                        generatePackageControls(data.data);
                    } else {
                        console.error('Failed to load ad packages:', data.message);
                    }
                }
            } catch (error) {
                console.error('Error loading ad packages:', error);
            }
        }

        // Generate package controls dynamically based on ad packages
        function generatePackageControls(packages) {
            const packageContainer = document.querySelector('.package-controls');
            if (!packageContainer) return;

            // Clear existing package controls
            packageContainer.innerHTML = '';

            if (packages.length === 0) {
                packageContainer.innerHTML = '<div class="no-data">No active packages found</div>';
                return;
            }

            packages.forEach((pkg) => {
                const pkgId = pkg.id;
                const pkgName = pkg.name;
                const currentBoost = pkg.algorithm_boost || 50;

                // Initialize config
                if (!algorithmConfig.packageBoosts) algorithmConfig.packageBoosts = {};
                algorithmConfig.packageBoosts[`package_${pkgId}_boost`] = currentBoost;

                // Create Package control group
                const pkgControlGroup = document.createElement('div');
                pkgControlGroup.className = 'vip-control-group'; // Reuse same styling
                pkgControlGroup.id = `package-control-${pkgId}`;

                pkgControlGroup.innerHTML = `
                    <div class="control-label">
                        <span class="vip-badge">${pkg.icon ? `<img src="${pkg.icon}" style="width:20px;height:20px;">` : '📦'}</span>
                        <span>${pkgName} Boost</span>
                        <span class="weight-value" id="package-${pkgId}-value">${currentBoost}%</span>
                    </div>
                    <input type="range" min="0" max="100" value="${currentBoost}" id="package-${pkgId}-weight" 
                           oninput="updatePackageWeight(${pkgId}, this.value)" class="weight-slider">
                    <div class="vip-description">Ranking boost for ads with ${pkgName} package</div>
                `;

                packageContainer.appendChild(pkgControlGroup);
            });
        }


        // Get badge class based on plan name
        function getPlanBadgeClass(planName) {
            const name = planName.toLowerCase();
            if (name.includes('pro') || name.includes('premium')) return 'platinum';
            if (name.includes('seller') || name.includes('gold')) return 'gold';
            if (name.includes('buyer') || name.includes('silver')) return 'silver';
            if (name.includes('standard') || name.includes('free')) return 'free';
            return 'silver'; // Default
        }

        // Get plan icon based on plan name
        function getPlanIcon(planName) {
            const name = planName.toLowerCase();
            if (name.includes('pro') || name.includes('premium')) return '🏆';
            if (name.includes('seller') || name.includes('gold')) return '🥇';
            if (name.includes('buyer') || name.includes('silver')) return '🥈';
            if (name.includes('standard') || name.includes('free')) return '🆓';
            return '⭐'; // Default
        }

        // Generate default hardcoded VIP controls (fallback)
        function generateDefaultVIPControls() {
            const vipContainer = document.querySelector('.vip-controls');
            if (!vipContainer) return;

            // Clear existing VIP controls
            vipContainer.innerHTML = '';

            // Add hardcoded VIP controls as fallback
            const defaultControls = [
                { name: 'Platinum VIP', id: 'platinum', value: 100, icon: '🏆' },
                { name: 'Gold VIP', id: 'gold', value: 75, icon: '🥇' },
                { name: 'Silver VIP', id: 'silver', value: 50, icon: '🥈' },
                { name: 'Free User', id: 'free', value: 20, icon: '🆓' }
            ];

            defaultControls.forEach(control => {
                const vipControlGroup = document.createElement('div');
                vipControlGroup.className = 'vip-control-group';

                vipControlGroup.innerHTML = `
                    <div class="control-label">
                        <span class="vip-badge ${getPlanBadgeClass(control.name)}">${control.icon}</span>
                        <span>${control.name} Boost</span>
                        <span class="weight-value" id="${control.id}-value">${control.value}%</span>
                    </div>
                    <input type="range" min="0" max="100" value="${control.value}" id="${control.id}-weight" 
                           oninput="updateVIPWeight('${control.id}', this.value)" class="weight-slider">
                    <div class="vip-description">Algorithm boost for ${control.name} members</div>
                `;

                vipContainer.appendChild(vipControlGroup);
            });

            // Add priority toggle
            const priorityToggle = document.createElement('div');
            priorityToggle.className = 'priority-toggle';
            priorityToggle.innerHTML = `
                <label class="toggle-switch">
                    <input type="checkbox" id="priority-ranking" checked onchange="togglePriorityRanking()">
                    <span class="toggle-slider"></span>
                </label>
                <div class="toggle-label">
                    <span>Enable VIP Priority Ranking</span>
                    <span class="toggle-description">Give VIP members algorithmic advantages</span>
                </div>
            `;
            vipContainer.appendChild(priorityToggle);
        }

        // Update plan weight for dynamic VIP controls
        function updatePlanWeight(planId, value) {
            const valueElement = document.getElementById(`plan-${planId}-value`);
            if (valueElement) {
                valueElement.textContent = value + '%';
            }
            
            // Update algorithm config with plan-specific boost
            if (!algorithmConfig.vipSettings) {
                algorithmConfig.vipSettings = {};
            }
            algorithmConfig.vipSettings[`plan_${planId}_boost`] = parseInt(value);
        }

        // Update VIP weight for fallback controls
        function updateVIPWeight(type, value) {
            console.log('updateVIPWeight function called with:', { type, value });
            
            // Ensure vipSettings object exists
            if (!algorithmConfig.vipSettings) {
                algorithmConfig.vipSettings = {};
            }
            
            algorithmConfig.vipSettings[type + '_boost'] = parseInt(value);
            
            // Update the display value
            const valueElement = document.getElementById(type + '-value');
            if (valueElement) {
                valueElement.textContent = value + '%';
            } else {
                console.error('VIP value element not found:', type + '-value');
            }
            
            console.log('VIP Weight Updated:', {
                type: type,
                value: parseInt(value),
                vipSettings: algorithmConfig.vipSettings
            });
        }

        // Update UI from configuration
        function updateUIFromConfig() {
            const weights = algorithmConfig.weights;
            const advanced = algorithmConfig.advanced;
            const vipSettings = algorithmConfig.vipSettings || {};

            // Update weight sliders
            document.getElementById('location-weight').value = weights.location_relevance || 80;
            document.getElementById('search-weight').value = weights.search_history || 60;
            document.getElementById('profile-weight').value = weights.user_profile || 70;
            document.getElementById('performance-weight').value = weights.ad_performance || 90;
            document.getElementById('freshness-weight').value = weights.freshness_factor || 40;

            // Update weight values
            updateWeightValue('location', weights.location_relevance || 80);
            updateWeightValue('search', weights.search_history || 60);
            updateWeightValue('profile', weights.user_profile || 70);
            updateWeightValue('performance', weights.ad_performance || 90);
            updateWeightValue('freshness', weights.freshness_factor || 40);

            // Update advanced settings
            document.getElementById('learning-rate').value = advanced.learning_rate || 0.7;
            document.getElementById('memory-window').value = advanced.memory_window || 30;
            document.getElementById('personalization').value = advanced.personalization ? 'on' : 'off';
            document.getElementById('diversity-factor').value = advanced.diversity_factor || 40;

            // Update advanced values
            document.getElementById('learning-rate-value').textContent = advanced.learning_rate || 0.7;
            document.getElementById('diversity-value').textContent = (advanced.diversity_factor || 40) + '%';

            // Update VIP settings - handle both dynamic and fallback
            if (vipSettings && Object.keys(vipSettings).some(key => key.startsWith('plan_'))) {
                // Dynamic plan-based VIP settings
                Object.keys(vipSettings).forEach(key => {
                    if (key.startsWith('plan_') && key.endsWith('_boost')) {
                        const planId = key.replace('plan_', '').replace('_boost', '');
                        const value = vipSettings[key];
                        const valueElement = document.getElementById(`plan-${planId}-value`);
                        const sliderElement = document.getElementById(`plan-${planId}-weight`);
                        
                        if (valueElement) valueElement.textContent = value + '%';
                        if (sliderElement) sliderElement.value = value;
                    }
                });
            } else {
                // Fallback to hardcoded VIP settings
                document.getElementById('platinum-weight').value = vipSettings.platinum_boost || 100;
                document.getElementById('gold-weight').value = vipSettings.gold_boost || 75;
                document.getElementById('silver-weight').value = vipSettings.silver_boost || 50;
                document.getElementById('free-weight').value = vipSettings.free_boost || 20;
                document.getElementById('priority-ranking').checked = vipSettings.priority_ranking || true;

                // Update VIP values
                updateVIPValue('platinum', vipSettings.platinum_boost || 100);
                updateVIPValue('gold', vipSettings.gold_boost || 75);
                updateVIPValue('silver', vipSettings.silver_boost || 50);
                updateVIPValue('free', vipSettings.free_boost || 20);
            }
        }

        // Update weight value display
        function updateWeight(type, value) {
            document.getElementById(type + '-value').textContent = value + '%';
            
            // Map slider types to database field names
            const weightMap = {
                'location': 'location_relevance',
                'search': 'search_history',
                'profile': 'user_profile',
                'performance': 'ad_performance',
                'freshness': 'freshness_factor'
            };
            
            const fieldName = weightMap[type];
            if (fieldName) {
                algorithmConfig.weights[fieldName] = parseInt(value);
            }
        }

        // Update weight value display
        function updateWeightValue(type, value) {
            const el = document.getElementById(type + '-value');
            if (el) el.textContent = value + '%';
        }

        // Update VIP value display (fallback)
        function updateVIPValue(type, value) {
            const el = document.getElementById(type + '-value');
            if (el) el.textContent = value + '%';
            if (!algorithmConfig.vipSettings) algorithmConfig.vipSettings = {};
            algorithmConfig.vipSettings[type + '_boost'] = parseInt(value);
        }

        // Update advanced setting
        function updateAdvancedSetting(setting, value) {
            if (setting === 'personalization') {
                algorithmConfig.advanced[setting] = value === 'on';
            } else if (setting === 'memory_window') {
                algorithmConfig.advanced[setting] = parseInt(value);
            } else {
                algorithmConfig.advanced[setting] = parseFloat(value);
            }

            if (setting === 'learning_rate') {
                document.getElementById('learning-rate-value').textContent = value;
            } else if (setting === 'diversity_factor') {
                document.getElementById('diversity-value').textContent = value + '%';
            }
        }

        // Toggle VIP priority ranking
        function togglePriorityRanking() {
            algorithmConfig.vipSettings.priority_ranking = document.getElementById('priority-ranking').checked;
        }

        // Save algorithm configuration
        async function saveAlgorithmConfig() {
            try {
                console.log('Saving algorithm config:', algorithmConfig);
                
                const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
                console.log('CSRF Token:', csrfToken);
                
                // Build VIP tiers object dynamically based on available plans
                const vipTiers = {};
                
                if (algorithmConfig.vipSettings) {
                    Object.keys(algorithmConfig.vipSettings).forEach(key => {
                        // 1. Include dynamic plan keys
                        if (key.startsWith('plan_') && key.endsWith('_boost')) {
                            vipTiers[key] = algorithmConfig.vipSettings[key];
                        }
                        // 2. Include static mapped keys (legacy/fallback)
                        if (['platinum_boost', 'gold_boost', 'silver_boost', 'free_boost', 'priority_ranking'].includes(key)) {
                            vipTiers[key] = algorithmConfig.vipSettings[key];
                        }
                    });
                }

                // If no keys found at all, ensure defaults
                if (Object.keys(vipTiers).length === 0) {
                     vipTiers.platinum_boost = 100;
                     vipTiers.gold_boost = 75;
                     vipTiers.silver_boost = 50;
                     vipTiers.free_boost = 20;
                }

                const payload = {
                    weights: algorithmConfig.weights,
                    learning_rate: algorithmConfig.advanced.learning_rate,
                    memory_window: algorithmConfig.advanced.memory_window,
                    personalization: algorithmConfig.advanced.personalization,
                    diversity_factor: algorithmConfig.advanced.diversity_factor,
                    vip_tiers: vipTiers,
                    priority_ranking: algorithmConfig.vipSettings?.priority_ranking || true,
                    package_boosts: algorithmConfig.packageBoosts || {}
                };
                
                console.log('Payload:', payload);

                const response = await fetch('/admin/algorithm/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken
                    },
                    body: JSON.stringify(payload)
                });

                console.log('Response status:', response.status);
                
                // Check if response is JSON or HTML
                const contentType = response.headers.get('content-type');
                if (contentType && contentType.includes('application/json')) {
                    const data = await response.json();
                    console.log('Response data:', data);

                    if (data.success) {
                        showNotification('Algorithm configuration saved successfully!', 'success');
                        updateRealTimeStatus();
                    } else {
                        showNotification('Error saving configuration: ' + data.message, 'error');
                    }
                } else {
                    // Server returned HTML instead of JSON
                    const htmlResponse = await response.text();
                    console.log('Server returned HTML instead of JSON:', htmlResponse);
                    showNotification('Server error - check console for details', 'error');
                }
            } catch (error) {
                console.error('Error saving algorithm config:', error);
                showNotification('Error saving configuration: ' + error.message, 'error');
            }
        }

        // Run A/B test
        async function runABTest() {
            try {
                const testConfig = {
                    variants: [
                        { name: 'Current', config: algorithmConfig },
                        { name: 'Optimized', config: getOptimizedConfig() }
                    ],
                    duration_days: 7,
                    sample_size: 1000
                };

                const response = await fetch('/admin/algorithm/ab-test', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({ test_config: testConfig })
                });

                const data = await response.json();

                if (data.success) {
                    showNotification('A/B test initiated successfully!', 'success');
                } else {
                    showNotification('Error running A/B test: ' + data.message, 'error');
                }
            } catch (error) {
                console.error('Error running A/B test:', error);
                showNotification('Error running A/B test', 'error');
            }
        }

        // Get optimized configuration for A/B test
        function getOptimizedConfig() {
            const config = JSON.parse(JSON.stringify(algorithmConfig));
            // Apply some optimizations for the test
            config.weights.freshness_factor = 50;
            config.advanced.diversity_factor = 50;
            return config;
        }

        // Reset to defaults
        async function resetToDefaults() {
            if (confirm('Are you sure you want to reset algorithm to default settings?')) {
                try {
                    const response = await fetch('/admin/algorithm/reset-defaults', {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        }
                    });

                    const data = await response.json();

                    if (data.success) {
                        showNotification('Algorithm reset to defaults successfully!', 'success');
                        loadAlgorithmConfig();
                    } else {
                        showNotification('Error resetting defaults: ' + data.message, 'error');
                    }
                } catch (error) {
                    console.error('Error resetting defaults:', error);
                    showNotification('Error resetting defaults', 'error');
                }
            }
        }

        // Emergency stop algorithm
        async function emergencyStop() {
            if (confirm('Are you sure you want to emergency stop the algorithm? This will temporarily disable recommendations.')) {
                try {
                    const response = await fetch('/admin/algorithm/emergency-stop', {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        }
                    });

                    const data = await response.json();

                    if (data.success) {
                        showNotification('Algorithm emergency stop activated!', 'warning');
                        updateAlgorithmStatus(false);
                    } else {
                        showNotification('Error activating emergency stop: ' + data.message, 'error');
                    }
                } catch (error) {
                    console.error('Error activating emergency stop:', error);
                    showNotification('Error activating emergency stop', 'error');
                }
            }
        }

        // Update real-time status
        async function updateRealTimeStatus() {
            try {
                const response = await fetch('/admin/algorithm/real-time-status');
                const data = await response.json();

                if (data.success) {
                    const status = data.data;
                    document.getElementById('processing-queue').textContent = status.processing_queue;
                    document.getElementById('cache-hit-rate').textContent = status.cache_hit_rate + '%';
                    document.getElementById('api-response-time').textContent = status.api_response_time + 'ms';
                    document.getElementById('last-updated').textContent = status.last_updated;
                    
                    if (status.is_active) {
                        updateAlgorithmStatus(true);
                    }
                }
            } catch (error) {
                console.error('Error updating real-time status:', error);
            }
        }

        // Update algorithm status indicator
        function updateAlgorithmStatus(active) {
            const statusIndicator = document.getElementById('algorithm-status');
            const statusDot = statusIndicator.querySelector('.status-dot');
            const statusText = statusIndicator.querySelector('.status-text');

            if (active) {
                statusDot.className = 'status-dot active';
                statusText.textContent = 'Active';
            } else {
                statusDot.className = 'status-dot inactive';
                statusText.textContent = 'Inactive';
            }
        }

        // Export algorithm data
        async function exportAlgorithmData() {
            try {
                const response = await fetch('/admin/algorithm/export-data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        type: 'all',
                        start_date: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // Last 30 days
                        end_date: new Date().toISOString().split('T')[0]
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // Create download link for JSON
                    const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data.data, null, 2));
                    const downloadAnchorNode = document.createElement('a');
                    downloadAnchorNode.setAttribute("href", dataStr);
                    downloadAnchorNode.setAttribute("download", "algorithm_export_" + new Date().toISOString() + ".json");
                    document.body.appendChild(downloadAnchorNode);
                    downloadAnchorNode.click();
                    downloadAnchorNode.remove();
                    
                    showNotification('Algorithm data exported successfully!', 'success');
                } else {
                    showNotification('Error exporting data: ' + data.message, 'error');
                }
            } catch (error) {
                console.error('Error exporting algorithm data:', error);
                showNotification('Error exporting data', 'error');
            }
        }

        // Clear algorithm cache
        async function clearAlgorithmCache() {
            if (confirm('Are you sure you want to clear the algorithm cache?')) {
                try {
                    const response = await fetch('/admin/algorithm/clear-cache', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        }
                    });
                    const data = await response.json();
                    if(data.success) {
                        showNotification(data.message, 'success');
                    } else {
                        showNotification('Failed to clear cache: ' + data.message, 'error');
                    }
                } catch (e) {
                    showNotification('Error clearing cache', 'error');
                }
            }
        }

        // Optimize cache
        async function optimizeCache() {
             if (confirm('Are you sure you want to reset optimizations?')) {
                try {
                    const response = await fetch('/admin/algorithm/optimize-cache', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        }
                    });
                    const data = await response.json();
                    if(data.success) {
                        showNotification(data.message, 'success');
                    } else {
                        showNotification('Failed to optimize: ' + data.message, 'error');
                    }
                } catch (e) {
                    showNotification('Error optimizing system', 'error');
                }
            }
        }

        // Show notification
        function showNotification(message, type) {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.textContent = message;

            // Add to page
            document.body.appendChild(notification);

            // Remove after 3 seconds
            setTimeout(() => {
                notification.remove();
            }, 3000);
        }
    </script>

    <style>
        .algorithm-control-panel {
            padding: 20px;
            background: #f8fafc;
            min-height: 100vh;
        }

        .page-header {
            background: white;
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-content h1 {
            margin: 0 0 8px 0;
            font-size: 2rem;
            color: #1f2937;
            font-weight: 800;
        }

        .header-subtitle {
            margin: 0;
            color: #6b7280;
            font-size: 1rem;
        }

        .header-actions {
            display: flex;
            gap: 12px;
        }

        .btn-primary, .btn-secondary, .btn-warning, .btn-danger {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-primary {
            background: #3b82f6;
            color: white;
        }

        .btn-primary:hover {
            background: #2563eb;
        }

        .btn-secondary {
            background: #10b981;
            color: white;
        }

        .btn-secondary:hover {
            background: #059669;
        }

        .btn-warning {
            background: #f59e0b;
            color: white;
        }

        .btn-warning:hover {
            background: #d97706;
        }

        .btn-danger {
            background: #ef4444;
            color: white;
        }

        .btn-danger:hover {
            background: #dc2626;
        }

        .status-section {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 24px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 16px;
        }

        .status-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 16px;
            text-align: center;
            border: 1px solid #e5e7eb;
        }

        .status-icon {
            font-size: 1.5rem;
            margin-bottom: 8px;
            display: block;
        }

        .status-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 4px;
        }

        .status-label {
            font-size: 0.875rem;
            color: #6b7280;
        }

        .control-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 24px;
        }

        .control-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .card-header h3 {
            margin: 0 0 8px 0;
            color: #1f2937;
            font-size: 1.25rem;
        }

        .card-subtitle {
            margin: 0;
            color: #6b7280;
            font-size: 0.875rem;
        }

        .control-content {
            margin-top: 16px;
        }

        .weight-controls, .vip-controls, .advanced-controls, .action-controls, .performance-metrics, .insights-container {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .weight-control-group, .vip-control-group, .control-group, .action-group, .metric-card, .insight-item {
            background: #f8fafc;
            border-radius: 8px;
            padding: 16px;
            border: 1px solid #e5e7eb;
        }

        .control-label {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            font-weight: 600;
            color: #374151;
        }

        .control-icon {
            margin-right: 8px;
            font-size: 1.25rem;
        }

        .weight-slider, .advanced-slider {
            width: 100%;
            margin-bottom: 8px;
        }

        .weight-value, .control-value {
            font-weight: 700;
            color: #3b82f6;
        }

        .weight-description, .vip-description, .control-description, .action-description {
            font-size: 0.875rem;
            color: #6b7280;
        }

        .vip-badge {
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 700;
            font-size: 0.75rem;
        }

        .vip-badge.platinum { background: #e5e7eb; color: #374151; }
        .vip-badge.gold { background: #fde68a; color: #92400e; }
        .vip-badge.silver { background: #cbd5e1; color: #1e293b; }
        .vip-badge.free { background: #dcfce7; color: #166534; }

        .priority-toggle {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px;
            background: white;
            border-radius: 6px;
        }

        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 44px;
            height: 24px;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 24px;
        }

        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .toggle-slider {
            background-color: #3b82f6;
        }

        input:checked + .toggle-slider:before {
            transform: translateX(20px);
        }

        .toggle-label {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .toggle-description {
            font-size: 0.75rem;
            color: #6b7280;
        }

        .advanced-input, .advanced-select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            font-size: 0.875rem;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            width: 100%;
            justify-content: flex-start;
        }

        .action-btn.primary { background: #3b82f6; color: white; }
        .action-btn.secondary { background: #10b981; color: white; }
        .action-btn.warning { background: #f59e0b; color: white; }
        .action-btn.danger { background: #ef4444; color: white; }
        .action-btn.info { background: #60a5fa; color: white; }
        .action-btn.neutral { background: #6b7280; color: white; }

        .action-btn:hover {
            opacity: 0.9;
        }

        .metric-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
        }

        .metric-icon {
            font-size: 1.25rem;
        }

        .metric-title {
            font-weight: 600;
            color: #374151;
        }

        .metric-subtitle {
            font-size: 0.75rem;
            color: #6b7280;
        }

        .insight-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
        }

        .insight-icon {
            font-size: 1.25rem;
        }

        .insight-title {
            font-weight: 600;
            color: #374151;
        }

        .insight-content {
            margin-bottom: 12px;
            color: #4b5563;
            line-height: 1.5;
        }

        .insight-actions {
            display: flex;
            gap: 8px;
        }

        .insight-btn {
            padding: 6px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            background: white;
            cursor: pointer;
            font-size: 0.875rem;
            font-weight: 600;
        }

        .insight-btn.secondary {
            background: #f3f4f6;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
        }

        .status-dot.active {
            background-color: #10b981;
            box-shadow: 0 0 8px #10b981;
        }

        .status-dot.inactive {
            background-color: #ef4444;
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 8px;
            color: white;
            font-weight: 600;
            z-index: 1000;
            animation: slideIn 0.3s ease-out;
        }

        .notification.success { background: #10b981; }
        .notification.error { background: #ef4444; }
        .notification.warning { background: #f59e0b; }
        .notification.info { background: #3b82f6; }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @media (max-width: 768px) {
            .status-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .control-grid {
                grid-template-columns: 1fr;
            }

            .page-header {
                flex-direction: column;
                gap: 16px;
            }

            .header-actions {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\DND\Apps\CLXpro\clx_backend\resources\views/admin/algorithm/control_panel.blade.php ENDPATH**/ ?>