<?php
// Dashboard View
$total_clicks = $stats->total_clicks;
$prev_total = $prev_stats->total_clicks;
$total_change = essb_calculate_percentage_change($total_clicks, $prev_total);

$best_network = 'None';
$best_network_clicks = 0;
if (!empty($stats->networks) && is_array($stats->networks)) {
    $best_network = array_keys($stats->networks, max($stats->networks))[0];
    $best_network_clicks = $stats->networks[$best_network];
}

$prev_best_network = 'None';
if (!empty($prev_stats->networks) && is_array($prev_stats->networks)) {
    $prev_best_network = array_keys($prev_stats->networks, max($prev_stats->networks))[0];
}

$best_position = 'None';
$best_position_clicks = 0;
if (!empty($stats->positions) && is_array($stats->positions)) {
    $best_position = array_keys($stats->positions, max($stats->positions))[0];
    $best_position_clicks = $stats->positions[$best_position];
}

$prev_best_position = 'None';
if (!empty($prev_stats->positions) && is_array($prev_stats->positions)) {
    $prev_best_position = array_keys($prev_stats->positions, max($prev_stats->positions))[0];
}

$best_device = $stats->desktop_clicks > $stats->mobile_clicks ? 'Desktop' : 'Mobile';
$best_device_clicks = max($stats->desktop_clicks, $stats->mobile_clicks);
$prev_best_device = $prev_stats->desktop_clicks > $prev_stats->mobile_clicks ? 'Desktop' : 'Mobile';

$chart_data = essb_get_full_date_range_chart_data($date_from, $date_to);
$top_posts = essb_get_top_posts($date_from, $date_to, 10);

// Prepare chart data
$chart_labels = array();
$chart_values = array();
if (!empty($chart_data) && is_array($chart_data)) {
    foreach ($chart_data as $data) {
        $chart_labels[] = $data['label'];
        $chart_values[] = $data['clicks'];
    }
}
?>

<div class="essb-kpi-grid">
    <!-- Total Clicks Card -->
    <div class="essb-kpi-card">
        <div class="essb-kpi-title">Total Clicks</div>
        <div class="essb-kpi-value"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($total_clicks); ?></div>
        <div class="essb-kpi-compare">
            <span class="<?php echo $total_change >= 0 ? 'essb-trend-up' : 'essb-trend-down'; ?>">
                <?php echo $total_change >= 0 ? '↑' : '↓'; ?> <?php echo abs($total_change); ?>%
            </span>
            <span>vs previous period</span>
        </div>
        <div class="essb-kpi-stats">
            <div class="essb-stat-item">
                <span class="essb-stat-label">Desktop</span>
                <span class="essb-stat-value"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($stats->desktop_clicks); ?></span>
            </div>
            <div class="essb-stat-item">
                <span class="essb-stat-label">Mobile</span>
                <span class="essb-stat-value"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($stats->mobile_clicks); ?></span>
            </div>
        </div>
    </div>
    
<!-- Best Network Card -->
<div class="essb-kpi-card">
    <div class="essb-kpi-title">Best Network</div>
    <div class="essb-chip-wrapper">
        <div class="essb-chip essb-chip-network"><?php echo essb_stats_get_network_name($best_network); ?></div>
        <div class="essb-value-wrapper">
            <div class="essb-kpi-value-small"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($best_network_clicks); ?></div>
            <div class="essb-kpi-label-small">clicks</div>
        </div>
    </div>
    <?php if ($prev_best_network && $prev_best_network != $best_network && $prev_best_network != 'None'): ?>
    <div class="essb-kpi-sub" style="display: none;">
        <span class="essb-kpi-sub-label">Previous:</span>
        <span class="essb-chip essb-chip-small essb-chip-network"><?php echo ucfirst($prev_best_network); ?></span>
    </div>
    <?php endif; ?>
    <?php if ($total_clicks > 0): ?>
    <div class="essb-progress-bar" style="margin-top: 12px;">
        <div class="essb-progress-fill" style="width: <?php echo $best_network_clicks / $total_clicks * 100; ?>%"></div>
    </div>
    <div class="essb-kpi-percent"><?php echo round($best_network_clicks / $total_clicks * 100, 1); ?>% of total</div>
    <?php endif; ?>
