<?php
// includes/header.php

// Previne acceso directo
if (!defined('BASE_PATH')) {
    die('Acceso directo no permitido');
}

// Define valores padrão para evitar warnings
$pageTitle = $pageTitle ?? SITE_NAME;
$metaDescription = $metaDescription ?? 'Cursos gratuitos para tu evolución profesional';
$metaKeywords = $metaKeywords ?? 'cursos gratuitos, educación online, aprendizaje';
$currentPage = $currentPage ?? '';
$showHeader = $showHeader ?? false;
$breadcrumbs = $breadcrumbs ?? [];

/**
 * Obtém a URL da imagem destacada com fallback
 */
function getFeaturedImageUrl($page, $withFallback = true) {
    if (!empty($page['featured_image'])) {
        // Verificar se o arquivo existe
        $imagePath = BASE_PATH . $page['featured_image'];
        if (file_exists($imagePath)) {
            return SITE_URL . $page['featured_image'];
        }
    }
    
    // Fallback para imagem padrão
    if ($withFallback) {
        $defaultImage = '/assets/img/default-featured-image.jpg';
        $defaultImagePath = BASE_PATH . $defaultImage;
        
        // Verifica se a imagem padrão existe
        if (file_exists($defaultImagePath)) {
            return SITE_URL . $defaultImage;
        }
        
        // Fallback final - logo do site
        return SITE_URL . '/assets/img/logo.png';
    }
    
    return '';
}

/**
 * Obtém dimensões da imagem destacada
 */
function getFeaturedImageDimensions($page) {
    if (!empty($page['featured_image'])) {
        $imagePath = BASE_PATH . $page['featured_image'];
        if (file_exists($imagePath)) {
            $imageInfo = getimagesize($imagePath);
            if ($imageInfo) {
                return [
                    'width' => $imageInfo[0],
                    'height' => $imageInfo[1],
                    'type' => $imageInfo['mime']
                ];
            }
        }
    }
    
    // Dimensões padrão otimizadas para redes sociais
    return [
        'width' => 1200,
        'height' => 630,
        'type' => 'image/jpeg'
    ];
}

/**
 * Gera alt text otimizado para a imagem
 */
function getFeaturedImageAlt($page) {
    if (!empty($page['title'])) {
        return htmlspecialchars($page['title'] . ' - ' . SITE_NAME);
    }
    
    return htmlspecialchars(SITE_NAME . ' - Cursos gratuitos online');
}

/**
 * Verifica se uma imagem é válida
 */
function isValidImage($imagePath) {
    if (!file_exists($imagePath)) {
        return false;
    }
    
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $imageInfo = getimagesize($imagePath);
    
    return $imageInfo && in_array($imageInfo['mime'], $allowedTypes);
}

// Preparar dados da imagem destacada
$featuredImage = '';
$imageDimensions = ['width' => 1200, 'height' => 630, 'type' => 'image/jpeg'];
$imageAlt = '';

if (isset($page) && is_array($page)) {
    $featuredImage = getFeaturedImageUrl($page);
    $imageDimensions = getFeaturedImageDimensions($page);
    $imageAlt = getFeaturedImageAlt($page);
} else {
    // Página sem dados específicos - usar imagem padrão
    $featuredImage = getFeaturedImageUrl([], true);
    $imageAlt = htmlspecialchars(SITE_NAME . ' - Cursos gratuitos online');
}

// Carrega sistema de tracking de visitantes únicos
if (file_exists(BASE_PATH . '/includes/visitor-tracking.php')) {
    require_once BASE_PATH . '/includes/visitor-tracking.php';
}

// Carrega sistema de tracking UTM
if (file_exists(BASE_PATH . '/includes/utm-tracking.php')) {
    require_once BASE_PATH . '/includes/utm-tracking.php';
    
    // Inicializa tracking
    try {
        initUtmTracking();
        
        // Registra page view com UTMs se tiver página definida
        if (isset($page) && isset($page['id'])) {
            registerConversion($page['id'], 'page_view', [
                'page_type' => $pageType ?? 'unknown',
                'page_title' => $page['title'] ?? '',
                'landing_page_id' => $page['landing_page_id'] ?? null
            ]);
        }
    } catch (Exception $e) {
        if (function_exists('logError')) {
            logError("Erro no tracking UTM: " . $e->getMessage());
        }
    }
} else {
    // Fallback se arquivo não existir
    if (function_exists('logError')) {
        logError("Arquivo utm-tracking.php não encontrado");
    }
}

