@extends('admin.layouts.app')

@section('title', 'Individual Ad Analytics')

@section('content')
    <!-- Individual Ad Analytics Dashboard -->
    <div class="analytics-dashboard">
        <!-- Ad Header Section -->
        <div class="ad-header">
            <div class="ad-info">
                <div class="ad-title">{{ $ad->title }}</div>
                <div class="ad-meta">
                    <span class="category">{{ $ad->category->name }}</span>
                    <span class="price">{{ $ad->currency }} {{ number_format($ad->price, 2) }}</span>
                    <span class="status status-{{ $ad->status }}">{{ ucfirst($ad->status) }}</span>
                </div>
                <div class="ad-location">
                    <i class="fas fa-map-marker-alt"></i>
                    {{ $ad->city }}, {{ $ad->state }}, {{ $ad->country }}
                </div>
            </div>
            <div class="ad-actions">
                <button onclick="exportAnalytics('pdf')" class="btn-export">📄 PDF Report</button>
                <button onclick="exportAnalytics('excel')" class="btn-export">📊 Excel Report</button>
                <button onclick="exportAnalytics('csv')" class="btn-export">📈 CSV Report</button>
                <button onclick="exportAnalytics('json')" class="btn-export">📋 JSON Report</button>
            </div>
        </div>

        <!-- Date Range Controls -->
        <div class="date-controls">
            <div class="date-group">
                <label>Start Date:</label>
                <input type="date" id="start-date" onchange="updateAnalytics()">
            </div>
            <div class="date-group">
                <label>End Date:</label>
                <input type="date" id="end-date" onchange="updateAnalytics()">
            </div>
            <div class="date-group">
                <label>Quick Range:</label>
                <select id="date-range" onchange="applyDateRange(this.value)">
                    <option value="today">Today</option>
                    <option value="yesterday">Yesterday</option>
                    <option value="last-7-days">Last 7 Days</option>
                    <option value="last-30-days">Last 30 Days</option>
                    <option value="this-month">This Month</option>
                    <option value="last-month">Last Month</option>
                </select>
            </div>
        </div>

        <!-- Performance Score Section -->
        <div class="performance-score">
            <div class="score-card">
                <div class="score-circle" id="performance-score">0</div>
                <div class="score-label">Performance Score</div>
                <div class="score-tier" id="score-tier">Loading...</div>
            </div>
            <div class="score-details">
                <div class="detail-item">
                    <span class="detail-label">Views:</span>
                    <span class="detail-value" id="total-views">0</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">CTR:</span>
                    <span class="detail-value" id="ctr-value">0%</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Engagement:</span>
                    <span class="detail-value" id="engagement-value">0%</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Conversions:</span>
                    <span class="detail-value" id="conversion-value">0</span>
                </div>
            </div>
        </div>

        <!-- Main Analytics Grid -->
        <div class="analytics-grid">
            <!-- Performance Metrics -->
            <div class="analytics-card">
                <div class="card-header">
                    <h3>📊 Performance Metrics</h3>
                    <div class="card-actions">
                        <button onclick="toggleChart('performance')">Toggle Chart</button>
                    </div>
                </div>
                <div class="card-content">
                    <div class="metrics-grid">
                        <div class="metric-item">
                            <div class="metric-label">Total Impressions</div>
                            <div class="metric-value" id="impressions">0</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">Unique Views</div>
                            <div class="metric-value" id="unique-views">0</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">Total Clicks</div>
                            <div class="metric-value" id="total-clicks">0</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">Click-Through Rate</div>
                            <div class="metric-value" id="ctr">0%</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">Engagement Rate</div>
                            <div class="metric-value" id="engagement-rate">0%</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">Time Spent (avg)</div>
                            <div class="metric-value" id="time-spent">0s</div>
                        </div>
                    </div>
                    <div class="chart-container">
                        <canvas id="performance-chart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- Geographic Analytics -->
            <div class="analytics-card">
                <div class="card-header">
                    <h3>🌍 Geographic Analytics</h3>
                    <div class="card-actions">
                        <button onclick="toggleChart('geographic')">Toggle Chart</button>
                    </div>
                </div>
                <div class="card-content">
                    <div class="geo-stats">
                        <div class="geo-item">
                            <div class="geo-label">Top Country</div>
                            <div class="geo-value" id="top-country">-</div>
                        </div>
                        <div class="geo-item">
                            <div class="geo-label">Top City</div>
                            <div class="geo-value" id="top-city">-</div>
                        </div>
                        <div class="geo-item">
                            <div class="geo-label">Coverage</div>
                            <div class="geo-value" id="coverage">0 countries</div>
                        </div>
                    </div>
                    <div class="chart-container">
                        <canvas id="geographic-chart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- Temporal Analytics -->
            <div class="analytics-card">
                <div class="card-header">
                    <h3>⏰ Temporal Analytics</h3>
                    <div class="card-actions">
                        <button onclick="toggleChart('temporal')">Toggle Chart</button>
                    </div>
                </div>
                <div class="card-content">
                    <div class="temporal-stats">
                        <div class="temporal-item">
                            <div class="temporal-label">Peak Hour</div>
                            <div class="temporal-value" id="peak-hour">-</div>
                        </div>
                        <div class="temporal-item">
                            <div class="temporal-label">Peak Day</div>
                            <div class="temporal-value" id="peak-day">-</div>
                        </div>
                        <div class="temporal-item">
                            <div class="temporal-label">Best Time</div>
                            <div class="temporal-value" id="best-time">-</div>
                        </div>
                    </div>
                    <div class="chart-container">
                        <canvas id="temporal-chart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- User Interaction Analytics -->
            <div class="analytics-card">
                <div class="card-header">
                    <h3>👥 User Interaction</h3>
                    <div class="card-actions">
                        <button onclick="toggleChart('interaction')">Toggle Chart</button>
                    </div>
                </div>
                <div class="card-content">
                    <div class="interaction-stats">
                        <div class="interaction-item">
                            <div class="interaction-label">Likes</div>
                            <div class="interaction-value" id="likes">0</div>
                        </div>
                        <div class="interaction-item">
                            <div class="interaction-label">Favorites</div>
                            <div class="interaction-value" id="favorites">0</div>
                        </div>
                        <div class="interaction-item">
                            <div class="interaction-label">Call Clicks</div>
                            <div class="interaction-value" id="call-clicks">0</div>
                        </div>
                        <div class="interaction-item">
                            <div class="interaction-label">WhatsApp Clicks</div>
                            <div class="interaction-value" id="whatsapp-clicks">0</div>
                        </div>
                    </div>
                    <div class="chart-container">
                        <canvas id="interaction-chart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- Chat Analytics -->
            <div class="analytics-card">
                <div class="card-header">
                    <h3>💬 Chat Analytics</h3>
                    <div class="card-actions">
                        <button onclick="toggleChart('chat')">Toggle Chart</button>
                        <button onclick="downloadChatTranscripts()" class="btn-secondary">📥 Download Transcripts</button>
                    </div>
                </div>
                <div class="card-content">
                    <div class="chat-stats">
                        <div class="chat-item">
                            <div class="chat-label">Total Chats</div>
                            <div class="chat-value" id="total-chats">0</div>
                        </div>
                        <div class="chat-item">
                            <div class="chat-label">Total Messages</div>
                            <div class="chat-value" id="total-messages">0</div>
                        </div>
                        <div class="chat-item">
                            <div class="chat-label">Avg Response Time</div>
                            <div class="chat-value" id="avg-response-time">0 min</div>
                        </div>
                        <div class="chat-item">
                            <div class="chat-label">Conversion Rate</div>
                            <div class="chat-value" id="chat-conversion-rate">0%</div>
                        </div>
                    </div>
                    <div class="chart-container">
                        <canvas id="chat-chart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- Engagement Analytics -->
            <div class="analytics-card">
                <div class="card-header">
                    <h3>🎯 Engagement Analytics</h3>
                    <div class="card-actions">
                        <button onclick="toggleChart('engagement')">Toggle Chart</button>
                    </div>
                </div>
                <div class="card-content">
                    <div class="engagement-stats">
                        <div class="engagement-item">
                            <div class="engagement-label">Share Count</div>
                            <div class="engagement-value" id="shares">0</div>
                        </div>
                        <div class="engagement-item">
                            <div class="engagement-label">Save Count</div>
                            <div class="engagement-value" id="saves">0</div>
                        </div>
                        <div class="engagement-item">
                            <div class="engagement-label">Report Count</div>
                            <div class="engagement-value" id="reports">0</div>
                        </div>
                        <div class="engagement-item">
                            <div class="engagement-label">Feedback Score</div>
                            <div class="engagement-value" id="feedback-score">0/5</div>
                        </div>
                    </div>
                    <div class="chart-container">
                        <canvas id="engagement-chart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- Revenue Analytics -->
            <div class="analytics-card">
                <div class="card-header">
                    <h3>💰 Revenue Analytics</h3>
                    <div class="card-actions">
                        <button onclick="toggleChart('revenue')">Toggle Chart</button>
                    </div>
                </div>
                <div class="card-content">
                    <div class="revenue-stats">
                        <div class="revenue-item">
                            <div class="revenue-label">Ad Spend</div>
                            <div class="revenue-value" id="ad-spend">₹0</div>
                        </div>
                        <div class="revenue-item">
                            <div class="revenue-label">Revenue Generated</div>
                            <div class="revenue-value" id="revenue-generated">₹0</div>
                        </div>
                        <div class="revenue-item">
                            <div class="revenue-label">ROI</div>
                            <div class="revenue-value" id="roi">0%</div>
                        </div>
                        <div class="revenue-item">
                            <div class="revenue-label">Cost Per Click</div>
                            <div class="revenue-value" id="cpc">₹0</div>
                        </div>
                    </div>
                    <div class="chart-container">
                        <canvas id="revenue-chart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- Recommendations -->
            <div class="analytics-card recommendations-card">
                <div class="card-header">
                    <h3>💡 Optimization Recommendations</h3>
                    <div class="card-actions">
                        <button onclick="refreshRecommendations()">🔄 Refresh</button>
                    </div>
                </div>
                <div class="card-content">
                    <div id="recommendations-list">
                        <!-- Recommendations will be loaded here -->
                    </div>
                </div>
            </div>
        </div>
    </div>

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

    <!-- Individual Ad Analytics JavaScript -->
    <script>
        let adId = {{ $ad->id }};
        let charts = {};

        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            // Set default date range to last 30 days
            const today = new Date();
            const last30Days = new Date();
            last30Days.setDate(today.getDate() - 30);
            
            document.getElementById('start-date').value = last30Days.toISOString().split('T')[0];
            document.getElementById('end-date').value = today.toISOString().split('T')[0];

            // Initialize charts
            initializeCharts();
            
            // Load initial data
            loadAnalyticsData();
        });

        function initializeCharts() {
            // Performance Chart
            const performanceCtx = document.getElementById('performance-chart').getContext('2d');
            charts.performance = new Chart(performanceCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Views',
                        data: [],
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        fill: true
                    }, {
                        label: 'Clicks',
                        data: [],
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true
                        }
                    }
                }
            });

            // Geographic Chart
            const geoCtx = document.getElementById('geographic-chart').getContext('2d');
            charts.geographic = new Chart(geoCtx, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });

            // Temporal Chart
            const temporalCtx = document.getElementById('temporal-chart').getContext('2d');
            charts.temporal = new Chart(temporalCtx, {
                type: 'bar',
                data: {
                    labels: ['12AM', '1AM', '2AM', '3AM', '4AM', '5AM', '6AM', '7AM', '8AM', '9AM', '10AM', '11AM', '12PM', '1PM', '2PM', '3PM', '4PM', '5PM', '6PM', '7PM', '8PM', '9PM', '10PM', '11PM'],
                    datasets: [{
                        label: 'Views by Hour',
                        data: [],
                        backgroundColor: '#3b82f6'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });

            // Interaction Chart
            const interactionCtx = document.getElementById('interaction-chart').getContext('2d');
            charts.interaction = new Chart(interactionCtx, {
                type: 'radar',
                data: {
                    labels: ['Likes', 'Favorites', 'Call Clicks', 'WhatsApp Clicks', 'Shares', 'Saves'],
                    datasets: [{
                        label: 'Interactions',
                        data: [],
                        borderColor: '#7c3aed',
                        backgroundColor: 'rgba(124, 58, 237, 0.2)',
                        pointBackgroundColor: '#7c3aed'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        r: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });

            // Chat Chart
            const chatCtx = document.getElementById('chat-chart').getContext('2d');
            charts.chat = new Chart(chatCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Messages per Day',
                        data: [],
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });

            // Engagement Chart
            const engagementCtx = document.getElementById('engagement-chart').getContext('2d');
            charts.engagement = new Chart(engagementCtx, {
                type: 'polarArea',
                data: {
                    labels: ['Shares', 'Saves', 'Reports', 'Feedback'],
                    datasets: [{
                        data: [],
                        backgroundColor: ['#3b82f6', '#10b981', '#ef4444', '#f59e0b']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });

            // Revenue Chart
            const revenueCtx = document.getElementById('revenue-chart').getContext('2d');
            charts.revenue = new Chart(revenueCtx, {
                type: 'bar',
                data: {
                    labels: ['Ad Spend', 'Revenue', 'ROI'],
                    datasets: [{
                        label: 'Amount (₹)',
                        data: [],
                        backgroundColor: ['#ef4444', '#10b981', '#3b82f6']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }

        async function loadAnalyticsData() {
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;

            try {
                // Load all analytics data
                const [
                    performanceResponse,
                    geographicResponse,
                    temporalResponse,
                    interactionResponse,
                    chatResponse,
                    engagementResponse,
                    revenueResponse
                ] = await Promise.all([
                    fetch(`/api/admin/analytics/ad/${adId}/performance?start_date=${startDate}&end_date=${endDate}`),
                    fetch(`/api/admin/analytics/ad/${adId}/geographic?start_date=${startDate}&end_date=${endDate}`),
                    fetch(`/api/admin/analytics/ad/${adId}/temporal?start_date=${startDate}&end_date=${endDate}`),
                    fetch(`/api/admin/analytics/ad/${adId}/interaction?start_date=${startDate}&end_date=${endDate}`),
                    fetch(`/api/admin/analytics/ad/${adId}/chat?start_date=${startDate}&end_date=${endDate}`),
                    fetch(`/api/admin/analytics/ad/${adId}/engagement?start_date=${startDate}&end_date=${endDate}`),
                    fetch(`/api/admin/analytics/ad/${adId}/revenue?start_date=${startDate}&end_date=${endDate}`)
                ]);

                const performanceData = await performanceResponse.json();
                const geographicData = await geographicResponse.json();
                const temporalData = await temporalResponse.json();
                const interactionData = await interactionResponse.json();
                const chatData = await chatResponse.json();
                const engagementData = await engagementResponse.json();
                const revenueData = await revenueResponse.json();

                // Update UI with data
                if (performanceData.success) updatePerformanceMetrics(performanceData.data);
                if (geographicData.success) updateGeographicAnalytics(geographicData.data);
                if (temporalData.success) updateTemporalAnalytics(temporalData.data);
                if (interactionData.success) updateInteractionAnalytics(interactionData.data);
                if (chatData.success) updateChatAnalytics(chatData.data);
                if (engagementData.success) updateEngagementAnalytics(engagementData.data);
                if (revenueData.success) updateRevenueAnalytics(revenueData.data);

                // Calculate and display performance score
                calculatePerformanceScore(performanceData.data);

                // Load recommendations
                loadRecommendations();

            } catch (error) {
                console.error('Error loading analytics data:', error);
                alert('Error loading analytics data. Please try again.');
            }
        }

        function updatePerformanceMetrics(data) {
            document.getElementById('impressions').textContent = data.impressions || 0;
            document.getElementById('unique-views').textContent = data.views?.unique || 0;
            document.getElementById('total-clicks').textContent = data.clicks?.total || 0;
            document.getElementById('ctr').textContent = (data.ctr || 0) + '%';
            document.getElementById('engagement-rate').textContent = (data.engagement_rate || 0) + '%';
            document.getElementById('time-spent').textContent = (data.time_spent_avg || 0) + 's';

            // Update chart
            if (data.time_series) {
                charts.performance.data.labels = data.time_series.labels;
                charts.performance.data.datasets[0].data = data.time_series.views;
                charts.performance.data.datasets[1].data = data.time_series.clicks;
                charts.performance.update();
            }
        }

        function updateGeographicAnalytics(data) {
            document.getElementById('top-country').textContent = data.top_country || '-';
            document.getElementById('top-city').textContent = data.top_city || '-';
            document.getElementById('coverage').textContent = (data.countries_count || 0) + ' countries';

            // Update chart
            if (data.locations) {
                charts.geographic.data.labels = data.locations.map(loc => loc.country);
                charts.geographic.data.datasets[0].data = data.locations.map(loc => loc.views);
                charts.geographic.update();
            }
        }

        function updateTemporalAnalytics(data) {
            document.getElementById('peak-hour').textContent = data.peak_hour || '-';
            document.getElementById('peak-day').textContent = data.peak_day || '-';
            document.getElementById('best-time').textContent = data.best_time || '-';

            // Update chart
            if (data.hourly_data) {
                charts.temporal.data.datasets[0].data = data.hourly_data;
                charts.temporal.update();
            }
        }

        function updateInteractionAnalytics(data) {
            document.getElementById('likes').textContent = data.likes || 0;
            document.getElementById('favorites').textContent = data.favorites || 0;
            document.getElementById('call-clicks').textContent = data.call_clicks || 0;
            document.getElementById('whatsapp-clicks').textContent = data.whatsapp_clicks || 0;

            // Update chart
            charts.interaction.data.datasets[0].data = [
                data.likes || 0,
                data.favorites || 0,
                data.call_clicks || 0,
                data.whatsapp_clicks || 0,
                data.shares || 0,
                data.saves || 0
            ];
            charts.interaction.update();
        }

        function updateChatAnalytics(data) {
            document.getElementById('total-chats').textContent = data.total_chats || 0;
            document.getElementById('total-messages').textContent = data.total_messages || 0;
            document.getElementById('avg-response-time').textContent = (data.avg_response_time || 0) + ' min';
            document.getElementById('chat-conversion-rate').textContent = (data.conversion_rate || 0) + '%';

            // Update chart
            if (data.daily_messages) {
                charts.chat.data.labels = data.daily_messages.labels;
                charts.chat.data.datasets[0].data = data.daily_messages.data;
                charts.chat.update();
            }
        }

        function updateEngagementAnalytics(data) {
            document.getElementById('shares').textContent = data.shares || 0;
            document.getElementById('saves').textContent = data.saves || 0;
            document.getElementById('reports').textContent = data.reports || 0;
            document.getElementById('feedback-score').textContent = (data.feedback_score || 0) + '/5';

            // Update chart
            charts.engagement.data.datasets[0].data = [
                data.shares || 0,
                data.saves || 0,
                data.reports || 0,
                data.feedback_score || 0
            ];
            charts.engagement.update();
        }

        function updateRevenueAnalytics(data) {
            document.getElementById('ad-spend').textContent = '₹' + (data.ad_spend || 0);
            document.getElementById('revenue-generated').textContent = '₹' + (data.revenue_generated || 0);
            document.getElementById('roi').textContent = (data.roi || 0) + '%';
            document.getElementById('cpc').textContent = '₹' + (data.cpc || 0);

            // Update chart
            charts.revenue.data.datasets[0].data = [
                data.ad_spend || 0,
                data.revenue_generated || 0,
                data.roi || 0
            ];
            charts.revenue.update();
        }

        function calculatePerformanceScore(data) {
            // Calculate performance score based on various metrics
            let score = 0;
            let maxScore = 100;

            // Base score
            score += 20;

            // CTR score (max 20 points)
            const ctr = data.ctr || 0;
            if (ctr > 5) score += 20;
            else if (ctr > 2) score += 15;
            else if (ctr > 1) score += 10;
            else if (ctr > 0.5) score += 5;

            // Engagement rate score (max 20 points)
            const engagement = data.engagement_rate || 0;
            if (engagement > 10) score += 20;
            else if (engagement > 5) score += 15;
            else if (engagement > 2) score += 10;
            else if (engagement > 1) score += 5;

            // Views score (max 20 points)
            const views = data.views?.total || 0;
            if (views > 1000) score += 20;
            else if (views > 500) score += 15;
            else if (views > 100) score += 10;
            else if (views > 50) score += 5;

            // Time spent score (max 20 points)
            const timeSpent = data.time_spent_avg || 0;
            if (timeSpent > 60) score += 20;
            else if (timeSpent > 30) score += 15;
            else if (timeSpent > 15) score += 10;
            else if (timeSpent > 5) score += 5;

            // Update UI
            const scoreElement = document.getElementById('performance-score');
            const tierElement = document.getElementById('score-tier');
            const totalViewsElement = document.getElementById('total-views');
            const ctrElement = document.getElementById('ctr-value');
            const engagementElement = document.getElementById('engagement-value');
            const conversionElement = document.getElementById('conversion-value');

            scoreElement.textContent = Math.round(score);
            totalViewsElement.textContent = data.views?.total || 0;
            ctrElement.textContent = (data.ctr || 0) + '%';
            engagementElement.textContent = (data.engagement_rate || 0) + '%';
            conversionElement.textContent = data.conversions || 0;

            // Set tier and color
            let tier = '';
            let color = '';
            if (score >= 90) {
                tier = 'Platinum Tier';
                color = '#e5e7eb';
            } else if (score >= 80) {
                tier = 'Gold Tier';
                color = '#f59e0b';
            } else if (score >= 70) {
                tier = 'Silver Tier';
                color = '#64748b';
            } else if (score >= 60) {
                tier = 'Bronze Tier';
                color = '#ef4444';
            } else {
                tier = 'Needs Improvement';
                color = '#ef4444';
            }

            tierElement.textContent = tier;
            scoreElement.style.color = color;
        }

        function loadRecommendations() {
            // Generate AI-powered recommendations based on analytics data
            const recommendations = [
                {
                    priority: 'high',
                    title: 'Optimize Ad Timing',
                    description: 'Your ad performs best between 6-8 PM. Consider boosting during these hours for maximum engagement.'
                },
                {
                    priority: 'medium',
                    title: 'Improve CTR',
                    description: 'Your CTR is below average. Try using more compelling images and clearer call-to-action text.'
                },
                {
                    priority: 'low',
                    title: 'Expand Geographic Reach',
                    description: 'Most of your views come from one location. Consider targeting nearby areas for growth.'
                }
            ];

            const container = document.getElementById('recommendations-list');
            container.innerHTML = recommendations.map(rec => `
                <div class="recommendation-item ${rec.priority}">
                    <div class="recommendation-header">
                        <span class="priority-badge ${rec.priority}">${rec.priority.toUpperCase()}</span>
                        <span class="recommendation-title">${rec.title}</span>
                    </div>
                    <div class="recommendation-description">${rec.description}</div>
                </div>
            `).join('');
        }

        function updateAnalytics() {
            loadAnalyticsData();
        }

        function applyDateRange(range) {
            const today = new Date();
            let startDate;

            switch(range) {
                case 'today':
                    startDate = today;
                    break;
                case 'yesterday':
                    startDate = new Date(today);
                    startDate.setDate(today.getDate() - 1);
                    break;
                case 'last-7-days':
                    startDate = new Date(today);
                    startDate.setDate(today.getDate() - 7);
                    break;
                case 'last-30-days':
                    startDate = new Date(today);
                    startDate.setDate(today.getDate() - 30);
                    break;
                case 'this-month':
                    startDate = new Date(today.getFullYear(), today.getMonth(), 1);
                    break;
                case 'last-month':
                    startDate = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                    const endDate = new Date(today.getFullYear(), today.getMonth(), 0);
                    document.getElementById('end-date').value = endDate.toISOString().split('T')[0];
                    break;
            }

            document.getElementById('start-date').value = startDate.toISOString().split('T')[0];
            loadAnalyticsData();
        }

        function toggleChart(chartName) {
            const chart = charts[chartName];
            if (chart) {
                chart.options.animation = false;
                chart.update();
            }
        }

        function exportAnalytics(format) {
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            const url = `/admin/analytics/ad/${adId}/export/${format}?start_date=${startDate}&end_date=${endDate}`;
            window.open(url, '_blank');
        }

        function downloadChatTranscripts() {
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            const url = `/admin/analytics/ad/${adId}/chat-transcripts?start_date=${startDate}&end_date=${endDate}`;
            window.open(url, '_blank');
        }

        function refreshRecommendations() {
            loadRecommendations();
        }
    </script>

    <style>
        .analytics-dashboard {
            padding: 20px;
            background: #f8fafc;
            min-height: 100vh;
        }

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

        .ad-title {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 8px;
        }

        .ad-meta {
            display: flex;
            gap: 16px;
            margin-bottom: 8px;
        }

        .category, .price, .status {
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 600;
        }

        .category {
            background: #e5e7eb;
            color: #374151;
        }

        .price {
            background: #dcfce7;
            color: #166534;
        }

        .status {
            background: #fef3c7;
            color: #92400e;
        }

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

        .status.pending {
            background: #fef3c7;
            color: #92400e;
        }

        .status.suspended {
            background: #fee2e2;
            color: #991b1b;
        }

        .ad-location {
            color: #6b7280;
            font-size: 0.875rem;
        }

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

        .btn-export {
            padding: 8px 16px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            background: white;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.2s;
        }

        .btn-export:hover {
            background: #f3f4f6;
            border-color: #d1d5db;
        }

        .date-controls {
            background: white;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 20px;
            display: flex;
            gap: 20px;
            align-items: center;
        }

        .date-group {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .date-group label {
            font-size: 0.875rem;
            color: #6b7280;
            font-weight: 600;
        }

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

        .performance-score {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            gap: 40px;
            align-items: center;
        }

        .score-card {
            text-align: center;
        }

        .score-circle {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            border: 8px solid #e5e7eb;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            font-weight: 800;
            margin: 0 auto 12px;
            position: relative;
        }

        .score-label {
            font-size: 0.875rem;
            color: #6b7280;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .score-tier {
            font-size: 0.875rem;
            font-weight: 700;
            color: #374151;
        }

        .score-details {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
        }

        .detail-item {
            text-align: center;
            padding: 12px;
            background: #f9fafb;
            border-radius: 8px;
        }

        .detail-label {
            display: block;
            font-size: 0.75rem;
            color: #6b7280;
            margin-bottom: 4px;
        }

        .detail-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1f2937;
        }

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

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

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            border-bottom: 1px solid #e5e7eb;
            padding-bottom: 12px;
        }

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

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

        .btn-secondary {
            padding: 6px 12px;
            background: #3b82f6;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.875rem;
            font-weight: 600;
        }

        .card-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .metrics-grid, .geo-stats, .temporal-stats, .interaction-stats, .chat-stats, .engagement-stats, .revenue-stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
        }

        .metric-item, .geo-item, .temporal-item, .interaction-item, .chat-item, .engagement-item, .revenue-item {
            background: #f9fafb;
            padding: 12px;
            border-radius: 8px;
            text-align: center;
        }

        .metric-label, .geo-label, .temporal-label, .interaction-label, .chat-label, .engagement-label, .revenue-label {
            display: block;
            font-size: 0.75rem;
            color: #6b7280;
            margin-bottom: 4px;
        }

        .metric-value, .geo-value, .temporal-value, .interaction-value, .chat-value, .engagement-value, .revenue-value {
            font-size: 1.125rem;
            font-weight: 700;
            color: #1f2937;
        }

        .chart-container {
            grid-column: 1 / -1;
            height: 300px;
            position: relative;
        }

        .recommendations-card {
            grid-column: 1 / -1;
        }

        .recommendation-item {
            background: #f9fafb;
            border-left: 4px solid #e5e7eb;
            padding: 16px;
            margin-bottom: 12px;
            border-radius: 0 8px 8px 0;
        }

        .recommendation-item.high {
            border-left-color: #ef4444;
        }

        .recommendation-item.medium {
            border-left-color: #f59e0b;
        }

        .recommendation-item.low {
            border-left-color: #10b981;
        }

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

        .priority-badge {
            padding: 2px 8px;
            border-radius: 999px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            color: white;
        }

        .priority-badge.high {
            background: #ef4444;
        }

        .priority-badge.medium {
            background: #f59e0b;
        }

        .priority-badge.low {
            background: #10b981;
        }

        .recommendation-title {
            font-weight: 700;
            color: #1f2937;
        }

        .recommendation-description {
            color: #6b7280;
            font-size: 0.875rem;
            line-height: 1.5;
        }

        @media (max-width: 768px) {
            .analytics-grid {
                grid-template-columns: 1fr;
            }
            
            .score-details {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .card-content {
                grid-template-columns: 1fr;
            }
        }
    </style>
@endsection
