<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Flappy English: Sky Adventure</title>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600&display=swap" rel="stylesheet">
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #333;
            overflow: hidden;
            font-family: 'Fredoka', sans-serif;
            touch-action: none; /* Prevent scroll on mobile */
        }

        #game-container {
            position: relative;
            width: 100vw;
            height: 100vh;
            background: linear-gradient(to bottom, #4ec0ca, #ececec);
            overflow: hidden;
        }

        canvas {
            display: block;
            width: 100%;
            height: 100%;
        }

        /* UI Overlays */
        .overlay {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: white;
            z-index: 10;
            width: 90%;
            max-width: 400px;
        }

        .hidden { display: none !important; }

        /* Start & Game Over Screen */
        .card {
            background: white;
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 10px 0 #dcdcdc;
            color: #555;
            border: 4px solid #555;
        }

        h1 { margin: 0 0 10px; color: #f48c28; font-size: 32px; -webkit-text-stroke: 1px #fff; }
        p { font-size: 18px; margin-bottom: 20px; }

        .btn {
            background: #89ce10;
            border: none;
            padding: 15px 40px;
            font-size: 20px;
            color: white;
            border-radius: 10px;
            cursor: pointer;
            font-family: inherit;
            box-shadow: 0 5px 0 #6ba30d;
            transition: transform 0.1s;
        }
        .btn:active { transform: translateY(5px); box-shadow: none; }

        .btn-back {
            color: #888;
            text-decoration: none;
            font-size: 14px;
            display: inline-block;
            margin-top: 15px;
        }
        .btn-back:hover { color: #555; }

        /* Quiz Modal */
        #quiz-modal {
            background: rgba(0,0,0,0.8);
            width: 100%;
            height: 100%;
            z-index: 20;
            display: flex; /* Flex to center */
            justify-content: center;
            align-items: center;
            top: 0; left: 0; transform: none; /* Override centered overlay */
        }

        .quiz-box {
            background: #fff;
            padding: 20px;
            border-radius: 15px;
            width: 90%;
            max-width: 350px;
            text-align: center;
            border: 4px solid #f48c28;
            box-shadow: 0 0 30px rgba(0,0,0,0.5);
        }

        .quiz-question {
            font-size: 22px;
            color: #333;
            margin-bottom: 20px;
            font-weight: 600;
        }

        .quiz-opt {
            display: block;
            width: 100%;
            padding: 12px;
            margin: 8px 0;
            background: #f0f0f0;
            border: 2px solid #ccc;
            border-radius: 8px;
            font-size: 18px;
            cursor: pointer;
            color: #333;
            transition: 0.2s;
        }
        .quiz-opt:hover { background: #e0e0e0; }

        /* HUD */
        #score-display {
            position: absolute;
            top: 20px;
            left: 0;
            width: 100%;
            text-align: center;
            font-size: 50px;
            font-weight: bold;
            color: white;
            text-shadow: 2px 2px 0 #000;
            pointer-events: none;
            z-index: 5;
        }
        
        #progress-display {
            position: absolute;
            top: 80px;
            left: 0;
            width: 100%;
            text-align: center;
            font-size: 16px;
            color: #fff;
            text-shadow: 1px 1px 0 #000;
            z-index: 5;
        }

        #mobile-tap-area {
            position: absolute;
            top: 0; left: 0; width: 100%; height: 100%;
            z-index: 1; /* Below UI */
        }
    </style>
