<?php
/**
 * Fixed Navbar Component - Reusable navigation bar for StyleScore platform
 * Based on event_actions_menu.php structure with enhanced features
 * 
 * Required variables:
 * - $current_user: User information (optional)
 * - $event_id: The ID of the current event (optional)
 * 
 * Optional variables:
 * - $show_token_balance: Whether to show token balance (default: true)
 * - $show_event_selector: Whether to show event dropdown (default: true)
 * - $use_localStorage: Whether to use localStorage for event switching (default: true)
 * - $navbar_theme: 'light' or 'dark' (default: 'dark')
 */

// Set default values for optional variables
$show_token_balance = $show_token_balance ?? true;
$show_event_selector = $show_event_selector ?? true;
$use_localStorage = $use_localStorage ?? true;
$navbar_theme = $navbar_theme ?? 'dark';

// Database connection for dynamic data
require_once __DIR__ . '/../includes/db.php';

// Fetch user token balance if available using existing TokenSystem
$token_balance = 0;
if (isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0 && $show_token_balance) {
    try {
        if (file_exists(__DIR__ . '/../includes/TokenSystem.php')) {
            include_once __DIR__ . '/../includes/TokenSystem.php';
            $token_balance = TokenSystem::getBalance($_SESSION['user_id']);
        }
    } catch (Exception $e) {
        error_log("Token balance error: " . $e->getMessage());
        $token_balance = 0;
    }
}

// Fetch recent events for dropdown
$recent_events = [];
if ($show_event_selector) {
    $stmt = $pdo->prepare("SELECT id, name, date, status FROM events ORDER BY date DESC LIMIT 10");
    $stmt->execute();
    $recent_events = $stmt->fetchAll();
}

// Get current event info if event_id is provided
$current_event = null;
if (isset($event_id) && $event_id) {
    $stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
    $stmt->execute([$event_id]);
    $current_event = $stmt->fetch();
}

// Generate unique ID for this navbar instance
$navbar_id = 'stylescore-navbar-' . uniqid();
?>

<style>
.navbar-fixed-top {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1050;
    backdrop-filter: blur(10px);
    box-shadow: 0 2px 20px rgba(0,0,0,0.1);
}

.navbar-brand-logo {
    font-size: 1.5rem;
    font-weight: bold;
    background: linear-gradient(45deg, #007bff, #6f42c1);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.token-balance {
    background: linear-gradient(45deg, #28a745, #20c997);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.875rem;
    font-weight: 600;
    animation: pulse-subtle 2s infinite;
}

@keyframes pulse-subtle {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.8; }
}

.event-status-indicator {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    display: inline-block;
    margin-right: 0.5rem;
}

.event-status-active { background-color: #28a745; }
.event-status-setup { background-color: #ffc107; }
.event-status-completed { background-color: #6c757d; }

.navbar-nav .nav-link {
    display: flex;
    align-items: center;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    transition: all 0.2s ease;
}

.navbar-nav .nav-link:hover {
    background-color: rgba(255,255,255,0.1);
    transform: translateY(-1px);
}

.user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: linear-gradient(45deg, #007bff, #6f42c1);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
    font-size: 0.875rem;
}

.notification-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background: #dc3545;
    color: white;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    font-size: 0.75rem;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: bounce 2s infinite;
}

@keyframes bounce {
    0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
    40% { transform: translateY(-10px); }
    60% { transform: translateY(-5px); }
}

.dropdown-menu {
    border: none;
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    border-radius: 10px;
    margin-top: 0.5rem;
}

.dropdown-item {
    padding: 0.75rem 1rem;
    transition: all 0.2s ease;
}

.dropdown-item:hover {
    background-color: #f8f9fa;
    transform: translateX(5px);
}
.navbar-brand-logo img {
    height: 35px;
}

/* Quick Search Styles */
#quickSearch {
    background: rgba(255,255,255,0.9);
    border: 1px solid rgba(255,255,255,0.3);
    transition: all 0.3s ease;
}

#quickSearch:focus {
    background: rgba(255,255,255,1);
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
}

.search-result-item:hover {
    background-color: #f8f9fa !important;
    transform: translateX(3px);
}

#quickSearchResults {
    border: 1px solid rgba(0,0,0,0.1);
    border-radius: 8px;
    max-width: 400px;
}

