/**
 * HTML5 Game Generator
 * Generate complete HTML5 games with animations, sound effects, and celebrations
 */

import { EventEmitter } from 'events';

export interface GameAssets {
  sounds: {
    spinSound: string;
    winSound: string;
    bonusSound: string;
    backgroundMusic: string;
  };
  animations: {
    spinAnimation: string;
    winAnimation: string;
    bonusAnimation: string;
    celebrationAnimation: string;
  };
  particles: {
    confetti: string;
    sparkles: string;
    coins: string;
  };
}

export class HTML5GameGenerator extends EventEmitter {
  /**
   * Generate complete HTML5 game code
   */
  generateGameHTML(config: {
    gameName: string;
    reels: number;
    paylines: number;
    minBet: number;
    maxBet: number;
    rtp: number;
    symbols: string[];
  }): string {
    return `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${config.gameName}</title>
    <script src="https://cdn.jsdelivr.net/npm/framer-motion@10.16.4/dist/framer-motion.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }

        .game-container {
            background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
            border: 2px solid #06b6d4;
            border-radius: 20px;
            padding: 30px;
            max-width: 800px;
            width: 100%;
            box-shadow: 0 0 50px rgba(6, 182, 212, 0.3);
        }

        .game-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .game-title {
            font-size: 2.5em;
            font-weight: bold;
            background: linear-gradient(135deg, #06b6d4, #ec4899);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 10px;
        }

        .wallet-display {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
            background: rgba(15, 23, 42, 0.5);
            padding: 20px;
            border-radius: 10px;
            border: 1px solid rgba(6, 182, 212, 0.3);
        }

        .balance-item {
            text-align: center;
        }

        .balance-label {
            font-size: 0.9em;
            color: #94a3b8;
            margin-bottom: 5px;
        }

        .balance-value {
            font-size: 1.8em;
            font-weight: bold;
            color: #06b6d4;
        }

        .reels-container {
            display: grid;
            grid-template-columns: repeat(${config.reels}, 1fr);
            gap: 15px;
            margin: 30px 0;
            background: rgba(15, 23, 42, 0.5);
            padding: 20px;
            border-radius: 10px;
            border: 2px solid rgba(6, 182, 212, 0.3);
        }

        .reel {
            background: linear-gradient(180deg, #334155 0%, #1e293b 100%);
            border: 2px solid #06b6d4;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
            min-height: 120px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            gap: 10px;
            font-size: 2.5em;
        }

        .reel.spinning {
            animation: spin 0.5s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotateY(0deg); }
            100% { transform: rotateY(360deg); }
        }

        .reel.win {
            animation: pulse 0.5s ease-in-out;
            background: linear-gradient(180deg, rgba(6, 182, 212, 0.3), rgba(236, 72, 153, 0.3));
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }

        .win-display {
            text-align: center;
            padding: 20px;
            background: linear-gradient(135deg, rgba(236, 72, 153, 0.2), rgba(6, 182, 212, 0.2));
            border: 2px solid #ec4899;
            border-radius: 10px;
            margin: 20px 0;
            display: none;
        }

        .win-display.show {
            display: block;
            animation: slideIn 0.5s ease-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .win-amount {
            font-size: 2em;
            font-weight: bold;
            color: #10b981;
            margin: 10px 0;
        }

        .controls {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin: 20px 0;
        }

        .bet-control {
            background: rgba(15, 23, 42, 0.5);
            padding: 15px;
            border-radius: 8px;
            border: 1px solid rgba(6, 182, 212, 0.3);
        }

        .bet-label {
            font-size: 0.9em;
            color: #94a3b8;
            margin-bottom: 10px;
        }

        .bet-buttons {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 8px;
            margin-bottom: 10px;
        }

        .bet-btn {
            background: #06b6d4;
            border: none;
            color: white;
            padding: 8px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s;
        }

        .bet-btn:hover {
            background: #0891b2;
            transform: scale(1.05);
        }

        .bet-btn.active {
            background: #ec4899;
        }

        .bet-slider {
            width: 100%;
            cursor: pointer;
        }

        .spin-button {
            grid-column: 1 / -1;
            background: linear-gradient(135deg, #06b6d4, #ec4899);
            border: none;
            color: white;
            padding: 15px 30px;
            font-size: 1.2em;
            font-weight: bold;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .spin-button:hover:not(:disabled) {
            transform: scale(1.05);
            box-shadow: 0 0 20px rgba(6, 182, 212, 0.5);
        }

        .spin-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .spin-button.spinning {
            animation: buttonPulse 1s infinite;
        }

        @keyframes buttonPulse {
            0%, 100% { box-shadow: 0 0 20px rgba(6, 182, 212, 0.5); }
            50% { box-shadow: 0 0 40px rgba(6, 182, 212, 0.8); }
        }

        .celebration {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 3em;
            animation: celebrate 1s ease-out;
            pointer-events: none;
        }

        @keyframes celebrate {
            0% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1);
            }
            100% {
                opacity: 0;
                transform: translate(-50%, -150%) scale(0.5);
            }
        }

        .confetti {
            position: fixed;
            width: 10px;
            height: 10px;
            background: #06b6d4;
            animation: confettiFall 3s ease-in forwards;
            pointer-events: none;
        }

        @keyframes confettiFall {
            to {
                transform: translateY(100vh) rotate(360deg);
                opacity: 0;
            }
        }

        .game-info {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-top: 20px;
            font-size: 0.9em;
        }

        .info-item {
            text-align: center;
            padding: 10px;
            background: rgba(6, 182, 212, 0.1);
            border-radius: 5px;
            border: 1px solid rgba(6, 182, 212, 0.3);
        }

        .info-label {
            color: #94a3b8;
            margin-bottom: 5px;
        }

        .info-value {
            font-weight: bold;
            color: #06b6d4;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <div class="game-header">
            <div class="game-title">🎰 ${config.gameName}</div>
        </div>

        <div class="wallet-display">
            <div class="balance-item">
                <div class="balance-label">Sweeps Coins</div>
                <div class="balance-value" id="scBalance">0.00</div>
            </div>
            <div class="balance-item">
                <div class="balance-label">Total Won</div>
                <div class="balance-value" id="totalWon">0.00</div>
            </div>
        </div>

        <div class="reels-container" id="reelsContainer"></div>

        <div class="win-display" id="winDisplay">
            <div>You Won!</div>
            <div class="win-amount" id="winAmount">0.00 SC</div>
        </div>

        <div class="controls">
            <div class="bet-control">
                <div class="bet-label">Bet Amount (SC)</div>
                <div class="bet-buttons">
                    <button class="bet-btn" onclick="setBet(0.1)">0.1</button>
                    <button class="bet-btn" onclick="setBet(0.5)">0.5</button>
                    <button class="bet-btn" onclick="setBet(1)">1</button>
                    <button class="bet-btn" onclick="setBet(5)">5</button>
                    <button class="bet-btn" onclick="setBet(10)">10</button>
                    <button class="bet-btn" onclick="setBet(50)">50</button>
                </div>
                <input type="range" class="bet-slider" id="betSlider" min="${config.minBet}" max="${config.maxBet}" step="0.1" value="1" oninput="updateBetDisplay()">
                <div class="bet-label" id="betDisplay">Current: 1.00 SC</div>
            </div>
        </div>

        <button class="spin-button" id="spinButton" onclick="spin()">SPIN</button>

        <div class="game-info">
            <div class="info-item">
                <div class="info-label">RTP</div>
                <div class="info-value">${config.rtp}%</div>
            </div>
            <div class="info-item">
                <div class="info-label">Paylines</div>
                <div class="info-value">${config.paylines}</div>
            </div>
            <div class="info-item">
                <div class="info-label">Max Bet</div>
                <div class="info-value">${config.maxBet} SC</div>
            </div>
        </div>
    </div>

    <script>
        const symbols = ${JSON.stringify(config.symbols)};
        let currentBet = 1;
        let walletBalance = 100; // Will be loaded from backend
        let totalWon = 0;
        let isSpinning = false;

        // Initialize game
        function initGame() {
            createReels();
            loadWalletBalance();
            updateDisplay();
        }

        // Create reel elements
        function createReels() {
            const container = document.getElementById('reelsContainer');
            for (let i = 0; i < ${config.reels}; i++) {
                const reel = document.createElement('div');
                reel.className = 'reel';
                reel.id = 'reel-' + i;
                reel.textContent = symbols[Math.floor(Math.random() * symbols.length)];
                container.appendChild(reel);
            }
        }

        // Load wallet balance from backend
        async function loadWalletBalance() {
            try {
                // This will be connected to tRPC wallet.getBalance
                const response = await fetch('/api/wallet/balance');
                const data = await response.json();
                walletBalance = data.sweepsCoins || 100;
                updateDisplay();
            } catch (error) {
                console.error('Failed to load wallet balance:', error);
                walletBalance = 100;
            }
        }

        // Set bet amount
        function setBet(amount) {
            currentBet = amount;
            document.getElementById('betSlider').value = amount;
            updateBetDisplay();
        }

        // Update bet display
        function updateBetDisplay() {
            currentBet = parseFloat(document.getElementById('betSlider').value);
            document.getElementById('betDisplay').textContent = 'Current: ' + currentBet.toFixed(2) + ' SC';
        }

        // Update display
        function updateDisplay() {
            document.getElementById('scBalance').textContent = walletBalance.toFixed(2);
            document.getElementById('totalWon').textContent = totalWon.toFixed(2);
        }

        // Spin reels
        async function spin() {
            if (isSpinning || walletBalance < currentBet) {
                alert('Insufficient balance');
                return;
            }

            isSpinning = true;
            document.getElementById('spinButton').disabled = true;
            document.getElementById('spinButton').classList.add('spinning');

            // Debit bet amount in real-time
            walletBalance -= currentBet;
            updateDisplay();

            // Play spin sound
            playSound('spin');

            // Spin reels
            const reels = document.querySelectorAll('.reel');
            reels.forEach((reel, index) => {
                reel.classList.add('spinning');
                setTimeout(() => {
                    reel.classList.remove('spinning');
                    reel.textContent = symbols[Math.floor(Math.random() * symbols.length)];
                }, 1000 + index * 200);
            });

            // Check for win after spin
            setTimeout(async () => {
                const winAmount = calculateWin();
                
                if (winAmount > 0) {
                    // Credit win amount in real-time
                    walletBalance += winAmount;
                    totalWon += winAmount;
                    
                    // Show win animation
                    showWinAnimation(winAmount);
                    playSound('win');
                    createCelebration();
                }

                updateDisplay();
                isSpinning = false;
                document.getElementById('spinButton').disabled = false;
                document.getElementById('spinButton').classList.remove('spinning');
            }, 1500);
        }

        // Calculate win amount
        function calculateWin() {
            const reels = document.querySelectorAll('.reel');
            const symbols = Array.from(reels).map(r => r.textContent);
            
            // Simple win logic: all reels match
            if (symbols.every(s => s === symbols[0])) {
                return currentBet * 10; // 10x multiplier
            }
            
            // Two reels match
            if (symbols[0] === symbols[1] || symbols[1] === symbols[2]) {
                return currentBet * 3; // 3x multiplier
            }
            
            return 0;
        }

        // Show win animation
        function showWinAnimation(amount) {
            const winDisplay = document.getElementById('winDisplay');
            const winAmount = document.getElementById('winAmount');
            winAmount.textContent = amount.toFixed(2) + ' SC';
            winDisplay.classList.add('show');
            
            setTimeout(() => {
                winDisplay.classList.remove('show');
            }, 2000);
        }

        // Create celebration effect
        function createCelebration() {
            for (let i = 0; i < 20; i++) {
                const confetti = document.createElement('div');
                confetti.className = 'confetti';
                confetti.style.left = Math.random() * 100 + '%';
                confetti.style.background = ['#06b6d4', '#ec4899', '#10b981', '#f59e0b'][Math.floor(Math.random() * 4)];
                document.body.appendChild(confetti);
                
                setTimeout(() => confetti.remove(), 3000);
            }
        }

        // Play sound (placeholder)
        function playSound(type) {
            // Will be connected to Web Audio API
            console.log('Playing sound:', type);
        }

        // Initialize on load
        window.addEventListener('load', initGame);
    </script>
</body>
</html>
    `;
  }

