    </main>

    <!-- New Search Modal -->
    <div id="searchModal" class="modal">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3><i class="fa-solid fa-magnifying-glass"></i> Global Search</h3>
                <button id="closeSearchModal" class="modal-close-btn">&times;</button>
            </div>
            <div class="form-group" style="margin-bottom: 15px;">
                <input type="text" id="global-search-input" placeholder="Search players, teams, leagues..." style="padding: 12px; font-size: 1.1rem;">
            </div>
            <div id="global-search-results" style="max-height: 60vh; overflow-y: auto;">
                <p class="no-data-msg" style="padding: 20px; text-align: center; color: #888;">Start typing to see results.</p>
            </div>
        </div>
    </div>

    <!-- New Notifications Modal -->
    <div id="notificationsModal" class="modal">
        <div class="modal-content" style="max-width: 500px; max-height: 80vh; display: flex; flex-direction: column;">
            <div class="modal-header" style="flex-shrink: 0;">
                <h3><i class="fa-solid fa-bell"></i> Notifications</h3>
                <button id="closeNotificationsModal" class="modal-close-btn">&times;</button>
            </div>
            <div class="notification-list" style="overflow-y: auto; flex-grow: 1;">
                <?php if (empty($unread_notifications)): ?>
                    <div class="notification-empty">No new notifications</div>
                <?php else: ?>
                    <?php foreach ($unread_notifications as $notif): ?>
                        <?php include 'notification_item.php'; // Use a partial for cleanliness ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php 
    $currentPage = basename($_SERVER['PHP_SELF']); // This is used to highlight the active nav item

    // Use session variables to determine login state and role.
    $is_logged_in = isset($_SESSION['user_id']);
    $current_user_role = $_SESSION['user_role'] ?? 'guest';
    ?>
    <nav class="bottom-nav">
        <a href="<?php echo URL_ROOT; ?>/app/index.php" class="nav-item <?php echo ($currentPage == 'index.php') ? 'active' : ''; ?>">
            <i class="fa-solid fa-newspaper"></i>
            <span>Latest</span>
        </a>
        <a href="<?php echo URL_ROOT; ?>/app/fantasy.php" class="nav-item <?php echo ($currentPage == 'fantasy.php' || $currentPage == 'fantasy_lineup.php') ? 'active' : ''; ?>">
            <i class="fa-solid fa-shield-halved"></i>
            <span>Fantasy</span>
        </a>
        <a href="<?php echo URL_ROOT; ?>/app/matches.php" class="nav-item <?php echo ($currentPage == 'matches.php' || $currentPage == 'fixture.php') ? 'active' : ''; ?>">
            <i class="fa-solid fa-futbol"></i>
            <span>Matches</span>
        </a>
        <a href="#" id="footer-account-trigger" class="nav-item" style="position: relative;">
            <i class="fa-solid fa-user"></i>
            <span>Account</span>
            <?php if (count($unread_notifications) > 0): ?>
                <span class="notification-badge" style="top: 5px; right: 20%; width: 16px; height: 16px; font-size: 0.65rem; border: 2px solid #fff; display: flex; align-items: center; justify-content: center;"><?php echo count($unread_notifications); ?></span>
            <?php endif; ?>
        </a>
    </nav>

    <!-- New Account Panel (replaces dropdown) -->
    <div class="account-panel-overlay"></div>
    <div class="account-panel" id="account-panel">
        <?php if ($currentUser): ?>
            <div class="account-dropdown-header">
                <img src="<?php echo htmlspecialchars($currentUser->profile_picture ?? URL_ROOT . '/app/assets/images/default_avatar.png'); ?>" class="dropdown-avatar">
                <div class="dropdown-user-info">
                    <strong><?php echo htmlspecialchars($currentUser->first_name . ' ' . $currentUser->last_name); ?></strong>
                    <span><?php echo ucwords(str_replace('_', ' ', $currentUser->role)); ?></span>
                </div>
                <button id="close-account-panel" class="panel-close-btn"><i class="fa-solid fa-xmark"></i></button>
            </div>

            <div class="account-dropdown-actions">
                <a href="#" id="search-modal-trigger" class="dropdown-action-item" title="Search">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <span>Search</span>
                </a>
                <a href="<?php echo URL_ROOT; ?>/app/wallet.php" class="dropdown-action-item" title="Wallet">
                    <i class="fa-solid fa-wallet"></i>
                    <span>Wallet</span>
                </a>
                <a href="#" id="notifications-modal-trigger" class="dropdown-action-item" title="Notifications">
                    <i class="fa-solid fa-bell"></i>
                    <span>Notify</span>
                    <?php if (count($unread_notifications) > 0): ?>
                        <span class="notification-badge" style="top: 5px; right: 20px;"><?php echo count($unread_notifications); ?></span>
                    <?php endif; ?>
                </a>
                <button id="theme-toggle" class="dropdown-action-item" title="Toggle Theme">
                    <i class="fa-solid fa-moon"></i>
                    <span>Theme</span>
                </button>
            </div>

            <div class="account-dropdown-menu">
                <?php include 'account_menu_links.php'; ?>
            </div>
        <?php else: ?>
            <div class="account-dropdown-header">
                <div class="dropdown-user-info">
                    <strong>Guest</strong>
                    <span>Welcome to Smart Football</span>
                </div>
                <button id="close-account-panel" class="panel-close-btn"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div class="account-dropdown-menu" style="padding: 20px; text-align: center;">
                <p style="margin-bottom: 20px; color: var(--text-color);">Please login to access your account, wallet, and fantasy team.</p>
                <a href="<?php echo URL_ROOT; ?>/app/login.php" class="btn btn-save" style="display: block; margin-bottom: 10px; background-color: var(--primary-color); text-align: center; padding: 12px; border-radius: 8px; color: white;">Login</a>
                <a href="<?php echo URL_ROOT; ?>/app/register.php" class="btn" style="display: block; background-color: #f0f2f5; color: #333; text-align: center; padding: 12px; border-radius: 8px;">Register</a>
            </div>
        <?php endif; ?>
    </div>

    <script type="module" src="<?php echo URL_ROOT; ?>/app/assets/js/main.js"></script>
    <style>
        /* Bottom Navigation Styling */
        .bottom-nav {
            position: fixed; bottom: 0; left: 0; width: 100%; height: var(--bottom-nav-height, 70px); background-color: var(--nav-bg, #ffffff); border-top: 1px solid var(--border-color, #e0e0e0); display: flex; justify-content: space-around; align-items: center; z-index: 9999; box-shadow: 0 -2px 10px rgba(0,0,0,0.05); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
        }
        .nav-item { display: flex; flex-direction: column; align-items: center; text-decoration: none; color: #95a5a6; font-size: 0.75rem; transition: color 0.3s ease; flex: 1; padding: 8px 0; }
        .nav-item i { font-size: 1.4rem; margin-bottom: 4px; }
        .nav-item.active { color: var(--primary-color, #3498db); }
        .notification-footer a { text-decoration: none; color: var(--primary-color, #3498db); font-weight: 600; font-size: 0.9rem; }

        /* New Account Panel Styles */
        .account-panel-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: var(--bottom-nav-height, 70px); background-color: rgba(0,0,0,0.5); opacity: 0; visibility: hidden; z-index: 10000; transition: opacity 0.3s, visibility 0.3s; }
        .account-panel-overlay.visible { opacity: 1; visibility: visible; }
        .account-panel { visibility: hidden; position: fixed; bottom: var(--bottom-nav-height, 70px); left: 0; right: 0; width: 100%; background-color: var(--card-bg); border-top-left-radius: 20px; border-top-right-radius: 20px; transform: translateY(100%); transition: transform 0.3s ease-in-out, visibility 0.3s; z-index: 10001; max-height: calc(90vh - var(--bottom-nav-height, 70px)); overflow-y: auto; padding: 0; padding-bottom: 20px; box-shadow: 0 -5px 25px rgba(0,0,0,0.1); }
        .account-panel.visible { visibility: visible; transform: translateY(0); }
        .account-panel::before { content: ''; position: absolute; top: 8px; left: 50%; transform: translateX(-50%); width: 40px; height: 4px; background-color: var(--border-color); border-radius: 2px; }
        .account-panel .account-dropdown-header { padding: 30px 20px 15px 20px; width: 100%; box-sizing: border-box; border-radius: 20px 20px 0 0; margin: 0; }
        .account-panel .account-dropdown-actions { padding: 15px; grid-template-columns: repeat(4, 1fr); }
        .account-panel .dropdown-action-item span { font-size: 0.7rem; }
        .account-panel .account-dropdown-menu { padding: 0 20px; }
        .panel-close-btn { margin-left: auto; background: rgba(255,255,255,0.2); border: none; color: white; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background 0.2s; font-size: 1rem; }
        .panel-close-btn:hover { background: rgba(255,255,255,0.3); }

        /* Search Modal Results */
        #global-search-results h3 { font-size: 0.9rem; text-transform: uppercase; color: #999; margin: 15px 0 5px 0; padding-bottom: 5px; border-bottom: 1px solid var(--border-color); }
        .search-result-item { display: flex; align-items: center; gap: 15px; padding: 10px; border-radius: 8px; text-decoration: none; color: var(--text-color); }
        .search-result-item:hover { background-color: var(--bg-color); }
        .search-result-item img { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; }
        .search-result-item .player-name, .search-result-item .team-name { font-weight: 600; }
        .search-result-item .club-name, .search-result-item .player-position { font-size: 0.85rem; color: #777; }

        /* Notification Modal List */
        .notification-list .notification-item { border-bottom: 1px solid var(--border-color); }
        .notification-list .notification-item:last-child { border-bottom: none; }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // All global JS is now in main.js
            // And player comparison logic which is on a specific page.
        });

        // --- Player Comparison Page Logic ---
        if (document.querySelector('.comparison-container')) {
            let player1 = null;
            let player2 = null;
            let comparisonChart = null; // To hold the chart instance

            const setupPlayerBox = (playerNumber) => {
                const box = document.getElementById(`player${playerNumber}-box`);
                const placeholder = document.getElementById(`player${playerNumber}-placeholder`);
                const searchWrapper = box.querySelector('.search-wrapper');
                const searchInput = box.querySelector('.player-search-input');
                const resultsContainer = box.querySelector('.search-results');

                placeholder.addEventListener('click', () => {
                    placeholder.style.display = 'none';
                    searchWrapper.style.display = 'block';
                    searchInput.focus();
                });

                searchInput.addEventListener('keyup', function() {
                    const query = this.value;
                    if (query.length < 2) {
                        resultsContainer.innerHTML = '';
                        return;
                    }
                    fetch(`<?php echo URL_ROOT; ?>/app/api/search_players.php?q=${encodeURIComponent(query)}`)
                        .then(response => response.json())
                        .then(data => {
                            let html = '';
                            data.forEach(player => {
                                html += `<div class="search-result-item" data-player-id="${player.id}">
                                            <img src="${player.club_logo}" alt="${player.club_name}"><div><div class="player-name">${player.first_name} ${player.last_name}</div><div class="club-name">${player.club_name}</div></div></div>`;
                            });
                            resultsContainer.innerHTML = html;
                        });
                });

                resultsContainer.addEventListener('click', function(e) {
                    const item = e.target.closest('.search-result-item');
                    if (item) {
                        const playerId = item.dataset.playerId;
                        loadPlayer(playerId, playerNumber);
                        resultsContainer.innerHTML = '';
                        searchInput.value = '';
                    }
                });
            };

            function loadPlayer(playerId, playerNumber) {
                fetch(`<?php echo URL_ROOT; ?>/app/api/get_player_comparison_stats.php?id=${playerId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (playerNumber === 1) player1 = data; else player2 = data;
                        renderPlayerCard(data, playerNumber);
                        checkAndRenderComparison();
                    });
            }

            function renderPlayerCard(player, playerNumber) {
                const cardContainer = document.getElementById(`player${playerNumber}-card`);
                const searchWrapper = document.getElementById(`player${playerNumber}-search`).parentElement;
                const placeholder = document.getElementById(`player${playerNumber}-placeholder`);
                
                cardContainer.innerHTML = `
                    <img src="${player.club_logo}" class="card-bg-logo" alt="">
                    <button class="remove-player-btn" data-player-number="${playerNumber}">&times;</button> 
                    <img src="${player.profile_picture || '<?php echo URL_ROOT; ?>/public/assets/images/default_avatar.png'}" alt="${player.first_name}" class="player-photo"> 
                    <h4>${player.first_name} ${player.last_name}</h4> 
                    <p>${player.position} | ${player.club_name}</p>`;
                
                cardContainer.style.display = 'block';
                searchWrapper.style.display = 'none';
                placeholder.style.display = 'none';
                
                cardContainer.querySelector('.remove-player-btn').addEventListener('click', () => removePlayer(playerNumber));
            }

            function removePlayer(playerNumber) {
                document.getElementById(`player${playerNumber}-card`).style.display = 'none';
                document.getElementById(`player${playerNumber}-placeholder`).style.display = 'flex';
                document.getElementById(`player${playerNumber}-search`).parentElement.style.display = 'none';
                
                if (playerNumber === 1) player1 = null; else player2 = null;
                checkAndRenderComparison();
            }

            function checkAndRenderComparison() {
                const comparisonTable = document.getElementById('comparison-table');
                const chartContainer = document.getElementById('comparison-chart');

                if (player1 && player2) {
                    const container = comparisonTable.querySelector('.stats-comparison-container');
                    let html = '';
                    const stats = [
                        { label: 'Appearances', key: 'appearances' },
                        { label: 'Minutes Played', key: 'minutes_played' },
                        { label: 'Goals', key: 'goals' },
                        { label: 'Assists', key: 'assists' },
                        { label: 'Shots', key: 'shots' },
                        { label: 'Shots on Target', key: 'shots_on_target' },
                        { label: 'Fouls', key: 'fouls' },
                        { label: 'Yellow Cards', key: 'yellow_cards' },
                        { label: 'Red Cards', key: 'red_cards' }
                    ];

                    stats.forEach(stat => {
                        const val1 = parseInt(player1[stat.key]) || 0;
                        const val2 = parseInt(player2[stat.key]) || 0;
                        const total = val1 + val2;
                        let perc1 = 50, perc2 = 50;
                        if (total > 0) {
                            perc1 = (val1 / total) * 100;
                            perc2 = (val2 / total) * 100;
                        }
                        
                        const winner1 = val1 > val2 ? 'winner' : '';
                        const winner2 = val2 > val1 ? 'winner' : '';

                        html += `<div class="stat-row"><span class="stat-value ${winner1}">${val1}</span> <span class="stat-label">${stat.label}</span> <span class="stat-value ${winner2}">${val2}</span></div><div class="stat-bar"><div class="bar-player1" style="width: ${perc1}%;"></div><div class="bar-player2" style="width: ${perc2}%;"></div></div>`;
                    });
                    container.innerHTML = html;
                    comparisonTable.style.display = 'block';
                    
                    // Render the new chart
                    renderComparisonChart(player1, player2);
                    chartContainer.style.display = 'block';
                } else {
                    comparisonTable.style.display = 'none';
                    chartContainer.style.display = 'none';
                    if (comparisonChart) {
                        comparisonChart.destroy();
                        comparisonChart = null;
                    }
                }
            }

            function hexToRgba(hex, alpha = 1) {
                if (!hex) return `rgba(0,0,0,${alpha})`;
                const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
                return result ? `rgba(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}, ${alpha})` : `rgba(0,0,0,${alpha})`;
            }

            function renderComparisonChart(p1, p2) {
                const ctx = document.getElementById('comparisonRadarChart').getContext('2d');

                if (comparisonChart) {
                    comparisonChart.destroy();
                }

                const maxValues = {
                    goals: 30,
                    assists: 20,
                    shots: 100,
                    minutes_played: 38 * 90,
                    fouls: 50,
                };

                const normalize = (value, max) => Math.min(100, (value / max) * 100);
                const normalizeInverted = (value, max) => Math.max(0, 100 - ((value / max) * 100));

                const p1Data = [
                    normalize(p1.goals, maxValues.goals),
                    normalize(p1.assists, maxValues.assists),
                    normalize(p1.shots, maxValues.shots),
                    normalize(p1.minutes_played, maxValues.minutes_played),
                    normalizeInverted(p1.fouls, maxValues.fouls)
                ];

                const p2Data = [
                    normalize(p2.goals, maxValues.goals),
                    normalize(p2.assists, maxValues.assists),
                    normalize(p2.shots, maxValues.shots),
                    normalize(p2.minutes_played, maxValues.minutes_played),
                    normalizeInverted(p2.fouls, maxValues.fouls)
                ];

                const primaryColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();
                const secondaryColor = getComputedStyle(document.documentElement).getPropertyValue('--secondary-color').trim();

                comparisonChart = new Chart(ctx, {
                    type: 'radar',
                    data: {
                        labels: ['Scoring', 'Playmaking', 'Shooting', 'Stamina', 'Discipline'],
                        datasets: [{
                            label: `${p1.first_name} ${p1.last_name}`,
                            data: p1Data,
                            backgroundColor: hexToRgba(primaryColor, 0.2),
                            borderColor: hexToRgba(primaryColor, 1),
                            pointBackgroundColor: hexToRgba(primaryColor, 1),
                        }, {
                            label: `${p2.first_name} ${p2.last_name}`,
                            data: p2Data,
                            backgroundColor: hexToRgba(secondaryColor, 0.2),
                            borderColor: hexToRgba(secondaryColor, 1),
                            pointBackgroundColor: hexToRgba(secondaryColor, 1),
                        }]
                    },
                    options: {
                        scales: { r: { angleLines: { display: true }, suggestedMin: 0, suggestedMax: 100, pointLabels: { font: { size: 14 } }, ticks: { display: false } } },
                        plugins: { legend: { position: 'top' } }
                    }
                });
            }

            setupPlayerBox(1);
            setupPlayerBox(2);
        }
    </script>
</body>
</html>