</head>
<body>
<div id="game-container">
    <canvas id="gameCanvas"></canvas>
    
    <div id="score-display">0</div>
    <div id="progress-display">Soal: 0/5</div>
    
    <div id="mobile-tap-area"></div>

    <div id="start-screen" class="overlay">
        <div class="card">
            <h1>FLAPPY ENGLISH</h1>
            <p>Ketuk Layar / Spasi untuk terbang.<br>Jawab 5 soal Bahasa Inggris untuk menang!</p>
            <button class="btn" onclick="startGame()">START GAME</button>
            <a href="index.php?game_id=4&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
        </div>
    </div>

    <div id="game-over-screen" class="overlay hidden">
        <div class="card">
            <h1 id="go-title">GAME OVER</h1>
            <p id="go-msg">Burung jatuh!</p>
            <div style="font-size: 40px; font-weight:bold; margin-bottom:20px;" id="final-score">0</div>
            <button class="btn" onclick="resetGame()">TRY AGAIN</button>
            <a href="index.php?game_id=4&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
        </div>
    </div>

    <div id="quiz-modal" class="overlay hidden">
        <div class="quiz-box">
            <p style="color:#f48c28; font-weight:bold; margin:0;">QUIZ TIME!</p>
            <div class="quiz-question" id="q-text">Loading...</div>
            <div id="q-options"></div>
        </div>
    </div>
</div>

