<?php
$pageTitle = htmlspecialchars($game['title']);
$pageDescription = strip_tags(substr($game['description'], 0, 160));

// Add custom CSS and JS for this page
$customCss = ['/public/css/share-buttons.css', '/public/css/game-fullscreen.css'];
$customJs = ['/public/js/share-buttons.js'];

// Add coins.js only if user is logged in and points system is enabled
if (isset($_SESSION['user_id']) && ($settings['enable_points_system'] ?? '0') == '1') {
    $customJs[] = '/public/js/coins.js';
}

// Add Quill content styling
$customCss[] = '/public/css/quill-content.css';

include __DIR__ . '/layout/header.php';
?>


<div class="container mx-auto px-4 py-8">
    <div class="mb-6">
        <nav class="flex" aria-label="Breadcrumb">
            <ol class="inline-flex items-center space-x-1 md:space-x-3">
                <li class="inline-flex items-center">
                    <a href="/" class="text-gray-400 hover:text-white transition-colors">
                        <i class="fas fa-home mr-2"></i>Home
                    </a>
                </li>
                <li class="breadcrumb-item">
                    <div class="flex items-center">
                        <i class="fas fa-chevron-right text-gray-400 mx-2 text-xs"></i>
                        <a href="/category/<?= $game['category_slug'] ?>" class="text-gray-400 hover:text-white transition-colors">
                            <span class="breadcrumb-text"><?= htmlspecialchars($game['category_name']) ?></span>
                        </a>
                    </div>
                </li>
                <li aria-current="page" class="breadcrumb-item">
                    <div class="flex items-center">
                        <i class="fas fa-chevron-right text-gray-400 mx-2 text-xs"></i>
                        <span class="text-white font-medium breadcrumb-text-last"><?= htmlspecialchars($game['title']) ?></span>
                    </div>
                </li>
            </ol>
        </nav>
    </div>

    <!-- Game Page Ad - Top -->
    <?php if (isset($settings['enable_ads']) && $settings['enable_ads'] == '1' && isset($settings['game_page_ad']) && !empty($settings['game_page_ad'])): ?>
    <div class="ad-container game-page-ad mb-8">
        <?= $settings['game_page_ad'] ?>
    </div>
    <?php endif; ?>

    <!-- Coin Earning Notification -->
    <?php if (isset($_SESSION['user_id']) && ($settings['enable_points_system'] ?? '0') == '1'): ?>
    <div class="mb-6 p-4 bg-yellow-900/20 border border-yellow-600 rounded-xl">
        <div class="flex items-center text-yellow-400">
            <i class="fas fa-coins mr-3 text-xl"></i>
            <span class="font-medium">Earn coins by playing this game! The longer you play, the more you earn.</span>
        </div>
    </div>
    <?php endif; ?>



    <!-- Main Game Container -->
    <div class="max-w-6xl mx-auto">
        <!-- Game Frame -->
        <div class="mb-8">
            <div class="bg-card-bg rounded-xl overflow-hidden shadow-2xl">
                <div id="gameContainer" class="relative w-full" style="aspect-ratio: 16/9;" data-game-id="<?= $game['id'] ?>">
                    <!-- Game thumbnail and play button overlay -->
                    <div id="gameOverlay" class="absolute inset-0 flex items-center justify-center bg-dark z-10">
                        <img src="<?= htmlspecialchars($game['thumbnail']) ?>" alt="<?= htmlspecialchars($game['title']) ?>" class="absolute inset-0 w-full h-full object-cover opacity-50" loading="lazy">
                        <div class="absolute inset-0 bg-gradient-to-t from-black to-transparent"></div>
                        <button id="playGameBtn" class="relative z-20 flex items-center justify-center bg-primary hover:bg-primary/90 text-white font-bold py-3 px-6 sm:py-6 sm:px-12 rounded-full transition-all transform hover:scale-105 focus:outline-none shadow-lg">
                            <i class="fas fa-play mr-2 sm:mr-3 text-lg sm:text-2xl"></i>
                            <span class="text-base sm:text-xl">Play Game</span>
                        </button>
                    </div>
                    <!-- Game embed container (empty initially) -->
                    <div id="gameEmbed" class="hidden flex items-center justify-center w-full h-full absolute inset-0" data-embed-code="<?= htmlspecialchars($game['embed_code']) ?>"></div>

                    <!-- Fullscreen exit button (visible only in fullscreen mode) -->
                    <button id="fullscreenExitBtn" class="fullscreen-exit-btn" title="Exit Fullscreen" data-action="exit-fullscreen">
                        <i class="fas fa-compress"></i>
                    </button>
                </div>

                <!-- Game Toolbar -->
                <div class="game-toolbar">
                    <div class="flex items-center">
                        <span class="text-gray-300 text-sm mr-4">
                            <i class="fas fa-gamepad text-primary mr-2"></i>
                            <?= htmlspecialchars($game['title']) ?>
                        </span>
                    </div>
                    <div class="flex items-center">
                        <button id="fullscreenBtn" class="btn-secondary text-sm py-1 px-3">
                            <i class="fas fa-expand mr-2"></i>Fullscreen
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Game Description and Actions -->
        <div class="bg-card-bg rounded-xl p-6 mb-8">
            <!-- Game Title and Info -->
            <div class="mb-6">
                <h1 class="text-3xl font-bold mb-4"><?= htmlspecialchars($game['title']) ?></h1>
                <div class="mb-4">
                    <span class="category-badge inline-flex">
                        <i class="fas fa-tag mr-1"></i>
                        <?= htmlspecialchars($game['category_name']) ?>
                    </span>
                </div>
            </div>
            
            <h2 class="text-xl font-semibold mb-4">About This Game</h2>
            <div class="text-gray-300 quill-content mb-6"><?= nl2br($game['description']) ?></div>
            
            <div class="flex flex-wrap gap-3 mb-6">
                <a href="/category/<?= $game['category_slug'] ?>" class="btn-primary">
                    <i class="fas fa-th-large mr-2"></i>More Games
                </a>
                <?php if (isset($_SESSION['user_id'])): ?>
                <button id="favoriteBtn" class="btn-secondary" data-game-id="<?= $game['id'] ?>">
                    <i id="favoriteIcon" class="far fa-heart mr-2"></i><span id="favoriteText">Add to Favorites</span>
                </button>
                <?php endif; ?>
            </div>

            <!-- Share Buttons -->
            <div>
                <h3 class="text-lg font-semibold mb-3">Share This Game</h3>
                <div class="flex flex-wrap gap-2">
                    <?php
                    // Get the current URL
                    $currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                    $encodedUrl = urlencode($currentUrl);
                    $encodedTitle = urlencode($game['title']);
                    ?>

                    <!-- Facebook Share -->
                    <a href="https://www.facebook.com/sharer/sharer.php?u=<?= $encodedUrl ?>" target="_blank" class="share-button facebook">
                        <i class="fab fa-facebook-f"></i>
                    </a>

                    <!-- Twitter/X Share -->
                    <a href="https://twitter.com/intent/tweet?url=<?= $encodedUrl ?>&text=<?= $encodedTitle ?>" target="_blank" class="share-button twitter">
                        <i class="fab fa-twitter"></i>
                    </a>

                    <!-- WhatsApp Share -->
                    <a href="https://api.whatsapp.com/send?text=<?= $encodedTitle ?>: <?= $encodedUrl ?>" target="_blank" class="share-button whatsapp">
                        <i class="fab fa-whatsapp"></i>
                    </a>

                    <!-- Telegram Share -->
                    <a href="https://t.me/share/url?url=<?= $encodedUrl ?>&text=<?= $encodedTitle ?>" target="_blank" class="share-button telegram">
                        <i class="fab fa-telegram-plane"></i>
                    </a>

                    <!-- Email Share -->
                    <a href="mailto:?subject=<?= $encodedTitle ?>&body=Check out this game: <?= $encodedUrl ?>" class="share-button email">
                        <i class="fas fa-envelope"></i>
                    </a>

                    <!-- Copy Link -->
                    <button id="copyLinkBtn" class="share-button copy" data-url="<?= $currentUrl ?>">
                        <i class="fas fa-link"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Related Games -->
        <div class="bg-card-bg rounded-xl p-6">
            <h2 class="text-xl font-bold mb-6">Related Games</h2>

            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
                <?php foreach ($relatedGames as $relatedGame): ?>
                <a href="/game/<?= $relatedGame['slug'] ?>" class="game-card group">
                    <div class="relative aspect-square overflow-hidden rounded-xl">
                        <img src="<?= htmlspecialchars($relatedGame['thumbnail']) ?>" alt="<?= htmlspecialchars($relatedGame['title']) ?>"
                             class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110" loading="lazy">
                        <div class="game-card-overlay">
                            <h3 class="game-card-title text-xs md:text-sm"><?= htmlspecialchars($relatedGame['title']) ?></h3>
                        </div>
                        <div class="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                            <button class="w-8 h-8 bg-primary rounded-full flex items-center justify-center">
                                <i class="fas fa-play text-white text-xs"></i>
                            </button>
                        </div>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

    <!-- Game Page Ad - Bottom -->
    <?php if (isset($settings['enable_ads']) && $settings['enable_ads'] == '1' && isset($settings['game_page_ad']) && !empty($settings['game_page_ad'])): ?>
    <div class="ad-container game-page-ad my-8">
        <?= $settings['game_page_ad'] ?>
    </div>
    <?php endif; ?>