// Carrega funções de anúncios
if (file_exists(BASE_PATH . '/includes/ads-functions.php')) {
    require_once BASE_PATH . '/includes/ads-functions.php';
}

// Função para registrar visita única automaticamente
function autoTrackPageView() {
    global $visitorTracking, $page, $db;
    
    // Só registra se tiver o sistema de tracking e uma página definida
    if (isset($visitorTracking) && is_object($visitorTracking) && isset($page) && isset($page['id'])) {
        try {
            $isNewUniqueVisit = $visitorTracking->trackUniquePageView($page['id']);
            
            // Retorna dados para usar no JavaScript
            return [
                'page_id' => $page['id'],
                'page_type' => $page['type'] ?? 'unknown',
                'page_title' => $page['title'] ?? '',
                'landing_page_id' => $page['landing_page_id'] ?? null,
                'is_new_unique_visit' => $isNewUniqueVisit,
                'slug' => $page['slug'] ?? ''
            ];
        } catch (Exception $e) {
            if (function_exists('logError')) {
                logError("Erro no auto-tracking: " . $e->getMessage());
            }
        }
    }
    
    return null;
}

// Registra a visita automaticamente
$trackingData = autoTrackPageView();

// Função helper para verificar página ativa
function isActivePage($page, $currentPage = '') {
    return $currentPage === $page ? 'active' : '';
}

