const initApp = function () {

    // --- Unified Account Panel Logic ---
    const accountPanel = document.getElementById('account-panel');
    const panelOverlay = document.querySelector('.account-panel-overlay');
    const headerTrigger = document.getElementById('header-account-trigger');
    const footerTrigger = document.getElementById('footer-account-trigger');
    const closeBtn = document.getElementById('close-account-panel');

    function toggleAccountPanel(e) {
        if (e) e.preventDefault();
        if (accountPanel) accountPanel.classList.toggle('visible');
        if (panelOverlay) panelOverlay.classList.toggle('visible');
    }

    if (headerTrigger) headerTrigger.addEventListener('click', toggleAccountPanel);
    if (footerTrigger) footerTrigger.addEventListener('click', toggleAccountPanel);
    if (closeBtn) closeBtn.addEventListener('click', toggleAccountPanel);
    if (panelOverlay) panelOverlay.addEventListener('click', toggleAccountPanel);

    // Close panel when any link inside is clicked
    if (accountPanel) {
        const panelLinks = accountPanel.querySelectorAll('a, button:not(#close-account-panel)');
        panelLinks.forEach(link => {
            link.addEventListener('click', () => {
                accountPanel.classList.remove('visible');
                if (panelOverlay) panelOverlay.classList.remove('visible');
            });
        });
    }

    // --- Logic for controls inside the Account Panel ---
    const themeToggle = document.getElementById('theme-toggle');
    const body = document.body;

    if (themeToggle) {
        const icon = themeToggle.querySelector('i');
        const currentTheme = localStorage.getItem('theme') || 'light';
        body.setAttribute('data-theme', currentTheme);
        if (icon) updateIcon(currentTheme);

        themeToggle.addEventListener('click', function () {
            const newTheme = body.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
            body.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            if (icon) updateIcon(newTheme);
        });

        function updateIcon(theme) {
            if (theme === 'dark') {
                icon.classList.replace('fa-moon', 'fa-sun');
            } else {
                icon.classList.replace('fa-sun', 'fa-moon');
            }
        }
    }

    // --- New Modal Logic ---
    const searchModal = document.getElementById('searchModal');
    const notificationsModal = document.getElementById('notificationsModal');
    const searchModalTrigger = document.getElementById('search-modal-trigger');
    const notificationsModalTrigger = document.getElementById('notifications-modal-trigger');

    // Search Modal
    if (searchModal && searchModalTrigger) {
        const searchInput = document.getElementById('global-search-input');
        const searchResultsContainer = document.getElementById('global-search-results');
        const closeSearchBtn = document.getElementById('closeSearchModal');

        const openSearchModal = () => searchModal.classList.add('show');
        const closeSearchModal = () => searchModal.classList.remove('show');

        searchModalTrigger.addEventListener('click', (e) => { e.preventDefault(); openSearchModal(); });
        closeSearchBtn.addEventListener('click', closeSearchModal);

        let debounceTimer;
        searchInput.addEventListener('input', () => {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                const query = searchInput.value;
                if (query.length < 2) {
                    searchResultsContainer.innerHTML = '<p class="no-data-msg" style="padding: 20px; text-align: center; color: #888;">Type at least 2 characters to search.</p>';
                    return;
                }
                searchResultsContainer.innerHTML = '<p class="no-data-msg" style="padding: 20px; text-align: center; color: #888;">Searching...</p>';

                fetch(`${SITE_URL}/app/api/global_search.php?q=${encodeURIComponent(query)}`)
                    .then(res => res.json())
                    .then(data => {
                        let html = '';
                        if (data.teams && data.teams.length > 0) {
                            html += '<h3>Teams</h3>';
                            data.teams.forEach(team => {
                                html += `<a href="#" class="search-result-item">
                                    <img src="${team.club_logo}" alt="${team.name}">
                                    <div><div class="team-name">${team.name}</div><div class="club-name">${team.club_name}</div></div>
                                </a>`;
                            });
                        }
                        if (data.players && data.players.length > 0) {
                            html += '<h3>Players</h3>';
                            data.players.forEach(player => {
                                html += `<a href="${SITE_URL}/app/player.php?id=${player.id}" class="search-result-item">
                                    <img src="${player.profile_picture || `${SITE_URL}/app/assets/images/default_avatar.png`}" alt="${player.first_name}">
                                    <div><div class="player-name">${player.first_name} ${player.last_name}</div><div class="player-position">${player.position} - ${player.club_name || 'Free Agent'}</div></div>
                                </a>`;
                            });
                        }
                        if (html === '') {
                            html = '<p class="no-data-msg" style="padding: 20px; text-align: center; color: #888;">No results found.</p>';
                        }
                        searchResultsContainer.innerHTML = html;
                    }).catch(() => {
                        searchResultsContainer.innerHTML = '<p class="no-data-msg" style="padding: 20px; text-align: center; color: #888;">Error during search.</p>';
                    });
            }, 300);
        });
    }

    // Notifications Modal
    if (notificationsModal && notificationsModalTrigger) {
        const closeNotificationsBtn = document.getElementById('closeNotificationsModal');
        const openNotificationsModal = () => notificationsModal.classList.add('show');
        const closeNotificationsModal = () => notificationsModal.classList.remove('show');

        notificationsModalTrigger.addEventListener('click', (e) => { e.preventDefault(); openNotificationsModal(); });
        closeNotificationsBtn.addEventListener('click', closeNotificationsModal);

        // Mark notifications as read when clicked
        const notificationList = notificationsModal.querySelector('.notification-list');
        if (notificationList) {
            notificationList.addEventListener('click', function (e) {
                const item = e.target.closest('.notification-item.unread');
                if (item) {
                    const id = item.dataset.id;

                    // Optimistic UI update
                    item.classList.remove('unread');

                    // Update all badges
                    const unreadCount = document.querySelectorAll('.notification-item.unread').length;
                    const badges = document.querySelectorAll('.notification-badge');
                    badges.forEach(badge => {
                        if (unreadCount > 0) {
                            badge.textContent = unreadCount;
                        } else {
                            badge.style.display = 'none';
                        }
                    });

                    // Send request to backend
                    fetch(SITE_URL + '/app/api/mark_notification_read.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: 'id=' + id
                    });
                }
            });
        }
    }

    // Generic modal close on overlay click
    window.addEventListener('click', (e) => {
        if (e.target == searchModal) searchModal.classList.remove('show');
        if (e.target == notificationsModal) notificationsModal.classList.remove('show');
    });

    // --- Countdown Timer Logic ---
    const countdownElement = document.getElementById('countdown-timer');
    if (countdownElement) {
        const matchTime = countdownElement.getAttribute('data-match-time');
        if (matchTime) {
            const targetDate = new Date(matchTime.replace(' ', 'T')).getTime();

            const interval = setInterval(() => {
                const now = new Date().getTime();
                const distance = targetDate - now;

                if (distance < 0) {
                    clearInterval(interval);
                    countdownElement.innerHTML = "<p>The match should be starting soon!</p>";
                    setTimeout(() => window.location.reload(), 30000);
                    return;
                }

                document.getElementById('days').innerText = String(Math.floor(distance / (1000 * 60 * 60 * 24))).padStart(2, '0');
                document.getElementById('hours').innerText = String(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))).padStart(2, '0');
                document.getElementById('minutes').innerText = String(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))).padStart(2, '0');
                document.getElementById('seconds').innerText = String(Math.floor((distance % (1000 * 60)) / 1000)).padStart(2, '0');
            }, 1000);
        }
    }

    // --- Fantasy Transfers Page Logic ---
    const transfersPage = document.getElementById('transfers-page');
    if (transfersPage) {
        // --- State Variables ---
        const initialBudget = parseFloat(transfersPage.dataset.budget);
        let moneyRemaining = initialBudget;
        let selectedPlayers = new Set();
        const positionCounts = { Goalkeeper: 0, Defender: 0, Midfielder: 0, Forward: 0 };
        const positionLimits = { Goalkeeper: 2, Defender: 5, Midfielder: 5, Forward: 3 };
        const SQUAD_SIZE = 15;

        // --- UI Elements ---
        const moneyRemainingEl = document.getElementById('money-remaining');
        const playersSelectedCountEl = document.getElementById('players-selected-count');
        const confirmBtn = document.getElementById('confirm-transfers-btn');
        const playerTableBody = document.querySelector('.transfers-table tbody');
        const positionFilters = document.querySelectorAll('.player-filters .sub-tab-link');

        // --- Functions ---
        function updateUI() {
            // Update header info
            moneyRemainingEl.textContent = `$${moneyRemaining.toFixed(1)}m`;
            playersSelectedCountEl.textContent = `${selectedPlayers.size} / ${SQUAD_SIZE}`;

            // Update footer position counts
            document.getElementById('gk-count').textContent = positionCounts.Goalkeeper;
            document.getElementById('def-count').textContent = positionCounts.Defender;
            document.getElementById('mid-count').textContent = positionCounts.Midfielder;
            document.getElementById('fwd-count').textContent = positionCounts.Forward;

            // Update color if limit is reached
            for (const pos in positionLimits) {
                const el = document.querySelector(`.squad-position-count[data-position="${pos}"]`);
                if (positionCounts[pos] >= positionLimits[pos]) {
                    el.classList.add('limit-reached');
                } else {
                    el.classList.remove('limit-reached');
                }
            }

            // Enable/disable confirm button
            if (selectedPlayers.size === SQUAD_SIZE) {
                confirmBtn.disabled = false;
            } else {
                confirmBtn.disabled = true;
            }
        }

        function handlePlayerAction(e) {
            if (!e.target.matches('.btn-add, .btn-remove')) return;

            const button = e.target;
            const playerRow = button.closest('tr');
            const playerId = playerRow.dataset.playerId;
            const price = parseFloat(playerRow.dataset.price);
            const position = playerRow.dataset.position;

            if (button.classList.contains('btn-add')) {
                // --- Add Player Logic ---
                if (selectedPlayers.size >= SQUAD_SIZE) {
                    alert('Your squad is full (15 players).');
                    return;
                }
                if (positionCounts[position] >= positionLimits[position]) {
                    alert(`You can only have ${positionLimits[position]} players in this position.`);
                    return;
                }
                if (moneyRemaining < price) {
                    alert('Not enough money remaining.');
                    return;
                }

                // Add player
                selectedPlayers.add(playerId);
                moneyRemaining -= price;
                positionCounts[position]++;
                playerRow.classList.add('selected');
                button.textContent = 'Remove';
                button.classList.replace('btn-add', 'btn-remove');

            } else {
                // --- Remove Player Logic ---
                selectedPlayers.delete(playerId);
                moneyRemaining += price;
                positionCounts[position]--;
                playerRow.classList.remove('selected');
                button.textContent = 'Add';
                button.classList.replace('btn-remove', 'btn-add');
            }

            updateUI();
        }

        function filterPlayerList(e) {
            e.preventDefault();
            const selectedPosition = e.target.dataset.position;

            // Update active filter button
            positionFilters.forEach(f => f.classList.remove('active'));
            e.target.classList.add('active');

            // Show/hide table rows
            const allRows = playerTableBody.querySelectorAll('tr');
            allRows.forEach(row => {
                if (selectedPosition === 'All' || row.dataset.position === selectedPosition) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }

        function confirmTransfers() {
            if (selectedPlayers.size !== SQUAD_SIZE) {
                alert('You must select exactly 15 players.');
                return;
            }

            // Create a hidden form to submit the player IDs
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'fantasy_squad_process.php';

            const playerIds = Array.from(selectedPlayers);
            playerIds.forEach(id => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'player_ids[]';
                input.value = id;
                form.appendChild(input);
            });

            document.body.appendChild(form);
            form.submit();
        }

        // --- Event Listeners ---
        playerTableBody.addEventListener('click', handlePlayerAction);
        positionFilters.forEach(filter => filter.addEventListener('click', filterPlayerList));
        confirmBtn.addEventListener('click', confirmTransfers);

        // --- Initial UI Update ---
        updateUI();
    }
};

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initApp);
} else {
    initApp();
}