</div>

<script>
    // Play button functionality
    const playGameBtn = document.getElementById('playGameBtn');
    const gameOverlay = document.getElementById('gameOverlay');
    const gameEmbed = document.getElementById('gameEmbed');
    let gameLoaded = false;

    // Variable to track if game is landscape oriented
    let isLandscapeGame = false;

    // Function to check if game is landscape oriented
    function checkGameOrientation() {
        const iframes = gameEmbed.querySelectorAll('iframe');
        if (iframes.length > 0) {
            const iframe = iframes[0];
            try {
                // Try to access iframe content if possible (same-origin policy may prevent this)
                if (iframe.contentWindow && iframe.contentWindow.document) {
                    const iframeWidth = iframe.contentWindow.document.body.scrollWidth;
                    const iframeHeight = iframe.contentWindow.document.body.scrollHeight;
                    isLandscapeGame = iframeWidth > iframeHeight;
                } else {
                    // If we can't access iframe content, use the iframe dimensions
                    isLandscapeGame = iframe.width > iframe.height;
                }
            } catch (e) {
                // If we can't access iframe content due to cross-origin restrictions,
                // use the iframe's width and height attributes or default to true for landscape games
                isLandscapeGame = true;
            }

            // Store the orientation but don't automatically enter fullscreen
            // We'll suggest fullscreen for landscape games with a button instead
            if (isLandscapeGame) {
                // Show a suggestion to go fullscreen instead of forcing it
                showFullscreenSuggestion();
            }
        }
    }

    // Function to show a suggestion to go fullscreen for landscape games
    function showFullscreenSuggestion() {
        // Only show suggestion if not already in fullscreen
        if (!document.fullscreenElement &&
            !document.webkitFullscreenElement &&
            !document.mozFullScreenElement &&
            !document.msFullscreenElement) {

            // Highlight the fullscreen button to draw attention
            fullscreenBtn.classList.add('animate-pulse', 'bg-primary', 'text-white');

            // Remove the animation after a few seconds
            setTimeout(() => {
                fullscreenBtn.classList.remove('animate-pulse');
            }, 3000);
        }
    }

    // Function to lazy load the game iframe
    function loadGame() {
        if (!gameLoaded) {
            // Get the embed code from the data attribute
            let embedCode = gameEmbed.getAttribute('data-embed-code');

            <?php if ($game['source'] === 'gamezop' && isset($_SESSION['user_id'])): ?>
            // For Gamezop games, add user ID to URL for progress saving
            // Extract the iframe src URL
            const srcMatch = embedCode.match(/src="([^"]+)"/i);
            if (srcMatch && srcMatch[1]) {
                const originalUrl = srcMatch[1];
                // Add sub parameter with user ID for progress saving
                const userId = '<?= $_SESSION['user_id'] ?>';
                const separator = originalUrl.includes('?') ? '&' : '?';
                const newUrl = originalUrl + separator + 'sub=' + userId;
                // Replace the URL in the embed code
                embedCode = embedCode.replace(srcMatch[1], newUrl);
            }
            <?php endif; ?>

            // Insert the embed code into the container
            gameEmbed.innerHTML = embedCode;

            // Apply styling to center the iframe content
            const iframes = gameEmbed.querySelectorAll('iframe');
            iframes.forEach(iframe => {
                iframe.style.maxWidth = '100%';
                iframe.style.maxHeight = '100%';
                iframe.style.margin = 'auto';
                iframe.style.display = 'block';
                iframe.style.position = 'absolute';
                iframe.style.top = '0';
                iframe.style.left = '0';
                iframe.style.right = '0';
                iframe.style.bottom = '0';
                iframe.style.width = '100%';
                iframe.style.height = '100%';

                // Add load event to check orientation after game loads
                iframe.addEventListener('load', checkGameOrientation);
            });

            // Mark as loaded
            gameLoaded = true;

            // Record game play for logged-in users
            <?php if (isset($_SESSION['user_id'])): ?>
            fetch('/record-game-play', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'game_id=<?= $game['id'] ?>'
            });
            <?php endif; ?>
        }

        // Hide the overlay
        gameOverlay.classList.add('hidden');

        // Show the game embed
        gameEmbed.classList.remove('hidden');

        // Focus on the game container
        gameContainer.focus();
    }

    // Add click event to play button
    playGameBtn.addEventListener('click', loadGame);

    // Fullscreen functionality
    const fullscreenBtn = document.getElementById('fullscreenBtn');
    const fullscreenExitBtn = document.getElementById('fullscreenExitBtn');
    const gameContainer = document.getElementById('gameContainer');

    // Detect iOS device
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

    // Function to enter fullscreen
    function enterFullscreen() {
        // If game hasn't been started yet, start it
        if (!gameOverlay.classList.contains('hidden')) {
            loadGame();
        }

        // Check if it's an iOS device
        if (isIOS) {
            // iOS doesn't support fullscreen API, use CSS-based fullscreen
            document.body.classList.add('ios-fullscreen-mode');
            gameContainer.classList.add('ios-fullscreen');
            fullscreenExitBtn.style.display = 'flex';

            // Add active class after a short delay
            setTimeout(() => {
                fullscreenExitBtn.classList.add('active');
            }, 300);

            // Show a message for iOS users about adding to home screen for true fullscreen
            const iosMessage = document.createElement('div');
            iosMessage.className = 'ios-fullscreen-message';
            iosMessage.innerHTML = '<p>For true fullscreen, add this page to your home screen</p><button id="dismissMessage">Got it</button>';
            document.body.appendChild(iosMessage);

            // Dismiss message when button is clicked
            document.getElementById('dismissMessage').addEventListener('click', function() {
                iosMessage.style.display = 'none';
            });

            // Auto-hide message after 5 seconds
            setTimeout(() => {
                iosMessage.style.opacity = '0';
                setTimeout(() => {
                    iosMessage.style.display = 'none';
                }, 500);
            }, 5000);
        } else {
            // For non-iOS devices, use standard fullscreen API
            try {
                // Ensure this function is called from a user gesture handler
                // by checking if it's being called synchronously from a click or touch event
                const isUserGesture = (document.currentScript === null);

                // Request fullscreen with proper error handling
                if (gameContainer.requestFullscreen) {
                    gameContainer.requestFullscreen().catch(err => {
                        console.warn('Fullscreen request failed:', err.message);
                    });
                } else if (gameContainer.webkitRequestFullscreen) {
                    gameContainer.webkitRequestFullscreen().catch(err => {
                        console.warn('Webkit fullscreen request failed:', err.message);
                    });
                } else if (gameContainer.mozRequestFullScreen) {
                    gameContainer.mozRequestFullScreen().catch(err => {
                        console.warn('Mozilla fullscreen request failed:', err.message);
                    });
                } else if (gameContainer.msRequestFullscreen) {
                    gameContainer.msRequestFullscreen().catch(err => {
                        console.warn('MS fullscreen request failed:', err.message);
                    });
                }
            } catch (err) {
                console.warn('Error attempting to enter fullscreen:', err.message);
                // If fullscreen fails, we'll just continue in windowed mode
            }
        }
    }

    // Function to exit fullscreen
    function exitFullscreen() {
        // Check if it's an iOS device
        if (isIOS) {
            // Remove iOS fullscreen classes
            document.body.classList.remove('ios-fullscreen-mode');
            gameContainer.classList.remove('ios-fullscreen');
            fullscreenExitBtn.style.display = 'none';
            fullscreenExitBtn.classList.remove('active');

            // Remove any iOS fullscreen message if it exists
            const iosMessage = document.querySelector('.ios-fullscreen-message');
            if (iosMessage) {
                iosMessage.remove();
            }
        } else {
            // For non-iOS devices, use standard fullscreen API
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        }
    }

    // Add click event to fullscreen button
    fullscreenBtn.addEventListener('click', enterFullscreen);

    // Add event listener for orientation changes
    window.addEventListener('orientationchange', function() {
        // If the game is landscape and we're not already in fullscreen, suggest fullscreen
        if (isLandscapeGame && !document.fullscreenElement && !document.webkitFullscreenElement &&
            !document.mozFullScreenElement && !document.msFullscreenElement &&
            !document.body.classList.contains('ios-fullscreen-mode')) {
            setTimeout(() => {
                // Instead of automatically entering fullscreen, show a suggestion
                showFullscreenSuggestion();
            }, 500); // Short delay to allow orientation change to complete
        }
    });

    // Variables for mobile optimization
    let isExpanded = false;
    let autoHideTimer = null;
    let lastTapTime = 0;
    const doubleTapThreshold = 500; // ms between taps to count as double tap

    // Function to expand the button
    function expandButton() {
        isExpanded = true;
        fullscreenExitBtn.classList.add('expanded');
        fullscreenExitBtn.classList.remove('collapsing');

        // Set a timer to auto-collapse after 3 seconds
        clearTimeout(autoHideTimer);
        autoHideTimer = setTimeout(() => {
            collapseButton();
        }, 3000);
    }

    // Function to collapse the button
    function collapseButton() {
        if (!isExpanded) return;

        fullscreenExitBtn.classList.add('collapsing');

        // Remove expanded and collapsing classes after transition
        setTimeout(() => {
            isExpanded = false;
            fullscreenExitBtn.classList.remove('expanded');
            fullscreenExitBtn.classList.remove('collapsing');
            // Ensure transform is reset to default collapsed state
            fullscreenExitBtn.style.transform = 'translateX(-70%)';
        }, 300); // Match the CSS transition duration
    }

    // Function to exit fullscreen and reset button state
    function exitFullscreenAndReset() {
        exitFullscreen();
        isExpanded = false;
        fullscreenExitBtn.classList.remove('expanded');
        fullscreenExitBtn.classList.remove('collapsing');

        // Reset transform to ensure button collapses properly
        if (isIOS) {
            fullscreenExitBtn.style.transform = 'translateX(-50%)';
        } else {
            fullscreenExitBtn.style.transform = 'translateX(-70%)';
        }

        clearTimeout(autoHideTimer);
    }

    // Improved mobile touch handler with single-tap functionality
    function handleMobileTouch(event) {
        // Always prevent default to avoid any browser interference
        event.preventDefault();

        const currentTime = new Date().getTime();
        const timeSinceLastTap = currentTime - lastTapTime;

        // Update last tap time
        lastTapTime = currentTime;

        // If this is a double tap (second tap within threshold)
        if (timeSinceLastTap < doubleTapThreshold && isExpanded) {
            // Second tap - exit fullscreen
            exitFullscreenAndReset();
            return;
        }

        // If not expanded yet, expand it
        if (!isExpanded) {
            expandButton();
        } else {
            // If already expanded, exit fullscreen on tap
            exitFullscreenAndReset();
        }
    }

    // Desktop click handler
    function handleDesktopClick() {
        exitFullscreen();
    }

    // Detect if we're on a mobile device
    const isMobileDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

    // Add appropriate event listeners based on device type
    if (isMobileDevice) {
        // For mobile: use touchstart for immediate response
        fullscreenExitBtn.addEventListener('touchstart', handleMobileTouch, { passive: false });

        // Add touchend listener to prevent any unwanted behaviors
        fullscreenExitBtn.addEventListener('touchend', (e) => {
            e.preventDefault();
        }, { passive: false });

        // Add touchcancel listener to reset state if touch is canceled
        fullscreenExitBtn.addEventListener('touchcancel', () => {
            // Don't collapse immediately on touch cancel
            // The auto-collapse timer will handle this
        });
    } else {
        // For desktop: use click event
        fullscreenExitBtn.addEventListener('click', handleDesktopClick);
    }

    // Add hover events for the exit button (desktop only)
    // Use matchMedia to only apply hover effects on non-touch devices
    if (window.matchMedia('(hover: hover)').matches) {
        fullscreenExitBtn.addEventListener('mouseenter', () => {
            fullscreenExitBtn.style.transform = 'translateX(0)';
        });

        fullscreenExitBtn.addEventListener('mouseleave', () => {
            if (fullscreenExitBtn.classList.contains('active') && !isExpanded) {
                fullscreenExitBtn.style.transform = 'translateX(-70%)';
            }
        });
    }

    // Listen for fullscreen change events
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
    document.addEventListener('mozfullscreenchange', handleFullscreenChange);
    document.addEventListener('MSFullscreenChange', handleFullscreenChange);

    // Initialize fullscreen button state
    handleFullscreenChange();

    function handleFullscreenChange() {
        // Check if we're in fullscreen mode
        const isFullscreen = document.fullscreenElement ||
                           document.webkitFullscreenElement ||
                           document.mozFullScreenElement ||
                           document.msFullscreenElement ||
                           document.body.classList.contains('ios-fullscreen-mode'); // Check for iOS fullscreen

        // Make sure the game is loaded when entering fullscreen
        if (isFullscreen) {
            if (!gameLoaded) {
                loadGame();
            }
            // Explicitly show the exit button
            fullscreenExitBtn.style.display = 'flex';

            // Make sure any inline styles are removed
            fullscreenExitBtn.style.transform = '';

            // Reset position after a short delay to ensure CSS transition works
            setTimeout(() => {
                fullscreenExitBtn.classList.add('active');

                // For mobile devices, make the button slightly more visible
                if (isMobileDevice) {
                    // Make sure the button is slightly visible to encourage tapping
                    fullscreenExitBtn.style.opacity = '0.9';
                }
            }, 300);

            // Don't reset expanded state when entering fullscreen
            // This allows the button to stay expanded if the user has tapped it
        } else {
            // Only hide the exit button if we're not in iOS fullscreen mode
            if (!document.body.classList.contains('ios-fullscreen-mode')) {
                fullscreenExitBtn.style.display = 'none';
                fullscreenExitBtn.classList.remove('active');
                fullscreenExitBtn.classList.remove('expanded');
                fullscreenExitBtn.classList.remove('collapsing');

                // Remove any inline styles
                fullscreenExitBtn.style.transform = '';
                fullscreenExitBtn.style.opacity = '';

                // Clear any auto-hide timers
                clearTimeout(autoHideTimer);
                isExpanded = false;
            }
        }
    }