  /**
   * Generate game CSS with animations
   */
  generateGameCSS(config: { theme: 'dark' | 'light'; primaryColor: string }): string {
    return `
/* Game animations */
@keyframes spinReel {
    0% { transform: rotateY(0deg); }
    100% { transform: rotateY(360deg); }
}

@keyframes winPulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.1); }
}

@keyframes celebrationBounce {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-20px); }
}

@keyframes confettiFall {
    to {
        transform: translateY(100vh) rotate(360deg);
        opacity: 0;
    }
}

/* Theme variables */
:root {
    --primary-color: ${config.primaryColor};
    --bg-color: ${config.theme === 'dark' ? '#0f172a' : '#f8fafc'};
    --text-color: ${config.theme === 'dark' ? '#ffffff' : '#000000'};
    --border-color: ${config.theme === 'dark' ? 'rgba(6, 182, 212, 0.3)' : 'rgba(6, 182, 212, 0.5)'};
}
    `;
  }

  /**
   * Generate game JavaScript with wallet integration
   */
  generateGameJS(config: { gameId: string; walletIntegration: boolean }): string {
    return `
// Game state
const gameState = {
    isSpinning: false,
    currentBet: 1,
    walletBalance: 0,
    totalWon: 0,
    gameId: '${config.gameId}',
};

// Real-time wallet balance loading
async function loadWalletBalance() {
    try {
        const response = await fetch('/api/trpc/wallet.getBalance');
        const data = await response.json();
        gameState.walletBalance = data.sweepsCoins || 0;
        updateWalletDisplay();
    } catch (error) {
        console.error('Failed to load wallet:', error);
    }
}

// Real-time balance update
function updateWalletDisplay() {
    const balanceElement = document.getElementById('scBalance');
    if (balanceElement) {
        balanceElement.textContent = gameState.walletBalance.toFixed(2);
    }
}

// Debit bet amount in real-time
async function debitBet(amount) {
    try {
        const response = await fetch('/api/trpc/wallet.debit', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ amount, gameId: gameState.gameId }),
        });
        const data = await response.json();
        gameState.walletBalance = data.newBalance;
        updateWalletDisplay();
    } catch (error) {
        console.error('Failed to debit bet:', error);
    }
}

// Credit win amount in real-time
async function creditWin(amount) {
    try {
        const response = await fetch('/api/trpc/wallet.credit', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ amount, gameId: gameState.gameId }),
        });
        const data = await response.json();
        gameState.walletBalance = data.newBalance;
        gameState.totalWon += amount;
        updateWalletDisplay();
    } catch (error) {
        console.error('Failed to credit win:', error);
    }
}

// Initialize game
window.addEventListener('load', () => {
    loadWalletBalance();
    setInterval(loadWalletBalance, 5000); // Refresh every 5 seconds
});
    `;
  }
}

export const html5GameGenerator = new HTML5GameGenerator();