.search-result-item mark {
    background-color: #fff3cd;
    padding: 1px 2px;
    border-radius: 2px;
}
.navbar-fixed-top .nav-link {
    color: white;
}
.nav-link:focus, .nav-link:hover {
    color: var(--bs-nav-link-hover-color);
}
/* Mobile responsiveness */
@media (max-width: 768px) {
    .navbar-nav {
        text-align: center;
        padding: 1rem 0;
    }
    
    .token-balance {
        margin: 0.5rem 0;
    }
}
</style>

<nav class="navbar navbar-expand-lg navbar-<?= $navbar_theme ?> bg-ss-gradient navbar-fixed-top" id="<?= $navbar_id ?>">
    <div class="container-fluid">
        <!-- Brand -->
        
        <a class="navbar-brand navbar-brand-logo" href="/v2/dashboard.php">
            <img src="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/assets/img/SVG/logo-ss-_2.svg" alt="Logo" class="me-2">
        </a>

        <!-- Mobile toggle -->
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarContent">
            <!-- Event Selector -->
            <?php if ($show_event_selector): ?>
            <div class="navbar-nav me-auto">
                <div class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i data-lucide="calendar" class="me-1"></i>
                        <?php if ($current_event): ?>
                            <span class="event-status-indicator event-status-<?= $current_event['status'] ?>"></span>
                            <?= htmlspecialchars(substr($current_event['name'], 0, 20)) ?><?= strlen($current_event['name']) > 20 ? '...' : '' ?>
                        <?php else: ?>
                            Select Event
                        <?php endif; ?>
                    </a>
                    <ul class="dropdown-menu">
                        <li><h6 class="dropdown-header">Recent Events</h6></li>
                        <?php foreach ($recent_events as $recent_event): ?>
                        <li>
                            <a class="dropdown-item" href="?event_id=<?= $recent_event['id'] ?>" data-event-id="<?= $recent_event['id'] ?>">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="event-status-indicator event-status-<?= $recent_event['status'] ?>"></span>
                                        <?= htmlspecialchars($recent_event['name']) ?>
                                    </div>
                                    <small class="text-muted"><?= date('M j', strtotime($recent_event['date'])) ?></small>
                                </div>
                            </a>
                        </li>
                        <?php endforeach; ?>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="/v2/admin/events.php">
                            <i data-lucide="plus" class="me-2"></i>Manage Events
                        </a></li>
                    </ul>
                </div>
            </div>
            <?php endif; ?>

            <!-- Main Navigation Dropdowns -->
            <ul class="navbar-nav me-auto">
                <!-- Event Management -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i data-lucide="calendar" class="me-1"></i>Events
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/events.php">
                            <i data-lucide="clipboard-list" class="me-2"></i>Events
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/event_dashboard.php?event_id=<?= $event_id ?>">
                            <i data-lucide="layout-dashboard" class="me-2"></i>Event Dashboard
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/event_create.php">
                            <i data-lucide="plus" class="me-2"></i>Create Event
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/event_categories.php?event_id=<?= $event_id ?>">
                            <i data-lucide="tags" class="me-2"></i>Sport Categories
                        </a></li>
                    </ul>
                </li>

                <!-- Participants & Scoring -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i data-lucide="users" class="me-1"></i>Participants
                    </a>
                    <ul class="dropdown-menu">
                        <li><h6 class="dropdown-header">Participants & BIBs</h6></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/participants.php">
                            <i data-lucide="users" class="me-2"></i>Participants
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/bib_assign.php">
                            <i data-lucide="hash" class="me-2"></i>BIB Series
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/bib_distribute.php">
                            <i data-lucide="target" class="me-2"></i>BIB Distribution
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><h6 class="dropdown-header">Heat Configuration</h6></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/heats_configure.php">
                            <i data-lucide="users" class="me-2"></i>Assign to Heats
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/admin_heat_config.php">
                            <i data-lucide="settings" class="me-2"></i>Edit Heats
                        </a></li>
                    </ul>
                </li>

                <!-- Judges & Scoring -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i data-lucide="scale" class="me-1"></i>Judges
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/judge_add.php">
                            <i data-lucide="user-plus" class="me-2"></i>Judges Management
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/judge_assign.php">
                            <i data-lucide="link-2" class="me-2"></i>Assign Judge
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/judge/score.php" title="Alt+S">
                            <i data-lucide="pencil" class="me-2"></i>Score Input
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/judge/head_judge.php" title="Alt+H">
                            <i data-lucide="crown" class="me-2"></i>Head Judge
                        </a></li>
                    </ul>
                </li>

                <!-- Results & Reports -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i data-lucide="file-text" class="me-1"></i>Results
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/event_start_list.php">
                            <i data-lucide="clipboard-list" class="me-2"></i>Start Lists
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/event_start_list.php?view_type=summary_table">
                            <i data-lucide="trophy" class="me-2"></i>Results
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/results_styling.php">
                            <i data-lucide="palette" class="me-2"></i>Results Styling
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                         <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/head_judge_override.php">
                            <i data-lucide="edit-3" class="me-2"></i>Override Scores
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/judge/event_reports.php">
                            <i data-lucide="line-chart" class="me-2"></i>Event Reports
                        </a></li>
                        
                    </ul>
                </li>

                <!-- Live Features -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i data-lucide="monitor" class="me-1"></i>Live
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/live_scoreboard_tabs.php">
                            <i data-lucide="monitor" class="me-2"></i>Live Board
                            <span class="badge bg-danger ms-1">LIVE</span>
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/public_event_dashboard.php" target="_blank">
                            <i data-lucide="globe" class="me-2"></i>Public View
                            <span class="badge bg-danger ms-1">LIVE</span>
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/tv-overlay/" target="_blank">
                            <i data-lucide="tv" class="me-2"></i>TV Overlay
                        </a></li>
                    </ul>
                </li>

                <!-- System -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i data-lucide="settings" class="me-1"></i>System
                    </a>
                    <ul class="dropdown-menu">
                        <li><h6 class="dropdown-header">Format Management</h6></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/scoring_format_edit.php">
                            <i data-lucide="settings" class="me-2"></i>Scoring Format Editor
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/figures_viewer.php">
                            <i data-lucide="book-open" class="me-2"></i>Figures Dictionary
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><h6 class="dropdown-header">Advanced</h6></li>
                       
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/scoring_analytics.php">
                            <i data-lucide="bar-chart-3" class="me-2"></i>Analytics
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/publish_servers.php">
                            <i data-lucide="server" class="me-2"></i>Publish Servers
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/notifications.php">
                            <i data-lucide="bell" class="me-2"></i>Notifications
                            <span class="notification-badge" id="navbar-notification-badge" style="display: none;">0</span>
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><h6 class="dropdown-header">Administration</h6></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/user_management.php">
                            <i data-lucide="users" class="me-2"></i>User Management
                            <span class="badge bg-primary ms-1">Admin</span>
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/token_management.php">
                            <i data-lucide="coins" class="me-2"></i>Token System
                            <span class="badge bg-warning ms-1">Credits</span>
                        </a></li>
                        <li><a class="dropdown-item" href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/faq.php">
                            <i data-lucide="help-circle" class="me-2"></i>Help
                        </a></li>
                    </ul>
                </li>
            </ul>

            <!-- Right Side - Token Balance & User Menu -->
            <ul class="navbar-nav">
                <!-- Token Balance -->
                <?php if ($show_token_balance && isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0): ?>
                <li class="nav-item">
                    <a class="nav-link" href="/v2/admin/token_management.php" title="Manage Tokens" data-ss-tooltip="Current token balance - click to manage tokens" data-ss-placement="bottom">
                        <span class="token-balance" data-stat="token-balance">
                            <i data-lucide="coins" class="me-1"></i>
                            <?= number_format($token_balance, 2) ?>
                        </span>
                    </a>
                </li>
                <?php endif; ?>

                <!-- User Menu -->
                <?php if (isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0): ?>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" data-ss-tooltip="User menu and profile options" data-ss-placement="bottom-end">
                        <div class="user-avatar me-2">
                            <?= strtoupper(substr($_SESSION['username'] ?? 'U', 0, 1)) ?>
                        </div>
                        <span class="d-none d-lg-inline"><?= htmlspecialchars($_SESSION['username'] ?? 'User') ?></span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><h6 class="dropdown-header">
                            <?= htmlspecialchars($_SESSION['full_name'] ?? $_SESSION['username'] ?? 'User') ?>
                        </h6></li>
                        <li><a class="dropdown-item" href="/v2/profile.php">
                            <i data-lucide="user" class="me-2"></i>Profile
                        </a></li>
                        <li><a class="dropdown-item" href="/v2/settings.php">
                            <i data-lucide="settings" class="me-2"></i>Settings
                        </a></li>
                        <li><a class="dropdown-item" href="/v2/help.html">
                            <i data-lucide="help-circle" class="me-2"></i>Help
                        </a></li>
                        <li><a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#sessionModal">
              <i data-lucide="info" class="dropdown-icon"></i>Session Info
            </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="/v2/logout.php">
                            <i data-lucide="log-out" class="me-2"></i>Logout
                        </a></li>
                    </ul>
                </li>
                <?php else: ?>
                <li class="nav-item">
                    <a class="nav-link" href="/v2/login.php">
                        <i data-lucide="log-in" class="me-1"></i>Login
                    </a>
                </li>
                <?php endif; ?>
            </ul>
        </div>
    </div>