</div>

<!-- Best Position Card -->
<div class="essb-kpi-card">
    <div class="essb-kpi-title">Best Position</div>
    <div class="essb-chip-wrapper">
        <div class="essb-chip essb-chip-position"><?php echo ESSBSocialShareAnalyticsBackEnd::position_name($best_position); ?></div>
        <div class="essb-value-wrapper">
            <div class="essb-kpi-value-small"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($best_position_clicks); ?></div>
            <div class="essb-kpi-label-small">clicks</div>
        </div>
    </div>
    <?php if ($prev_best_position && $prev_best_position != $best_position && $prev_best_position != 'None'): ?>
    <div class="essb-kpi-sub" style="display: none;">
        <span class="essb-kpi-sub-label">Previous:</span>
        <span class="essb-chip essb-chip-small essb-chip-position"><?php echo ESSBSocialShareAnalyticsBackEnd::position_name($prev_best_position); ?></span>
    </div>
    <?php endif; ?>
    <?php if ($total_clicks > 0): ?>
    <div class="essb-progress-bar" style="margin-top: 12px;">
        <div class="essb-progress-fill" style="width: <?php echo $best_position_clicks / $total_clicks * 100; ?>%"></div>
    </div>
    <div class="essb-kpi-percent"><?php echo round($best_position_clicks / $total_clicks * 100, 1); ?>% of total</div>
    <?php endif; ?>
</div>

<!-- Best Device Card -->
<div class="essb-kpi-card">
    <div class="essb-kpi-title">Best Device</div>
    <div class="essb-chip-wrapper">
        <div class="essb-chip essb-chip-device"><?php echo $best_device; ?></div>
        <div class="essb-value-wrapper">
            <div class="essb-kpi-value-small"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($best_device_clicks); ?></div>
            <div class="essb-kpi-label-small">clicks</div>
        </div>
    </div>
    <?php if ($prev_best_device && $prev_best_device != $best_device): ?>
    <div class="essb-kpi-sub" style="display: none;">
        <span class="essb-kpi-sub-label">Previous:</span>
        <span class="essb-chip essb-chip-small essb-chip-device"><?php echo $prev_best_device; ?></span>
    </div>
    <?php endif; ?>
    <div class="essb-kpi-stats essb-kpi-stats-inline">
        <div class="essb-stat-item">
            <span class="essb-stat-label">Desktop</span>
            <span class="essb-stat-value"><?php echo round($stats->desktop_clicks / max(1, $total_clicks) * 100, 1); ?>%</span>
        </div>
        <div class="essb-stat-item">
            <span class="essb-stat-label">Mobile</span>
            <span class="essb-stat-value"><?php echo round($stats->mobile_clicks / max(1, $total_clicks) * 100, 1); ?>%</span>
        </div>
    </div>
</div>
</div>

<div class="essb-chart-container">
    <div class="essb-chart-title">Activity Trend (<?php echo date('M j, Y', strtotime($date_from)); ?> - <?php echo date('M j, Y', strtotime($date_to)); ?>)</div>
    
    <?php if (!empty($chart_labels) && count($chart_labels) > 0): ?>
    <canvas id="trend-line-chart" style="height: 400px; width: 100%;"></canvas>
    <?php else: ?>
        <div class="essb-empty-state">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <path d="M21 16v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2"/>
                <path d="M7 10l3-3 3 3 4-4"/>
                <path d="M17 10V4h-6"/>
            </svg>
            <p>No activity data available for this period</p>
            <p class="essb-empty-state-sub">Try selecting a different date range or wait for more data to be collected.</p>
        </div>
    <?php endif; ?>
</div>

