<?php
/**
 * Header compartilhado para páginas do dashboard
 * Incluir com: <?php include __DIR__ . '/../includes/dashboard-header.php'; ?>
 *
 * Variáveis opcionais que podem ser definidas antes de incluir:
 * - $pageTitle: Título da página
 * - $pageDescription: Descrição da página (meta)
 */

// Configurar título padrão
$pageTitle = $pageTitle ?? 'Dashboard';
$storeName = $store['name'] ?? $_SESSION['store_name'] ?? 'MontaLoja';
$fullTitle = $pageTitle . ' - ' . htmlspecialchars($storeName);

// Incluir funções de landing
require_once __DIR__ . '/landing-functions.php';
// Carregar configurações de logo
$pdoLogo = getDB();
$mobileLogo = getLandingConfig($pdoLogo, 'header_logo', '');
$mobileLogoType = getLandingConfig($pdoLogo, 'header_logo_type', 'text');
$mobileLogoText = getLandingConfig($pdoLogo, 'header_logo_text', 'MontaLoja');
$mobileLogoDark = getLandingConfig($pdoLogo, 'header_logo_dark', '');

// Buscar notificações não lidas
$unreadNotifications = 0;
$recentNotifications = [];
try {
    $storeId = $_SESSION['store_id'] ?? 0;
    if ($storeId) {
        $pdo = getDB();
        
        // Contar não lidas
        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE store_id = ? AND is_read = 0");
        $countStmt->execute([$storeId]);
        $unreadNotifications = $countStmt->fetchColumn();
        
        // Buscar últimas 10 notificações
        $notifStmt = $pdo->prepare("
            SELECT * FROM notifications 
            WHERE store_id = ? 
            ORDER BY created_at DESC 
            LIMIT 10
        ");
        $notifStmt->execute([$storeId]);
        $recentNotifications = $notifStmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Buscar tema do usuário (fora do if storeId)
    $userId = $_SESSION['user_id'] ?? 0;
    if ($userId) {
        $pdoTheme = getDB();
        $themeStmt = $pdoTheme->prepare("SELECT theme_preference FROM users WHERE id = ?");
        $themeStmt->execute([$userId]);
        $userTheme = $themeStmt->fetchColumn() ?: 'dark';
    } else {
        $userTheme = 'dark';
    }
} catch (Exception $e) {
    $userTheme = 'dark';
    // Silenciar erros
}
?>
<!DOCTYPE html>
<html lang="pt-BR" data-theme="<?php echo htmlspecialchars($userTheme ?? 'dark'); ?>">
<head>
<script>window.userThemeFromDB = "<?php echo htmlspecialchars($userTheme ?? 'dark'); ?>";</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $fullTitle; ?></title>
<meta name="robots" content="noindex, nofollow">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<?php include __DIR__ . '/dashboard-styles.php'; ?>
<link rel="stylesheet" href="/assets/css/dashboard-components.css">
<style>
/* Notifications Styles */
.notifications-wrapper {
    position: relative;
}

.notifications-btn {
    position: relative;
    width: 40px;
    height: 40px;
    border-radius: 10px;
    border: none;
    background: var(--bg-card);
    border: 1px solid var(--border);
    color: var(--text-secondary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.notifications-btn:hover {
    background: var(--bg-card-hover);
    color: var(--primary);
}

.notifications-btn.has-unread {
    color: var(--primary);
}

.notification-badge {
    position: absolute;
    top: -4px;
    right: -4px;
    min-width: 18px;
    height: 18px;
    padding: 0 5px;
    background: var(--error);
    color: white;
    font-size: 0.7rem;
    font-weight: 700;
    border-radius: 9px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.notifications-dropdown {
    position: absolute;
    top: calc(100% + 8px);
    right: 0;
    width: 360px;
    max-height: 480px;
    background: #FFFFFF !important;
    border: 1px solid var(--border);
    border-radius: 12px;
    box-shadow: var(--shadow-lg);
    opacity: 0;
    visibility: hidden;
    transform: translateY(-10px);
    transition: all 0.2s;
    z-index: 1000;
    overflow: hidden;
}

.notifications-dropdown.open {
    opacity: 1;
    visibility: visible;
    transform: translateY(0);
}

.notifications-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid var(--border);
}

.notifications-header h3 {
    font-size: 1rem;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 8px;
}

.notifications-header .mark-all-read {
    font-size: 0.8rem;
    color: var(--primary);
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 6px;
    transition: background 0.2s;
}

.notifications-header .mark-all-read:hover {
    background: var(--primary-light);
}

.notifications-list {
    max-height: 360px;
    overflow-y: auto;
}

.notification-item {
    display: flex;
    gap: 12px;
    padding: 14px 16px;
    border-bottom: 1px solid var(--border);
    cursor: pointer;
    transition: background 0.2s;
    text-decoration: none;
    color: inherit;
}

.notification-item:hover {
    background: var(--bg-card-hover);
}

.notification-item.unread {
    background: var(--primary-light);
}

.notification-item.unread:hover {
    background: rgba(var(--primary-rgb), 0.15);
}

.notification-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.notification-icon.order { background: rgba(34, 197, 94, 0.15); color: #22C55E; }
.notification-icon.stock { background: rgba(245, 158, 11, 0.15); color: #F59E0B; }
.notification-icon.payment { background: rgba(59, 130, 246, 0.15); color: #3B82F6; }
.notification-icon.system { background: rgba(168, 85, 247, 0.15); color: #A855F7; }
.notification-icon.info { background: var(--primary-light); color: var(--primary); }

.notification-icon.has-image {
    background: transparent;
    padding: 0;
    overflow: hidden;
}

.notification-icon.has-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 10px;
}

.notification-content {
    flex: 1;
    min-width: 0;
}

.notification-title {
    font-weight: 600;
    font-size: 0.9rem;
    margin-bottom: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.notification-message {
    font-size: 0.8rem;
    color: var(--text-secondary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.notification-time {
    font-size: 0.7rem;
    color: var(--text-muted);
    margin-top: 4px;
}

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

.notifications-empty iconify-icon {
    font-size: 3rem;
    margin-bottom: 12px;
    opacity: 0.5;
}

.notifications-footer {
    padding: 12px 16px;
    border-top: 1px solid var(--border);
    text-align: center;
}

.notifications-footer a {
    color: var(--primary);
    text-decoration: none;
    font-size: 0.85rem;
    font-weight: 600;
}

.notifications-footer a:hover {
    text-decoration: underline;
}

/* Theme Switcher */
.theme-switcher {
    display: flex;
    gap: 4px;
    padding: 4px;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 12px;
}

.theme-btn {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    border: none;
    background: transparent;
    color: var(--text-muted);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.theme-btn:hover {
    background: var(--primary-light);
    color: var(--primary);
}

.theme-btn.active {
    background: var(--primary);
    color: #1a1a1a;
}

@media (max-width: 768px) {
    .notifications-dropdown {
        position: fixed;
        top: 60px;
        right: 10px;
        right: 10px;
        width: auto;
        max-height: calc(100vh - 80px);
    }

    .notifications-list {
        max-height: calc(100vh - 200px);
    }

    .notification-item {
        padding: 12px;
        gap: 10px;
    }

    .notification-icon {
        width: 36px;
        height: 36px;
    }

    .notification-title {
        font-size: 0.85rem;
    }

    .notification-message {
        font-size: 0.75rem;
    }
}

@media (max-width: 480px) {
    .notifications-dropdown {
        top: 55px;
        left: 5px;
        right: 5px;
        border-radius: 10px;
    }

    .notifications-header {
        padding: 12px;
    }

    .notifications-header h3 {
        font-size: 0.9rem;
    }

    .notification-item {
        padding: 10px 12px;
    }

    .notification-icon {
        width: 32px;
        height: 32px;
    }

    .notifications-footer {
        padding: 10px 12px;
    }
}
</style>
    <!-- Injeção de CSS Customizado -->
    <?php if (!empty($customCss) && is_array($customCss)): ?>
        <?php foreach ($customCss as $cssFile): ?>
<link rel="stylesheet" href="<?php echo $cssFile; ?>?v=<?php echo time(); ?>">
        <?php endforeach; ?>
    <?php endif; ?>
</head>
<body>
<?php if (!empty($_SESSION['is_impersonating'])): 
$stopUrl = $_SESSION['superadmin_original']['return_url'] ?? '/pages/superadmin/stores/index.php';
$stopUrl = str_replace('index.php', 'impersonate.php?action=stop', $stopUrl);
?>
<div style="background: linear-gradient(90deg, #dc2626, #b91c1c); color: white; padding: 0.75rem 1rem; display: flex; align-items: center; justify-content: center; gap: 1rem; font-size: 0.9rem; position: fixed; top: 0; left: 0; right: 0; z-index: 9999;">
    <iconify-icon icon="solar:eye-bold" style="font-size: 1.25rem;"></iconify-icon>
    <span>Voce esta acessando como <strong><?= htmlspecialchars($_SESSION['user_name'] ?? 'Usuario') ?></strong> (<?= htmlspecialchars($_SESSION['store_name'] ?? 'Loja') ?>)</span>
    <a href="<?= $stopUrl ?>" style="background: white; color: #dc2626; padding: 0.4rem 1rem; border-radius: 6px; text-decoration: none; font-weight: 600; font-size: 0.85rem;">
        <iconify-icon icon="solar:logout-2-bold" style="vertical-align: middle;"></iconify-icon>
        Voltar para Admin
    </a>
</div>
<style>.dashboard-layout { padding-top: 50px !important; } .header-actions { top: calc(50px + 1rem) !important; } .sidebar { top: 50px !important; height: calc(100vh - 50px) !important; } .mobile-menu-toggle { top: calc(50px + 1rem) !important; }</style>
<?php endif; ?>
<div class="dashboard-layout<?php echo !empty($_SESSION['is_impersonating']) ? ' has-impersonation' : ''; ?>">
    <!-- Header Actions (Notifications + Theme Switcher) -->
    <div class="header-actions">
        <!-- Notifications -->
        <div class="notifications-wrapper">
            <button class="notifications-btn <?php echo $unreadNotifications > 0 ? 'has-unread' : ''; ?>" onclick="toggleNotifications()" title="Notificações">
                <iconify-icon icon="solar:bell-bold" width="22"></iconify-icon>
                <?php if ($unreadNotifications > 0): ?>
                <span class="notification-badge"><?php echo $unreadNotifications > 9 ? '9+' : $unreadNotifications; ?></span>
                <?php endif; ?>
            </button>
            
            <div class="notifications-dropdown" id="notificationsDropdown">
                <div class="notifications-header">
                    <h3>
                        <iconify-icon icon="solar:bell-bold"></iconify-icon>
                        Notificações
                    </h3>
                    <?php if ($unreadNotifications > 0): ?>
                    <button class="mark-all-read" onclick="markAllAsRead()">Marcar todas como lidas</button>
                    <?php endif; ?>
                </div>
                
                <div class="notifications-list">
                    <?php if (empty($recentNotifications)): ?>
                    <div class="notifications-empty">
                        <iconify-icon icon="solar:bell-off-bold"></iconify-icon>
                        <p>Nenhuma notificação</p>
                    </div>
                    <?php else: ?>
                        <?php foreach ($recentNotifications as $notif): ?>
                        <a href="<?php echo htmlspecialchars($notif['link'] ?? '#'); ?>" 
                           class="notification-item <?php echo $notif['is_read'] ? '' : 'unread'; ?>"
                           data-id="<?php echo $notif['id']; ?>"
                           onclick="markAsRead(<?php echo $notif['id']; ?>)">
                            <?php if (!empty($notif['image_url'])): ?>
                            <div class="notification-icon has-image">
                                <img src="<?php echo htmlspecialchars($notif['image_url']); ?>" alt="">
                            </div>
                            <?php else: ?>
                            <div class="notification-icon <?php echo htmlspecialchars($notif['type']); ?>">
                                <iconify-icon icon="<?php echo htmlspecialchars($notif['icon']); ?>"></iconify-icon>
                            </div>
                            <?php endif; ?>
                            <div class="notification-content">
                                <div class="notification-title"><?php echo htmlspecialchars($notif['title']); ?></div>
                                <div class="notification-message"><?php echo htmlspecialchars($notif['message']); ?></div>
                                <div class="notification-time"><?php echo timeAgo($notif['created_at']); ?></div>
                            </div>
                        </a>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                
                <?php if (!empty($recentNotifications)): ?>
<div class="notifications-footer" style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;">
                    <a href="/pages/notificacoes.php">Ver todas</a>
                    <button onclick="clearAllNotifications()" class="clear-all-btn" style="background:none;border:none;color:var(--error);font-size:0.8rem;cursor:pointer;display:flex;align-items:center;gap:4px;padding:4px 8px;border-radius:6px;transition:all 0.2s;" onmouseover="this.style.background='rgba(239,68,68,0.1)'" onmouseout="this.style.background='none'"><iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>Limpar todas</button>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Theme Switcher -->
        <div class="theme-switcher">
            <button class="theme-btn" data-theme="light" onclick="setTheme('light')" title="Modo Claro">
                <iconify-icon icon="solar:sun-bold"></iconify-icon>
            </button>
            <button class="theme-btn" data-theme="dark" onclick="setTheme('dark')" title="Modo Escuro">
                <iconify-icon icon="solar:moon-bold"></iconify-icon>
            </button>
            <button class="theme-btn" data-theme="auto" onclick="setTheme('auto')" title="Automático (Sistema)">
                <iconify-icon icon="solar:monitor-bold"></iconify-icon>
            </button>
        </div>
    </div>


    <!-- Mobile Logo -->
    <a href="/dashboard.php" class="mobile-logo">
        <?php if ($mobileLogoType === 'image' && !empty($mobileLogo)): ?>
            <img src="<?php echo htmlspecialchars($mobileLogo); ?>"
                 alt="<?php echo htmlspecialchars($mobileLogoText); ?>"
                 class="logo-light"
                 style="max-height: 28px; width: auto; object-fit: contain;">
            <?php if (!empty($mobileLogoDark)): ?>
            <img src="<?php echo htmlspecialchars($mobileLogoDark); ?>"
                 alt="<?php echo htmlspecialchars($mobileLogoText); ?>"
                 class="logo-dark"
                 style="max-height: 28px; width: auto; object-fit: contain;">
            <?php endif; ?>
        <?php else: ?>
            <iconify-icon icon="solar:bag-4-bold"></iconify-icon>
            <span><?php echo htmlspecialchars($mobileLogoText); ?></span>
        <?php endif; ?>
    </a>

    <!-- Sidebar Overlay -->
    <div class="sidebar-overlay"></div>

    <?php include __DIR__ . '/dashboard-sidebar.php'; ?>

<?php
// Helper function para tempo relativo
function timeAgo(string $datetime): string {
    $time = strtotime($datetime);
    $diff = time() - $time;
    
    if ($diff < 60) return 'Agora';
    if ($diff < 3600) return floor($diff / 60) . ' min atrás';
    if ($diff < 86400) return floor($diff / 3600) . 'h atrás';
    if ($diff < 604800) return floor($diff / 86400) . ' dias atrás';
    return date('d/m/Y', $time);
}
?>

<script>
// Scripts de Notificação e Tema movidos para dashboard-utils.js
</script>

<!-- Toast Container para Notificações em Tempo Real -->
<div id="toastContainer" class="toast-container"></div>

<style>
/* Toast Notifications - Centralizado e Evidente */
.toast-container {
    position: fixed;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 10000;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    max-width: 500px;
    width: 90%;
    pointer-events: none;
}

.toast {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 18px 24px;
    background: #FFFFFF !important;
    border: 2px solid var(--primary);
    border-radius: 16px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    animation: toastSlideDown 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    pointer-events: auto;
    cursor: pointer;
    transition: all 0.3s ease;
    width: 100%;
    max-width: 480px;
    position: relative;
    overflow: hidden;
}

.toast:hover {
    background: #FFFFFF !important;
    transform: scale(1.02);
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.2);
}


[data-theme="dark"] .toast {
    background: #151515 !important;
}

[data-theme="dark"] .toast:hover {
    background: #1A1A1A !important;
}
.toast.toast-exit {
    animation: toastSlideUp 0.4s ease-in forwards;
}


@keyframes toastSlideDown {
    from {
        opacity: 0;
        transform: translateY(-100px) scale(0.8);
    }
    to {
        opacity: 1;
        transform: translateY(0) scale(1);
    }
}

@keyframes toastSlideUp {
    from {
        opacity: 1;
        transform: translateY(0) scale(1);
    }
    to {
        opacity: 0;
        transform: translateY(-100px) scale(0.8);
    }
}


.toast-icon {
    width: 56px;
    height: 56px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    overflow: hidden;
    background: var(--primary-light);
}

.toast-icon.order { background: rgba(34, 197, 94, 0.15); }
.toast-icon.order iconify-icon { color: var(--success); }
.toast-icon.stock { background: rgba(245, 158, 11, 0.15); }
.toast-icon.stock iconify-icon { color: var(--warning); }
.toast-icon.payment { background: rgba(59, 130, 246, 0.15); }
.toast-icon.payment iconify-icon { color: var(--info); }
.toast-icon.system { background: rgba(168, 85, 247, 0.15); }
.toast-icon.system iconify-icon { color: #A855F7; }
.toast-icon.info { background: var(--primary-light); }
.toast-icon.info iconify-icon { color: var(--primary); }

.toast-icon img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 14px;
}

.toast-icon iconify-icon {
    font-size: 1.75rem;
    color: var(--primary);
}

.toast-content {
    flex: 1;
    min-width: 0;
}

.toast-title {
    font-weight: 700;
    font-size: 1.1rem;
    color: var(--primary);
    margin-bottom: 4px;
    text-shadow: 0 0 10px rgba(var(--primary-rgb), 0.3);
}

.toast-message {
    font-size: 0.95rem;
    color: var(--text-secondary);
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.toast-close {
    background: var(--primary-light);
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    padding: 8px;
    border-radius: 10px;
    transition: all 0.2s;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.toast-close:hover {
    background: rgba(239, 68, 68, 0.15);
    color: var(--error);
}

.toast-close iconify-icon {
    font-size: 1.25rem;
}

.toast-progress {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 4px;
    background: var(--primary);
    border-radius: 0 0 14px 14px;
    animation: toastProgress 6s linear forwards;
}

@keyframes toastProgress {
    from { width: 100%; }
    to { width: 0%; }
}


@media (max-width: 480px) {
    .toast-container {
        top: 10px;
        width: 95%;
    }
    
    .toast {
        padding: 14px 16px;
        gap: 12px;
    }
    
    .toast-icon {
        width: 48px;
        height: 48px;
    }
    
    .toast-title {
        font-size: 1rem;
    }
    
    .toast-message {
        font-size: 0.85rem;
    }
}
</style>

<script>
// ============================================
// SISTEMA DE NOTIFICAÇÕES EM TEMPO REAL
// ============================================

(function() {
    let lastNotificationId = 0;
    let lastUnreadCount = <?php echo $unreadNotifications; ?>;
    const POLL_INTERVAL = 5000; // 10 segundos
    
    // Inicializar com as notificações existentes
    <?php if (!empty($recentNotifications)): ?>
    lastNotificationId = <?php echo $recentNotifications[0]['id'] ?? 0; ?>;
    <?php endif; ?>
    
    // Função para criar Toast
    function showToast(notification) {
        const container = document.getElementById('toastContainer');
        if (!container) return;
        
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.style.position = 'relative';
        toast.onclick = function() {
            if (notification.link) {
                if (typeof markAsRead === 'function') {
                    markAsRead(notification.id);
                }
                window.location.href = notification.link;
            }
        };
        
        // Ícone ou imagem
        let iconHtml = '';
        if (notification.image_url) {
            iconHtml = '<div class="toast-icon"><img src="' + notification.image_url + '" alt="" onerror="this.parentElement.innerHTML=\'<iconify-icon icon=solar:bell-bold></iconify-icon>\'"></div>';
        } else {
            const iconType = notification.type || 'info';
            const icon = notification.icon || 'solar:bell-bold';
            iconHtml = '<div class="toast-icon ' + iconType + '"><iconify-icon icon="' + icon + '"></iconify-icon></div>';
        }
        
        toast.innerHTML = iconHtml +
            '<div class="toast-content">' +
                '<div class="toast-title">' + escapeHtml(notification.title) + '</div>' +
                '<div class="toast-message">' + escapeHtml(notification.message) + '</div>' +
            '</div>' +
            '<button class="toast-close" onclick="event.stopPropagation(); closeToast(this.parentElement);">' +
                '<iconify-icon icon="solar:close-circle-bold"></iconify-icon>' +
            '</button>' +
            '<div class="toast-progress"></div>';
        
        container.appendChild(toast);
        
        // Auto-remover após 5 segundos
        setTimeout(function() {
            closeToast(toast);
        }, 5000);
        
        // Som de notificação
        playNotificationSound();
    }
    
    // Função para fechar Toast
    window.closeToast = function(toast) {
        if (!toast || toast.classList.contains('toast-exit')) return;
        toast.classList.add('toast-exit');
        setTimeout(function() {
            if (toast.parentElement) {
                toast.parentElement.removeChild(toast);
            }
        }, 300);
    };
    
    // Escape HTML
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text || '';
        return div.innerHTML;
    }
    
    // Som de notificação
    function playNotificationSound() {
        try {
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.value = 800;
            oscillator.type = 'sine';
            gainNode.gain.value = 0.1;
            
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.15);
        } catch (e) {
            // Audio não suportado
        }
    }
    
    // Atualizar badge do sino
    function updateNotificationBadge(count) {
        const btn = document.querySelector('.notifications-btn');
        let badge = document.querySelector('.notification-badge');
        
        if (count > 0) {
            if (btn) btn.classList.add('has-unread');
            if (badge) {
                badge.textContent = count > 9 ? '9+' : count;
            } else if (btn) {
                const newBadge = document.createElement('span');
                newBadge.className = 'notification-badge';
                newBadge.textContent = count > 9 ? '9+' : count;
                btn.appendChild(newBadge);
            }
        } else {
            if (btn) btn.classList.remove('has-unread');
            if (badge) badge.remove();
        }
    }
    
    // Adicionar nova notificação na lista do dropdown
    function addNotificationToList(notification) {
        const list = document.querySelector('.notifications-list');
        if (!list) return;
        
        // Verificar se já existe essa notificação na lista
        const existingNotif = list.querySelector('[data-id="' + notification.id + '"]');
        if (existingNotif) return;
        const empty = list.querySelector('.notifications-empty');
        if (empty) {
            empty.remove();
        }
        
        // Criar elemento da notificação
        const notifEl = document.createElement('a');
        notifEl.href = notification.link || '#';
        notifEl.className = 'notification-item unread';
        notifEl.setAttribute('data-id', notification.id);
        notifEl.onclick = function() { 
            if (typeof markAsRead === 'function') {
                markAsRead(notification.id); 
            }
        };
        
        let iconHtml = '';
        if (notification.image_url) {
            iconHtml = '<div class="notification-icon has-image"><img src="' + notification.image_url + '" alt=""></div>';
        } else {
            const iconType = notification.type || 'info';
            const icon = notification.icon || 'solar:bell-bold';
            iconHtml = '<div class="notification-icon ' + iconType + '"><iconify-icon icon="' + icon + '"></iconify-icon></div>';
        }
        
        notifEl.innerHTML = iconHtml +
            '<div class="notification-content">' +
                '<div class="notification-title">' + escapeHtml(notification.title) + '</div>' +
                '<div class="notification-message">' + escapeHtml(notification.message) + '</div>' +
                '<div class="notification-time">Agora</div>' +
            '</div>';
        
        // Inserir no início da lista
        list.insertBefore(notifEl, list.firstChild);
        
        // Limitar a 10 notificações na lista
        const items = list.querySelectorAll('.notification-item');
        if (items.length > 10) {
            items[items.length - 1].remove();
        }
    }
    
    // Polling para novas notificações
    function checkNewNotifications() {
        fetch('/api/notifications.php?unread=1', {
            credentials: 'include'
        })
        .then(function(response) {
            if (!response.ok) throw new Error('Network error');
            return response.json();
        })
        .then(function(data) {
            if (!data.success) return;
            
            const newCount = data.unread_count || 0;
            
            // Atualizar badge se mudou
            if (newCount !== lastUnreadCount) {
                updateNotificationBadge(newCount);
                lastUnreadCount = newCount;
            }
            
            // Verificar novas notificações
            if (data.notifications && data.notifications.length > 0) {
                const newestId = parseInt(data.notifications[0].id);
                
                if (newestId > lastNotificationId) {
                    // Mostrar toast para cada nova notificação
                    for (let i = data.notifications.length - 1; i >= 0; i--) {
                        const notif = data.notifications[i];
                        const notifId = parseInt(notif.id);
                        if (notifId > lastNotificationId) {
                            showToast(notif);
                            addNotificationToList(notif);
                        }
                    }
                    lastNotificationId = newestId;
                }
            }
        })
        .catch(function(err) {
            console.log('Erro ao verificar notificações:', err);
        });
    }
    
    // Iniciar polling
    setInterval(checkNewNotifications, POLL_INTERVAL);
    
    // Verificar após 3 segundos (para pegar notificações muito recentes)
    setTimeout(checkNewNotifications, 3000);
    
    // Expor função para teste manual
    window.showTestToast = function() {
        showToast({
            id: 99999,
            title: 'Novo Pedido!',
            message: 'Produto de teste foi comprado',
            type: 'order',
            icon: 'solar:cart-check-bold',
            link: '/pages/pedidos.php'
        });
    };
})();
</script>
