

<?php $__env->startSection('title', 'Business Intelligence Analytics'); ?>

<?php $__env->startSection('content'); ?>
    <!-- Analytics Dashboard -->
    <div class="analytics-dashboard">
        <!-- Top Navigation Bar -->
        <div class="analytics-navigation">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
                <div>
                    <h1 style="margin: 0; font-size: 1.5rem; color: var(--text-primary);">Business Intelligence Analytics</h1>
                    <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 4px;">Comprehensive platform performance insights</div>
                </div>
                <div style="display: flex; gap: 8px;">
                    <a href="#" class="nav-tab active" onclick="loadSection('overview')">Overview</a>
                    <a href="#" class="nav-tab" onclick="loadSection('ad-post')">Ad Post Analytics</a>
                    <a href="#" class="nav-tab" onclick="loadSection('individual-ads')">Individual Ads</a>
                    <a href="#" class="nav-tab" onclick="loadSection('funnels')">Funnels</a>
                    <a href="#" class="nav-tab" onclick="loadSection('export')">Export</a>
                </div>
            </div>
        </div>

        <!-- Enhanced Analytics Controls -->
        <div class="analytics-controls">
            <div style="display: flex; gap: 16px; align-items: center; flex-wrap: wrap; margin-bottom: 24px;">
                <!-- Date Range Quick Select -->
                <div style="display: flex; gap: 8px; align-items: center;">
                    <span style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">Quick Range:</span>
                    <button onclick="setDateRange('today')" class="date-btn">Today</button>
                    <button onclick="setDateRange('yesterday')" class="date-btn">Yesterday</button>
                    <button onclick="setDateRange('last_7_days')" class="date-btn active">Last 7 Days</button>
                    <button onclick="setDateRange('last_30_days')" class="date-btn">Last 30 Days</button>
                    <button onclick="setDateRange('this_month')" class="date-btn">This Month</button>
                    <button onclick="setDateRange('last_month')" class="date-btn">Last Month</button>
                    <button onclick="setDateRange('this_year')" class="date-btn">This Year</button>
                    <button onclick="setDateRange('last_year')" class="date-btn">Last Year</button>
                </div>

                <!-- Custom Date Range -->
                <div style="display: flex; gap: 12px; align-items: center; padding: 8px; background: var(--bg-color); border-radius: 8px;">
                    <span style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">Custom:</span>
                    <div style="min-width: 160px;">
                        <label style="display: block; font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 2px;">Start Date</label>
                        <input type="date" id="start-date" style="padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg); color: var(--text-primary); font-size: 0.875rem;">
                    </div>
                    <div style="min-width: 160px;">
                        <label style="display: block; font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 2px;">End Date</label>
                        <input type="date" id="end-date" style="padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg); color: var(--text-primary); font-size: 0.875rem;">
                    </div>
                </div>

                <!-- Comparison Toggle -->
                <div style="display: flex; gap: 8px; align-items: center;">
                    <span style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">Compare:</span>
                    <label class="comparison-toggle">
                        <input type="checkbox" id="enable-comparison" onchange="toggleComparison()">
                        <span class="toggle-slider"></span>
                        <span style="margin-left: 8px; font-size: 0.875rem;">vs Previous Period</span>
                    </label>
                </div>

                <!-- Report Type -->
                <div style="min-width: 200px;">
                    <label style="display: block; font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 4px;">Report Type</label>
                    <select id="report-type" style="padding: 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg); color: var(--text-primary);">
                        <option value="business_intelligence">Business Intelligence</option>
                        <option value="executive_summary">Executive Summary</option>
                        <option value="detailed_report">Detailed Report</option>
                    </select>
                </div>

                <!-- Universal Export Controls -->
                <div style="margin-top: 24px; display: flex; gap: 8px; align-items: center;">
                    <span style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">Export:</span>
                    <button onclick="exportAnalytics()" style="padding: 8px 16px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.875rem;">Export Report</button>
                    <button onclick="exportCurrentSection()" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.875rem;">Export Current View</button>
                    <button onclick="scheduleExport()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.875rem;">Schedule Export</button>
                    <button onclick="refreshAnalytics()" style="padding: 8px 16px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.875rem;">Refresh</button>
                </div>
            </div>

            <!-- Comparison Info Bar -->
            <div id="comparison-info" style="display: none; background: #f3e8ff; border: 1px solid #e9d5ff; border-radius: 8px; padding: 12px; margin-bottom: 24px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div style="font-size: 0.875rem; color: #4f46e5; font-weight: 600;">
                        📊 Comparison Mode: Current Period vs Previous Period
                    </div>
                    <div style="font-size: 0.875rem; color: #6366f1;">
                        <span id="comparison-period-text">Last 7 Days vs Previous 7 Days</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Content Area -->
        <div id="analytics-content">
            <!-- Content will be loaded here -->
        </div>
    </div>

    <!-- Chart.js Library -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <!-- Analytics JavaScript -->
    <script>
        // Chart instances
        let revenueChart, marketTrendsChart, conversionFunnelChart;
        let currentSection = 'overview';

        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            initializeCharts();
            loadSection('overview');
            
            // Set default date range
            const today = new Date();
            const lastMonth = new Date();
            lastMonth.setMonth(lastMonth.getMonth() - 1);
            
            document.getElementById('start-date').value = lastMonth.toISOString().split('T')[0];
            document.getElementById('end-date').value = today.toISOString().split('T')[0];
            
            // Add event listeners
            document.getElementById('start-date').addEventListener('change', refreshCurrentSection);
            document.getElementById('end-date').addEventListener('change', refreshCurrentSection);
            document.getElementById('report-type').addEventListener('change', refreshCurrentSection);
        });

        function initializeCharts() {
            // Revenue Chart
            const revenueCtx = document.getElementById('revenueChart')?.getContext('2d');
            if (revenueCtx) {
                revenueChart = new Chart(revenueCtx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Daily Revenue',
                            data: [],
                            borderColor: '#7c3aed',
                            backgroundColor: 'rgba(124, 58, 237, 0.1)',
                            borderWidth: 2,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }

            // Market Trends Chart
            const marketCtx = document.getElementById('marketTrendsChart')?.getContext('2d');
            if (marketCtx) {
                marketTrendsChart = new Chart(marketCtx, {
                    type: 'bar',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Category Performance',
                            data: [],
                            backgroundColor: [
                                '#7c3aed', '#10b981', '#f59e0b', '#ef4444', '#3b82f6'
                            ]
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }

            // Conversion Funnel Chart
            const funnelCtx = document.getElementById('conversionFunnelChart')?.getContext('2d');
            if (funnelCtx) {
                conversionFunnelChart = new Chart(funnelCtx, {
                    type: 'doughnut',
                    data: {
                        labels: ['Registration', 'Profile Setup', 'First Ad', 'Payment'],
                        datasets: [{
                            data: [100, 80, 60, 40],
                            backgroundColor: ['#7c3aed', '#10b981', '#f59e0b', '#ef4444']
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }
        }

        function loadSection(section) {
            // Update navigation active states
            document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('active'));
            event?.target?.classList.add('active');
            
            currentSection = section;
            
            // Clear content area
            const contentArea = document.getElementById('analytics-content');
            contentArea.innerHTML = '';
            
            // Load appropriate content based on section
            switch(section) {
                case 'overview':
                    loadOverviewContent();
                    break;
                case 'ad-post':
                    loadAdPostContent();
                    break;
                case 'individual-ads':
                    loadIndividualAdsContent();
                    break;
                case 'funnels':
                    loadFunnelsContent();
                    break;
                case 'export':
                    loadExportContent();
                    break;
            }
        }

        function loadOverviewContent() {
            const contentArea = document.getElementById('analytics-content');
            contentArea.innerHTML = `
                <!-- KPI Overview Section -->
                <div class="dashboard-grid">
                    <!-- Total Revenue -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Total Revenue</div>
                                <div class="card-value" id="total-revenue">₹0</div>
                            </div>
                            <div class="stat-icon">💰</div>
                        </div>
                        <div class="card-change" id="revenue-growth">+0% from last month</div>
                    </div>

                    <!-- Active Users -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Active Users</div>
                                <div class="card-value" id="active-users">0</div>
                            </div>
                            <div class="stat-icon">👥</div>
                        </div>
                        <div class="card-change" id="user-growth">+0% from last month</div>
                    </div>

                    <!-- Conversion Rate -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Conversion Rate</div>
                                <div class="card-value" id="conversion-rate">0%</div>
                            </div>
                            <div class="stat-icon">📈</div>
                        </div>
                        <div class="card-change" id="conversion-change">+0% from last month</div>
                    </div>

                    <!-- ARPU -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">ARPU</div>
                                <div class="card-value" id="arpu">₹0</div>
                            </div>
                            <div class="stat-icon">📊</div>
                        </div>
                        <div class="card-change" id="arpu-change">+0% from last month</div>
                    </div>
                </div>

                <!-- Charts and Analytics Section -->
                <div class="content-grid">
                    <!-- Revenue Analytics Chart -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Revenue Analytics</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Daily revenue trends</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="revenueChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- User Behavior Analysis -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">User Behavior</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Feature usage and engagement</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Feature</th>
                                        <th>Usage</th>
                                        <th>Growth</th>
                                    </tr>
                                </thead>
                                <tbody id="user-behavior-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Market Trends and Predictive Insights -->
                <div class="content-grid">
                    <!-- Market Trends -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Market Trends</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Category performance</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="marketTrendsChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Predictive Insights -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Predictive Insights</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">AI-powered predictions</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <div class="insights-container">
                                <div class="insight-item">
                                    <div style="font-weight: 600; color: var(--text-primary);">Revenue Forecast</div>
                                    <div style="color: var(--text-secondary); font-size: 0.875rem;" id="revenue-forecast">Loading...</div>
                                </div>
                                <div class="insight-item">
                                    <div style="font-weight: 600; color: var(--text-primary);">User Acquisition</div>
                                    <div style="color: var(--text-secondary); font-size: 0.875rem;" id="user-acquisition">Loading...</div>
                                </div>
                                <div class="insight-item">
                                    <div style="font-weight: 600; color: var(--text-primary);">Churn Risk</div>
                                    <div style="color: var(--text-secondary); font-size: 0.875rem;" id="churn-risk">Loading...</div>
                                </div>
                                <div class="insight-item">
                                    <div style="font-weight: 600; color: var(--text-primary);">Opportunities</div>
                                    <div style="color: var(--text-secondary); font-size: 0.875rem;" id="opportunities">Loading...</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Conversion Funnels and CLV -->
                <div class="content-grid">
                    <!-- Conversion Funnels -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Conversion Funnels</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">User journey analysis</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="conversionFunnelChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Customer Lifetime Value -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Customer Lifetime Value</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">High-value customer analysis</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Customer Segment</th>
                                        <th>CLV</th>
                                        <th>Count</th>
                                    </tr>
                                </thead>
                                <tbody id="clv-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Executive Summary -->
                <div class="card" style="margin-bottom: 24px;">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Executive Summary</h3>
                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Key insights and recommendations</div>
                    </div>
                    
                    <div style="margin-top: 20px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
                        <div class="summary-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Top Performers</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="top-performers">Loading...</div>
                        </div>
                        <div class="summary-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Risks Identified</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="risks-identified">Loading...</div>
                        </div>
                        <div class="summary-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Strategic Recommendations</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="recommendations">Loading...</div>
                        </div>
                    </div>
                </div>
            `;
            
            // Re-initialize charts for the new content
            initializeCharts();
            loadAnalyticsData();
        }

        function loadAdPostContent() {
            const contentArea = document.getElementById('analytics-content');
            contentArea.innerHTML = `
                <!-- Ad Post Analytics Dashboard -->
                <div class="dashboard-grid">
                    <!-- Total Ads -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Total Ads</div>
                                <div class="card-value" id="total-ads">0</div>
                            </div>
                            <div class="stat-icon">📊</div>
                        </div>
                        <div class="card-change" id="ads-growth">+0% from last month</div>
                    </div>

                    <!-- Active Ads -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Active Ads</div>
                                <div class="card-value" id="active-ads">0</div>
                            </div>
                            <div class="stat-icon">✅</div>
                        </div>
                        <div class="card-change" id="active-growth">+0% from last month</div>
                    </div>

                    <!-- Ad Views -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Total Views</div>
                                <div class="card-value" id="total-views">0</div>
                            </div>
                            <div class="stat-icon">👁️</div>
                        </div>
                        <div class="card-change" id="views-growth">+0% from last month</div>
                    </div>

                    <!-- Ad CTR -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Avg CTR</div>
                                <div class="card-value" id="avg-ctr">0%</div>
                            </div>
                            <div class="stat-icon">📈</div>
                        </div>
                        <div class="card-change" id="ctr-change">+0% from last month</div>
                    </div>
                </div>

                <!-- Ad Engagement and Monetization Section -->
                <div class="content-grid">
                    <!-- Ad Engagement Chart -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Ad Engagement Metrics</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Messages, clicks, and interactions</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="adEngagementChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Ad Monetization -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Ad Monetization</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Revenue from ad features</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Feature</th>
                                        <th>Revenue</th>
                                        <th>Transactions</th>
                                    </tr>
                                </thead>
                                <tbody id="monetization-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Ad Conversion Funnels and Timing -->
                <div class="content-grid">
                    <!-- Conversion Funnels -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Ad Conversion Funnels</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">User journey analysis</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="adConversionChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Optimal Posting Times -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Optimal Posting Times</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Peak engagement hours</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Hour</th>
                                        <th>Views</th>
                                        <th>Best Time</th>
                                    </tr>
                                </thead>
                                <tbody id="timing-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Ad Category Performance and User Behavior -->
                <div class="content-grid">
                    <!-- Category Performance -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Category Performance</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Top performing categories</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="categoryPerformanceChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- User Behavior -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">User Behavior</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Buyer and seller patterns</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Behavior</th>
                                        <th>Value</th>
                                        <th>Insight</th>
                                    </tr>
                                </thead>
                                <tbody id="user-behavior-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Ad Optimization Recommendations -->
                <div class="card" style="margin-bottom: 24px;">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Ad Optimization Recommendations</h3>
                        <div style="font-size: 0.875rem; color: var(--text-secondary);">AI-powered insights for better performance</div>
                    </div>
                    
                    <div style="margin-top: 20px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
                        <div class="recommendation-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">High Priority</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="high-priority-recommendations">Loading...</div>
                        </div>
                        <div class="recommendation-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Medium Priority</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="medium-priority-recommendations">Loading...</div>
                        </div>
                        <div class="recommendation-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Low Priority</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="low-priority-recommendations">Loading...</div>
                        </div>
                    </div>
                </div>
            `;
            
            // Initialize charts for Ad Post Analytics
            initializeAdPostCharts();
            loadAdPostAnalyticsData();
        }

        function loadIndividualAdsContent() {
            const contentArea = document.getElementById('analytics-content');
            contentArea.innerHTML = `
                <!-- Individual Ads Analytics Dashboard -->
                <div class="dashboard-grid">
                    <!-- Total Individual Ads -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Total Individual Ads</div>
                                <div class="card-value" id="total-individual-ads">0</div>
                            </div>
                            <div class="stat-icon">🎯</div>
                        </div>
                        <div class="card-change" id="individual-ads-growth">+0% from last month</div>
                    </div>

                    <!-- High Performing Ads -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">High Performing</div>
                                <div class="card-value" id="high-performing-ads">0</div>
                            </div>
                            <div class="stat-icon">⭐</div>
                        </div>
                        <div class="card-change" id="high-performing-growth">+0% from last month</div>
                    </div>

                    <!-- Average Engagement -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Avg Engagement</div>
                                <div class="card-value" id="avg-engagement">0</div>
                            </div>
                            <div class="stat-icon">💬</div>
                        </div>
                        <div class="card-change" id="engagement-growth">+0% from last month</div>
                    </div>

                    <!-- Conversion Rate -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Conversion Rate</div>
                                <div class="card-value" id="individual-conversion-rate">0%</div>
                            </div>
                            <div class="stat-icon">🔄</div>
                        </div>
                        <div class="card-change" id="individual-conversion-change">+0% from last month</div>
                    </div>
                </div>

                <!-- Individual Ad Performance and Engagement -->
                <div class="content-grid">
                    <!-- Individual Ad Performance Chart -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Individual Ad Performance</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Per-ad metrics and trends</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="individualAdPerformanceChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Top Performing Ads -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Top Performing Ads</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Best performing individual ads</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Ad ID</th>
                                        <th>Views</th>
                                        <th>Engagement</th>
                                        <th>Revenue</th>
                                    </tr>
                                </thead>
                                <tbody id="top-ads-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Ad Engagement Analysis and Optimization -->
                <div class="content-grid">
                    <!-- Engagement Analysis -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Engagement Analysis</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Detailed engagement metrics</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="engagementAnalysisChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Optimization Opportunities -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Optimization Opportunities</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Areas for improvement</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Ad ID</th>
                                        <th>Issue</th>
                                        <th>Recommendation</th>
                                        <th>Potential</th>
                                    </tr>
                                </thead>
                                <tbody id="optimization-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Individual Ad Insights -->
                <div class="card" style="margin-bottom: 24px;">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Individual Ad Insights</h3>
                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Detailed analysis and recommendations</div>
                    </div>
                    
                    <div style="margin-top: 20px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
                        <div class="insight-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Performance Trends</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="performance-trends">Loading...</div>
                        </div>
                        <div class="insight-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Engagement Patterns</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="engagement-patterns">Loading...</div>
                        </div>
                        <div class="insight-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Revenue Optimization</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="revenue-optimization">Loading...</div>
                        </div>
                    </div>
                </div>
            `;
            
            // Initialize charts for Individual Ads Analytics
            initializeIndividualAdsCharts();
            loadIndividualAdsAnalyticsData();
        }

        function loadFunnelsContent() {
            const contentArea = document.getElementById('analytics-content');
            contentArea.innerHTML = `
                <!-- Conversion Funnels Analytics Dashboard -->
                <div class="dashboard-grid">
                    <!-- Funnel Completion Rate -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Funnel Completion</div>
                                <div class="card-value" id="funnel-completion">0%</div>
                            </div>
                            <div class="stat-icon">📊</div>
                        </div>
                        <div class="card-change" id="funnel-completion-growth">+0% from last month</div>
                    </div>

                    <!-- Drop-off Rate -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Drop-off Rate</div>
                                <div class="card-value" id="drop-off-rate">0%</div>
                            </div>
                            <div class="stat-icon">📉</div>
                        </div>
                        <div class="card-change" id="drop-off-growth">+0% from last month</div>
                    </div>

                    <!-- Conversion Optimization -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Optimization Score</div>
                                <div class="card-value" id="optimization-score">0/10</div>
                            </div>
                            <div class="stat-icon">🎯</div>
                        </div>
                        <div class="card-change" id="optimization-growth">+0 from last month</div>
                    </div>

                    <!-- Funnel Revenue -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Funnel Revenue</div>
                                <div class="card-value" id="funnel-revenue">₹0</div>
                            </div>
                            <div class="stat-icon">💰</div>
                        </div>
                        <div class="card-change" id="funnel-revenue-growth">+0% from last month</div>
                    </div>
                </div>

                <!-- Funnel Visualization and Analysis -->
                <div class="content-grid">
                    <!-- Funnel Visualization Chart -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Funnel Visualization</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">User journey through funnels</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="funnelVisualizationChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Funnel Analysis -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Funnel Analysis</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Detailed funnel performance</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Funnel Stage</th>
                                        <th>Users</th>
                                        <th>Drop-off</th>
                                        <th>Conversion</th>
                                    </tr>
                                </thead>
                                <tbody id="funnel-analysis-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Funnel Optimization and Insights -->
                <div class="content-grid">
                    <!-- Optimization Opportunities -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Optimization Opportunities</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Areas for funnel improvement</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="optimizationOpportunitiesChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Funnel Insights -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Funnel Insights</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Key insights and recommendations</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Insight</th>
                                        <th>Impact</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="funnel-insights-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Funnel Performance Summary -->
                <div class="card" style="margin-bottom: 24px;">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Funnel Performance Summary</h3>
                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Overall funnel health and recommendations</div>
                    </div>
                    
                    <div style="margin-top: 20px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
                        <div class="summary-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Health Score</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="funnel-health-score">Loading...</div>
                        </div>
                        <div class="summary-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Critical Issues</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="critical-issues">Loading...</div>
                        </div>
                        <div class="summary-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Quick Wins</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="quick-wins">Loading...</div>
                        </div>
                    </div>
                </div>
            `;
            
            // Initialize charts for Funnels Analytics
            initializeFunnelsCharts();
            loadFunnelsAnalyticsData();
        }

        function loadExportContent() {
            const contentArea = document.getElementById('analytics-content');
            contentArea.innerHTML = `
                <!-- Export Analytics Dashboard -->
                <div class="dashboard-grid">
                    <!-- Total Exports -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Total Exports</div>
                                <div class="card-value" id="total-exports">0</div>
                            </div>
                            <div class="stat-icon">📤</div>
                        </div>
                        <div class="card-change" id="exports-growth">+0% from last month</div>
                    </div>

                    <!-- Export Formats -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Export Formats</div>
                                <div class="card-value" id="export-formats">0</div>
                            </div>
                            <div class="stat-icon">📄</div>
                        </div>
                        <div class="card-change" id="formats-growth">+0 from last month</div>
                    </div>

                    <!-- Data Quality -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Data Quality</div>
                                <div class="card-value" id="data-quality">0%</div>
                            </div>
                            <div class="stat-icon">✅</div>
                        </div>
                        <div class="card-change" id="quality-growth">+0% from last month</div>
                    </div>

                    <!-- Export Revenue -->
                    <div class="card">
                        <div class="card-header">
                            <div>
                                <div class="card-title">Export Revenue</div>
                                <div class="card-value" id="export-revenue">₹0</div>
                            </div>
                            <div class="stat-icon">💰</div>
                        </div>
                        <div class="card-change" id="export-revenue-growth">+0% from last month</div>
                    </div>
                </div>

                <!-- Export Analytics and Performance -->
                <div class="content-grid">
                    <!-- Export Performance Chart -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Export Performance</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Export trends and performance</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="exportPerformanceChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Export Formats Analysis -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Export Formats</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Format usage and preferences</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Format</th>
                                        <th>Usage</th>
                                        <th>Quality</th>
                                        <th>Revenue</th>
                                    </tr>
                                </thead>
                                <tbody id="export-formats-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Data Quality and Usage -->
                <div class="content-grid">
                    <!-- Data Quality Chart -->
                    <div class="chart-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Data Quality</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Data quality metrics</div>
                        </div>
                        
                        <div style="margin-top: 20px; height: 300px; position: relative;">
                            <canvas id="dataQualityChart" width="600" height="300"></canvas>
                        </div>
                    </div>

                    <!-- Usage Analytics -->
                    <div class="table-card">
                        <div class="card-header">
                            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Usage Analytics</h3>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Export usage patterns</div>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Time Period</th>
                                        <th>Exports</th>
                                        <th>Users</th>
                                        <th>Revenue</th>
                                    </tr>
                                </thead>
                                <tbody id="usage-analytics-table">
                                    <!-- Data loaded via JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Export Optimization -->
                <div class="card" style="margin-bottom: 24px;">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Export Optimization</h3>
                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Export performance and optimization opportunities</div>
                    </div>
                    
                    <div style="margin-top: 20px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
                        <div class="optimization-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Performance Metrics</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="performance-metrics">Loading...</div>
                        </div>
                        <div class="optimization-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Quality Issues</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="quality-issues">Loading...</div>
                        </div>
                        <div class="optimization-card">
                            <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 8px;">Optimization Tips</div>
                            <div style="color: var(--text-secondary); font-size: 0.875rem;" id="optimization-tips">Loading...</div>
                        </div>
                    </div>
                </div>

                <!-- Export Controls -->
                <div class="card" style="margin-bottom: 24px;">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Export Controls</h3>
                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Export settings and controls</div>
                    </div>
                    
                    <div style="margin-top: 20px; display: flex; gap: 20px; align-items: center; flex-wrap: wrap;">
                        <div style="min-width: 200px;">
                            <label style="display: block; font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 4px;">Export Format</label>
                            <select id="export-format" style="padding: 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg); color: var(--text-primary);">
                                <option value="pdf">PDF</option>
                                <option value="excel">Excel</option>
                                <option value="csv">CSV</option>
                                <option value="json">JSON</option>
                            </select>
                        </div>
                        <div style="min-width: 200px;">
                            <label style="display: block; font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 4px;">Data Range</label>
                            <select id="data-range" style="padding: 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg); color: var(--text-primary);">
                                <option value="last_7_days">Last 7 Days</option>
                                <option value="last_30_days">Last 30 Days</option>
                                <option value="last_90_days">Last 90 Days</option>
                                <option value="custom">Custom Range</option>
                            </select>
                        </div>
                        <div style="margin-top: 24px;">
                            <button onclick="exportAnalyticsData()" style="padding: 10px 20px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">Export Data</button>
                            <button onclick="scheduleExport()" style="padding: 10px 20px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-left: 10px;">Schedule Export</button>
                            <button onclick="exportAnalytics()" style="padding: 10px 20px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-left: 10px;">Export Report</button>
                        </div>
                    </div>
                </div>
            `;
            
            // Initialize charts for Export Analytics
            initializeExportCharts();
            loadExportAnalyticsData();
        }

        // Chart initialization functions for each section
        function initializeAdPostCharts() {
            const engagementCtx = document.getElementById('adEngagementChart')?.getContext('2d');
            if (engagementCtx) {
                new Chart(engagementCtx, {
                    type: 'bar',
                    data: {
                        labels: ['Messages', 'Clicks', 'Views', 'Shares'],
                        datasets: [{
                            label: 'Ad Engagement',
                            data: [0, 0, 0, 0],
                            backgroundColor: ['#7c3aed', '#10b981', '#f59e0b', '#ef4444']
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }

            const conversionCtx = document.getElementById('adConversionChart')?.getContext('2d');
            if (conversionCtx) {
                new Chart(conversionCtx, {
                    type: 'doughnut',
                    data: {
                        labels: ['Post to View', 'View to Click', 'Click to Message', 'Message to Conversion'],
                        datasets: [{
                            data: [100, 80, 60, 40],
                            backgroundColor: ['#7c3aed', '#10b981', '#f59e0b', '#ef4444']
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }

            const categoryCtx = document.getElementById('categoryPerformanceChart')?.getContext('2d');
            if (categoryCtx) {
                new Chart(categoryCtx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Category Performance',
                            data: [],
                            borderColor: '#7c3aed',
                            backgroundColor: 'rgba(124, 58, 237, 0.1)',
                            borderWidth: 2,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }
        }

        function initializeIndividualAdsCharts() {
            const performanceCtx = document.getElementById('individualAdPerformanceChart')?.getContext('2d');
            if (performanceCtx) {
                new Chart(performanceCtx, {
                    type: 'bar',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Individual Ad Performance',
                            data: [],
                            backgroundColor: '#7c3aed'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }

            const engagementCtx = document.getElementById('engagementAnalysisChart')?.getContext('2d');
            if (engagementCtx) {
                new Chart(engagementCtx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Engagement Analysis',
                            data: [],
                            borderColor: '#10b981',
                            backgroundColor: 'rgba(16, 185, 129, 0.1)',
                            borderWidth: 2,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }
        }

        function initializeFunnelsCharts() {
            const funnelCtx = document.getElementById('funnelVisualizationChart')?.getContext('2d');
            if (funnelCtx) {
                new Chart(funnelCtx, {
                    type: 'doughnut',
                    data: {
                        labels: ['Registration', 'Profile Setup', 'First Ad', 'Payment'],
                        datasets: [{
                            data: [100, 80, 60, 40],
                            backgroundColor: ['#7c3aed', '#10b981', '#f59e0b', '#ef4444']
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }

            const optimizationCtx = document.getElementById('optimizationOpportunitiesChart')?.getContext('2d');
            if (optimizationCtx) {
                new Chart(optimizationCtx, {
                    type: 'bar',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Optimization Opportunities',
                            data: [],
                            backgroundColor: '#f59e0b'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }
        }

        function initializeExportCharts() {
            const performanceCtx = document.getElementById('exportPerformanceChart')?.getContext('2d');
            if (performanceCtx) {
                new Chart(performanceCtx, {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'Export Performance',
                            data: [],
                            borderColor: '#7c3aed',
                            backgroundColor: 'rgba(124, 58, 237, 0.1)',
                            borderWidth: 2,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }

            const qualityCtx = document.getElementById('dataQualityChart')?.getContext('2d');
            if (qualityCtx) {
                new Chart(qualityCtx, {
                    type: 'doughnut',
                    data: {
                        labels: ['Good', 'Fair', 'Poor'],
                        datasets: [{
                            data: [80, 15, 5],
                            backgroundColor: ['#10b981', '#f59e0b', '#ef4444']
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }
        }

        // Data loading functions for each section
        function loadAnalyticsData() {
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            const reportType = document.getElementById('report-type').value;

            try {
                // Load Business Intelligence Dashboard
                const biData = {
                    kpi_overview: {
                        total_revenue: 245000,
                        active_users: 1234,
                        conversion_rate: 3.2,
                        arpu: 198.50,
                        revenue_growth_rate: 12.5,
                        user_growth_rate: 8.3,
                        conversion_rate_change: 0.5,
                        arpu_change: 6.2
                    },
                    revenue_analytics: {
                        daily_revenue: generateDummyRevenueData()
                    },
                    user_behavior_analysis: {
                        feature_usage: getDummyFeatureUsage()
                    },
                    market_trends: {
                        category_trends: getDummyCategoryTrends()
                    },
                    conversion_funnels: {
                        conversion_funnels: [1000, 750, 450, 200]
                    },
                    customer_lifetime_value: {
                        high_value_customers: getDummyCLVData()
                    }
                };

                updateKPIs(biData.kpi_overview);
                updateRevenueChart(biData.revenue_analytics);
                updateUserBehavior(biData.user_behavior_analysis);
                updateMarketTrends(biData.market_trends);
                updateConversionFunnels(biData.conversion_funnels);
                updateCLV(biData.customer_lifetime_value);

                // Update insights
                updatePredictiveInsights(getFallbackInsights());
                updateExecutiveSummary(getFallbackSummary());

            } catch (error) {
                console.error('Error loading analytics data:', error);
                loadFallbackData();
            }
        }

        function loadAdPostAnalyticsData() {
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            const enableComparison = document.getElementById('enable-comparison').checked;

            try {
                // Load Ad Post Analytics data with comparison support
                const adPostData = {
                    total_ads: 1234,
                    active_ads: 987,
                    total_views: 45678,
                    avg_ctr: 3.2,
                    ads_growth: 12.5,
                    active_growth: 8.3,
                    views_growth: 15.2,
                    ctr_change: 0.5
                };

                // Update KPIs
                document.getElementById('total-ads').textContent = adPostData.total_ads.toLocaleString();
                document.getElementById('active-ads').textContent = adPostData.active_ads.toLocaleString();
                document.getElementById('total-views').textContent = adPostData.total_views.toLocaleString();
                document.getElementById('avg-ctr').textContent = `${adPostData.avg_ctr}%`;
                
                document.getElementById('ads-growth').textContent = `${adPostData.ads_growth > 0 ? '+' : ''}${adPostData.ads_growth.toFixed(1)}% from last month`;
                document.getElementById('active-growth').textContent = `${adPostData.active_growth > 0 ? '+' : ''}${adPostData.active_growth.toFixed(1)}% from last month`;
                document.getElementById('views-growth').textContent = `${adPostData.views_growth > 0 ? '+' : ''}${adPostData.views_growth.toFixed(1)}% from last month`;
                document.getElementById('ctr-change').textContent = `${adPostData.ctr_change > 0 ? '+' : ''}${adPostData.ctr_change.toFixed(1)}% from last month`;

                // Update charts with ad-specific data
                updateAdEngagementChart();
                updateAdConversionChart();
                updateCategoryPerformanceChart();

                // Load Ad Optimization Recommendations
                loadAdOptimizationRecommendations();

            } catch (error) {
                console.error('Error loading Ad Post Analytics data:', error);
                loadFallbackAdPostData();
            }
        }

        function loadIndividualAdsAnalyticsData() {
            // Load Individual Ads Analytics data
            document.getElementById('total-individual-ads').textContent = '856';
            document.getElementById('high-performing-ads').textContent = '124';
            document.getElementById('avg-engagement').textContent = '4.2';
            document.getElementById('individual-conversion-rate').textContent = '2.8%';
            
            document.getElementById('individual-ads-growth').textContent = '+9.7% from last month';
            document.getElementById('high-performing-growth').textContent = '+15.3% from last month';
            document.getElementById('engagement-growth').textContent = '+6.1% from last month';
            document.getElementById('individual-conversion-change').textContent = '+0.3% from last month';
        }

        function loadFunnelsAnalyticsData() {
            // Load Funnels Analytics data
            document.getElementById('funnel-completion').textContent = '23.5%';
            document.getElementById('drop-off-rate').textContent = '76.5%';
            document.getElementById('optimization-score').textContent = '7/10';
            document.getElementById('funnel-revenue').textContent = '₹125,000';
            
            document.getElementById('funnel-completion-growth').textContent = '+3.2% from last month';
            document.getElementById('drop-off-growth').textContent = '-2.1% from last month';
            document.getElementById('optimization-growth').textContent = '+1 from last month';
            document.getElementById('funnel-revenue-growth').textContent = '+8.7% from last month';
        }

        function loadExportAnalyticsData() {
            // Load Export Analytics data
            document.getElementById('total-exports').textContent = '156';
            document.getElementById('export-formats').textContent = '4';
            document.getElementById('data-quality').textContent = '94%';
            document.getElementById('export-revenue').textContent = '₹45,000';
            
            document.getElementById('exports-growth').textContent = '+12.8% from last month';
            document.getElementById('formats-growth').textContent = '+1 from last month';
            document.getElementById('quality-growth').textContent = '+2.1% from last month';
            document.getElementById('export-revenue-growth').textContent = '+15.3% from last month';
        }

        function refreshCurrentSection() {
            switch(currentSection) {
                case 'overview':
                    loadAnalyticsData();
                    break;
                case 'ad-post':
                    loadAdPostAnalyticsData();
                    break;
                case 'individual-ads':
                    loadIndividualAdsAnalyticsData();
                    break;
                case 'funnels':
                    loadFunnelsAnalyticsData();
                    break;
                case 'export':
                    loadExportAnalyticsData();
                    break;
            }
        }

        // Enhanced Date Range and Comparison Functions
        function setDateRange(range) {
            const today = new Date();
            const startInput = document.getElementById('start-date');
            const endInput = document.getElementById('end-date');
            
            // Remove active class from all buttons
            document.querySelectorAll('.date-btn').forEach(btn => btn.classList.remove('active'));
            // Add active class to clicked button
            event.target.classList.add('active');

            let startDate, endDate;

            switch(range) {
                case 'today':
                    startDate = endDate = today.toISOString().split('T')[0];
                    break;
                case 'yesterday':
                    const yesterday = new Date(today);
                    yesterday.setDate(yesterday.getDate() - 1);
                    startDate = endDate = yesterday.toISOString().split('T')[0];
                    break;
                case 'last_7_days':
                    startDate = new Date(today);
                    startDate.setDate(startDate.getDate() - 6);
                    endDate = today;
                    break;
                case 'last_30_days':
                    startDate = new Date(today);
                    startDate.setDate(startDate.getDate() - 29);
                    endDate = today;
                    break;
                case 'this_month':
                    startDate = new Date(today.getFullYear(), today.getMonth(), 1);
                    endDate = today;
                    break;
                case 'last_month':
                    const lastMonth = new Date(today);
                    lastMonth.setMonth(lastMonth.getMonth() - 1);
                    startDate = new Date(lastMonth.getFullYear(), lastMonth.getMonth(), 1);
                    endDate = new Date(lastMonth.getFullYear(), lastMonth.getMonth() + 1, 0);
                    break;
                case 'this_year':
                    startDate = new Date(today.getFullYear(), 0, 1);
                    endDate = today;
                    break;
                case 'last_year':
                    const lastYear = new Date(today);
                    lastYear.setFullYear(lastYear.getFullYear() - 1);
                    startDate = new Date(lastYear.getFullYear(), 0, 1);
                    endDate = new Date(lastYear.getFullYear(), 11, 31);
                    break;
            }

            startInput.value = startDate.toISOString().split('T')[0];
            endInput.value = endDate.toISOString().split('T')[0];

            // Update comparison info text
            updateComparisonInfo(range);

            // Refresh current section with new date range
            refreshCurrentSection();
        }

        function updateComparisonInfo(range) {
            const comparisonText = document.getElementById('comparison-period-text');
            const comparisonInfo = document.getElementById('comparison-info');
            const enableComparison = document.getElementById('enable-comparison');

            if (enableComparison.checked) {
                comparisonInfo.style.display = 'block';
                
                switch(range) {
                    case 'today':
                        comparisonText.textContent = 'Today vs Yesterday';
                        break;
                    case 'yesterday':
                        comparisonText.textContent = 'Yesterday vs Day Before';
                        break;
                    case 'last_7_days':
                        comparisonText.textContent = 'Last 7 Days vs Previous 7 Days';
                        break;
                    case 'last_30_days':
                        comparisonText.textContent = 'Last 30 Days vs Previous 30 Days';
                        break;
                    case 'this_month':
                        comparisonText.textContent = 'This Month vs Last Month';
                        break;
                    case 'last_month':
                        comparisonText.textContent = 'Last Month vs Month Before';
                        break;
                    case 'this_year':
                        comparisonText.textContent = 'This Year vs Last Year';
                        break;
                    case 'last_year':
                        comparisonText.textContent = 'Last Year vs Year Before';
                        break;
                }
            } else {
                comparisonInfo.style.display = 'none';
            }
        }

        function toggleComparison() {
            const comparisonInfo = document.getElementById('comparison-info');
            const enableComparison = document.getElementById('enable-comparison');
            
            if (enableComparison.checked) {
                comparisonInfo.style.display = 'block';
                // Refresh with comparison enabled
                refreshCurrentSection();
            } else {
                comparisonInfo.style.display = 'none';
                // Refresh without comparison
                refreshCurrentSection();
            }
        }

        function exportCurrentSection() {
            const section = currentSection;
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            const enableComparison = document.getElementById('enable-comparison').checked;

            // Create export data based on current section
            const exportData = {
                section: section,
                startDate: startDate,
                endDate: endDate,
                includeComparison: enableComparison,
                format: 'excel'
            };

            // For now, show alert with export details
            alert(`Exporting ${section} analytics data:\nDate Range: ${startDate} to ${endDate}\nInclude Comparison: ${enableComparison ? 'Yes' : 'No'}\nFormat: Excel`);
            
            // In a real implementation, this would make an API call to export the data
            console.log('Export data:', exportData);
        }

        // Helper functions (same as before)
        function generateDummyRevenueData() {
            const data = [];
            const today = new Date();
            for (let i = 14; i >= 0; i--) {
                const date = new Date(today);
                date.setDate(date.getDate() - i);
                data.push({
                    date: date.toISOString().split('T')[0],
                    revenue: Math.floor(Math.random() * 20000) + 10000
                });
            }
            return data;
        }

        function getDummyFeatureUsage() {
            return [
                { event_type: 'Ad Post', count: 156 },
                { event_type: 'User Registration', count: 89 },
                { event_type: 'Chat Messages', count: 1234 },
                { event_type: 'Profile Views', count: 2345 },
                { event_type: 'Search Queries', count: 5678 }
            ];
        }

        function getDummyCategoryTrends() {
            return [
                { category_id: 'Electronics', count: 1250 },
                { category_id: 'Vehicles', count: 980 },
                { category_id: 'Real Estate', count: 750 },
                { category_id: 'Jobs', count: 620 },
                { category_id: 'Services', count: 480 }
            ];
        }

        function getDummyCLVData() {
            return [
                { user_id: 101, total_spent: 15000 },
                { user_id: 205, total_spent: 8500 },
                { user_id: 312, total_spent: 12000 },
                { user_id: 419, total_spent: 6500 }
            ];
        }

        function getFallbackInsights() {
            return {
                trends: { revenue_trend: 'Growing' },
                opportunities: { 
                    high_demand_categories: ['Electronics', 'Vehicles'],
                    feature_improvement_opportunities: ['Mobile App', 'Search Filters']
                },
                risks: { churn_risk: 'Low' }
            };
        }

        function getFallbackSummary() {
            return {
                top_performers: { top_categories: ['Electronics', 'Vehicles', 'Real Estate'] },
                recommendations: ['Improve mobile experience', 'Add more payment options', 'Enhance search functionality']
            };
        }

        function updateKPIs(kpiData) {
            document.getElementById('total-revenue').textContent = `₹${kpiData.total_revenue.toLocaleString()}`;
            document.getElementById('active-users').textContent = kpiData.active_users.toLocaleString();
            document.getElementById('conversion-rate').textContent = `${kpiData.conversion_rate.toFixed(2)}%`;
            document.getElementById('arpu').textContent = `₹${kpiData.arpu.toFixed(2)}`;
            
            document.getElementById('revenue-growth').textContent = `${kpiData.revenue_growth_rate > 0 ? '+' : ''}${kpiData.revenue_growth_rate.toFixed(1)}% from last month`;
            document.getElementById('user-growth').textContent = `${kpiData.user_growth_rate > 0 ? '+' : ''}${kpiData.user_growth_rate.toFixed(1)}% from last month`;
            document.getElementById('conversion-change').textContent = `${kpiData.conversion_rate > 0 ? '+' : ''}${kpiData.conversion_rate.toFixed(1)}% from last month`;
            document.getElementById('arpu-change').textContent = `${kpiData.arpu > 0 ? '+' : ''}${kpiData.arpu.toFixed(1)}% from last month`;
        }

        function updateRevenueChart(revenueData) {
            if (revenueChart && revenueData.daily_revenue) {
                const labels = revenueData.daily_revenue.map(item => item.date);
                const data = revenueData.daily_revenue.map(item => item.revenue);

                revenueChart.data.labels = labels;
                revenueChart.data.datasets[0].data = data;
                revenueChart.update();
            }
        }

        function updateUserBehavior(behaviorData) {
            const tableBody = document.getElementById('user-behavior-table');
            if (tableBody && behaviorData.feature_usage) {
                tableBody.innerHTML = '';
                behaviorData.feature_usage.forEach(feature => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td style="font-weight: 600;">${feature.event_type}</td>
                        <td>${feature.count.toLocaleString()}</td>
                        <td><span class="status-badge status-active">Active</span></td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        }

        function updateMarketTrends(trendsData) {
            if (marketTrendsChart && trendsData.category_trends) {
                const categories = [...new Set(trendsData.category_trends.map(trend => trend.category_id))];
                const counts = categories.map(cat => 
                    trendsData.category_trends
                        .filter(trend => trend.category_id === cat)
                        .reduce((sum, trend) => sum + trend.count, 0)
                );

                marketTrendsChart.data.labels = categories;
                marketTrendsChart.data.datasets[0].data = counts;
                marketTrendsChart.update();
            }
        }

        function updateConversionFunnels(funnelData) {
            if (conversionFunnelChart) {
                conversionFunnelChart.data.datasets[0].data = [100, 80, 60, 40];
                conversionFunnelChart.update();
            }
        }

        function updateCLV(clvData) {
            const tableBody = document.getElementById('clv-table');
            if (tableBody && clvData.high_value_customers) {
                tableBody.innerHTML = '';
                clvData.high_value_customers.forEach(customer => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td style="font-weight: 600;">User ${customer.user_id}</td>
                        <td>₹${customer.total_spent.toLocaleString()}</td>
                        <td>High Value</td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        }

        function updatePredictiveInsights(insights) {
            document.getElementById('revenue-forecast').textContent = insights.trends.revenue_trend || 'Stable';
            document.getElementById('user-acquisition').textContent = insights.opportunities.high_demand_categories?.join(', ') || 'Normal';
            document.getElementById('churn-risk').textContent = insights.risks.churn_risk || 'Low';
            document.getElementById('opportunities').textContent = insights.opportunities.feature_improvement_opportunities?.join(', ') || 'None identified';
        }

        function updateExecutiveSummary(summary) {
            document.getElementById('top-performers').textContent = summary.top_performers.top_categories?.join(', ') || 'Loading...';
            document.getElementById('risks-identified').textContent = summary.recommendations?.length || 0 + ' risks identified';
            document.getElementById('recommendations').textContent = summary.recommendations?.length || 0 + ' recommendations available';
        }

        async function exportAnalytics() {
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            const reportType = document.getElementById('report-type').value;

            try {
                const response = await fetch(`/api/analytics/export?start_date=${startDate}&end_date=${endDate}&report_type=${reportType}`);
                const blob = await response.blob();
                
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `analytics-report-${new Date().toISOString().split('T')[0]}.pdf`;
                document.body.appendChild(a);
                a.click();
                a.remove();
                window.URL.revokeObjectURL(url);
            } catch (error) {
                console.error('Error exporting analytics:', error);
                alert('Error exporting analytics. Please try again.');
            }
        }

        async function exportAnalyticsData() {
            const format = document.getElementById('export-format').value;
            const range = document.getElementById('data-range').value;

            try {
                const response = await fetch(`/api/analytics/export-data?format=${format}&range=${range}`);
                const blob = await response.blob();
                
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `analytics-data-${new Date().toISOString().split('T')[0]}.${format}`;
                document.body.appendChild(a);
                a.click();
                a.remove();
                window.URL.revokeObjectURL(url);
            } catch (error) {
                console.error('Error exporting analytics data:', error);
                alert('Error exporting analytics data. Please try again.');
            }
        }

        function scheduleExport() {
            alert('Export scheduled successfully!');
        }

        function refreshAnalytics() {
            refreshCurrentSection();
        }

        function loadFallbackData() {
            // Update KPIs with realistic dummy data
            document.getElementById('total-revenue').textContent = '₹245,000';
            document.getElementById('active-users').textContent = '1,234';
            document.getElementById('conversion-rate').textContent = '3.2%';
            document.getElementById('arpu').textContent = '₹198.50';
            
            document.getElementById('revenue-growth').textContent = '+12.5% from last month';
            document.getElementById('user-growth').textContent = '+8.3% from last month';
            document.getElementById('conversion-change').textContent = '+0.5% from last month';
            document.getElementById('arpu-change').textContent = '+6.2% from last month';

            // Update charts with dummy data
            updateRevenueChart({ daily_revenue: generateDummyRevenueData() });
            updateUserBehavior({ feature_usage: getDummyFeatureUsage() });
            updateMarketTrends({ category_trends: getDummyCategoryTrends() });
            updateConversionFunnels({ conversion_funnels: getDummyFunnelData() });
            updateCLV({ high_value_customers: getDummyCLVData() });
        }

        function getDummyFunnelData() {
            return { conversion_funnels: [1000, 750, 450, 200] };
        }

        // Ad Post Analytics Chart Update Functions
        function updateAdEngagementChart() {
            const engagementCtx = document.getElementById('adEngagementChart')?.getContext('2d');
            if (engagementCtx) {
                const chart = Chart.getChart('adEngagementChart');
                if (chart) {
                    chart.data.datasets[0].data = [1234, 567, 45678, 890];
                    chart.update();
                }
            }
        }

        function updateAdConversionChart() {
            const conversionCtx = document.getElementById('adConversionChart')?.getContext('2d');
            if (conversionCtx) {
                const chart = Chart.getChart('adConversionChart');
                if (chart) {
                    chart.data.datasets[0].data = [100, 85, 65, 45];
                    chart.update();
                }
            }
        }

        function updateCategoryPerformanceChart() {
            const categoryCtx = document.getElementById('categoryPerformanceChart')?.getContext('2d');
            if (categoryCtx) {
                const chart = Chart.getChart('categoryPerformanceChart');
                if (chart) {
                    chart.data.labels = ['Electronics', 'Vehicles', 'Real Estate', 'Jobs', 'Services'];
                    chart.data.datasets[0].data = [1250, 980, 750, 620, 480];
                    chart.update();
                }
            }
        }

        // Ad Optimization Recommendations
        function loadAdOptimizationRecommendations() {
            const recommendations = {
                high_priority: [
                    {
                        title: 'Improve Click-Through Rate',
                        description: 'Your ad has a low CTR. Consider improving the title and adding high-quality images.',
                        impact: 'High',
                        effort: 'Medium',
                        expected_improvement: 'CTR could improve by 50-100%'
                    },
                    {
                        title: 'Optimize Conversion Funnel',
                        description: 'Low conversion rate indicates issues with ad content or pricing.',
                        impact: 'High',
                        effort: 'High',
                        expected_improvement: 'Conversions could improve by 30-60%'
                    }
                ],
                medium_priority: [
                    {
                        title: 'Improve Ad Content Engagement',
                        description: 'Users are leaving quickly. Add more detailed descriptions and better images.',
                        impact: 'Medium',
                        effort: 'Low',
                        expected_improvement: 'Session time could increase by 40-80%'
                    },
                    {
                        title: 'Optimize Posting Time',
                        description: 'Post during peak hours (7-9 AM, 6-8 PM) for better visibility.',
                        impact: 'Medium',
                        effort: 'Low',
                        expected_improvement: 'Views could increase by 20-40%'
                    },
                    {
                        title: 'Use Premium Features',
                        description: 'Consider using Featured Ad or Boost Promotion for better visibility.',
                        impact: 'Medium',
                        effort: 'Low',
                        expected_improvement: 'Visibility could increase by 200-400%'
                    }
                ],
                low_priority: [
                    {
                        title: 'Update Images Regularly',
                        description: 'Fresh images can improve engagement and prevent ad fatigue.',
                        impact: 'Low',
                        effort: 'Low',
                        expected_improvement: 'Engagement could improve by 10-20%'
                    },
                    {
                        title: 'Monitor Competitor Pricing',
                        description: 'Keep an eye on similar listings to stay competitive.',
                        impact: 'Low',
                        effort: 'Medium',
                        expected_improvement: 'Sales could improve by 5-15%'
                    }
                ]
            };

            // Update high priority recommendations
            const highPriorityContainer = document.getElementById('high-priority-recommendations');
            if (highPriorityContainer) {
                highPriorityContainer.innerHTML = '';
                recommendations.high_priority.forEach(rec => {
                    const recDiv = document.createElement('div');
                    recDiv.style.marginBottom = '12px';
                    recDiv.style.padding = '8px';
                    recDiv.style.backgroundColor = '#fef2f2';
                    recDiv.style.border = '1px solid #fecaca';
                    recDiv.style.borderRadius = '6px';
                    recDiv.innerHTML = `
                        <div style="font-weight: 600; color: #dc2626; margin-bottom: 4px;">${rec.title}</div>
                        <div style="font-size: 0.75rem; color: #7f1d1d; margin-bottom: 4px;">${rec.description}</div>
                        <div style="font-size: 0.75rem; color: #ef4444;">
                            Impact: ${rec.impact} | Effort: ${rec.effort} | Expected: ${rec.expected_improvement}
                        </div>
                    `;
                    highPriorityContainer.appendChild(recDiv);
                });
            }

            // Update medium priority recommendations
            const mediumPriorityContainer = document.getElementById('medium-priority-recommendations');
            if (mediumPriorityContainer) {
                mediumPriorityContainer.innerHTML = '';
                recommendations.medium_priority.forEach(rec => {
                    const recDiv = document.createElement('div');
                    recDiv.style.marginBottom = '12px';
                    recDiv.style.padding = '8px';
                    recDiv.style.backgroundColor = '#fffbeb';
                    recDiv.style.border = '1px solid #fde68a';
                    recDiv.style.borderRadius = '6px';
                    recDiv.innerHTML = `
                        <div style="font-weight: 600; color: #d97706; margin-bottom: 4px;">${rec.title}</div>
                        <div style="font-size: 0.75rem; color: #92400e; margin-bottom: 4px;">${rec.description}</div>
                        <div style="font-size: 0.75rem; color: #f59e0b;">
                            Impact: ${rec.impact} | Effort: ${rec.effort} | Expected: ${rec.expected_improvement}
                        </div>
                    `;
                    mediumPriorityContainer.appendChild(recDiv);
                });
            }

            // Update low priority recommendations
            const lowPriorityContainer = document.getElementById('low-priority-recommendations');
            if (lowPriorityContainer) {
                lowPriorityContainer.innerHTML = '';
                recommendations.low_priority.forEach(rec => {
                    const recDiv = document.createElement('div');
                    recDiv.style.marginBottom = '12px';
                    recDiv.style.padding = '8px';
                    recDiv.style.backgroundColor = '#f0fdf4';
                    recDiv.style.border = '1px solid #bbf7d0';
                    recDiv.style.borderRadius = '6px';
                    recDiv.innerHTML = `
                        <div style="font-weight: 600; color: #166534; margin-bottom: 4px;">${rec.title}</div>
                        <div style="font-size: 0.75rem; color: #14532d; margin-bottom: 4px;">${rec.description}</div>
                        <div style="font-size: 0.75rem; color: #22c55e;">
                            Impact: ${rec.impact} | Effort: ${rec.effort} | Expected: ${rec.expected_improvement}
                        </div>
                    `;
                    lowPriorityContainer.appendChild(recDiv);
                });
            }
        }

        function loadFallbackAdPostData() {
            // Update KPIs with fallback data
            document.getElementById('total-ads').textContent = '1,234';
            document.getElementById('active-ads').textContent = '987';
            document.getElementById('total-views').textContent = '45,678';
            document.getElementById('avg-ctr').textContent = '3.2%';
            
            document.getElementById('ads-growth').textContent = '+12.5% from last month';
            document.getElementById('active-growth').textContent = '+8.3% from last month';
            document.getElementById('views-growth').textContent = '+15.2% from last month';
            document.getElementById('ctr-change').textContent = '+0.5% from last month';

            // Update charts with fallback data
            updateAdEngagementChart();
            updateAdConversionChart();
            updateCategoryPerformanceChart();
            loadAdOptimizationRecommendations();
        }
    </script>

    <style>
        .analytics-dashboard {
            animation: fadeIn 0.5s ease-in;
        }

        .analytics-navigation {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 24px;
        }

        .nav-tab {
            padding: 8px 16px;
            border-radius: 8px;
            text-decoration: none;
            color: var(--text-secondary);
            font-weight: 500;
            transition: all 0.2s ease;
            border: 1px solid transparent;
        }

        .nav-tab:hover {
            background: var(--bg-color);
            color: var(--text-primary);
        }

        .nav-tab.active {
            background: #f3e8ff;
            color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .analytics-controls {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 24px;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 999px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .status-active {
            background-color: #dcfce7;
            color: #166534;
        }

        .insights-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .insight-item {
            background: #f8fafc;
            padding: 16px;
            border-radius: 8px;
            border-left: 4px solid var(--primary-color);
        }

        .summary-card {
            background: #f8fafc;
            padding: 16px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .recommendation-card {
            background: var(--bg-color);
            padding: 16px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .insight-card {
            background: #f8fafc;
            padding: 16px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .optimization-card {
            background: #f8fafc;
            padding: 16px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            transition: all 0.2s;
        }

        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 6px var(--shadow-color);
        }

        /* Enhanced Date Range Controls */
        .date-btn {
            padding: 6px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background: var(--card-bg);
            color: var(--text-primary);
            font-size: 0.875rem;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 500;
        }

        .date-btn:hover {
            background: var(--bg-color);
            border-color: var(--primary-color);
            color: var(--text-primary);
        }

        .date-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
            box-shadow: 0 2px 4px rgba(124, 58, 237, 0.3);
        }

        /* Comparison Toggle */
        .comparison-toggle {
            display: flex;
            align-items: center;
            cursor: pointer;
            user-select: none;
        }

        .comparison-toggle input[type="checkbox"] {
            display: none;
        }

        .toggle-slider {
            width: 40px;
            height: 20px;
            background-color: #ccc;
            border-radius: 20px;
            position: relative;
            transition: background-color 0.3s;
            margin-right: 8px;
        }

        .toggle-slider::after {
            content: '';
            position: absolute;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background-color: white;
            top: 2px;
            left: 2px;
            transition: transform 0.3s;
        }

        .comparison-toggle input[type="checkbox"]:checked + .toggle-slider {
            background-color: var(--primary-color);
        }

        .comparison-toggle input[type="checkbox"]:checked + .toggle-slider::after {
            transform: translateX(20px);
        }

        /* Enhanced Card Styles */
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .card-title {
            font-size: 0.875rem;
            color: var(--text-secondary);
            margin-bottom: 4px;
        }

        .card-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--text-primary);
        }

        .card-change {
            font-size: 0.875rem;
            color: #10b981;
            font-weight: 600;
        }

        .stat-icon {
            font-size: 1.5rem;
            opacity: 0.6;
        }

        /* Chart Cards */
        .chart-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 20px;
            height: 100%;
        }

        .table-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 20px;
            height: 100%;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th {
            text-align: left;
            font-size: 0.875rem;
            color: var(--text-secondary);
            font-weight: 600;
            padding-bottom: 8px;
            border-bottom: 1px solid var(--border-color);
        }

        .table td {
            padding: 8px 0;
            font-size: 0.875rem;
            color: var(--text-primary);
            border-bottom: 1px solid var(--border-color);
        }

        /* Dashboard Grid */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 24px;
        }

        .content-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
            margin-bottom: 24px;
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .dashboard-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .dashboard-grid {
                grid-template-columns: 1fr;
            }
            
            .content-grid {
                grid-template-columns: 1fr;
            }
            
            .date-btn {
                padding: 4px 8px;
                font-size: 0.75rem;
            }
            
            .analytics-controls {
                padding: 16px;
            }
        }

        @media (max-width: 480px) {
            .analytics-controls {
                padding: 12px;
            }
            
            .date-btn {
                padding: 3px 6px;
                font-size: 0.7rem;
            }
        }

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

        @media (max-width: 768px) {
            .dashboard-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .content-grid {
                grid-template-columns: 1fr;
            }
            
            .insights-container {
                grid-template-columns: 1fr;
            }
        }
    </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/analytics.blade.php ENDPATH**/ ?>