<script>
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    
    // Game Variables
    let frames = 0;
    let score = 0;
    let gamesSpeed = 4; // Start speed (increased slightly)
    let isRunning = false;
    let isPaused = false;
    let quizCount = 0;
    const TOTAL_QUESTIONS = 5;
    const PIPE_INTERVAL = 3; // Trigger quiz every 3 pipes passed

    // Audio placeholders (optional)
    const flapSound = new Audio(); // Add src if you have sound
    const scoreSound = new Audio();

    // Resize Canvas
    function resize() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }
    resize();
    window.addEventListener('resize', resize);

    // --- GAME OBJECTS ---
    
    const bird = {
        x: 50,
        y: 150,
        w: 35,
        h: 25,
        radius: 12,
        velocity: 0,
        gravity: 0.25,
        jump: 5.5, // slightly snappier jump
        
        draw: function() {
            ctx.fillStyle = "#f48c28";
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
            ctx.fill();
            // Eye
            ctx.fillStyle = "white";
            ctx.beginPath();
            ctx.arc(this.x+6, this.y-6, 5, 0, Math.PI*2);
            ctx.fill();
            ctx.fillStyle = "black";
            ctx.beginPath();
            ctx.arc(this.x+8, this.y-6, 2, 0, Math.PI*2);
            ctx.fill();
            // Wing
            ctx.fillStyle = "#fff";
            ctx.beginPath();
            ctx.ellipse(this.x-5, this.y+5, 8, 5, 0, 0, Math.PI*2);
            ctx.fill();
        },
        
        update: function() {
            if(isPaused) return;
            this.velocity += this.gravity;
            this.y += this.velocity;
            
            // Floor Collision
            if(this.y + this.radius >= canvas.height - 20) { // 20 is ground height
                gameOver("Kamu jatuh ke tanah!");
            }
            // Ceiling Collision
            if(this.y - this.radius <= 0) {
                this.y = this.radius;
                this.velocity = 0;
            }
        },
        
        flap: function() {
            if(isPaused) return;
            this.velocity = -this.jump;
        }
    };

    const pipes = {
        position: [],
        w: 65, // Pipe width
        h: 150, // Min pipe height (gap logic handles the rest)
        gap: 170, // Gap between top and bottom pipe
        dx: 4, // Moving speed
        
        draw: function() {
            for(let i=0; i<this.position.length; i++){
                let p = this.position[i];
                let topY = p.y;
                let bottomY = p.y + this.h + this.gap;
                
                ctx.fillStyle = "#73bf2e"; // Light green
                ctx.strokeStyle = "#558c22"; // Dark green border
                ctx.lineWidth = 3;

                // Top Pipe
                ctx.fillRect(p.x, 0, this.w, topY);
                ctx.strokeRect(p.x, 0, this.w, topY);
                // Cap Top
                ctx.fillRect(p.x - 5, topY - 20, this.w + 10, 20);
                ctx.strokeRect(p.x - 5, topY - 20, this.w + 10, 20);
                
                // Bottom Pipe
                ctx.fillRect(p.x, topY + this.gap, this.w, canvas.height - (topY + this.gap));
                ctx.strokeRect(p.x, topY + this.gap, this.w, canvas.height - (topY + this.gap));
                // Cap Bottom
                ctx.fillRect(p.x - 5, topY + this.gap, this.w + 10, 20);
                ctx.strokeRect(p.x - 5, topY + this.gap, this.w + 10, 20);
            }
        },
        
        update: function() {
            if(isPaused) return;

            // Add new pipe every 100 frames (roughly)
            if(frames % 120 === 0) {
                // Random Y position for gap
                // Max Y = canvas.height - ground - gap - min_pipe_bot
                // Min Y = min_pipe_top
                let maxY = canvas.height - 150 - this.gap;
                let minY = 50; 
                let randomY = Math.floor(Math.random() * (maxY - minY + 1) + minY);
                
                this.position.push({
                    x: canvas.width,
                    y: randomY,
                    passed: false
                });
            }
            
            for(let i=0; i<this.position.length; i++){
                let p = this.position[i];
                p.x -= this.dx;
                
                // Collision Detection
                // Horizontal check
                if(bird.x + bird.radius > p.x && bird.x - bird.radius < p.x + this.w) {
                    // Vertical check (Hit top pipe OR Hit bottom pipe)
                    if((bird.y - bird.radius < p.y) || (bird.y + bird.radius > p.y + this.gap)) {
                        gameOver("Menabrak Pipa!");
                    }
                }

                // Score & Quiz Logic
                if(p.x + this.w < bird.x && !p.passed) {
                    score++;
                    p.passed = true;
                    document.getElementById('score-display').innerText = score;
                    
                    // Trigger quiz every N pipes
                    if(score % PIPE_INTERVAL === 0 && quizCount < TOTAL_QUESTIONS) {
                        triggerQuiz();
                    }
                }
                
                // Remove off-screen pipes
                if(p.x + this.w <= 0) {
                    this.position.shift();
                    scoreSound.play().catch(()=>{});
                }
            }
        },
        
        reset: function() {
            this.position = [];
        }
    };

    const background = {
        draw: function() {
            ctx.fillStyle = "#ded895";
            ctx.fillRect(0, canvas.height - 20, canvas.width, 20); // Ground
            
            // Grass
            ctx.fillStyle = "#73bf2e";
            ctx.fillRect(0, canvas.height - 30, canvas.width, 10);
        }
    };

    // --- QUIZ DATA ---
    let questions = [
        { q: "What is the past tense of 'Go'?", options: ["Goed", "Gone", "Went", "Going"], ans: 2 },
        { q: "Translate: 'Saya sedang makan'", options: ["I am eat", "I am eating", "I was eat", "I eating"], ans: 1 },
        { q: "Opposite of 'Big' is...", options: ["Small", "Large", "Huge", "Tall"], ans: 0 },
        { q: "Which one is a color?", options: ["Apple", "Run", "Blue", "Car"], ans: 2 },
        { q: "Sun is to Day as Moon is to...", options: ["Light", "Night", "Star", "Sky"], ans: 1 }
    ];

    // Fetch Questions from DB
    async function fetchQuestions() {
        const urlParams = new URLSearchParams(window.location.search);
        const gameId = urlParams.get('game_id') || 4;
        try {
            const res = await fetch(`questions.php?game_id=${gameId}`);
            if (res.ok) {
                const data = await res.json();
                if (data && Object.keys(data).length > 0) {
                    const newQuestions = [];
                    Object.keys(data).forEach(lvl => {
                        const q = data[lvl];
                        newQuestions.push({
                            q: q.q,
                            options: q.options,
                            ans: q.correct
                        });
                    });
                    
                    if (newQuestions.length > 0) {
                        // Repeat if needed
                        while (newQuestions.length < 5) {
                            newQuestions.push(newQuestions[newQuestions.length % newQuestions.length]);
                        }
                        questions = newQuestions;
                        console.log("Questions loaded from DB:", questions);
                    }
                }
            }
        } catch (e) {
            console.error("Failed to fetch questions:", e);
        }
    }

    // Init Data
    fetchQuestions();

    function triggerQuiz() {
        isPaused = true;
        const qIndex = quizCount;
        const qData = questions[qIndex];
        
        document.getElementById('quiz-modal').classList.remove('hidden');
        document.getElementById('q-text').innerText = `Question ${qIndex+1}/5:\n${qData.q}`;
        
        const optsContainer = document.getElementById('q-options');
        optsContainer.innerHTML = '';
        
        qData.options.forEach((opt, idx) => {
            let btn = document.createElement('button');
            btn.className = 'quiz-opt';
            btn.innerText = opt;
            btn.onclick = function() {
                checkAnswer(idx, qData.ans);
            };
            optsContainer.appendChild(btn);
        });
    }

    function checkAnswer(selected, correct) {
        if(selected === correct) {
            // Correct
            quizCount++;
            document.getElementById('progress-display').innerText = `Soal: ${quizCount}/${TOTAL_QUESTIONS}`;
            document.getElementById('quiz-modal').classList.add('hidden');
            
            if(quizCount >= TOTAL_QUESTIONS) {
                // Win Condition
                winGame();
            } else {
                // Resume Game
                // Countdown slightly before resuming could be nice, but instant is fine
                isPaused = false;
            }
        } else {
            // Wrong
            document.getElementById('quiz-modal').classList.add('hidden');
            gameOver("Jawaban Salah!");
        }
    }

    // --- GAME LOOPS ---

    function loop() {
        if(!isRunning) return;

        // Draw
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // Background logic (simple static for now)
        
        pipes.update();
        pipes.draw();
        
        background.draw();
        
        bird.update();
        bird.draw();

        if(!isPaused) {
            frames++;
        }
        
        requestAnimationFrame(loop);
    }

    function startGame() {
        document.getElementById('start-screen').classList.add('hidden');
        document.getElementById('game-over-screen').classList.add('hidden');
        resetVariables();
        isRunning = true;
        loop();
    }

    function resetVariables() {
        bird.y = 150;
        bird.velocity = 0;
        pipes.reset();
        score = 0;
        quizCount = 0;
        frames = 0;
        isPaused = false;
        document.getElementById('score-display').innerText = "0";
        document.getElementById('progress-display').innerText = "Soal: 0/5";
    }

    function gameOver(reason) {
        isRunning = false;
        document.getElementById('game-over-screen').classList.remove('hidden');
        document.getElementById('go-title').innerText = "GAME OVER";
        document.getElementById('go-title').style.color = "#d9534f"; // Red
        document.getElementById('go-msg').innerText = reason;
        document.getElementById('final-score').innerText = score;
    }
    
    function winGame() {
        isRunning = false;
        document.getElementById('game-over-screen').classList.remove('hidden');
        document.getElementById('go-title').innerText = "YOU WIN!";
        document.getElementById('go-title').style.color = "#5cb85c"; // Green
        document.getElementById('go-msg').innerText = "Selamat! Semua soal terjawab.";
        document.getElementById('final-score').innerText = score;
    }

    function resetGame() {
        startGame();
    }

    // --- INPUTS ---
    window.addEventListener('keydown', (e) => {
        if(e.code === 'Space') {
            if(isRunning && !isPaused) bird.flap();
            if(!isRunning && document.getElementById('start-screen').classList.contains('hidden') && document.getElementById('game-over-screen').classList.contains('hidden')) {
                // Prevent space from scrolling if something else focused
            } 
        }
    });

    const tapArea = document.getElementById('mobile-tap-area');
    tapArea.addEventListener('touchstart', (e) => {
        e.preventDefault();
        if(isRunning && !isPaused) bird.flap();
    });
    
    tapArea.addEventListener('mousedown', (e) => {
        if(isRunning && !isPaused) bird.flap();
    });

</script>
</body>
</html>


