<?php
// admin/index.php - Dashboard Moderno com Sistema de Visitantes Únicos com Reset à Meia-Noite

// Define BASE_PATH apenas se não estiver definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__FILE__)));
}

$pageTitle = 'Dashboard';
$pageHeader = 'Dashboard';
$currentPage = 'dashboard';

require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/unique-visits-tracker.php'; // Sistema de visitantes únicos

// Requer autenticação
if (!$auth->isLoggedIn()) {
    redirect('admin/login.php');
    exit;
}

/**
 * Funções auxiliares
 */
function getPageTypeIcon($type) {
    $icons = [
        'landing' => 'fa-rocket',
        'step1' => 'fa-play-circle',
        'step2' => 'fa-forward', 
        'step3' => 'fa-fast-forward',
        'registration' => 'fa-user-plus',
        'about' => 'fa-info-circle',
        'contact' => 'fa-envelope',
        'blog' => 'fa-newspaper',
        'course' => 'fa-graduation-cap',
        'service' => 'fa-cogs',
        'product' => 'fa-box',
        'home' => 'fa-home',
        'database' => 'fa-database',
        'static' => 'fa-file'
    ];
    return isset($icons[$type]) ? $icons[$type] : 'fa-file-alt';
}

function getPageTypeName($type) {
    $names = [
        'landing' => 'Landing Page',
        'step1' => 'Etapa 1', 
        'step2' => 'Etapa 2',
        'step3' => 'Etapa 3',
        'registration' => 'Registro',
        'about' => 'Sobre',
        'contact' => 'Contato', 
        'blog' => 'Blog',
        'course' => 'Curso',
        'service' => 'Serviço',
        'product' => 'Produto',
        'home' => 'Início',
        'database' => 'Do Banco',
        'static' => 'Estática'
    ];
    return isset($names[$type]) ? $names[$type] : ucfirst($type);
}

function timeAgo($date) {
    $timestamp = strtotime($date);
    $diff = time() - $timestamp;
    
    if ($diff < 60) return 'agora mesmo';
    if ($diff < 3600) return 'há ' . floor($diff / 60) . ' min';
    if ($diff < 86400) return 'há ' . floor($diff / 3600) . ' h';
    if ($diff < 2592000) return 'há ' . floor($diff / 86400) . ' dias';
    
    return date('d/m/Y', $timestamp);
}

function formatPercentage($value, $showIcon = true) {
    $class = $value >= 0 ? 'trend-up' : 'trend-down';
    $icon = $value >= 0 ? 'fa-trending-up' : 'fa-trending-down';
    $iconHtml = $showIcon ? "<i class='fas $icon'></i> " : '';
    return "<span class='$class'>{$iconHtml}" . number_format(abs($value), 1) . "%</span>";
}

// Verificar preferência do usuário para tipo de métrica
$metricsType = isset($_GET['metrics']) ? $_GET['metrics'] : 'unique'; // 'unique' ou 'all'

// Verificar período selecionado
$period = isset($_GET['period']) ? $_GET['period'] : '24h'; // '24h', '7d', '30d'

// Inicializar variáveis
$stats = ['total' => 0, 'published' => 0, 'drafts' => 0];
$visitorStats = [
    'unique_visitors_24h' => 0,
    'unique_visitors_7d' => 0,
    'unique_visitors_30d' => 0,
    'total_visits_24h' => 0,
    'total_visits_7d' => 0,
    'total_visits_30d' => 0,
    'conversion_rate' => 0,
    'avg_time_spent' => 0
];
$recentPages = [];
$viewsChart = [];
$topPages = [];
$conversionStats = [];
$systemHealth = [];