// Função para adicionar scripts de tracking no header
function addTrackingScripts($trackingData = null) {
    $trackingJson = $trackingData ? json_encode($trackingData) : 'null';
    
    echo "
    <script>
    // Dados de tracking da página
    window.pageTrackingData = {$trackingJson};
    
    // Sistema de rastreamento de visitantes únicos
    (function() {
        let startTime = Date.now();
        let maxScroll = 0;
        let isActive = true;
        let engagementTimer;
        
        // Função para rastrear scroll
        function trackScroll() {
            const scrollPercent = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
            maxScroll = Math.max(maxScroll, scrollPercent);
        }
        
        // Função para enviar dados de engajamento
        function sendEngagement() {
            if (!window.pageTrackingData || !window.pageTrackingData.page_id) return;
            
            const timeSpent = Math.round((Date.now() - startTime) / 1000);
            
            fetch('/api/track-engagement.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    page_id: window.pageTrackingData.page_id,
                    time_spent: timeSpent,
                    max_scroll: maxScroll,
                    is_active: isActive
                })
            }).catch(error => {
                console.warn('Erro no tracking de engajamento:', error);
            });
        }
        
        // Função para rastrear ações
        function trackAction(action, targetUrl = null) {
            if (!window.pageTrackingData || !window.pageTrackingData.page_id) return;
            
            const timeSpent = Math.round((Date.now() - startTime) / 1000);
            
            fetch('/api/track-action.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    page_id: window.pageTrackingData.page_id,
                    action: action,
                    target_url: targetUrl,
                    time_spent: timeSpent,
                    max_scroll: maxScroll
                })
            }).catch(error => {
                console.warn('Erro no tracking de ação:', error);
            });
        }
        
        // Event listeners
        document.addEventListener('DOMContentLoaded', function() {
            // Log inicial (apenas se debug estiver ativo)
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.has('debug') && urlParams.get('debug') === '1' && window.pageTrackingData) {
                console.log('=== DEBUG TRACKING ===');
                console.log('Dados da página:', window.pageTrackingData);
                console.log('Nova visita única:', window.pageTrackingData.is_new_unique_visit);
            }
            
            // Rastrear scroll
            window.addEventListener('scroll', trackScroll, { passive: true });
            
            // Rastrear cliques em links externos
            document.addEventListener('click', function(e) {
                const link = e.target.closest('a');
                if (link && link.href) {
                    const url = new URL(link.href, window.location.origin);
                    
                    // Link externo
                    if (url.hostname !== window.location.hostname) {
                        trackAction('external_link', link.href);
                    }
                    // Link interno
                    else if (url.pathname !== window.location.pathname) {
                        trackAction('internal_navigation', link.href);
                    }
                }
            });
            
            // Rastrear cliques em botões CTA
            document.addEventListener('click', function(e) {
                if (e.target.matches('.btn-primary, .cta-button, [data-track=\"cta\"]')) {
                    trackAction('cta_click', e.target.href || e.target.dataset.target);
                }
            });
            
            // Rastrear envio de formulários
            document.addEventListener('submit', function(e) {
                trackAction('form_submit', e.target.action);
            });
            
            // Rastrear atividade da aba
            document.addEventListener('visibilitychange', function() {
                isActive = !document.hidden;
                if (document.hidden) {
                    sendEngagement();
                }
            });
            
            // Rastrear saída da página
            window.addEventListener('beforeunload', function() {
                const timeSpent = Math.round((Date.now() - startTime) / 1000);
                
                // Usar sendBeacon para garantir que os dados sejam enviados
                if (navigator.sendBeacon && window.pageTrackingData && window.pageTrackingData.page_id) {
                    const data = JSON.stringify({
                        page_id: window.pageTrackingData.page_id,
                        action: 'page_exit',
                        time_spent: timeSpent,
                        max_scroll: maxScroll
                    });
                    
                    navigator.sendBeacon('/api/track-action.php', data);
                }
            });
            
            // Enviar engajamento a cada 30 segundos
            engagementTimer = setInterval(sendEngagement, 30000);
        });
        
        // Expor funções globalmente para uso em páginas específicas
        window.trackAction = trackAction;
        window.sendEngagement = sendEngagement;
        
    })();
    </script>";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <!-- Meta Pixel Code -->
    <script>
    !function(f,b,e,v,n,t,s)
    {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};
    if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
    n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t,s)}(window, document,'script',
    'https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', '1072962847376387');
    fbq('track', 'PageView');
    
    // Track unique visitor event if it's a new unique visit
    <?php if ($trackingData && $trackingData['is_new_unique_visit']): ?>
    fbq('track', 'UniqueVisitor', {
        page_type: '<?php echo $trackingData['page_type']; ?>',
        page_id: '<?php echo $trackingData['page_id']; ?>'
    });
    <?php endif; ?>
    </script>
    <noscript><img height="1" width="1" style="display:none"
    src="https://www.facebook.com/tr?id=1072962847376387&ev=PageView&noscript=1"
    /></noscript>
    <!-- End Meta Pixel Code -->
    
    <!-- Meta Pixel Code -->
    <script>
    !function(f,b,e,v,n,t,s)
    {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};
    if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
    n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t,s)}(window, document,'script',
    'https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', '532372875999076');
    fbq('track', 'PageView');
    
    // Track unique visitor event for second pixel too
    <?php if ($trackingData && $trackingData['is_new_unique_visit']): ?>
    fbq('track', 'UniqueVisitor', {
        page_type: '<?php echo $trackingData['page_type']; ?>',
        page_id: '<?php echo $trackingData['page_id']; ?>'
    });
    <?php endif; ?>
    </script>
    <noscript><img height="1" width="1" style="display:none"
    src="https://www.facebook.com/tr?id=532372875999076&ev=PageView&noscript=1"
    /></noscript>
    <!-- End Meta Pixel Code -->
       
     <!-- Clarity -->
    <script type="text/javascript">
    (function(c,l,a,r,i,t,y){
        c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
        t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
        y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
    })(window, document, "clarity", "script", "ro1sk2ftbh");