</nav>



<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Lucide icons
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
    
    // Keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        if (e.altKey) {
            switch(e.key.toLowerCase()) {
                case 'd':
                    e.preventDefault();
                    window.location.href = '/v2/dashboard.php';
                    break;
                case 's':
                    e.preventDefault();
                    const scoreBtn = document.querySelector('a[title="Alt+S"]');
                    if (scoreBtn) window.location.href = scoreBtn.href;
                    break;
                case 'h':
                    e.preventDefault();
                    const headJudgeBtn = document.querySelector('a[title="Alt+H"]');
                    if (headJudgeBtn) window.location.href = headJudgeBtn.href;
                    break;
            }
        }
    });
    
    // Quick Search functionality with enhanced Popper.js
    const quickSearch = document.getElementById('quickSearch');
    const quickSearchBtn = document.getElementById('quickSearchBtn');
    const quickSearchResults = document.getElementById('quickSearchResults');
    
    if (quickSearch && quickSearchResults) {
        let searchTimeout;
        let searchDropdown = null;
        
        // Initialize search dropdown with Popper.js
        if (window.StyleScorePopper) {
            searchDropdown = StyleScorePopper.createSearchDropdown(quickSearch, quickSearchResults, {
                placement: 'bottom-start',
                modifiers: [
                    {
                        name: 'offset',
                        options: { offset: [0, 4] }
                    }
                ]
            });
        }
        
        quickSearch.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const query = this.value.trim();
            
            if (query.length >= 2) {
                searchTimeout = setTimeout(() => {
                    performQuickSearch(query);
                }, 300);
            } else {
                hideSearchResults();
            }
        });
        
        quickSearch.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const query = this.value.trim();
                if (query.length >= 2) {
                    performQuickSearch(query);
                }
            } else if (e.key === 'Escape') {
                hideSearchResults();
                this.blur();
            }
        });
        
        quickSearchBtn.addEventListener('click', function() {
            const query = quickSearch.value.trim();
            if (query.length >= 2) {
                performQuickSearch(query);
            }
        });
        
        // Hide results when clicking outside
        document.addEventListener('click', function(e) {
            if (!quickSearch.contains(e.target) && !quickSearchResults.contains(e.target)) {
                hideSearchResults();
            }
        });
        
        function showSearchResults() {
            if (searchDropdown) {
                searchDropdown.show();
            } else {
                quickSearchResults.style.display = 'block';
            }
        }
        
        function hideSearchResults() {
            if (searchDropdown) {
                searchDropdown.hide();
            } else {
                quickSearchResults.style.display = 'none';
            }
        }
    }
    
    function performQuickSearch(query) {
        // Show loading state
        quickSearchResults.innerHTML = '<div class="p-3 text-center"><i data-lucide="loader" class="me-2"></i>Searching...</div>';
        showSearchResults();
        
        // Simple search implementation - can be enhanced to use existing search APIs
        const searchData = [
            { type: 'events', name: 'Sample Event 1', id: 1, url: '/v2/admin/event_dashboard.php?event_id=1' },
            { type: 'events', name: 'Championship 2025', id: 2, url: '/v2/admin/event_dashboard.php?event_id=2' },
            { type: 'participants', name: 'John Doe', id: 1, url: '/v2/admin/participants.php' },
            { type: 'judges', name: 'Jane Smith', id: 1, url: '/v2/admin/judges.php' }
        ];
        
        const results = searchData.filter(item => 
            item.name.toLowerCase().includes(query.toLowerCase())
        );
        
        setTimeout(() => displayQuickSearchResults(results, query), 200);
    }
    
    function displayQuickSearchResults(results, query) {
        if (results.length === 0) {
            quickSearchResults.innerHTML = `
                <div class="p-3 text-center text-muted">
                    <i data-lucide="search-x" class="me-2"></i>No results found for "${query}"
                </div>`;
        } else {
            let html = '';
            results.slice(0, 8).forEach(item => {
                const icon = getTypeIcon(item.type);
                html += `
                    <a href="${item.url}" class="d-block p-2 text-decoration-none text-dark border-bottom search-result-item">
                        <div class="d-flex align-items-center">
                            <i data-lucide="${icon}" class="me-2" style="width: 16px; height: 16px;"></i>
                            <div>
                                <div class="fw-medium">${highlightMatch(item.name, query)}</div>
                                <small class="text-muted text-capitalize">${item.type}</small>
                            </div>
                        </div>
                    </a>`;
            });
            
            quickSearchResults.innerHTML = html;
        }
        
        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    }
    
    function getTypeIcon(type) {
        const icons = {
            events: 'calendar',
            participants: 'user',
            judges: 'gavel'
        };
        return icons[type] || 'search';
    }
    
    function highlightMatch(text, query) {
        const regex = new RegExp(`(${query})`, 'gi');
        return text.replace(regex, '<mark>$1</mark>');
    }
    
    // Keyboard shortcut for quick search (Ctrl+K)
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key === 'k') {
            e.preventDefault();
            if (quickSearch) quickSearch.focus();
        }
    });
    
    // Event selector functionality
    <?php if ($use_localStorage): ?>
    document.querySelectorAll('[data-event-id]').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            const eventId = this.getAttribute('data-event-id');
            localStorage.setItem('selectedEventId', eventId);
            localStorage.setItem('event_id', eventId);
            //window.location.reload();
        });
    });
    
    // Load event from localStorage if available
    const savedEventId = localStorage.getItem('selectedEventId') || localStorage.getItem('event_id');
    if (savedEventId && !<?= json_encode(isset($event_id) ? $event_id : null) ?>) {
        //window.location.href = window.location.pathname + '?event_id=' + savedEventId;
    }
    
    // Event Actions functionality for localStorage mode
    function handleEventAction(action) {
        const eventId = localStorage.getItem('selectedEventId') || localStorage.getItem('event_id');
        
        if (!eventId) {
            alert('No event ID found in localStorage. Please select an event first.');
            return;
        }
        
        let url = '';
        switch(action) {
            case 'event-dashboard':
                url = `/v2/admin/event_dashboard.php?event_id=${eventId}`;
                break;
            case 'edit':
                url = `/v2/admin/event_edit.php?id=${eventId}`;
                break;
            case 'participants':
                url = `/v2/admin/heats_configure.php?event_id=${eventId}`;
                break;
            case 'categories':
                url = `/v2/admin/event_categories.php?event_id=${eventId}`;
                break;
            case 'judges':
                url = `/v2/admin/judge_assign.php?event_id=${eventId}`;
                break;
            case 'head-judge':
                url = `/v2/judge/head_judge.php?event_id=${eventId}`;
                break;
            case 'score':
                url = `/v2/judge/score.php?event_id=${eventId}`;
                break;
            case 'scoreboard':
                url = `/v2/admin/live_scoreboard_3.php?event_id=${eventId}`;
                break;
            case 'results':
                url = `/v2/admin/event_start_list.php?view_type=summary_table&event_id=${eventId}`;
                break;
            case 'reports':
                url = `/v2/judge/event_reports.php?event_id=${eventId}`;
                break;
            case 'heat-flow':
                url = `/v2/admin/heat_flow_preview.php?event_id=${eventId}`;
                break;
            case 'start-list':
                url = `/v2/admin/event_start_list.php?view_type=start_list&event_id=${eventId}`;
                break;
            case 'public-view':
                url = `/v2/public_event_dashboard.php?event_id=${eventId}`;
                window.open(url, '_blank');
                return;
            case 'publish_servers':
                url = `/v2/admin/publish_servers.php?event_id=${eventId}`;
                window.open(url, '_blank');
                return;
            default:
                console.warn('Unknown action:', action);
                return;
        }
        
        if (url) {
            window.location.href = url;
        }
    }
    
    // Add event listeners for localStorage-based event actions
    document.querySelectorAll('[data-action]').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            const action = this.getAttribute('data-action');
            handleEventAction(action);
        });
    });
    <?php endif; ?>
    
    // Auto-refresh token balance every 30 seconds using existing TokenSystem
    const tokenElement = document.querySelector('[data-stat="token-balance"]');
    if (tokenElement) {
        setInterval(function() {
            // Use existing token refresh mechanism if available
            if (typeof refreshTokenBalance === 'function') {
                refreshTokenBalance();
            } else {
                // Fallback to simple page reload for token balance
                // This will be replaced by existing token refresh system
                fetch(window.location.href)
                    .then(response => response.text())
                    .then(html => {
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(html, 'text/html');
                        const newTokenElement = doc.querySelector('[data-stat="token-balance"]');
                        if (newTokenElement && tokenElement) {
                            tokenElement.innerHTML = newTokenElement.innerHTML;
                            if (typeof lucide !== 'undefined') {
                                lucide.createIcons();
                            }
                        }
                    })
                    .catch(console.error);
            }
        }, 30000);
    }
    
    
    // Initialize notification badge polling
    initializeNotificationBadge();
    
    // Use existing notification system if available
    if (typeof updateNotificationBadge === 'function') {
        // Integrate with existing notification system
        const notificationBadge = document.getElementById('navbar-notification-badge');
        if (notificationBadge) {
            // Hook into existing notification updates
            document.addEventListener('notificationUpdate', function(e) {
                const count = e.detail.unreadCount || 0;
                updateNotificationBadgeDisplay(count);
            });
        }
    }
    
    function initializeNotificationBadge() {
        const currentEventId = getCurrentEventId();
        const currentUserId = getCurrentUserId();
        
        if (!currentEventId || !currentUserId) {
            console.log('Notification badge: Missing event ID or user ID');
            return;
        }
        
        let lastNotificationId = 0;
        
        function pollNotificationCount() {
            fetch(`/v2/api/get_notification_count.php?event_id=${currentEventId}&user_id=${currentUserId}&since=${lastNotificationId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateNotificationBadgeDisplay(data.count);
                        lastNotificationId = data.latest_id || lastNotificationId;
                    }
                })
                .catch(error => {
                    console.warn('Error polling notification count:', error);
                });
        }
        
        // Poll every 10 seconds
        pollNotificationCount();
        setInterval(pollNotificationCount, 10000);
    }
    
    function updateNotificationBadgeDisplay(count) {
        const notificationBadge = document.getElementById('navbar-notification-badge');
        if (notificationBadge) {
            if (count > 0) {
                notificationBadge.style.display = 'flex';
                notificationBadge.textContent = count > 99 ? '99+' : count;
                notificationBadge.classList.add('animate__animated', 'animate__bounce');
            } else {
                notificationBadge.style.display = 'none';
                notificationBadge.classList.remove('animate__animated', 'animate__bounce');
            }
        }
    }
    
    function getCurrentEventId() {
        // Try to get event ID from various sources
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('event_id') || 
               document.querySelector('[data-event-id]')?.getAttribute('data-event-id') ||
               window.currentEventId ||
               null;
    }
    
    function getCurrentUserId() {
        // Get user ID from session or page data
        return window.currentUserId || 
               document.querySelector('[data-user-id]')?.getAttribute('data-user-id') ||
               '<?php echo $_SESSION['user_id'] ?? 'admin'; ?>' ||
               'admin';
    }
    
    // Add body padding to account for fixed navbar
    document.body.style.paddingTop = '80px';
});
</script>

<!-- Add body padding to prevent content from being hidden behind fixed navbar -->
<style>
body {
    padding-top: 80px !important;
}
</style>

<!-- StyleScore JavaScript includes -->
<?php include_once __DIR__ . '/../includes/scripts.php'; ?>

<?php
// Include existing notification system
if (function_exists('render_notification_system')) {
    render_notification_system();
}
?>
