// Coins system JavaScript functionality

// Prevent multiple declarations
if (typeof window.CoinsSystem === 'undefined') {

class CoinsSystem {
    constructor() {
        this.gameStartTime = null;
        this.gameId = null;
        this.isPlaying = false;
        this.pointsSystemEnabled = false;
        this.balanceRefreshInterval = null;
        this.checkPointsSystemStatus();
    }

    async checkPointsSystemStatus() {
        try {
            const response = await fetch('/api/coins/balance');
            const data = await response.json();
            this.pointsSystemEnabled = data.success;
            
            if (this.pointsSystemEnabled) {
                this.updateBalanceDisplay(data.balance.balance);
                // Start continuous balance refresh
                this.startBalanceRefreshTimer();
            }
        } catch (error) {
            console.log('Points system not available or user not logged in:', error);
        }
    }

    startBalanceRefreshTimer() {
        // Clear any existing interval
        if (this.balanceRefreshInterval) {
            clearInterval(this.balanceRefreshInterval);
        }
        
        // Refresh balance every 5 seconds for real-time updates
        this.balanceRefreshInterval = setInterval(() => {
            this.refreshBalance();
        }, 5000);
    }

    startGame(gameId) {
        if (!this.pointsSystemEnabled) {
            console.log('Points system not enabled, not starting coin earning');
            return;
        }
        
        this.gameId = gameId;
        this.gameStartTime = Date.now();
        this.isPlaying = true;
        
        console.log('Started earning coins for game:', gameId, 'at time:', this.gameStartTime);
    }

    async endGame() {
        if (!this.pointsSystemEnabled || !this.isPlaying || !this.gameStartTime) {
            console.log('End game conditions not met:', {
                pointsSystemEnabled: this.pointsSystemEnabled,
                isPlaying: this.isPlaying,
                gameStartTime: this.gameStartTime
            });
            return;
        }
        
        const playTime = Math.floor((Date.now() - this.gameStartTime) / 1000);
        console.log('Ending game. Play time:', playTime, 'seconds');
        
        if (playTime >= 60) { // Minimum 1 minute to earn coins
            console.log('Play time meets minimum requirement, awarding coins...');
            try {
                const requestData = {
                    game_id: this.gameId,
                    play_time: playTime
                };
                console.log('Sending coin award request:', requestData);
                
                const response = await fetch('/api/coins/award', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestData)
                });

                console.log('Response status:', response.status);
                const data = await response.json();
                console.log('Response data:', data);
                
                if (data.success) {
                    this.showCoinsEarned(data.coins_earned);
                    // Force update the balance display immediately
                    this.updateBalanceDisplay(data.new_balance);
                    console.log('Coins awarded successfully:', data.coins_earned);
                    console.log('Updated balance to:', data.new_balance);
                    
                    // Also refresh balance from server to ensure accuracy
                    setTimeout(() => {
                        this.refreshBalance();
                    }, 500);
                } else {
                    console.error('Failed to award coins:', data.message);
                }
            } catch (error) {
                console.error('Error awarding coins:', error);
            }
        } else {
            console.log('Play time too short for coins:', playTime, 'seconds (need 60+)');
        }
        
        this.resetGame();
    }

    resetGame() {
        this.gameStartTime = null;
        this.gameId = null;
        this.isPlaying = false;
        
        // Keep balance refresh timer running for real-time updates
    }

    showCoinsEarned(amount) {
        // Create a notification for earned coins
        const notification = document.createElement('div');
        notification.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 bg-green-600 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-bounce';
        notification.innerHTML = `
            <div class="flex items-center">
                <i class="fas fa-coins mr-2"></i>
                <span>+${amount} coins earned!</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        console.log('Showing coins earned notification:', amount);
        
        // Remove notification after 5 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 5000);
    }

    showSuccessMessage(message) {
        // Create a success notification
        const notification = document.createElement('div');
        notification.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 bg-green-600 text-white px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300';
        notification.innerHTML = `
            <div class="flex items-center">
                <i class="fas fa-check-circle mr-2"></i>
                <span>${message}</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // Add entrance animation
        setTimeout(() => {
            notification.style.transform = 'translateX(-50%) translateY(0)';
        }, 10);
        
        // Remove notification after 3 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(-50%) translateY(-20px)';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.remove();
                    }
                }, 300);
            }
        }, 3000);
    }

    showErrorMessage(message) {
        // Create an error notification
        const notification = document.createElement('div');
        notification.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 bg-red-600 text-white px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300';
        notification.innerHTML = `
            <div class="flex items-center">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <span>${message}</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // Add entrance animation
        setTimeout(() => {
            notification.style.transform = 'translateX(-50%) translateY(0)';
        }, 10);
        
        // Remove notification after 5 seconds (longer for errors)
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(-50%) translateY(-20px)';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.remove();
                    }
                }, 300);
            }
        }, 5000);
    }

    updateBalanceDisplay(balance) {
        const balanceElements = document.querySelectorAll('.coin-balance');
        const formattedBalance = balance.toLocaleString();
        
        balanceElements.forEach(element => {
            if (element.textContent !== formattedBalance) {
                element.textContent = formattedBalance;
            }
        });
    }

    async refreshBalance() {
        try {
            const response = await fetch('/api/coins/balance');
            const data = await response.json();
            
            if (data.success) {
                this.updateBalanceDisplay(data.balance.balance);
                return data.balance.balance;
            }
        } catch (error) {
            console.error('Error refreshing balance:', error);
        }
        return null;
    }

    async openWithdrawalModal() {
        if (!this.pointsSystemEnabled) return;

        // Get current balance and withdrawal settings
        const [balanceResponse, settingsResponse] = await Promise.all([
            fetch('/api/coins/balance'),
            fetch('/api/coins/withdrawal-settings')
        ]);
        
        const balanceData = await balanceResponse.json();
        const settingsData = await settingsResponse.json();
        
        if (!balanceData.success) {
            alert('Unable to load balance');
            return;
        }
        
        if (!settingsData.success) {
            alert('Unable to load withdrawal settings');
            return;
        }

        const balance = balanceData.balance.balance;
        const settings = settingsData.settings;
        const minimumWithdrawal = settings.minimum_withdrawal;

        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        modal.innerHTML = `
            <div class="bg-card-bg rounded-lg p-6 max-w-md w-full mx-4">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">Withdraw Coins</h3>
                    <button onclick="this.closest('.fixed').remove()" class="text-gray-400 hover:text-white">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div class="mb-4">
                    <p class="text-gray-300">Current Balance: <span class="text-yellow-400">${balance.toLocaleString()} coins</span></p>
                    <p class="text-sm text-gray-400">Minimum withdrawal: ${minimumWithdrawal.toLocaleString()} coins</p>
                </div>
                
                <form id="withdrawalForm" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-1">Amount (coins)</label>
                        <input type="number" id="withdrawAmount" min="${minimumWithdrawal}" max="${balance}" 
                               class="w-full bg-darker border border-gray-700 rounded px-3 py-2 text-white" required>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-1">Payment Method</label>
                        <select id="paymentMethod" class="w-full bg-darker border border-gray-700 rounded px-3 py-2 text-white" required>
                            <option value="">Select payment method</option>
                            ${settings.withdrawal_methods.map(method => 
                                `<option value="${method.toLowerCase().replace(/\s+/g, '_')}">${method}</option>`
                            ).join('')}
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-1">Payment Details</label>
                        <textarea id="paymentDetails" placeholder="Enter your payment details (email, wallet address, etc.)" 
                                  class="w-full bg-darker border border-gray-700 rounded px-3 py-2 text-white h-20" required></textarea>
                    </div>
                    
                    <div class="flex gap-3">
                        <button type="submit" class="flex-1 bg-primary hover:bg-primary-dark text-white py-2 px-4 rounded">
                            Submit Request
                        </button>
                        <button type="button" onclick="this.closest('.fixed').remove()" 
                                class="px-4 py-2 border border-gray-700 text-gray-300 rounded hover:bg-gray-800">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        `;

        document.body.appendChild(modal);

        // Handle form submission
        document.getElementById('withdrawalForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const amount = parseInt(document.getElementById('withdrawAmount').value);
            const paymentMethod = document.getElementById('paymentMethod').value;
            const paymentDetails = document.getElementById('paymentDetails').value;

            try {
                const response = await fetch('/api/coins/withdraw', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        amount: amount,
                        payment_method: paymentMethod,
                        payment_details: paymentDetails
                    })
                });

                const result = await response.json();
                
                if (result.success) {
                    // Show success message
                    this.showSuccessMessage('Withdrawal request submitted successfully!');
                    modal.remove();
                    
                    // Refresh the page after a short delay
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    this.showErrorMessage('Error: ' + result.message);
                }
            } catch (error) {
                console.error('Error submitting withdrawal:', error);
                alert('An error occurred while submitting your withdrawal request.');
            }
        });
    }
}

// Store the class globally
window.CoinsSystem = CoinsSystem;

// Initialize coins system
window.coinsSystem = new CoinsSystem();

// Global functions for easy access
window.startEarningCoins = (gameId) => window.coinsSystem.startGame(gameId);
window.stopEarningCoins = () => window.coinsSystem.endGame();
window.openWithdrawalModal = () => window.coinsSystem.openWithdrawalModal();
window.refreshCoinBalance = () => window.coinsSystem.refreshBalance();

// Balance refresh is now handled by the continuous 5-second timer in startBalanceRefreshTimer()

} // End of multiple declaration check

// Auto-detect game iframes and track play time
if (typeof window.coinsGameTrackingInitialized === 'undefined') {
    window.coinsGameTrackingInitialized = true;
    
    document.addEventListener('DOMContentLoaded', function() {
        // Look for game container with data-game-id first, then fallback to iframes
        const gameContainer = document.querySelector('[data-game-id]');
        const gameId = gameContainer?.getAttribute('data-game-id');
        
        // Only initialize game tracking if we're actually on a game page
        const isGamePage = gameContainer !== null || window.location.pathname.includes('/game/');
        
        console.log('Game tracking initialized. Game ID:', gameId, 'Container found:', !!gameContainer, 'Is game page:', isGamePage);
        
        if (gameId && isGamePage) {
            // Start tracking when play button is clicked (when game actually loads)
            const playButton = document.getElementById('playGameBtn');
            if (playButton) {
                playButton.addEventListener('click', () => {
                    console.log('Play button clicked, starting coin tracking');
                    setTimeout(() => {
                        window.coinsSystem.startGame(gameId);
                    }, 2000); // Wait 2 seconds for game to load
                });
            } else {
                // If no play button, start tracking immediately
                console.log('No play button found, starting tracking immediately');
                window.coinsSystem.startGame(gameId);
            }
            
            // Stop tracking when user leaves the page
            window.addEventListener('beforeunload', () => {
                console.log('Page unloading, ending coin tracking');
                window.coinsSystem.endGame();
            });
            
            // Removed page inactivity tracking - only track game start/stop
        } else {
            console.log('No game ID found, coin tracking not initialized');
        }
    });
}