</script>

    <?php if (function_exists('addTrackingHeaderCodes')) addTrackingHeaderCodes(); ?>
  
   <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9919806376063326"
     crossorigin="anonymous"></script>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($pageTitle) && $pageTitle !== SITE_NAME ? $pageTitle . ' - ' . SITE_NAME : SITE_NAME; ?></title>
    
    <!-- Meta tags básicas -->
    <meta name="description" content="<?php echo htmlspecialchars($metaDescription); ?>">
    <meta name="keywords" content="<?php echo htmlspecialchars($metaKeywords); ?>">
    <meta name="robots" content="index, follow">
    <link rel="canonical" href="<?php echo getCurrentUrl(); ?>">
    
    <!-- Open Graph Meta Tags -->
    <meta property="og:title" content="<?php echo htmlspecialchars($pageTitle . ' - ' . SITE_NAME); ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($metaDescription); ?>">
    <meta property="og:image" content="<?php echo $featuredImage; ?>">
    <meta property="og:image:width" content="<?php echo $imageDimensions['width']; ?>">
    <meta property="og:image:height" content="<?php echo $imageDimensions['height']; ?>">
    <meta property="og:image:type" content="<?php echo $imageDimensions['type']; ?>">
    <meta property="og:image:alt" content="<?php echo $imageAlt; ?>">
    <meta property="og:url" content="<?php echo getCurrentUrl(); ?>">
    <meta property="og:type" content="article">
    <meta property="og:site_name" content="<?php echo htmlspecialchars(SITE_NAME); ?>">
    <meta property="og:locale" content="es_ES">
    
    <!-- Twitter Card Meta Tags -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo htmlspecialchars($pageTitle); ?>">
    <meta name="twitter:description" content="<?php echo htmlspecialchars($metaDescription); ?>">
    <meta name="twitter:image" content="<?php echo $featuredImage; ?>">
    <meta name="twitter:image:alt" content="<?php echo $imageAlt; ?>">
    <meta name="twitter:site" content="@<?php echo SITE_NAME; ?>">
    <meta name="twitter:creator" content="@<?php echo SITE_NAME; ?>">
    
    <!-- Meta tags adicionales para SEO -->
    <meta name="author" content="<?php echo SITE_NAME; ?>">
    <meta name="generator" content="Custom CMS">
    <?php if (isset($page) && isset($page['created_at'])): ?>
    <meta name="article:published_time" content="<?php echo date('c', strtotime($page['created_at'])); ?>">
    <?php endif; ?>
    <?php if (isset($page) && isset($page['updated_at']) && $page['updated_at']): ?>
    <meta name="article:modified_time" content="<?php echo date('c', strtotime($page['updated_at'])); ?>">
    <?php endif; ?>
    
    <!-- Favicon -->
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon" href="/assets/img/icon-192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/assets/img/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/assets/img/favicon-16x16.png">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Estilos de Anúncios -->
    <?php if (function_exists('addAdStyles')) addAdStyles(); ?>
    
    <!-- JSON-LD Structured Data -->
    <?php if (isset($page) && is_array($page)): ?>
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "Article",
        "headline": "<?php echo htmlspecialchars($page['title'] ?? $pageTitle); ?>",
        "description": "<?php echo htmlspecialchars($metaDescription); ?>",
        "image": "<?php echo $featuredImage; ?>",
        "url": "<?php echo getCurrentUrl(); ?>",
        "datePublished": "<?php echo isset($page['created_at']) ? date('c', strtotime($page['created_at'])) : date('c'); ?>",
        <?php if (isset($page['updated_at']) && $page['updated_at']): ?>
        "dateModified": "<?php echo date('c', strtotime($page['updated_at'])); ?>",
        <?php endif; ?>
        "author": {
            "@type": "Organization",
            "name": "<?php echo htmlspecialchars(SITE_NAME); ?>",
            "url": "<?php echo SITE_URL; ?>"
        },
        "publisher": {
            "@type": "Organization",
            "name": "<?php echo htmlspecialchars(SITE_NAME); ?>",
            "logo": {
                "@type": "ImageObject",
                "url": "<?php echo SITE_URL; ?>/assets/img/logo.png"
            }
        },
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "<?php echo getCurrentUrl(); ?>"
        }
    }
    </script>
    <?php endif; ?>
    
    <style>
        :root {
            --primary-color: #4F46E5;
            --secondary-color: #7C3AED;
            --accent-color: #EC4899;
            --dark-color: #1F2937;
            --light-color: #F8FAFC;
            --text-color: #1F2937;
            --border-color: #E5E7EB;
            --gradient: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            --whatsapp-color: #25D366;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            color: var(--text-color);
            line-height: 1.6;
            background-color: #ffffff;
        }
        
        .navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            padding: 1rem 0;
            transition: all 0.3s ease;
        }
        
        .navbar.scrolled {
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }
        
        .navbar-brand {
            font-weight: 600;
            font-size: 1.3rem;
            color: var(--primary-color) !important;
            text-decoration: none;
            display: flex;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .navbar-brand:hover {
            color: var(--secondary-color) !important;
            transform: scale(1.05);
        }
        
        .navbar-brand img {
            height: 40px;
            width: auto;
            margin-right: 0.5rem;
            object-fit: contain;
        }
        
        .navbar-toggler {
            border: none;
            outline: none;
            box-shadow: none;
        }
        
        .navbar-toggler:focus {
            box-shadow: none;
        }
        
        .navbar-toggler-icon {
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%2879, 70, 229, 1%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
        }
        
        .nav-link {
            color: var(--text-color) !important;
            font-weight: 500;
            padding: 0.5rem 1rem !important;
            transition: all 0.3s ease;
            border-radius: 6px;
            margin: 0 0.25rem;
        }
        
        .nav-link:hover {
            color: var(--primary-color) !important;
            background-color: rgba(79, 70, 229, 0.1);
            transform: translateY(-2px);
        }
        
        .nav-link.active {
            color: var(--primary-color) !important;
            background-color: rgba(79, 70, 229, 0.15);
            font-weight: 600;
        }
        
        .btn-primary {
            background: var(--gradient);
            border: none;
            border-radius: 8px;
            padding: 0.75rem 1.5rem;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 70, 229, 0.4);
            background: linear-gradient(135deg, #4338CA, #6D28D9);
        }
        
        .page-header {
            background: var(--gradient);
            color: white;
            padding: 4rem 0;
            margin-bottom: 3rem;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .page-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 100" fill="rgba(255,255,255,0.1)"><polygon points="1000,100 1000,0 0,100"/></svg>') no-repeat bottom;
            background-size: cover;
        }
        
        .page-header h1 {
            font-size: 2.5rem;
            font-weight: 600;
            margin-bottom: 1rem;
            position: relative;
            z-index: 1;
        }
        
        .page-header p {
            font-size: 1.1rem;
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }
        
        .breadcrumb {
            background: transparent;
            padding: 0;
            margin: 1rem 0 0 0;
            position: relative;
            z-index: 1;
        }
        
        .breadcrumb-item + .breadcrumb-item::before {
            color: rgba(255, 255, 255, 0.8);
            content: ">";
        }
        
        .breadcrumb-item a {
            color: white;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .breadcrumb-item a:hover {
            color: rgba(255, 255, 255, 0.8);
            text-decoration: underline;
        }
        
        .breadcrumb-item.active {
            color: rgba(255, 255, 255, 0.8);
        }
        
        .alert {
            border-radius: 10px;
            padding: 1rem 1.5rem;
            margin-bottom: 2rem;
            border: none;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            animation: slideInDown 0.5s ease-out;
        }
        
        .alert-success {
            background-color: #DEF7EC;
            color: #047857;
            border-left: 4px solid #10B981;
        }
        
        .alert-danger {
            background-color: #FEF2F2;
            color: #DC2626;
            border-left: 4px solid #EF4444;
        }
        
        .alert-warning {
            background-color: #FFFBEB;
            color: #D97706;
            border-left: 4px solid #F59E0B;
        }
        
        .alert-info {
            background-color: #EFF6FF;
            color: #1D4ED8;
            border-left: 4px solid #3B82F6;
        }
        
        .container {
            max-width: 1200px;
            padding: 0 1rem;
        }
        
        main {
            min-height: calc(100vh - 200px);
        }
        
        /* Estilos para elementos de tracking */
        .cta-button {
            background: var(--gradient);
            color: white !important;
            border: none;
            border-radius: 8px;
            padding: 0.75rem 1.5rem;
            font-weight: 500;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .cta-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 70, 229, 0.4);
            color: white !important;
        }
        
        .whatsapp-cta-container {
            text-align: center;
            margin: 2rem 0;
            padding: 1.5rem;
            background-color: rgba(37, 211, 102, 0.1);
            border-radius: 0.75rem;
            border: 1px solid rgba(37, 211, 102, 0.2);
        }
        
        .whatsapp-title {
            font-size: 1.25rem;
            margin-bottom: 1rem;
            color: #075E54;
            font-weight: 600;
        }

        .whatsapp-cta-button {
            display: inline-block;
            background-color: #25D366;
            color: white !important;
            font-weight: 600;
            padding: 1rem 2rem;
            border-radius: 0.5rem;
            text-decoration: none !important;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(37, 211, 102, 0.4);
            font-size: 1.1rem;
        }

        .whatsapp-cta-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(37, 211, 102, 0.5);
            color: white !important;
        }

        .whatsapp-cta-button i {
            margin-right: 0.5rem;
            font-size: 1.2rem;
        }
        
        /* Indicador de debug */
        .debug-indicator {
            position: fixed;
            top: 10px;
            right: 10px;
            background: #ff4444;
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 12px;
            z-index: 9999;
            opacity: 0.8;
        }
        
        /* Animações */
        @keyframes slideInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .navbar {
                padding: 0.5rem 0;
            }
            
            .navbar-brand {
                font-size: 1.25rem;
            }
            
            .navbar-brand img {
                height: 30px;
            }
            
            .page-header {
                padding: 2rem 0;
            }
            
            .page-header h1 {
                font-size: 1.75rem;
            }
            
            .page-header p {
                font-size: 1rem;
            }
            
            .nav-link {
                margin: 0.25rem 0;
            }
            
            .btn-primary {
                width: 100%;
                margin-top: 1rem;
            }
        }
        
        @media (max-width: 576px) {
            .container {
                padding: 0 0.75rem;
            }
            
            .page-header h1 {
                font-size: 1.5rem;
            }
            
            .alert {
                margin-left: -0.75rem;
                margin-right: -0.75rem;
                border-radius: 0;
            }
            
            .whatsapp-cta-container {
                margin-left: -0.75rem;
                margin-right: -0.75rem;
            }
        }
        
        /* Melhorias de acessibilidade */
        .sr-only {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0, 0, 0, 0);
            white-space: nowrap;
            border: 0;
        }
        
        /* Estados de foco para acessibilidade */
        .nav-link:focus,
        .btn-primary:focus,
        .navbar-brand:focus,
        .cta-button:focus,
        .whatsapp-cta-button:focus {
            outline: 2px solid var(--primary-color);
            outline-offset: 2px;
        }
        
        /* Preloader (opcional) */
        .preloader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: white;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            transition: opacity 0.5s ease;
        }
        
        .preloader.hidden {
            opacity: 0;
            pointer-events: none;
        }
        
        .preloader .spinner {
            width: 50px;
            height: 50px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
    
    <!-- Estilos customizados da página -->
    <?php if (isset($customStyles)): ?>
    <style><?php echo $customStyles; ?></style>
    <?php endif; ?>

    <!-- UTM Tracking Scripts -->
    <script>
    // Preserva UTMs durante navegação
    (function() {
        // Captura UTMs da URL atual
        const urlParams = new URLSearchParams(window.location.search);
        const utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'];
        const currentUtms = {};
        
        utmParams.forEach(param => {
            if (urlParams.has(param)) {
                currentUtms[param] = urlParams.get(param);
                // Preserva no sessionStorage
                sessionStorage.setItem(param, urlParams.get(param));
            }
        });
        
        // Adiciona UTMs preservados aos links internos
        document.addEventListener('DOMContentLoaded', function() {
            const internalLinks = document.querySelectorAll('a[href^="/"], a[href^="./"], a[href^="../"]');
            
            internalLinks.forEach(link => {
                link.addEventListener('click', function() {
                    const href = this.getAttribute('href');
                    const hasQuery = href.includes('?');
                    const separator = hasQuery ? '&' : '?';
                    
                    // Adiciona UTMs preservados ao link
                    const utmString = utmParams
                        .filter(param => sessionStorage.getItem(param))
                        .map(param => `${param}=${encodeURIComponent(sessionStorage.getItem(param))}`)
                        .join('&');
                        
                    if (utmString) {
                        this.setAttribute('href', href + separator + utmString);
                    }
                });
            });
        });
        
        // Debug UTMs (apenas se debug=1 na URL)
        if (urlParams.has('debug') && urlParams.get('debug') === '1') {
            console.log('=== DEBUG UTM ===');
            console.log('UTMs na URL:', currentUtms);
            console.log('UTMs no sessionStorage:', {
                utm_source: sessionStorage.getItem('utm_source'),
                utm_medium: sessionStorage.getItem('utm_medium'),
                utm_campaign: sessionStorage.getItem('utm_campaign')
            });
            
            // Adiciona indicador visual de debug
            document.addEventListener('DOMContentLoaded', function() {
                const debugDiv = document.createElement('div');
                debugDiv.className = 'debug-indicator';
                debugDiv.textContent = 'DEBUG MODE';
                document.body.appendChild(debugDiv);
            });
        }
    })();
    </script>
    
    <!-- Scripts de tracking de visitantes únicos -->
    <?php addTrackingScripts($trackingData); ?>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg sticky-top" id="mainNavbar">
        <div class="container">
            <a class="navbar-brand" href="/" aria-label="Ir al inicio" data-track="brand-click">
                <img src="/assets/img/logo.png" alt="Logo de <?php echo SITE_NAME; ?>">
                <?php echo SITE_NAME; ?>
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMain" 
                    aria-controls="navbarMain" aria-expanded="false" aria-label="Alternar navegación">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarMain">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link <?php echo isActivePage('home', $currentPage); ?>" href="/" aria-label="Ir al inicio">
                            <i class="fas fa-home me-1"></i>Inicio
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?php echo isActivePage('cursos', $currentPage); ?>" href="/cursos.php" aria-label="Ver cursos disponibles">
                            <i class="fas fa-graduation-cap me-1"></i>Cursos
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?php echo isActivePage('about', $currentPage); ?>" href="/sobre.php" aria-label="Sobre nosotros">
                            <i class="fas fa-info-circle me-1"></i>Sobre
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?php echo isActivePage('contact', $currentPage); ?>" href="/contacto.php" aria-label="Contactar">
                            <i class="fas fa-envelope me-1"></i>Contacto
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="btn btn-primary ms-2" href="/empezar.php" aria-label="Comenzar ahora" data-track="cta">
                            <i class="fas fa-rocket me-1"></i>Empezar Ahora
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    
    <?php if ($showHeader): ?>
    <!-- Page Header -->
    <header class="page-header">
        <div class="container">
            <h1><?php echo htmlspecialchars($pageTitle); ?></h1>
            
            <?php if (isset($pageDescription) && !empty($pageDescription)): ?>
            <p><?php echo htmlspecialchars($pageDescription); ?></p>
            <?php endif; ?>
            
            <?php if (!empty($breadcrumbs)): ?>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb justify-content-center">
                    <li class="breadcrumb-item">
                        <a href="/">Inicio</a>
                    </li>
                    <?php foreach ($breadcrumbs as $url => $title): ?>
                    <li class="breadcrumb-item <?php echo empty($url) ? 'active' : ''; ?>" <?php echo empty($url) ? 'aria-current="page"' : ''; ?>>
                        <?php if (!empty($url)): ?>
                            <a href="<?php echo htmlspecialchars($url); ?>"><?php echo htmlspecialchars($title); ?></a>
                        <?php else: ?>
                            <?php echo htmlspecialchars($title); ?>
                        <?php endif; ?>
                    </li>
                    <?php endforeach; ?>
                </ol>
            </nav>
            <?php endif; ?>
        </div>
    </header>
    <?php endif; ?>
    
    <?php 
    // Verificar se existe função getAlert antes de usar
    $alert = function_exists('getAlert') ? getAlert() : null;
    if ($alert): 
    ?>
    <div class="container mt-4">
        <div class="alert alert-<?php echo htmlspecialchars($alert['type']); ?>" role="alert">
            <i class="fas fa-info-circle me-2"></i>
            <?php echo htmlspecialchars($alert['message']); ?>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Contenido Principal -->
    <main id="main-content">

<script>
// Script para melhorar a experiência de navegação
document.addEventListener('DOMContentLoaded', function() {
    // Navbar scroll effect
    const navbar = document.getElementById('mainNavbar');
    
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        });
    }
    
    // Auto-close mobile menu when clicking on a link
    const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    const navbarCollapse = document.getElementById('navbarMain');
    
    navLinks.forEach(link => {
        link.addEventListener('click', () => {
            if (navbarCollapse.classList.contains('show')) {
                new bootstrap.Collapse(navbarCollapse).hide();
            }
        });
    });
    
    // Smooth scroll for anchor links
    const anchorLinks = document.querySelectorAll('a[href^="#"]');
    
    anchorLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                e.preventDefault();
                
                const offsetTop = targetElement.offsetTop - 100; // Adjust for navbar height
                
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
                
                // Track scroll to anchor
                if (window.trackAction) {
                    window.trackAction('scroll_to_anchor', targetId);
                }
            }
        });
    });
    
    // Auto-hide alerts after 5 seconds
    const alerts = document.querySelectorAll('.alert');
    
    alerts.forEach(alert => {
        setTimeout(() => {
            alert.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
            alert.style.opacity = '0';
            alert.style.transform = 'translateY(-20px)';
            
            setTimeout(() => {
                alert.remove();
            }, 500);
        }, 5000);
    });
    
    // Add loading states to buttons
    const buttons = document.querySelectorAll('.btn, .cta-button');
    
    buttons.forEach(button => {
        button.addEventListener('click', function() {
            if (this.type === 'submit' || this.dataset.loading) {
                this.disabled = true;
                const originalText = this.innerHTML;
                this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Cargando...';
                
                // Re-enable after 3 seconds (adjust as needed)
                setTimeout(() => {
                    this.disabled = false;
                    this.innerHTML = originalText;
                }, 3000);
            }
        });
    });
    
    // Track performance metrics
    if (window.pageTrackingData && window.pageTrackingData.page_id) {
        // Track load time
        window.addEventListener('load', function() {
            const loadTime = performance.timing.loadEventEnd - performance.timing.navigationStart;
            
            if (window.trackAction) {
                window.trackAction('page_load_complete', null);
            }
            
            // Log performance for debug
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.has('debug') && urlParams.get('debug') === '1') {
                console.log('=== PERFORMANCE ===');
                console.log(`Tempo de carregamento: ${loadTime}ms`);
                console.log('Performance timing:', performance.timing);
            }
        });
    }
});