</script>

<!-- Favorite Game Script -->
<?php if (isset($_SESSION['user_id'])): ?>
<script>
    // Favorite button functionality
    const favoriteBtn = document.getElementById('favoriteBtn');
    const favoriteIcon = document.getElementById('favoriteIcon');
    const favoriteText = document.getElementById('favoriteText');
    const gameId = favoriteBtn.getAttribute('data-game-id');

    // Check if game is already favorited
    function checkFavoriteStatus() {
        fetch(`/is-game-favorited?game_id=${gameId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.is_favorited) {
                    // Game is favorited, update UI
                    favoriteIcon.classList.remove('far');
                    favoriteIcon.classList.add('fas');
                    favoriteIcon.classList.add('text-red-500');
                    favoriteText.textContent = 'Remove from Favorites';
                }
            })
            .catch(error => console.error('Error checking favorite status:', error));
    }

    // Toggle favorite status
    function toggleFavorite() {
        // Show loading state
        favoriteBtn.disabled = true;
        favoriteIcon.classList.remove('far', 'fas', 'text-red-500');
        favoriteIcon.classList.add('fas', 'fa-spinner', 'fa-spin');

        fetch('/toggle-favorite', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `game_id=${gameId}`
        })
        .then(response => response.json())
        .then(data => {
            // Remove loading state
            favoriteBtn.disabled = false;
            favoriteIcon.classList.remove('fa-spinner', 'fa-spin');

            if (data.success) {
                if (data.is_favorited) {
                    // Game was added to favorites
                    favoriteIcon.classList.remove('far');
                    favoriteIcon.classList.add('fas', 'text-red-500');
                    favoriteText.textContent = 'Remove from Favorites';
                } else {
                    // Game was removed from favorites
                    favoriteIcon.classList.remove('fas', 'text-red-500');
                    favoriteIcon.classList.add('far');
                    favoriteText.textContent = 'Add to Favorites';
                }
            }
        })
        .catch(error => {
            console.error('Error toggling favorite:', error);
            // Reset button on error
            favoriteBtn.disabled = false;
            favoriteIcon.classList.remove('fa-spinner', 'fa-spin');
            favoriteIcon.classList.add('far');
        });
    }

    // Add click event to favorite button
    favoriteBtn.addEventListener('click', toggleFavorite);

    // Check favorite status on page load
    checkFavoriteStatus();
</script>
<?php endif; ?>

<?php include __DIR__ . '/layout/footer.php'; ?>
