<!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>Moto Quiz GP - IPS Kelas 6</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Black+Ops+One&family=Roboto:wght@400;700&display=swap');

        body {
            margin: 0;
            overflow: hidden;
            background-color: #374151;
            font-family: 'Roboto', sans-serif;
            touch-action: none;
            user-select: none;
        }

        #game-container {
            position: relative;
            width: 100vw;
            height: 100vh;
            background: #111;
            overflow: hidden;
        }

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

        /* UI Overlay */
        .ui-layer {
            position: absolute;
            top: 0; left: 0; width: 100%; height: 100%;
            pointer-events: none;
            z-index: 10;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        /* HUD */
        #hud {
            padding: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #fff;
            font-family: 'Black Ops One', cursive;
            font-size: 1.2rem;
            text-shadow: 2px 2px 0 #000;
        }

        #lives-display {
            color: #ef4444;
            font-size: 1.5rem;
        }

        /* Question Box */
        #question-box {
            background: rgba(0, 0, 0, 0.85);
            color: #fff;
            padding: 15px;
            margin: 0 20px;
            border-radius: 10px;
            border: 3px solid #facc15;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.5);
            transform: translateY(-150%);
            transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        #question-box.show {
            transform: translateY(10px);
        }

        .q-title {
            color: #facc15;
            font-size: 0.8rem;
            text-transform: uppercase;
            font-weight: bold;
            letter-spacing: 1px;
            margin-bottom: 5px;
        }

        .q-text {
            font-size: 1.1rem;
            font-weight: bold;
            line-height: 1.3;
        }

        /* Start / End Screens */
        .screen {
            position: absolute;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 50;
            pointer-events: auto;
            text-align: center;
            color: white;
            transition: opacity 0.3s;
        }

        .btn-race {
            background: linear-gradient(to bottom, #ef4444, #b91c1c);
            border: 4px solid #fca5a5;
            padding: 15px 50px;
            font-size: 1.5rem;
            font-family: 'Black Ops One', cursive;
            color: white;
            border-radius: 8px;
            cursor: pointer;
            box-shadow: 0 8px 0 #7f1d1d;
            transition: transform 0.1s;
            margin-top: 30px;
            text-shadow: 2px 2px 0 rgba(0,0,0,0.5);
            text-transform: uppercase;
        }

        .btn-race:active {
            transform: translateY(8px);
            box-shadow: none;
        }

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

        .hidden { 
            opacity: 0; 
            pointer-events: none; 
        }

        /* Controls Hint */
        .controls-hint {
            position: absolute;
            bottom: 20px;
            width: 100%;
            text-align: center;
            color: rgba(255,255,255,0.5);
            font-size: 0.9rem;
            animation: blink 2s infinite;
        }

        @keyframes blink { 0%, 100% { opacity: 0.5; } 50% { opacity: 1; } }

        /* Floating Text Effect */
        .feedback {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-family: 'Black Ops One', cursive;
            font-size: 2.5rem;
            text-shadow: 3px 3px 0 #000;
            pointer-events: none;
            opacity: 0;
            width: 100%;
            text-align: center;
        }

        .feedback.correct { color: #4ade80; animation: popUp 1s forwards; }
        .feedback.wrong { color: #ef4444; animation: shake 0.5s forwards; }

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

        @keyframes shake {
            0% { transform: translate(-50%, -50%) translateX(0); opacity: 1; }
            25% { transform: translate(-50%, -50%) translateX(-10px); }
            50% { transform: translate(-50%, -50%) translateX(10px); }
            75% { transform: translate(-50%, -50%) translateX(-10px); }
            100% { transform: translate(-50%, -50%) translateX(0); opacity: 0; }
        }

    </style>
</head>
<body>
<div id="game-container">
    <canvas id="gameCanvas"></canvas>

    <div class="ui-layer">
        <div id="hud">
            <div>
                <div>LAP: <span id="lap-counter">1/5</span></div>
                <div style="font-size: 0.9rem; color: #aaa;">SCORE: <span id="score-display">0</span></div>
            </div>
            <div id="lives-display">❤️❤️❤️</div>
        </div>

        <div id="question-box">
            <div class="q-title">PERTANYAAN IPS</div>
            <div id="q-text" class="q-text">Siap-siap...</div>
        </div>

        <div id="feedback-text" class="feedback"></div>

        <div class="controls-hint">
            Tap KIRI atau KANAN layar untuk berbelok
        </div>
    </div>

    <!-- Start Screen -->
    <div id="start-screen" class="screen">
        <h1 class="text-6xl text-yellow-400 mb-2 font-bold" style="font-family: 'Black Ops One'">MOTO QUIZ GP</h1>
        <p class="text-xl text-gray-300 font-bold">Edisi IPS Kelas 6</p>
        
        <div class="bg-gray-800 p-6 rounded-lg max-w-sm text-left text-sm mt-8 border border-gray-600">
            <p class="text-yellow-400 font-bold mb-2">🚦 INSTRUKSI BALAP:</p>
            <ul class="list-disc pl-5 space-y-2 text-gray-300">
                <li>Jawab pertanyaan dengan <b>menabrak Gerbang Jawaban</b> yang benar.</li>
                <li>Tap <b>Kiri</b> atau <b>Kanan</b> layar untuk menyetir motor.</li>
                <li>Kamu punya <b>3 Nyawa</b> ❤️. Hati-hati!</li>
            </ul>
        </div>
        
        <button class="btn-race" onclick="startGame()">GAS POOL!</button>
        <a href="index.php?game_id=8&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
    </div>

    <!-- End Screen -->
    <div id="end-screen" class="screen hidden">
        <h1 class="text-5xl text-white mb-4" id="end-title" style="font-family: 'Black Ops One'">FINISH LINE!</h1>
        <div class="text-6xl mb-4" id="end-icon">🏆</div>
        <p class="text-xl text-gray-300 mb-2">Score Akhir:</p>
        <div class="text-4xl text-yellow-400 font-bold mb-8" id="final-score">0</div>
        <button class="btn-race" onclick="location.reload()">BALAP LAGI</button>
        <a href="index.php?game_id=8&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
    </div>
</div>

<script>
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');

    // --- CONFIG ---
    let width, height;
    function resize() {
        width = window.innerWidth;
        height = window.innerHeight;
        canvas.width = width;
        canvas.height = height;
    }
    window.addEventListener('resize', resize);
    resize();

    // --- QUESTIONS (IPS Kelas 6) ---
    let questions = [
        {
            q: "Julukan 'Negara Gajah Putih' diberikan untuk negara...",
            correct: "Thailand",
            wrong: "Vietnam"
        },
        {
            q: "Tokoh yang menjahit bendera Merah Putih adalah...",
            correct: "Fatmawati",
            wrong: "R.A. Kartini"
        },
        {
            q: "ASEAN didirikan pada tanggal...",
            correct: "8 Agustus 1967",
            wrong: "17 Agustus 1945"
        },
        {
            q: "Kegiatan menjual barang ke luar negeri disebut...",
            correct: "Ekspor",
            wrong: "Impor"
        },
        {
            q: "Ibu kota negara Filipina adalah...",
            correct: "Manila",
            wrong: "Kuala Lumpur"
        }
    ];

    // Fetch Questions from DB
    async function fetchQuestions() {
        const urlParams = new URLSearchParams(window.location.search);
        const gameId = urlParams.get('game_id') || 8;
        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];
                        const correctAns = q.options[q.correct];
                        const wrongAns = q.options.filter((_, i) => i !== q.correct)[0] || "Salah";
                        
                        newQuestions.push({
                            q: q.q,
                            correct: correctAns,
                            wrong: wrongAns
                        });
                    });
                    
                    if (newQuestions.length > 0) {
                        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();

    // --- ASSETS (Simple Drawing) ---
    const colors = {
        grass: '#15803d',
        road: '#374151',
        line: '#ffffff',
        rumble: ['#ef4444', '#ffffff'],
        gateCorrect: 'rgba(34, 197, 94, 0.8)',
        gateWrong: 'rgba(239, 68, 68, 0.8)'
    };

    // --- GAME STATE ---
    let state = 'MENU'; // MENU, PLAY, END
    let score = 0;
    let lives = 3;
    let currentQIdx = 0;
    let speed = 0;
    
    // ADJUSTED SPEED (SUPER SLOW MODE)
    const maxSpeed = 3.5; // Sangat pelan
    const acceleration = 0.015; // Percepatan sangat halus
    
    let roadOffset = 0;
    
    // Player
    let player = {
        x: 0, 
        y: 0,
        tilt: 0
    };
    
    // Input
    let input = { left: false, right: false };

    // Gate Logic
    let gate = {
        active: false,
        leftText: "",
        rightText: "",
        correctSide: 0, // -1 for Left, 1 for Right
        hit: false
    };

    // Animation
    let shake = 0;
    let objectZ = 3000; // Distance of the gate

    // --- INPUT HANDLERS ---
    const handleStart = (e) => {
        const cx = window.innerWidth / 2;
        const x = e.touches ? e.touches[0].clientX : e.clientX;
        if (x < cx) input.left = true;
        else input.right = true;
    };
    const handleEnd = () => { input.left = false; input.right = false; };

    window.addEventListener('mousedown', handleStart);
    window.addEventListener('mouseup', handleEnd);
    window.addEventListener('touchstart', (e) => { e.preventDefault(); handleStart(e); }, {passive: false});
    window.addEventListener('touchend', handleEnd);
    
    // Keyboard support
    window.addEventListener('keydown', (e) => {
        if(e.key === 'ArrowLeft') input.left = true;
        if(e.key === 'ArrowRight') input.right = true;
    });
    window.addEventListener('keyup', (e) => {
        if(e.key === 'ArrowLeft') input.left = false;
        if(e.key === 'ArrowRight') input.right = false;
    });

    // --- GAME LOGIC ---

    function startGame() {
        document.getElementById('start-screen').classList.add('hidden');
        document.getElementById('end-screen').classList.add('hidden');
        score = 0;
        lives = 3;
        currentQIdx = 0;
        speed = 0;
        player.x = 0;
        updateLivesUI();
        
        setupQuestion(0);
        
        state = 'PLAY';
        gameLoop();
    }

    function updateLivesUI() {
        let hearts = "";
        for(let i=0; i<lives; i++) hearts += "❤️";
        document.getElementById('lives-display').innerText = hearts;
    }

    function setupQuestion(idx) {
        if (idx >= questions.length) {
            endGame(true);
            return;
        }

        const q = questions[idx];
        
        // Show Question UI
        const qBox = document.getElementById('question-box');
        document.getElementById('q-text').innerText = q.q;
        document.getElementById('lap-counter').innerText = (idx + 1) + "/" + questions.length;
        qBox.classList.add('show');

        // Setup Gate
        gate.active = true;
        objectZ = 3000; // Start far away
        gate.hit = false;

        // Randomize Answer Position
        const isLeftCorrect = Math.random() > 0.5;
        gate.correctSide = isLeftCorrect ? -1 : 1;
        
        if (isLeftCorrect) {
            gate.leftText = q.correct;
            gate.rightText = q.wrong;
        } else {
            gate.leftText = q.wrong;
            gate.rightText = q.correct;
        }
    }

    function resetGate(penalty) {
        // Called when hitting wrong gate (Retry current level)
        speed = -1.5; // Mundur pelan sekali
        shake = 15;
        gate.hit = false;
        
        if (penalty) {
            lives--;
            updateLivesUI();
            if (lives <= 0) {
                setTimeout(() => endGame(false), 500);
            } else {
                showFeedback("SALAH! -1 NYAWA", "wrong");
            }
        }
    }

    function showFeedback(text, type) {
        const el = document.getElementById('feedback-text');
        el.innerText = text;
        el.className = `feedback ${type}`;
        
        // Reset animation hack
        void el.offsetWidth;
        
        // Clear after animation
        setTimeout(() => {
            if(el.innerText === text) el.innerText = "";
        }, 1000);
    }

    function endGame(win) {
        state = 'END';
        document.getElementById('question-box').classList.remove('show');
        const endScreen = document.getElementById('end-screen');
        endScreen.classList.remove('hidden');
        
        if (win) {
            document.getElementById('end-title').innerText = "FINISH LINE!";
            document.getElementById('end-title').className = "text-5xl text-white mb-4";
            document.getElementById('end-icon').innerText = "🏆";
        } else {
            document.getElementById('end-title').innerText = "GAME OVER";
            document.getElementById('end-title').className = "text-5xl text-red-500 mb-4";
            document.getElementById('end-icon').innerText = "💀";
        }
        
        document.getElementById('final-score').innerText = score;
    }

    function updatePhysics() {
        if (state !== 'PLAY') return;
        
        // Player Steering
        if (input.left) player.x -= 0.04; // Even smoother steering
        if (input.right) player.x += 0.04;
        
        // Keep inside road
        if (player.x < -1.2) { player.x = -1.2; speed *= 0.9; }
        if (player.x > 1.2) { player.x = 1.2; speed *= 0.9; }

        // Speed Logic
        if (speed < maxSpeed) speed += acceleration;
        
        // Road Scrolling
        roadOffset += speed;
        
        // Object (Gate) Approach
        if (gate.active) {
            objectZ -= speed; // Move closer
            
            // Collision Zone
            // Changed from 100 to 400 to ensure detection before clipping
            if (objectZ < 400 && !gate.hit) {
                // Determine which lane player is in
                // Left Lane: x < 0. Right Lane: x > 0.
                let playerSide = player.x < 0 ? -1 : 1;
                
                if (playerSide === gate.correctSide) {
                    // CORRECT
                    gate.hit = true;
                    score += 100;
                    showFeedback("BENAR!", "correct");
                    document.getElementById('score-display').innerText = score;
                    
                    // Hide Question Box
                    document.getElementById('question-box').classList.remove('show');
                    
                    // Next Level setup
                    setTimeout(() => {
                        currentQIdx++;
                        objectZ = 3000; // Reset distance for next
                        setupQuestion(currentQIdx);
                    }, 1000);
                } else {
                    // WRONG
                    resetGate(true); // Bounce back with penalty
                    objectZ = 1500; // Push back gate to retry distance
                }
            }
            
            // Passed behind camera
            if (objectZ < -200) {
                 // Should be handled by collision logic
            }
        }
        
        // Shake decay
        if (shake > 0) shake *= 0.9;
        if (shake < 0.5) shake = 0;
    }

    // --- RENDERING ---
    
    function draw() {
        // Clear
        ctx.fillStyle = '#111'; // Sky
        ctx.fillRect(0, 0, width, height);
        
        // Shake Effect
        ctx.save();
        if(shake > 0) {
            const dx = (Math.random() - 0.5) * shake;
            const dy = (Math.random() - 0.5) * shake;
            ctx.translate(dx, dy);
        }

        const horizonY = height * 0.3;
        const roadWidth = width * 1.5; // Bottom width
        const roadTopW = width * 0.1; // Top width (perspective)
        
        // 1. Draw Ground/Grass
        ctx.fillStyle = colors.grass;
        ctx.fillRect(0, horizonY, width, height - horizonY);
        
        // 2. Draw Road (Trapezoid)
        ctx.beginPath();
        ctx.fillStyle = colors.road;
        ctx.moveTo(width/2 - roadTopW/2, horizonY);
        ctx.lineTo(width/2 + roadTopW/2, horizonY);
        ctx.lineTo(width/2 + roadWidth/2, height);
        ctx.lineTo(width/2 - roadWidth/2, height);
        ctx.fill();
        
        // 3. Draw Stripes (Perspective)
        ctx.fillStyle = colors.line;
        const totalStripes = 20;
        for(let i=0; i<totalStripes; i++) {
            // Perspective Math
            let z = (i / totalStripes) - (roadOffset % 100)/1000; 
            z = (z + 10) % 1; 
            let y = horizonY + (height - horizonY) * (z * z * z); 
            let w = roadTopW + (roadWidth - roadTopW) * (z * z * z);
            let stripH = 5 + 20 * (z*z); 
            
            if (y > horizonY && y < height) {
                // Center Line
                if (i % 2 === 0) {
                    ctx.fillRect(width/2 - (w * 0.02), y, w * 0.04, stripH);
                }
                // Side Rumble Strips
                ctx.fillStyle = (i % 2 === 0) ? colors.rumble[0] : colors.rumble[1];
                ctx.fillRect(width/2 - w/2 - (w*0.05), y, w*0.05, stripH); // Left
                ctx.fillRect(width/2 + w/2, y, w*0.05, stripH); // Right
                ctx.fillStyle = colors.line; 
            }
        }
        
        // 4. Draw Gate (Object)
        // Ensure gate is drawn even if close to camera (objectZ > -100) to prevent popping
        if (gate.active && objectZ > -100) {
            const maxZ = 3000;
            const normZ = 1 - (objectZ / maxZ); 
            
            if (normZ > 0) {
                const persp = normZ * normZ * normZ; 
                const gateY = horizonY + (height - horizonY) * persp;
                const gateScale = 0.1 + 0.9 * persp; 
                
                const gateW = width * 0.8 * gateScale;
                const gateH = height * 0.4 * gateScale;
                
                const cx = width / 2;
                
                // Left Gate
                const lx = cx - gateW * 0.5;
                drawSign(lx, gateY, gateW * 0.4, gateH, gate.leftText, colors.gateWrong); 
                
                // Right Gate
                const rx = cx + gateW * 0.5;
                drawSign(rx, gateY, gateW * 0.4, gateH, gate.rightText, colors.gateWrong);
            }
        }

        // 5. Draw Player (Motorbike)
        const playerScreenX = width/2 + player.x * (width * 0.5); 
        const playerScreenY = height - 120;
        
        drawBike(playerScreenX, playerScreenY, player.tilt);

        ctx.restore();
    }

    function drawSign(x, bottomY, w, h, text, colorBase) {
        ctx.save();
        ctx.translate(x, bottomY);
        
        // Pole
        ctx.fillStyle = '#555';
        ctx.fillRect(-5, -h, 10, h);
        
        // Board
        ctx.fillStyle = 'rgba(0,0,0,0.8)';
        ctx.strokeStyle = '#facc15';
        ctx.lineWidth = 3;
        const boardH = h * 0.6;
        ctx.beginPath();
        ctx.roundRect(-w/2, -h - boardH/2, w, boardH, 10);
        ctx.fill();
        ctx.stroke();
        
        // Text
        ctx.fillStyle = '#fff';
        ctx.font = `bold ${Math.max(10, w * 0.15)}px Roboto`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        const words = text.split(" ");
        if (words.length > 2) {
             ctx.fillText(words.slice(0,2).join(" "), 0, -h - boardH/2 - 10);
             ctx.fillText(words.slice(2).join(" "), 0, -h - boardH/2 + 10);
        } else {
             ctx.fillText(text, 0, -h - boardH/2);
        }

        ctx.restore();
    }

    function drawBike(x, y, tilt) {
        ctx.save();
        ctx.translate(x, y);
        ctx.rotate(tilt * 0.2); 

        // Shadow
        ctx.fillStyle = 'rgba(0,0,0,0.5)';
        ctx.beginPath();
        ctx.ellipse(0, 10, 30, 10, 0, 0, Math.PI*2);
        ctx.fill();

        // Bike Body
        ctx.fillStyle = '#ef4444'; 
        ctx.fillRect(-15, -40, 30, 40);
        
        // Rider
        ctx.fillStyle = '#3b82f6'; 
        ctx.beginPath();
        ctx.arc(0, -50, 15, 0, Math.PI*2); 
        ctx.fill();
        ctx.fillRect(-12, -45, 24, 25); 

        // Wheel
        ctx.fillStyle = '#111';
        ctx.fillRect(-10, -5, 20, 20);

        // Exhaust
        if (speed > 3) {
            ctx.fillStyle = `rgba(255, 165, 0, ${Math.random()})`;
            ctx.beginPath();
            ctx.moveTo(-5, 0);
            ctx.lineTo(0, 20 + Math.random()*20);
            ctx.lineTo(5, 0);
            ctx.fill();
        }

        ctx.restore();
    }

    function gameLoop() {
        if(state === 'PLAY') {
            updatePhysics();
            draw();
        }
        requestAnimationFrame(gameLoop);
    }
    
    // Initial draw
    ctx.fillStyle = '#111';
    ctx.fillRect(0,0,width,height);

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