// Function to show loading
function showLoading(element) {
    if (element) {
        element.disabled = true;
        const originalText = element.innerHTML;
        element.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Cargando...';
        element.dataset.originalText = originalText;
    }
}

// Function to hide loading
function hideLoading(element) {
    if (element && element.dataset.originalText) {
        element.disabled = false;
        element.innerHTML = element.dataset.originalText;
        delete element.dataset.originalText;
    }
}

// Global error handler for better UX
window.addEventListener('error', function(e) {
    console.error('Error:', e.error);
    
    // Track error if tracking is available
    if (window.trackAction) {
        window.trackAction('javascript_error', e.filename + ':' + e.lineno);
    }
});

// Service Worker registration (for PWA capabilities - optional)
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/sw.js')
            .then(function(registration) {
                console.log('SW registered: ', registration);
            })
            .catch(function(registrationError) {
                console.log('SW registration failed: ', registrationError);
            });
    });
}

// Expose global tracking functions
window.trackPageView = function(pageId, pageType) {
    if (window.trackAction) {
        window.trackAction('manual_page_view', null);
    }
};

window.trackConversion = function(conversionType, value) {
    if (window.trackAction) {
        window.trackAction('conversion_' + conversionType, value);
    }
    
    // Track Facebook Pixel events
    if (typeof fbq !== 'undefined') {
        fbq('track', 'Conversion', {
            conversion_type: conversionType,
            value: value
        });
    }
};
</script>