try {
    // === ESTATÍSTICAS BÁSICAS DAS PÁGINAS ===
    $db->query("SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN published = 1 THEN 1 ELSE 0 END) as published,
        SUM(CASE WHEN published = 0 THEN 1 ELSE 0 END) as drafts
        FROM pages");
    $result = $db->single();
    if ($result) {
        $stats = $result;
    }

    // === ESTATÍSTICAS DE VISITANTES ÚNICOS (SISTEMA COM RESET À MEIA-NOITE) ===
    
    // Visitantes únicos de HOJE (resetados automaticamente à meia-noite)
    $db->query("SELECT 
        COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
        COUNT(vs.id) as total_visits,
        AVG(COALESCE(vs.time_spent, 0)) as avg_time_spent,
        SUM(COALESCE(vs.converted, 0)) as conversions
        FROM visitor_sessions vs 
        WHERE DATE(vs.created_at) = CURDATE()");
    $statsToday = $db->single();
    
    if ($statsToday) {
        $visitorStats['unique_visitors_24h'] = $statsToday['unique_visitors'];
        $visitorStats['total_visits_24h'] = $statsToday['total_visits'];
        $visitorStats['avg_time_spent'] = $statsToday['avg_time_spent'] ?: 0;
        $visitorStats['conversion_rate'] = $statsToday['unique_visitors'] > 0 ? 
            round(($statsToday['conversions'] / $statsToday['unique_visitors']) * 100, 2) : 0;
    }

    // Visitantes únicos de ONTEM (para comparação de crescimento)
    $db->query("SELECT 
        COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
        COUNT(vs.id) as total_visits
        FROM visitor_sessions vs 
        WHERE DATE(vs.created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)");
    $statsYesterday = $db->single();

    // Visitantes únicos dos últimos 7 dias (soma diária)
    $db->query("SELECT 
        COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
        COUNT(vs.id) as total_visits
        FROM visitor_sessions vs 
        WHERE DATE(vs.created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
    $stats7d = $db->single();
    
    if ($stats7d) {
        $visitorStats['unique_visitors_7d'] = $stats7d['unique_visitors'];
        $visitorStats['total_visits_7d'] = $stats7d['total_visits'];
    }

    // Visitantes únicos dos últimos 30 dias (soma diária)
    $db->query("SELECT 
        COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
        COUNT(vs.id) as total_visits
        FROM visitor_sessions vs 
        WHERE DATE(vs.created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
    $stats30d = $db->single();
    
    if ($stats30d) {
        $visitorStats['unique_visitors_30d'] = $stats30d['unique_visitors'];
        $visitorStats['total_visits_30d'] = $stats30d['total_visits'];
    }

    // === CALCULAR CRESCIMENTO BASEADO NO PERÍODO ===
    $currentMetric = 0;
    $previousMetric = 0;
    
    switch($period) {
        case '7d':
            $currentMetric = $metricsType === 'unique' ? $visitorStats['unique_visitors_7d'] : $visitorStats['total_visits_7d'];
            
            // Buscar 7 dias anteriores (semana passada)
            $db->query("SELECT 
                COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
                COUNT(vs.id) as total_visits
                FROM visitor_sessions vs 
                WHERE DATE(vs.created_at) >= DATE_SUB(CURDATE(), INTERVAL 14 DAY)
                AND DATE(vs.created_at) < DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
            $prevResult = $db->single();
            $previousMetric = $metricsType === 'unique' ? $prevResult['unique_visitors'] : $prevResult['total_visits'];
            break;
            
        case '30d':
            $currentMetric = $metricsType === 'unique' ? $visitorStats['unique_visitors_30d'] : $visitorStats['total_visits_30d'];
            
            // Buscar 30 dias anteriores (mês passado)
            $db->query("SELECT 
                COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
                COUNT(vs.id) as total_visits
                FROM visitor_sessions vs 
                WHERE DATE(vs.created_at) >= DATE_SUB(CURDATE(), INTERVAL 60 DAY)
                AND DATE(vs.created_at) < DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
            $prevResult = $db->single();
            $previousMetric = $metricsType === 'unique' ? $prevResult['unique_visitors'] : $prevResult['total_visits'];
            break;
            
        default: // 24h (hoje vs ontem)
            $currentMetric = $metricsType === 'unique' ? $visitorStats['unique_visitors_24h'] : $visitorStats['total_visits_24h'];
            $previousMetric = $metricsType === 'unique' ? 
                ($statsYesterday['unique_visitors'] ?? 0) : 
                ($statsYesterday['total_visits'] ?? 0);
    }
    
    $growthPercentage = $previousMetric > 0 ? 
        (($currentMetric - $previousMetric) / $previousMetric) * 100 : 
        ($currentMetric > 0 ? 100 : 0); // Se não há dados anteriores mas há atuais, crescimento de 100%

    // === PÁGINAS MAIS VISITADAS (ADAPTADO PARA NOVO SISTEMA) ===
    
    // Para o sistema de reset diário, vamos usar queries diretas em vez das views
    $periodCondition = '';
    
    switch($period) {
        case '7d':
            $periodCondition = "AND DATE(vs.created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
            break;
        case '30d':
            $periodCondition = "AND DATE(vs.created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
            break;
        default: // 24h - hoje
            $periodCondition = "AND DATE(vs.created_at) = CURDATE()";
    }
    
    $db->query("SELECT 
        pv.id, 
        pv.page_url, 
        pv.page_title, 
        pv.page_type,
        COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
        COUNT(vs.id) as total_visits,
        COALESCE(COUNT(DISTINCT vs.visitor_hash), 0) as metric_value
        FROM pages_visitor pv
        LEFT JOIN visitor_sessions vs ON pv.id = vs.pages_visitor_id {$periodCondition}
        WHERE pv.is_active = 1
        GROUP BY pv.id, pv.page_url, pv.page_title, pv.page_type
        HAVING COUNT(DISTINCT vs.visitor_hash) > 0
        ORDER BY " . ($metricsType === 'unique' ? 'unique_visitors' : 'total_visits') . " DESC 
        LIMIT 10");
    $topPages = $db->resultSet();

    // === PÁGINAS RECENTES COM ESTATÍSTICAS (ADAPTADO) ===
    $db->query("SELECT 
        pv.id, 
        pv.page_title, 
        pv.page_type, 
        pv.page_url, 
        pv.first_detected as created_at,
        pv.page_id, 
        p.published,
        
        -- Estatísticas de hoje
        (SELECT COUNT(DISTINCT vs1.visitor_hash) 
         FROM visitor_sessions vs1 
         WHERE vs1.pages_visitor_id = pv.id 
         AND DATE(vs1.created_at) = CURDATE()) as unique_visitors_24h,
         
        (SELECT COUNT(vs2.id) 
         FROM visitor_sessions vs2 
         WHERE vs2.pages_visitor_id = pv.id 
         AND DATE(vs2.created_at) = CURDATE()) as total_visits_24h,
         
        -- Estatísticas dos últimos 7 dias
        (SELECT COUNT(DISTINCT vs3.visitor_hash) 
         FROM visitor_sessions vs3 
         WHERE vs3.pages_visitor_id = pv.id 
         AND DATE(vs3.created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)) as unique_visitors_7d,
         
        (SELECT COUNT(vs4.id) 
         FROM visitor_sessions vs4 
         WHERE vs4.pages_visitor_id = pv.id 
         AND DATE(vs4.created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)) as total_visits_7d
         
        FROM pages_visitor pv
        LEFT JOIN pages p ON pv.page_id = p.id
        WHERE pv.is_active = 1
        ORDER BY pv.first_detected DESC 
        LIMIT 8");
    $recentPages = $db->resultSet();

    // === DADOS PARA GRÁFICO (ADAPTADO PARA RESET DIÁRIO) ===
    
    if ($period === '24h') {
        // Para hoje, mostrar por horas
        $db->query("SELECT 
            HOUR(vs.created_at) as time_unit,
            DATE_FORMAT(vs.created_at, '%H:00') as formatted_time,
            COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
            COUNT(vs.id) as total_visits
            FROM visitor_sessions vs 
            WHERE DATE(vs.created_at) = CURDATE()
            GROUP BY HOUR(vs.created_at)
            ORDER BY time_unit");
    } else {
        // Para períodos maiores, mostrar por dias
        $intervalDays = $period === '30d' ? 30 : 7;
        
        $db->query("SELECT 
            DATE(vs.created_at) as time_unit,
            DATE_FORMAT(vs.created_at, '%d/%m') as formatted_time,
            COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
            COUNT(vs.id) as total_visits
            FROM visitor_sessions vs 
            WHERE DATE(vs.created_at) >= DATE_SUB(CURDATE(), INTERVAL {$intervalDays} DAY)
            GROUP BY DATE(vs.created_at)
            ORDER BY time_unit");
    }
    $viewsChart = $db->resultSet();

    // === ESTATÍSTICAS POR TIPO DE PÁGINA (ADAPTADO) ===
    $db->query("SELECT 
        pv.page_type,
        COUNT(DISTINCT pv.id) as page_count,
        
        -- Visitantes únicos de hoje por tipo
        (SELECT COUNT(DISTINCT vs1.visitor_hash)
         FROM visitor_sessions vs1 
         WHERE vs1.pages_visitor_id IN (
             SELECT pv1.id FROM pages_visitor pv1 
             WHERE pv1.page_type = pv.page_type AND pv1.is_active = 1
         )
         AND DATE(vs1.created_at) = CURDATE()) as unique_visitors_24h,
         
        -- Total de visitas de hoje por tipo  
        (SELECT COUNT(vs2.id)
         FROM visitor_sessions vs2 
         WHERE vs2.pages_visitor_id IN (
             SELECT pv2.id FROM pages_visitor pv2 
             WHERE pv2.page_type = pv.page_type AND pv2.is_active = 1
         )
         AND DATE(vs2.created_at) = CURDATE()) as total_visits_24h
         
        FROM pages_visitor pv
        WHERE pv.is_active = 1
        GROUP BY pv.page_type
        ORDER BY unique_visitors_24h DESC");
    $pageTypeStats = $db->resultSet();

    // === CONVERSÕES POR TIPO (ADAPTADO) ===
    $db->query("SELECT 
        vc.conversion_type,
        COUNT(*) as conversion_count,
        COUNT(DISTINCT vc.visitor_hash) as unique_converters
        FROM visitor_conversions vc
        WHERE DATE(vc.created_at) = CURDATE()
        GROUP BY vc.conversion_type
        ORDER BY conversion_count DESC");
    $conversionStats = $db->resultSet();

    // === STATUS DO SISTEMA ===
    
    // Verificar integridade das tabelas
    $db->query("SELECT COUNT(*) as total_pages FROM pages_visitor WHERE is_active = 1");
    $totalPagesResult = $db->single();
    
    $db->query("SELECT COUNT(*) as total_sessions FROM visitor_sessions WHERE DATE(created_at) = CURDATE()");
    $totalSessionsResult = $db->single();
    
    $systemHealth = [
        'total_tracked_pages' => $totalPagesResult['total_pages'] ?? 0,
        'sessions_24h' => $totalSessionsResult['total_sessions'] ?? 0,
        'database_status' => 'online',
        'tracking_status' => 'active',
        'cache_status' => CACHE_ENABLED ? 'enabled' : 'disabled',
        'last_cleanup' => date('H:i'),
        'unique_system_working' => true,
        'reset_working' => 'Reset à meia-noite ativo'
    ];

    // === PERFORMANCE E MÉTRICAS AVANÇADAS ===
    
    // Tempo médio de carregamento estimado
    $avgLoadTime = 2.1; // Pode ser integrado com ferramentas reais
    $performanceScore = 95;
    
    // Taxa de rejeição estimada (baseada no tempo gasto < 10 segundos)
    $db->query("SELECT 
        COUNT(CASE WHEN COALESCE(vs.time_spent, 0) < 10 THEN 1 END) as quick_exits,
        COUNT(*) as total_sessions
        FROM visitor_sessions vs 
        WHERE DATE(vs.created_at) = CURDATE()");
    $bounceResult = $db->single();
    
    $bounceRate = $bounceResult['total_sessions'] > 0 ? 
        round(($bounceResult['quick_exits'] / $bounceResult['total_sessions']) * 100, 1) : 0;
        
    // === ESTATÍSTICAS COMPARATIVAS (NOVO) ===
    
    // Comparação com ontem
    $comparisonStats = [
        'today_vs_yesterday' => [
            'unique_visitors_today' => $visitorStats['unique_visitors_24h'],
            'unique_visitors_yesterday' => $statsYesterday['unique_visitors'] ?? 0,
            'total_visits_today' => $visitorStats['total_visits_24h'],
            'total_visits_yesterday' => $statsYesterday['total_visits'] ?? 0
        ]
    ];
    
    // Cálculo de crescimento dia a dia
    $dailyGrowth = [
        'unique_visitors' => $comparisonStats['today_vs_yesterday']['unique_visitors_yesterday'] > 0 ?
            round((($comparisonStats['today_vs_yesterday']['unique_visitors_today'] - $comparisonStats['today_vs_yesterday']['unique_visitors_yesterday']) / $comparisonStats['today_vs_yesterday']['unique_visitors_yesterday']) * 100, 1) : 
            ($comparisonStats['today_vs_yesterday']['unique_visitors_today'] > 0 ? 100 : 0),
            
        'total_visits' => $comparisonStats['today_vs_yesterday']['total_visits_yesterday'] > 0 ?
            round((($comparisonStats['today_vs_yesterday']['total_visits_today'] - $comparisonStats['today_vs_yesterday']['total_visits_yesterday']) / $comparisonStats['today_vs_yesterday']['total_visits_yesterday']) * 100, 1) : 
            ($comparisonStats['today_vs_yesterday']['total_visits_today'] > 0 ? 100 : 0)
    ];

} catch (Exception $e) {
    logError("Erro no dashboard: " . $e->getMessage());
    
    // Valores padrão em caso de erro
    $visitorStats = [
        'unique_visitors_24h' => 0,
        'unique_visitors_7d' => 0,
        'unique_visitors_30d' => 0,
        'total_visits_24h' => 0,
        'total_visits_7d' => 0,
        'total_visits_30d' => 0,
        'conversion_rate' => 0,
        'avg_time_spent' => 0
    ];
    $growthPercentage = 0;
    $bounceRate = 0;
    $dailyGrowth = ['unique_visitors' => 0, 'total_visits' => 0];
    $comparisonStats = [
        'today_vs_yesterday' => [
            'unique_visitors_today' => 0,
            'unique_visitors_yesterday' => 0,
            'total_visits_today' => 0,
            'total_visits_yesterday' => 0
        ]
    ];
    $topPages = [];
    $recentPages = [];
    $viewsChart = [];
    $pageTypeStats = [];
    $conversionStats = [];
    $systemHealth = [
        'total_tracked_pages' => 0,
        'sessions_24h' => 0,
        'database_status' => 'error',
        'tracking_status' => 'error',
        'cache_status' => 'unknown',
        'last_cleanup' => 'N/A',
        'unique_system_working' => false,
        'reset_working' => 'Erro no sistema'
    ];
}

// === LOGGING DE DEBUG (REMOVER EM PRODUÇÃO) ===
if (defined('DEBUG_UNIQUE_VISITS') && DEBUG_UNIQUE_VISITS) {
    logInfo("=== DEBUG DASHBOARD ===");
    logInfo("Visitantes únicos hoje: " . $visitorStats['unique_visitors_24h']);
    logInfo("Visitantes únicos ontem: " . ($statsYesterday['unique_visitors'] ?? 0));
    logInfo("Crescimento: " . $growthPercentage . "%");
    logInfo("Sistema de reset: " . ($systemHealth['reset_working'] ?? 'desconhecido'));
}

require_once 'inc/header.php';
?>

<div class="modern-dashboard">
    <!-- Header Principal -->
    <div class="dashboard-header">
        <div class="header-content">
            <div class="greeting-section">
                <h1 class="main-greeting">
                    <span class="greeting-text">Olá, <?php echo htmlspecialchars($_SESSION['admin_name'] ?? 'Usuário'); ?>!</span>
                    <span class="greeting-emoji">👋</span>
                </h1>
                <p class="date-subtitle">
                    <i class="fas fa-calendar-day"></i>
                    <?php echo strftime('%A, %d de %B de %Y'); ?>
                </p>
                <div class="quick-stats">
                    <span class="quick-stat">
                        <i class="fas fa-users"></i>
                        <?php 
                        $currentValue = $metricsType === 'unique' ? $visitorStats["unique_visitors_24h"] : $visitorStats["total_visits_24h"];
                        if ($period === '7d') {
                            $currentValue = $metricsType === 'unique' ? $visitorStats["unique_visitors_7d"] : $visitorStats["total_visits_7d"];
                        } elseif ($period === '30d') {
                            $currentValue = $metricsType === 'unique' ? $visitorStats["unique_visitors_30d"] : $visitorStats["total_visits_30d"];
                        }
                        echo number_format($currentValue);
                        ?> 
                        <?php echo $metricsType === 'unique' ? 'visitantes únicos' : 'visualizações'; ?> (<?php echo $period === '24h' ? 'hoje' : $period; ?>)
                    </span>
                    <span class="quick-stat">
                        <i class="fas fa-users"></i>
                        <?php echo number_format($comparisonStats['today_vs_yesterday']['unique_visitors_yesterday']); ?> visitantes únicos (ontem)
                    </span>
                    <span class="quick-stat">
                        <i class="fas fa-chart-line"></i>
                        <?php echo formatPercentage($growthPercentage, false); ?> vs período anterior
                    </span>
                    
                    <span class="quick-stat">
                        <i class="fas fa-percentage"></i>
                        <?php echo $bounceRate; ?>% taxa de rejeição
                    </span>
                </div>
            </div>
            <div class="header-actions">
                <div class="time-widget">
                    <div class="time-display" id="currentTime"></div>
                    <div class="timezone">Brasil/São Paulo</div>
                </div>
                <div class="controls-widget">
                    <div class="period-selector">
                        <button class="period-btn <?php echo $period === '24h' ? 'active' : ''; ?>" data-period="24h">Hoje</button>
                        <button class="period-btn <?php echo $period === '7d' ? 'active' : ''; ?>" data-period="7d">7d</button>
                        <button class="period-btn <?php echo $period === '30d' ? 'active' : ''; ?>" data-period="30d">30d</button>
                    </div>
                    <div class="metrics-toggle">
                        <label class="toggle-switch">
                            <input type="checkbox" <?php echo $metricsType === 'unique' ? 'checked' : ''; ?> onchange="toggleMetrics(this.checked)">
                            <span class="toggle-slider"></span>
                        </label>
                        <span class="toggle-label">Visitantes Únicos</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

   
    <!-- Cards de Métricas Principais -->
    <div class="metrics-grid">
        <!-- Métrica de Páginas Totais -->
        <div class="metric-card pages-metric">
            <div class="metric-header">
                <div class="metric-icon">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="metric-trend">
                    <span class="trend-value">+<?php echo $stats['drafts']; ?></span>
                    <span class="trend-period">rascunhos</span>
                </div>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($stats['total']); ?></div>
                <div class="metric-label">Páginas no Sistema</div>
                <div class="metric-description">
                    <?php echo number_format($stats['published']); ?> publicadas • 
                    <?php echo number_format($systemHealth['total_tracked_pages']); ?> sendo monitoradas
                </div>
            </div>
            <div class="metric-chart">
                <canvas id="pagesChart" width="100" height="40"></canvas>
            </div>
        </div>

        <!-- Métrica de Visitantes/Visitas -->
        <div class="metric-card views-metric">
            <div class="metric-header">
                <div class="metric-icon">
                    <i class="fas <?php echo $metricsType === 'unique' ? 'fa-users' : 'fa-eye'; ?>"></i>
                </div>
                <div class="metric-trend">
                    <?php echo formatPercentage($growthPercentage); ?>
                </div>
            </div>
            <div class="metric-content">
                <div class="metric-value">
                    <?php echo number_format($currentMetric); ?>
                </div>
                <div class="metric-label">
                    <?php echo $metricsType === 'unique' ? 'Visitantes Únicos' : 'Visualizações'; ?> (<?php echo $period === '24h' ? 'Hoje' : $period; ?>)
                </div>
                <div class="metric-description">
                    <?php if ($metricsType === 'unique'): ?>
                    <?php echo number_format($visitorStats['unique_visitors_24h']); ?> hoje • 
                    <?php echo number_format($visitorStats['unique_visitors_7d']); ?> esta semana
                    <br><small class="comparison-metric">
                        <?php echo number_format($visitorStats['total_visits_24h']); ?> visualizações totais hoje
                    </small>
                    <?php else: ?>
                    <?php echo number_format($visitorStats['total_visits_24h']); ?> hoje • 
                    <?php echo number_format($visitorStats['total_visits_7d']); ?> esta semana
                    <br><small class="comparison-metric">
                        <?php echo number_format($visitorStats['unique_visitors_24h']); ?> visitantes únicos hoje
                    </small>
                    <?php endif; ?>
                </div>
            </div>
            <div class="metric-chart">
                <canvas id="viewsChart" width="100" height="40"></canvas>
            </div>
        </div>

        <!-- Métrica de Conversões -->
        <div class="metric-card conversion-metric">
            <div class="metric-header">
                <div class="metric-icon">
                    <i class="fas fa-chart-pie"></i>
                </div>
                <div class="metric-trend">
                    <span class="trend-value trend-up">
                        <i class="fas fa-arrow-up"></i> 
                        <?php echo array_sum(array_column($conversionStats, 'conversion_count')); ?>
                    </span>
                </div>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo $visitorStats['conversion_rate']; ?>%</div>
                <div class="metric-label">Taxa de Conversão</div>
                <div class="metric-description">
                    <?php echo array_sum(array_column($conversionStats, 'conversion_count')); ?> conversões hoje • 
                    <?php echo array_sum(array_column($conversionStats, 'unique_converters')); ?> usuários converteram
                </div>
            </div>
            <div class="metric-chart">
                <canvas id="conversionChart" width="100" height="40"></canvas>
            </div>
        </div>

        <!-- Métrica de Performance -->
        <div class="metric-card performance-metric">
            <div class="metric-header">
                <div class="metric-icon">
                    <i class="fas fa-bolt"></i>
                </div>
                <div class="metric-trend">
                    <span class="trend-value trend-up">Score: <?php echo $performanceScore; ?>/100</span>
                </div>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo $avgLoadTime; ?>s</div>
                <div class="metric-label">Tempo de Carregamento</div>
                <div class="metric-description">
                    <?php echo $bounceRate; ?>% taxa de rejeição • 
                    Sistema de tracking ativo
                </div>
            </div>
            <div class="metric-chart">
                <canvas id="performanceChart" width="100" height="40"></canvas>
            </div>
        </div>
    </div>

    <!-- Seção Principal de Conteúdo -->
    <div class="main-content-grid">
        <!-- Gráfico Principal -->
        <div class="chart-section">
            <div class="section-card">
                <div class="section-header">
                    <div class="section-title">
                        <h3>Analítica de <?php echo $metricsType === 'unique' ? 'Visitantes Únicos' : 'Visualizações'; ?></h3>
                        <p>Sistema de tracking com reset à meia-noite - <?php echo $period === '24h' ? 'hoje por hora' : "últimos {$period}"; ?></p>
                    </div>
                    <div class="section-actions">
                        <button class="refresh-btn" onclick="refreshChart()">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                        <button class="export-btn" onclick="exportChartData()">
                            <i class="fas fa-download"></i>
                        </button>
                    </div>
                </div>
                <div class="chart-container">
                    <canvas id="mainChart"></canvas>
                </div>
                <div class="chart-legend">
                    <div class="legend-item">
                        <span class="legend-color primary-color"></span>
                        <span><?php echo $metricsType === 'unique' ? 'Visitantes Únicos' : 'Visualizações'; ?></span>
                    </div>
                    <div class="legend-item">
                        <span class="legend-color secondary-color"></span>
                        <span>Conversões</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Estatísticas por Tipo -->
        <div class="page-stats-section">
            <div class="section-card">
                <div class="section-header">
                    <div class="section-title">
                        <h3>Performance por Tipo</h3>
                        <p>Análise de hoje</p>
                    </div>
                </div>
                <div class="page-type-stats">
                    <?php foreach ($pageTypeStats as $typeData): ?>
                    <div class="stat-item">
                        <div class="stat-icon <?php echo $typeData['page_type']; ?>">
                            <i class="fas <?php echo getPageTypeIcon($typeData['page_type']); ?>"></i>
                        </div>
                        <div class="stat-info">
                            <div class="stat-value">
                                <?php echo number_format($metricsType === 'unique' ? $typeData['unique_visitors_24h'] : $typeData['total_visits_24h']); ?>
                            </div>
                            <div class="stat-label"><?php echo getPageTypeName($typeData['page_type']); ?></div>
                            <div class="stat-sublabel">
                                <?php echo $typeData['page_count']; ?> página<?php echo $typeData['page_count'] > 1 ? 's' : ''; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    
                    <?php if (empty($pageTypeStats)): ?>
                    <div class="empty-state">
                        <i class="fas fa-chart-bar"></i>
                        <p>Nenhuma estatística disponível hoje</p>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="chart-container small-chart">
                    <canvas id="pageTypeChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Seção Inferior -->
    <div class="bottom-grid">
        <!-- Páginas Mais Visitadas -->
        <div class="top-pages-section">
            <div class="section-card">
                <div class="section-header">
                    <div class="section-title">
                        <h3>Top Páginas (<?php echo $period === '24h' ? 'Hoje' : $period; ?>)</h3>
                        <p>Ranking das mais visitadas</p>
                    </div>
                    <a href="reports.php?report_type=pages" class="view-all-btn">
                        Ver Relatório <i class="fas fa-chart-line"></i>
                    </a>
                </div>
                <div class="top-pages-list">
                    <?php if (!empty($topPages)): ?>
                    <?php foreach ($topPages as $index => $page): ?>
                    <div class="top-page-item">
                        <div class="page-rank">
                            <span class="rank-number"><?php echo $index + 1; ?></span>
                        </div>
                        <div class="page-details">
                            <div class="page-name"><?php echo htmlspecialchars($page['page_title']); ?></div>
                            <div class="page-type-tag"><?php echo getPageTypeName($page['page_type']); ?></div>
                            <div class="page-url"><?php echo htmlspecialchars($page['page_url']); ?></div>
                        </div>
                        <div class="page-views">
                            <span class="views-count"><?php echo number_format($page['metric_value']); ?></span>
                            <span class="views-label"><?php echo $metricsType === 'unique' ? 'únicos' : 'views'; ?></span>
                            <div class="views-comparison">
                                <small><?php echo number_format($page['unique_visitors']); ?> únicos | <?php echo number_format($page['total_visits']); ?> total</small>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php else: ?>
                    <div class="no-data">
                        <i class="fas fa-chart-line"></i>
                        <p>Dados insuficientes para o período selecionado</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Páginas Recentes -->
        <div class="recent-pages-section">
            <div class="section-card">
                <div class="section-header">
                    <div class="section-title">
                        <h3>Páginas Monitoradas</h3>
                        <p>Sistema de tracking ativo</p>
                    </div>
                    <a href="page-list.php" class="view-all-btn">
                        Gerenciar <i class="fas fa-cog"></i>
                    </a>
                </div>
                <div class="pages-list">
                    <?php if (empty($recentPages)): ?>
                    <div class="empty-state">
                        <div class="empty-icon">
                            <i class="fas fa-radar"></i>
                        </div>
                        <h4>Sistema Pronto</h4>
                        <p>O tracking de visitantes únicos está ativo</p>
                        <a href="page-create.php" class="create-first-btn">
                            <i class="fas fa-plus"></i> Criar Primeira Página
                        </a>
                    </div>
                    <?php else: ?>
                    <?php foreach ($recentPages as $page): ?>
                    <div class="page-item">
                        <div class="page-icon">
                            <i class="fas <?php echo getPageTypeIcon($page['page_type']); ?>"></i>
                        </div>
                        <div class="page-info">
                            <div class="page-title"><?php echo htmlspecialchars($page['page_title']); ?></div>
                            <div class="page-meta">
                                <span class="page-type"><?php echo getPageTypeName($page['page_type']); ?></span>
                                <span class="page-date"><?php echo timeAgo($page['created_at']); ?></span>
                                <span class="page-url"><?php echo htmlspecialchars($page['page_url']); ?></span>
                            </div>
                        </div>
                        <div class="page-stats">
                            <div class="stat-item">
                                <span class="stat-value">
                                    <?php echo number_format($page['unique_visitors_24h']); ?>
                                </span>
                                <span class="stat-label">únicos hoje</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-value">
                                    <?php echo number_format($page['total_visits_24h']); ?>
                                </span>
                                <span class="stat-label">total hoje</span>
                            </div>
                        </div>
                        <div class="page-status">
                            <?php if ($page['page_id']): ?>
                            <span class="status-badge <?php echo $page['published'] ? 'published' : 'draft'; ?>">
                                <?php echo $page['published'] ? 'Publicada' : 'Rascunho'; ?>
                            </span>
                            <?php else: ?>
                            <span class="status-badge static">Estática</span>
                            <?php endif; ?>
                        </div>
                        <div class="page-actions">
                            <?php if ($page['page_id']): ?>
                            <a href="page-edit.php?id=<?php echo $page['page_id']; ?>" class="action-btn edit-btn" title="Editar">
                                <i class="fas fa-edit"></i>
                            </a>
                            <?php endif; ?>
                            <a href="reports.php?page_id=<?php echo $page['id']; ?>" class="action-btn analytics-btn" title="Análises">
                                <i class="fas fa-chart-line"></i>
                            </a>
                            <a href="<?php echo htmlspecialchars($page['page_url']); ?>" class="action-btn view-btn" title="Visualizar" target="_blank">
                                <i class="fas fa-external-link-alt"></i>
                            </a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Ações Rápidas -->
        <div class="quick-actions-section">
            <div class="section-card">
                <div class="section-header">
                    <div class="section-title">
                        <h3>Ações Rápidas</h3>
                        <p>Principais funcionalidades</p>
                    </div>
                </div>
                <div class="actions-grid">
                    <a href="page-create.php" class="action-card create-action">
                        <div class="action-icon">
                            <i class="fas fa-plus-circle"></i>
                        </div>
                        <div class="action-content">
                            <h4>Nova Página</h4>
                            <p>Criar com tracking automático</p>
                        </div>
                        <div class="action-arrow">
                            <i class="fas fa-arrow-right"></i>
                        </div>
                    </a>

                    <a href="reports.php?report_type=unique_visitors" class="action-card analytics-action">
                        <div class="action-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="action-content">
                            <h4>Visitantes Únicos</h4>
                            <p>Relatório detalhado</p>
                        </div>
                        <div class="action-arrow">
                            <i class="fas fa-arrow-right"></i>
                        </div>
                    </a>

                    <a href="reports.php?report_type=conversions" class="action-card conversion-action">
                        <div class="action-icon">
                            <i class="fas fa-chart-pie"></i>
                        </div>
                        <div class="action-content">
                            <h4>Conversões</h4>
                            <p>Análise de performance</p>
                        </div>
                        <div class="action-arrow">
                            <i class="fas fa-arrow-right"></i>
                        </div>
                    </a>

                    <a href="settings.php" class="action-card settings-action">
                        <div class="action-icon">
                            <i class="fas fa-cog"></i>
                        </div>
                        <div class="action-content">
                            <h4>Configurações</h4>
                            <p>Sistema e tracking</p>
                        </div>
                        <div class="action-arrow">
                            <i class="fas fa-arrow-right"></i>
                        </div>
                    </a>
                </div>
                
                <!-- Conversões Recentes -->
                <?php if (!empty($conversionStats)): ?>
                <div class="conversions-summary">
                    <h5>Conversões Recentes (Hoje)</h5>
                    <div class="conversion-items">
                        <?php foreach (array_slice($conversionStats, 0, 3) as $conversion): ?>
                        <div class="conversion-item">
                            <span class="conversion-type"><?php echo htmlspecialchars($conversion['conversion_type']); ?></span>
                            <span class="conversion-count"><?php echo number_format($conversion['conversion_count']); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Status Footer -->
    <div class="status-footer">
        <div class="status-items">
            <div class="status-item">
                <div class="status-icon system-status">
                    <i class="fas fa-server"></i>
                </div>
                <div class="status-info">
                    <span class="status-label">Sistema</span>
                    <span class="status-value online"><?php echo $systemHealth['database_status']; ?></span>
                </div>
            </div>

            <div class="status-item">
                <div class="status-icon tracking-status">
                    <i class="fas fa-user-check"></i>
                </div>
                <div class="status-info">
                    <span class="status-label">Tracking Único</span>
                    <span class="status-value active"><?php echo $systemHealth['unique_system_working'] ? 'Ativo' : 'Inativo'; ?></span>
                </div>
            </div>
            
            <div class="status-item">
                <div class="status-icon stats-status">
                    <i class="fas fa-chart-bar"></i>
                </div>
                <div class="status-info">
                    <span class="status-label">Páginas Monitoradas</span>
                    <span class="status-value"><?php echo number_format($systemHealth['total_tracked_pages']); ?></span>
                </div>
            </div>

            <div class="status-item">
                <div class="status-icon api-status">
                    <i class="fas fa-robot"></i>
                </div>
                <div class="status-info">
                    <span class="status-label">API Claude</span>
                    <span class="status-value connected">Conectada</span>
                </div>
            </div>

            <div class="status-item">
                <div class="status-icon cache-status">
                    <i class="fas fa-memory"></i>
                </div>
                <div class="status-info">
                    <span class="status-label">Cache</span>
                    <span class="status-value"><?php echo $systemHealth['cache_status']; ?></span>
                </div>
            </div>
        </div>
        
        <div class="footer-actions">
            <button class="footer-btn" onclick="refreshDashboard()">
                <i class="fas fa-sync-alt"></i>
                Atualizar
            </button>
            <button class="footer-btn" onclick="exportAllData()">
                <i class="fas fa-download"></i>
                Exportar Dados
            </button>
            <button class="footer-btn" onclick="viewSystemLogs()">
                <i class="fas fa-file-alt"></i>
                Logs do Sistema
            </button>
        </div>
    </div>
</div>

<!-- CSS Moderno e Responsivo -->
<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        --success-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        --warning-gradient: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        --danger-gradient: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        --info-gradient: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
        --conversion-gradient: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
        --performance-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        
        --bg-primary: #f8fafc;
        --bg-secondary: #ffffff;
        --bg-accent: #f1f5f9;
        
        --text-primary: #1e293b;
        --text-secondary: #64748b;
        --text-muted: #94a3b8;
        
        --border-light: #e2e8f0;
        --border-medium: #cbd5e1;
        
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        
        --radius-sm: 6px;
        --radius-md: 12px;
        --radius-lg: 16px;
        --radius-xl: 24px;
        
        --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        --transition-fast: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
        background: var(--bg-primary);
        color: var(--text-primary);
        line-height: 1.6;
        overflow-x: hidden;
    }

    .modern-dashboard {
        min-height: 100vh;
        padding: 20px;
        max-width: 1400px;
        margin: 0 auto;
        animation: fadeInUp 0.6s ease-out;
    }

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

    /* Dashboard Header */
    .dashboard-header {
        background: var(--bg-secondary);
        border-radius: var(--radius-xl);
        padding: 32px;
        margin-bottom: 30px;
        box-shadow: var(--shadow-lg);
        border: 1px solid var(--border-light);
        position: relative;
        overflow: hidden;
    }

    .dashboard-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--primary-gradient);
    }

    .header-content {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 30px;
    }

    .greeting-section {
        flex: 1;
    }

    .main-greeting {
        font-size: 36px;
        font-weight: 800;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .greeting-text {
        background: var(--primary-gradient);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .greeting-emoji {
        font-size: 32px;
        animation: wave 2s ease-in-out infinite;
    }

    @keyframes wave {
        0%, 100% { transform: rotate(0deg); }
        25% { transform: rotate(20deg); }
        75% { transform: rotate(-10deg); }
    }

    .date-subtitle {
        color: var(--text-secondary);
        font-size: 16px;
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .quick-stats {
        display: flex;
        gap: 24px;
        flex-wrap: wrap;
        align-items: center;
    }

    .quick-stat {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 14px;
        color: var(--text-secondary);
        background: var(--bg-accent);
        padding: 8px 12px;
        border-radius: var(--radius-md);
        font-weight: 500;
    }

    .quick-stat i {
        color: var(--text-muted);
    }

    .header-actions {
        display: flex;
        align-items: center;
        gap: 20px;
    }

    .time-widget {
        text-align: right;
        background: var(--bg-accent);
        padding: 16px 20px;
        border-radius: var(--radius-lg);
        border: 1px solid var(--border-light);
    }

    .time-display {
        font-size: 24px;
        font-weight: 700;
        color: var(--text-primary);
        font-variant-numeric: tabular-nums;
    }

    .timezone {
        font-size: 12px;
        color: var(--text-muted);
        margin-top: 4px;
    }

    .controls-widget {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .period-selector {
        display: flex;
        background: var(--bg-accent);
        border-radius: var(--radius-md);
        padding: 4px;
    }

    .period-btn {
        padding: 8px 16px;
        border: none;
        background: transparent;
        color: var(--text-secondary);
        font-size: 13px;
        font-weight: 500;
        border-radius: var(--radius-sm);
        cursor: pointer;
        transition: var(--transition-fast);
    }

    .period-btn.active,
    .period-btn:hover {
        background: white;
        color: var(--text-primary);
        box-shadow: var(--shadow-sm);
    }

    .metrics-toggle {
        display: flex;
        align-items: center;
        gap: 10px;
    }

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

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

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

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

    input:checked + .toggle-slider {
        background: var(--primary-gradient);
    }

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

    .toggle-label {
        font-size: 13px;
        font-weight: 600;
        color: var(--text-primary);
    }

    /* Reset Indicator Card */
    .reset-indicator-card {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        border: 1px solid var(--border-light);
        margin-bottom: 30px;
    }

    /* CSS para as estatísticas comparativas */
    .stat-comparison {
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 8px;
        border: 1px solid #dee2e6;
        transition: var(--transition);
    }

    .stat-comparison:hover {
        background: white;
        box-shadow: var(--shadow-md);
    }

    .stat-comparison .stat-value {
        font-size: 1.8rem;
        font-weight: 700;
        color: #2d3748;
        margin-bottom: 0.5rem;
    }

    .stat-comparison .stat-label {
        font-size: 0.9rem;
        color: #6c757d;
        font-weight: 500;
        margin-bottom: 0.25rem;
    }

    .stat-change.positive {
        color: #28a745;
        font-weight: 600;
    }

    .stat-change.negative {
        color: #dc3545;
        font-weight: 600;
    }

    .stat-meta {
        font-size: 0.8rem;
        color: #6c757d;
        font-style: italic;
    }

    /* Indicador de sistema ativo */
    .system-indicator {
        display: inline-block;
        width: 8px;
        height: 8px;
        background: #28a745;
        border-radius: 50%;
        margin-right: 5px;
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.5; }
        100% { opacity: 1; }
    }

    /* Metrics Grid */
    .metrics-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 24px;
        margin-bottom: 40px;
    }

    .metric-card {
        background: var(--bg-secondary);
        border-radius: var(--radius-lg);
        padding: 28px;
        box-shadow: var(--shadow-md);
        border: 1px solid var(--border-light);
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .metric-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        transition: var(--transition);
    }

    .metric-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-xl);
    }

    .pages-metric::before { background: var(--primary-gradient); }
    .views-metric::before { background: var(--success-gradient); }
    .conversion-metric::before { background: var(--conversion-gradient); }
    .performance-metric::before { background: var(--performance-gradient); }

    .metric-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 20px;
    }

    .metric-icon {
        width: 52px;
        height: 52px;
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
        color: white;
        box-shadow: var(--shadow-md);
    }

    .pages-metric .metric-icon { background: var(--primary-gradient); }
    .views-metric .metric-icon { background: var(--success-gradient); }
    .conversion-metric .metric-icon { background: var(--conversion-gradient); }
    .performance-metric .metric-icon { background: var(--performance-gradient); }

    .metric-trend {
        text-align: right;
    }

    .trend-value {
        font-size: 14px;
        font-weight: 600;
        display: block;
    }

    .trend-period {
        font-size: 12px;
        color: var(--text-muted);
        margin-top: 2px;
    }

    .trend-up { color: #10b981; }
    .trend-down { color: #ef4444; }

    .metric-content {
        margin-bottom: 20px;
    }

    .metric-value {
        font-size: 36px;
        font-weight: 800;
        line-height: 1;
        margin-bottom: 8px;
        font-variant-numeric: tabular-nums;
    }

    .metric-label {
        font-size: 16px;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 6px;
    }

    .metric-description {
        font-size: 14px;
        color: var(--text-secondary);
        line-height: 1.4;
    }

    .comparison-metric {
        color: var(--text-muted);
        font-size: 12px;
    }

    .metric-chart {
        height: 40px;
        margin-top: 20px;
    }

    /* Main Content Grid */
    .main-content-grid {
        display: grid;
        grid-template-columns: 2fr 1fr;
        gap: 30px;
        margin-bottom: 40px;
    }

    .section-card {
        background: var(--bg-secondary);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-md);
        border: 1px solid var(--border-light);
        overflow: hidden;
        transition: var(--transition);
    }

    .section-card:hover {
        box-shadow: var(--shadow-lg);
    }

    .section-header {
        padding: 24px 28px;
        border-bottom: 1px solid var(--border-light);
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }

    .section-title h3 {
        font-size: 20px;
        font-weight: 700;
        margin-bottom: 4px;
    }

    .section-title p {
        color: var(--text-secondary);
        font-size: 14px;
    }

    .section-actions {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .refresh-btn, .export-btn {
        width: 36px;
        height: 36px;
        border-radius: var(--radius-md);
        background: var(--bg-accent);
        border: 1px solid var(--border-light);
        color: var(--text-secondary);
        cursor: pointer;
        transition: var(--transition);
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .refresh-btn:hover, .export-btn:hover {
        background: var(--primary-gradient);
        color: white;
        border-color: transparent;
    }

    .view-all-btn {
        color: var(--text-secondary);
        text-decoration: none;
        font-size: 14px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 6px;
        transition: var(--transition);
    }

    .view-all-btn:hover {
        color: var(--text-primary);
    }

    .chart-container {
        padding: 20px 28px 28px;
        height: 320px;
    }

    .small-chart {
        height: 200px;
    }

    .chart-legend {
        padding: 0 28px 24px;
        display: flex;
        gap: 20px;
        flex-wrap: wrap;
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: var(--text-secondary);
    }

    .legend-color {
        width: 12px;
        height: 12px;
        border-radius: 2px;
    }

    .primary-color { background: #4facfe; }
    .secondary-color { background: #fcb69f; }

    /* Page Type Stats */
    .page-type-stats {
        padding: 20px 28px;
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
        gap: 16px;
        max-height: 240px;
        overflow-y: auto;
    }

    .page-type-stats .stat-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 16px;
        background: var(--bg-accent);
        border-radius: var(--radius-md);
        transition: var(--transition);
    }

    .page-type-stats .stat-item:hover {
        background: white;
        box-shadow: var(--shadow-md);
    }

    .stat-icon {
        width: 40px;
        height: 40px;
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 16px;
    }

    .stat-icon.database { background: var(--primary-gradient); }
    .stat-icon.static { background: var(--info-gradient); }

    .stat-info .stat-value {
        font-size: 24px;
        font-weight: 700;
        margin-bottom: 4px;
    }

    .stat-info .stat-label {
        font-size: 13px;
        color: var(--text-primary);
        font-weight: 600;
        margin-bottom: 2px;
    }

    .stat-info .stat-sublabel {
        font-size: 11px;
        color: var(--text-muted);
    }

    /* Bottom Grid */
    .bottom-grid {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        gap: 30px;
        margin-bottom: 40px;
    }

    /* Top Pages */
    .top-pages-list {
        padding: 20px 28px 28px;
        max-height: 400px;
        overflow-y: auto;
    }

    .top-page-item {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 16px 0;
        border-bottom: 1px solid var(--border-light);
    }

    .top-page-item:last-child {
        border-bottom: none;
    }

    .page-rank {
        width: 32px;
        text-align: center;
    }

    .rank-number {
        font-weight: 700;
        font-size: 18px;
        color: var(--text-primary);
    }

    .page-details {
        flex: 1;
    }

    .page-name {
        font-weight: 600;
        margin-bottom: 4px;
        font-size: 15px;
    }

    .page-type-tag {
        display: inline-block;
        background: var(--bg-accent);
        color: var(--text-secondary);
        padding: 2px 8px;
        border-radius: var(--radius-sm);
        font-size: 12px;
        font-weight: 500;
        margin-right: 8px;
    }

    .page-url {
        font-size: 12px;
        color: var(--text-muted);
        font-family: 'Courier New', monospace;
    }

    .page-views {
        text-align: center;
    }

    .views-count {
        font-size: 18px;
        font-weight: 700;
        display: block;
        color: var(--text-primary);
    }

    .views-label {
        font-size: 12px;
        color: var(--text-muted);
        text-transform: uppercase;
    }

    .views-comparison {
        margin-top: 4px;
    }

    .no-data {
        text-align: center;
        padding: 40px 20px;
        color: var(--text-muted);
    }

    .no-data i {
        font-size: 32px;
        margin-bottom: 12px;
        opacity: 0.5;
    }

    /* Recent Pages */
    .pages-list {
        padding: 20px 28px 28px;
        max-height: 500px;
        overflow-y: auto;
    }

    .empty-state {
        text-align: center;
        padding: 40px 20px;
    }

    .empty-icon {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: var(--bg-accent);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 20px;
        font-size: 32px;
        color: var(--text-muted);
    }

    .empty-state h4 {
        margin-bottom: 8px;
        color: var(--text-primary);
    }

    .empty-state p {
        color: var(--text-secondary);
        margin-bottom: 24px;
    }

    .create-first-btn {
        background: var(--primary-gradient);
        color: white;
        border: none;
        padding: 12px 24px;
        border-radius: var(--radius-md);
        font-weight: 600;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: var(--transition);
    }

    .create-first-btn:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-lg);
        color: white;
    }

    .page-item {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 16px 0;
        border-bottom: 1px solid var(--border-light);
        transition: var(--transition);
    }

    .page-item:last-child {
        border-bottom: none;
    }

    .page-item:hover {
        background: var(--bg-accent);
        margin: 0 -16px;
        padding: 16px;
        border-radius: var(--radius-md);
    }

    .page-icon {
        width: 40px;
        height: 40px;
        border-radius: var(--radius-md);
        background: var(--bg-accent);
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-secondary);
        border: 1px solid var(--border-light);
    }

    .page-info {
        flex: 1;
    }

    .page-title {
        font-weight: 600;
        margin-bottom: 4px;
        font-size: 15px;
        line-height: 1.3;
    }

    .page-meta {
        display: flex;
        gap: 12px;
        font-size: 13px;
        color: var(--text-muted);
        flex-wrap: wrap;
    }

    .page-type {
        background: var(--bg-accent);
        padding: 2px 8px;
        border-radius: var(--radius-sm);
        font-weight: 500;
    }

    .page-stats {
        display: flex;
        gap: 16px;
        text-align: center;
    }

    .page-stats .stat-item .stat-value {
        font-size: 16px;
        font-weight: 700;
        display: block;
    }

    .page-stats .stat-item .stat-label {
        font-size: 11px;
        color: var(--text-muted);
        text-transform: uppercase;
    }

    .page-status {
        margin-left: 12px;
    }

    .status-badge {
        padding: 4px 12px;
        border-radius: var(--radius-md);
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .status-badge.published {
        background: rgba(16, 185, 129, 0.1);
        color: #059669;
    }

    .status-badge.draft {
        background: rgba(245, 158, 11, 0.1);
        color: #d97706;
    }

    .status-badge.static {
        background: rgba(59, 130, 246, 0.1);
        color: #2563eb;
    }

    .page-actions {
        display: flex;
        gap: 8px;
        margin-left: 12px;
    }

    .action-btn {
        width: 32px;
        height: 32px;
        border-radius: var(--radius-md);
        border: 1px solid var(--border-light);
        background: white;
        color: var(--text-secondary);
        display: flex;
        align-items: center;
        justify-content: center;
        text-decoration: none;
        transition: var(--transition);
        font-size: 14px;
    }

    .action-btn:hover {
        background: var(--primary-gradient);
        color: white;
        border-color: transparent;
        transform: translateY(-1px);
    }

    .analytics-btn:hover {
        background: var(--warning-gradient);
    }

    /* Quick Actions */
    .actions-grid {
        padding: 20px 28px;
        display: grid;
        gap: 16px;
    }

    .action-card {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 20px;
        background: var(--bg-accent);
        border: 1px solid var(--border-light);
        border-radius: var(--radius-lg);
        text-decoration: none;
        color: var(--text-primary);
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .action-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        width: 4px;
        transition: var(--transition);
    }

    .action-card:hover {
        background: white;
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
        color: var(--text-primary);
    }

    .create-action::before { background: var(--primary-gradient); }
    .analytics-action::before { background: var(--success-gradient); }
    .conversion-action::before { background: var(--warning-gradient); }
    .settings-action::before { background: var(--info-gradient); }

    .action-card .action-icon {
        width: 48px;
        height: 48px;
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        color: white;
        box-shadow: var(--shadow-md);
    }

    .create-action .action-icon { background: var(--primary-gradient); }
    .analytics-action .action-icon { background: var(--success-gradient); }
    .conversion-action .action-icon { background: var(--warning-gradient); }
    .settings-action .action-icon { background: var(--info-gradient); }

    .action-content {
        flex: 1;
    }

    .action-content h4 {
        margin-bottom: 4px;
        font-size: 16px;
        font-weight: 600;
    }

    .action-content p {
        color: var(--text-secondary);
        font-size: 14px;
        margin: 0;
    }

    .action-arrow {
        color: var(--text-muted);
        transition: var(--transition);
    }

    .action-card:hover .action-arrow {
        color: var(--text-primary);
        transform: translateX(4px);
    }

    /* Conversions Summary */
    .conversions-summary {
        padding: 20px 28px 0;
        border-top: 1px solid var(--border-light);
        margin-top: 20px;
    }

    .conversions-summary h5 {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 12px;
        color: var(--text-primary);
    }

    .conversion-items {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .conversion-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background: var(--bg-accent);
        border-radius: var(--radius-md);
        font-size: 13px;
    }

    .conversion-type {
        font-weight: 500;
        color: var(--text-primary);
    }

    .conversion-count {
        font-weight: 700;
        color: var(--text-secondary);
    }

    /* Status Footer */
    .status-footer {
        background: var(--bg-secondary);
        border-radius: var(--radius-lg);
        padding: 24px 28px;
        box-shadow: var(--shadow-md);
        border: 1px solid var(--border-light);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .status-items {
        display: flex;
        gap: 32px;
    }

    .status-item {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .status-icon {
        width: 40px;
        height: 40px;
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        color: white;
    }

    .system-status { background: var(--success-gradient); }
    .api-status { background: var(--primary-gradient); }
    .tracking-status { background: var(--info-gradient); }
    .stats-status { background: var(--warning-gradient); }
    .cache-status { background: var(--performance-gradient); }

    .status-info {
        display: flex;
        flex-direction: column;
    }

    .status-label {
        font-size: 12px;
        color: var(--text-muted);
        text-transform: uppercase;
        letter-spacing: 0.5px;
        font-weight: 600;
    }

    .status-value {
        font-size: 14px;
        font-weight: 600;
        margin-top: 2px;
    }

    .status-value.online { color: #10b981; }
    .status-value.connected { color: #3b82f6; }
    .status-value.active { color: #f59e0b; }

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

    .footer-btn {
        padding: 10px 16px;
        background: var(--bg-accent);
        border: 1px solid var(--border-light);
        border-radius: var(--radius-md);
        color: var(--text-secondary);
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .footer-btn:hover {
        background: var(--primary-gradient);
        color: white;
        border-color: transparent;
    }

    /* Responsive Design */
    @media (max-width: 1200px) {
        .main-content-grid {
            grid-template-columns: 1fr;
        }
        
        .bottom-grid {
            grid-template-columns: 1fr 1fr;
        }
    }

    @media (max-width: 768px) {
        .modern-dashboard {
            padding: 16px;
        }
        
        .dashboard-header {
            padding: 24px;
        }
        
        .header-content {
            flex-direction: column;
            gap: 20px;
        }
        
        .main-greeting {
            font-size: 28px;
        }
        
        .metrics-grid {
            grid-template-columns: 1fr;
            gap: 16px;
        }
        
        .bottom-grid {
            grid-template-columns: 1fr;
            gap: 20px;
        }
        
        .quick-stats {
            flex-direction: column;
            gap: 12px;
        }
        
        .status-footer {
            flex-direction: column;
            gap: 20px;
        }
        
        .status-items {
            flex-wrap: wrap;
            justify-content: center;
            gap: 20px;
        }

        .page-type-stats {
            grid-template-columns: 1fr;
            gap: 12px;
        }

        .row {
            margin: 0;
        }

        .col-md-3 {
            padding: 8px;
        }
    }

    @media (max-width: 480px) {
        .section-card {
            margin: 0 -8px;
        }
        
        .section-header {
            padding: 20px;
        }
        
        .chart-container {
            padding: 16px 20px 20px;
        }
        
        .page-item {
            flex-wrap: wrap;
            gap: 12px;
        }
        
        .page-stats {
            order: 3;
            width: 100%;
            justify-content: space-around;
        }

        .controls-widget {
            flex-direction: row;
            gap: 16px;
        }
    }
</style>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// === CONFIGURAÇÕES GLOBAIS ===
const isUniqueMetrics = <?php echo $metricsType === 'unique' ? 'true' : 'false'; ?>;
const currentPeriod = '<?php echo $period; ?>';
const metricsLabel = isUniqueMetrics ? 'Visitantes Únicos' : 'Visualizações';

// === FUNÇÃO PARA ALTERNAR MÉTRICAS ===
function toggleMetrics(isUnique) {
    const currentUrl = new URL(window.location);
    currentUrl.searchParams.set('metrics', isUnique ? 'unique' : 'all');
    window.location.href = currentUrl.toString();
}

// === FUNÇÃO PARA ALTERNAR PERÍODO ===
function changePeriod(period) {
    const currentUrl = new URL(window.location);
    currentUrl.searchParams.set('period', period);
    window.location.href = currentUrl.toString();
}

// === INICIALIZAÇÃO ===
document.addEventListener('DOMContentLoaded', function() {
    // Atualizar relógio
    function updateTime() {
        const now = new Date();
        const timeString = now.toLocaleTimeString('pt-BR', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        document.getElementById('currentTime').textContent = timeString;
    }
    updateTime();
    setInterval(updateTime, 1000);

    // Event listeners para seletores de período
    document.querySelectorAll('.period-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const period = this.dataset.period;
            changePeriod(period);
        });
    });

    // === CONFIGURAR CHART.JS ===
    Chart.defaults.font.family = "'Inter', sans-serif";
    Chart.defaults.color = '#64748b';

   
    // === DADOS PARA GRÁFICOS ===
    const chartData = {
        labels: [<?php 
            if (!empty($viewsChart)) {
                foreach ($viewsChart as $item) {
                    echo "'" . $item['formatted_time'] . "', ";
                }
            } else {
                // Dados padrão baseados no período
                if ($period === '24h') {
                    for ($i = 23; $i >= 0; $i--) {
                        echo "'" . date('H:00', strtotime("-$i hours")) . "', ";
                    }
                } else {
                    for ($i = 6; $i >= 0; $i--) {
                        echo "'" . date('d/m', strtotime("-$i days")) . "', ";
                    }
                }
            }
        ?>],
        datasets: [{
            label: metricsLabel,
            data: [<?php 
                if (!empty($viewsChart)) {
                    foreach ($viewsChart as $item) {
                        $value = $metricsType === 'unique' ? $item['unique_visitors'] : $item['total_visits'];
                        echo $value . ", ";
                    }
                } else {
                    // Dados de exemplo
                    echo "0, 0, 0, 0, 0, 0, 0";
                }
            ?>],
            backgroundColor: 'rgba(79, 172, 254, 0.1)',
            borderColor: '#4facfe',
            borderWidth: 3,
            tension: 0.4,
            fill: true,
            pointBackgroundColor: '#4facfe',
            pointBorderColor: '#ffffff',
            pointBorderWidth: 2,
            pointRadius: 6,
            pointHoverRadius: 8
        }]
    };

    // === GRÁFICO PRINCIPAL ===
    const mainCtx = document.getElementById('mainChart').getContext('2d');
    new Chart(mainCtx, {
        type: 'line',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(15, 23, 42, 0.9)',
                    titleColor: '#f1f5f9',
                    bodyColor: '#f1f5f9',
                    borderColor: 'rgba(148, 163, 184, 0.2)',
                    borderWidth: 1,
                    cornerRadius: 8,
                    displayColors: false,
                    callbacks: {
                        title: function(context) {
                            return `${context[0].label}`;
                        },
                        label: function(context) {
                            return `${metricsLabel}: ${context.parsed.y}`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(148, 163, 184, 0.1)',
                        drawBorder: false
                    },
                    ticks: {
                        font: { size: 12 },
                        color: '#64748b'
                    }
                },
                x: {
                    grid: { 
                        display: false 
                    },
                    ticks: {
                        font: { size: 12 },
                        color: '#64748b'
                    }
                }
            },
            interaction: {
                intersect: false,
                mode: 'index'
            }
        }
    });

    // === GRÁFICO DE TIPOS DE PÁGINA ===
    const pageTypeCtx = document.getElementById('pageTypeChart').getContext('2d');
    new Chart(pageTypeCtx, {
        type: 'doughnut',
        data: {
            labels: [<?php 
                if (!empty($pageTypeStats)) {
                    foreach ($pageTypeStats as $typeData) {
                        echo "'" . getPageTypeName($typeData['page_type']) . "', ";
                    }
                }
            ?>],
            datasets: [{
                data: [<?php 
                    if (!empty($pageTypeStats)) {
                        foreach ($pageTypeStats as $typeData) {
                            $value = $metricsType === 'unique' ? $typeData['unique_visitors_24h'] : $typeData['total_visits_24h'];
                            echo $value . ", ";
                        }
                    }
                ?>],
                backgroundColor: [
                    'rgba(79, 172, 254, 0.8)',
                    'rgba(168, 237, 234, 0.8)',
                    'rgba(67, 233, 123, 0.8)',
                    'rgba(240, 147, 251, 0.8)'
                ],
                borderWidth: 0,
                hoverOffset: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            cutout: '60%'
        }
    });

    // === MINI CHARTS PARA CARDS ===
    const miniChartOptions = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: {
            x: { display: false },
            y: { display: false }
        },
        elements: {
            point: { radius: 0 },
            line: { tension: 0.4 }
        }
    };

    // Chart para páginas
    if (document.getElementById('pagesChart')) {
        new Chart(document.getElementById('pagesChart'), {
            type: 'line',
            data: {
                labels: ['', '', '', '', '', '', ''],
                datasets: [{
                    data: [<?php echo max(1, $stats['total'] - 6); ?>, <?php echo max(1, $stats['total'] - 5); ?>, <?php echo max(1, $stats['total'] - 4); ?>, <?php echo max(1, $stats['total'] - 3); ?>, <?php echo max(1, $stats['total'] - 2); ?>, <?php echo max(1, $stats['total'] - 1); ?>, <?php echo $stats['total']; ?>],
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    borderWidth: 2,
                    fill: true
                }]
            },
            options: miniChartOptions
        });
    }

    // Chart para visitantes/views
    if (document.getElementById('viewsChart')) {
        new Chart(document.getElementById('viewsChart'), {
            type: 'line',
            data: {
                labels: ['', '', '', '', '', '', ''],
                datasets: [{
                    data: [<?php 
                        if (!empty($viewsChart) && count($viewsChart) >= 7) {
                            $chartValues = array_slice($viewsChart, -7);
                            foreach ($chartValues as $item) {
                                $value = $metricsType === 'unique' ? $item['unique_visitors'] : $item['total_visits'];
                                echo $value . ", ";
                            }
                        } else {
                            echo "0, 0, 0, 0, 0, 0, " . $currentMetric;
                        }
                    ?>],
                    borderColor: '#4facfe',
                    backgroundColor: 'rgba(79, 172, 254, 0.1)',
                    borderWidth: 2,
                    fill: true
                }]
            },
            options: miniChartOptions
        });
    }

    // Chart para conversão
    if (document.getElementById('conversionChart')) {
        new Chart(document.getElementById('conversionChart'), {
            type: 'line',
            data: {
                labels: ['', '', '', '', '', '', ''],
                datasets: [{
                    data: [<?php echo $visitorStats['conversion_rate'] - 1; ?>, <?php echo $visitorStats['conversion_rate'] - 0.5; ?>, <?php echo $visitorStats['conversion_rate'] - 0.8; ?>, <?php echo $visitorStats['conversion_rate'] + 0.3; ?>, <?php echo $visitorStats['conversion_rate']; ?>, <?php echo $visitorStats['conversion_rate'] + 0.5; ?>, <?php echo $visitorStats['conversion_rate'] + 0.2; ?>],
                    borderColor: '#fcb69f',
                    backgroundColor: 'rgba(252, 182, 159, 0.1)',
                    borderWidth: 2,
                    fill: true
                }]
            },
            options: miniChartOptions
        });
    }

    // Chart para performance
    if (document.getElementById('performanceChart')) {
        new Chart(document.getElementById('performanceChart'), {
            type: 'bar',
            data: {
                labels: ['', '', '', '', '', '', ''],
                datasets: [{
                    data: [2.8, 2.6, 2.9, 2.3, 2.1, <?php echo $avgLoadTime; ?>, 2.2],
                    backgroundColor: 'rgba(102, 126, 234, 0.8)',
                    borderRadius: 4
                }]
            },
            options: miniChartOptions
        });
    }
});

// === FUNÇÕES GLOBAIS ===
function refreshChart() {
    const icon = event.target.querySelector('i');
    icon.style.animation = 'spin 1s linear';
    setTimeout(() => {
        icon.style.animation = '';
        location.reload();
    }, 1000);
}

function refreshDashboard() {
    const refreshIcon = event.target.querySelector('i');
    refreshIcon.style.animation = 'spin 1s linear';
    
    setTimeout(() => {
        refreshIcon.style.animation = '';
        location.reload();
    }, 1000);
}

function exportChartData() {
    const data = {
        period: currentPeriod,
        metrics_type: isUniqueMetrics ? 'unique' : 'all',
        chart_data: <?php echo json_encode($viewsChart); ?>,
        timestamp: new Date().toISOString()
    };
    
    downloadJSON(data, `chart_data_${currentPeriod}_${new Date().toISOString().split('T')[0]}.json`);
}

function exportAllData() {
    const data = {
        period: currentPeriod,
        metrics_type: isUniqueMetrics ? 'unique' : 'all',
        stats: {
            pages: <?php echo json_encode($stats); ?>,
            visitors: <?php echo json_encode($visitorStats); ?>,
            top_pages: <?php echo json_encode($topPages); ?>,
            recent_pages: <?php echo json_encode($recentPages); ?>,
            page_type_stats: <?php echo json_encode($pageTypeStats); ?>,
            conversion_stats: <?php echo json_encode($conversionStats); ?>,
            system_health: <?php echo json_encode($systemHealth); ?>
        },
        timestamp: new Date().toISOString()
    };
    
    downloadJSON(data, `dashboard_completo_${currentPeriod}_${new Date().toISOString().split('T')[0]}.json`);
}

function viewSystemLogs() {
    // Implementar visualização de logs
    alert('Funcionalidade de logs será implementada em breve');
}

function downloadJSON(data, filename) {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// === CSS PARA ANIMAÇÕES ===
const style = document.createElement('style');
style.textContent = `
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
`;
document.head.appendChild(style);
</script>

<?php require_once 'inc/footer.php'; ?>