<div class="essb-chart-container">
    <div class="essb-chart-title">
        Top 10 Content
        <a href="<?php echo essb_get_tab_url('content', $period, $date_from, $date_to); ?>" class="essb-btn essb-btn-secondary">View All Content →</a>
    </div>
    
    <?php if (!empty($top_posts) && is_array($top_posts) && count($top_posts) > 0): ?>
    <div class="essb-table-wrapper">
        <table class="essb-modern-table essb-table-simple">
            <thead>
                <tr>
                    <th class="essb-table-post">Post / Page</th>
                    <th class="essb-table-number">Total Clicks</th>
                    <th class="essb-table-number">Desktop</th>
                    <th class="essb-table-number">Mobile</th>
                    <?php if ($total_clicks > 0): ?>
                    <th class="essb-table-number">% of Total</th>
                    <?php endif; ?>
                    <th>Top Network</th>
                </thead>
            <tbody>
                <?php foreach($top_posts as $index => $post): ?>
                <tr>
                    <td class="essb-table-post">
                        <span class="essb-rank"><?php echo $index + 1; ?></span>
                        <a href="<?php echo $post->permalink; ?>" target="_blank"><?php echo esc_html($post->title ?: 'Untitled (ID: ' . $post->essb_post_id . ')'); ?></a>
                    </td>
                    <td class="essb-table-number"><strong><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($post->total_clicks); ?></strong></td>
                    <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($post->desktop_clicks); ?></td>
                    <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($post->mobile_clicks); ?></td>
                    <?php if ($total_clicks > 0): ?>
                    <td class="essb-table-number">
                        <?php echo round($post->total_clicks / $total_clicks * 100, 1); ?>%
                        <div class="essb-progress-bar essb-progress-bar-small">
                            <div class="essb-progress-fill" style="width: <?php echo $post->total_clicks / $total_clicks * 100; ?>%"></div>
                        </div>
                    </td>
                    <?php endif; ?>
                    <td>
                        <?php if(isset($post->top_network) && $post->top_network): ?>
                            <span class="essb-chip essb-chip-small essb-chip-network"><?php echo essb_stats_get_network_name($post->top_network); ?></span>
                            <span class="essb-clicks-small" style="display: none;">(<?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($post->top_network_clicks); ?>)</span>
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
        <div class="essb-empty-state">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <path d="M4 4h16v16H4z"/>
                <line x1="8" y1="8" x2="16" y2="16"/>
                <line x1="16" y1="8" x2="8" y2="16"/>
            </svg>
            <p>No content data available for this period</p>
            <p class="essb-empty-state-sub">Share buttons haven't been clicked yet or try a different date range.</p>
        </div>
    <?php endif; ?>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    <?php if (!empty($chart_labels) && count($chart_labels) > 0): ?>
    if (typeof Chart === 'undefined') {
        var script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
        script.onload = function() { createLineChart(); };
        document.head.appendChild(script);
    } else {
        createLineChart();
    }
    
    function createLineChart() {
        var ctx = document.getElementById('trend-line-chart').getContext('2d');
        var gradient = ctx.createLinearGradient(0, 0, 0, 400);
        gradient.addColorStop(0, 'rgba(59, 130, 246, 0.3)');
        gradient.addColorStop(1, 'rgba(59, 130, 246, 0.02)');
        
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($chart_labels); ?>,
                datasets: [{
                    label: 'Clicks',
                    data: <?php echo json_encode($chart_values); ?>,
                    borderColor: '#3b82f6',
                    backgroundColor: gradient,
                    borderWidth: 3,
                    pointRadius: 3,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#3b82f6',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                    pointHoverBackgroundColor: '#2563eb',
                    pointHoverBorderColor: '#ffffff',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { display: true, position: 'top', labels: { usePointStyle: true, boxWidth: 8, font: { size: 12 } } },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        callbacks: {
                            label: function(context) { return context.dataset.label + ': ' + formatNumber(context.parsed.y); }
                        }
                    }
                },
                scales: {
                    y: { beginAtZero: true, grid: { color: '#e2e8f0' }, ticks: { callback: function(v) { return formatNumber(v); } } },
                    x: { grid: { display: false }, ticks: { maxRotation: 45, minRotation: 45, autoSkip: true, maxTicksLimit: 15 } }
                }
            }
        });
    }
    
    function formatNumber(n) {
        if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
        if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
        return n.toString();
    }
    <?php endif; ?>
});
</script>