<!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>English Burger Master</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600;700&display=swap');

        body {
            font-family: 'Fredoka', sans-serif;
            background-color: #fef3c7; /* Cream background */
            overflow: hidden;
            touch-action: none;
            user-select: none;
        }

        #game-screen {
            position: relative;
            width: 100vw;
            height: 100vh;
            max-width: 600px;
            margin: 0 auto;
            background: #fff;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        /* Kitchen Background */
        .kitchen-bg {
            position: absolute;
            top: 0; left: 0; width: 100%; height: 100%;
            background: linear-gradient(180deg, #fde68a 0%, #fef3c7 40%, #ffffff 40%);
            z-index: 0;
        }

        /* Counters */
        .counter-top {
            position: absolute;
            top: 40%;
            left: 0;
            width: 100%;
            height: 20px;
            background: #d97706;
            z-index: 1;
            border-bottom: 5px solid #b45309;
        }

        /* HUD */
        .hud {
            position: absolute;
            top: 10px;
            left: 10px;
            right: 10px;
            display: flex;
            justify-content: space-between;
            z-index: 10;
            font-size: 1.2rem;
            font-weight: bold;
            color: #78350f;
        }

        /* Customer Area */
        #customer-area {
            position: absolute;
            top: 10%;
            left: 0;
            width: 100%;
            height: 35%;
            display: flex;
            justify-content: center;
            align-items: flex-end;
            z-index: 2;
        }

        .customer {
            font-size: 8rem;
            transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            transform: translateY(200px); /* Hidden initially */
            filter: drop-shadow(0 10px 10px rgba(0,0,0,0.2));
        }

        .customer.active {
            transform: translateY(20px);
        }

        .customer.happy {
            animation: bounce 0.5s infinite;
        }

        .customer.angry {
            animation: shake 0.5s;
            filter: hue-rotate(90deg); /* Turn reddish/purple */
        }

        /* Speech Bubble (Order/Question) */
        #order-bubble {
            position: absolute;
            top: 50px;
            left: 50%;
            transform: translateX(-50%) scale(0);
            background: white;
            padding: 15px 25px;
            border-radius: 20px;
            border: 4px solid #3b82f6;
            max-width: 90%;
            text-align: center;
            z-index: 20;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        #order-bubble.show {
            transform: translateX(-50%) scale(1);
        }

        #order-bubble::after {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
            border-width: 10px 10px 0;
            border-style: solid;
            border-color: #3b82f6 transparent;
            display: block;
            width: 0;
        }

        .question-text {
            font-size: 1.1rem;
            color: #1e293b;
            margin-bottom: 5px;
        }

        .blank-space {
            display: inline-block;
            width: 60px;
            border-bottom: 3px solid #3b82f6;
            margin: 0 5px;
        }

        /* Preparation Area (Bottom) */
        #prep-area {
            position: absolute;
            bottom: 0;
            width: 100%;
            height: 55%;
            background: #fff;
            padding: 20px;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            align-items: center;
            z-index: 5;
            border-top: 8px solid #f3f4f6;
        }

        .plate {
            width: 120px;
            height: 10px;
            background: #e5e7eb;
            border-radius: 50%;
            margin-bottom: 20px;
            box-shadow: 0 5px 0 #d1d5db;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: flex-end;
        }

        /* Burger Stack Animation Container */
        #burger-stack {
            position: absolute;
            bottom: 5px;
            display: flex;
            flex-direction: column-reverse; /* Build up */
            align-items: center;
        }

        .ingredient-anim {
            font-size: 3rem;
            animation: dropIn 0.3s forwards;
            margin-bottom: -15px; /* Stack overlap */
        }

        /* Ingredient Buttons */
        .ingredients-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            width: 100%;
        }

        .ingredient-btn {
            background: white;
            border: 3px solid #e5e7eb;
            border-radius: 15px;
            padding: 10px;
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;
            transition: all 0.1s;
            box-shadow: 0 4px 0 #d1d5db;
        }

        .ingredient-btn:active {
            transform: translateY(4px);
            box-shadow: 0 0 0 #d1d5db;
        }

        .ingredient-btn:hover {
            border-color: #fbbf24;
            background: #fffbeb;
        }

        .ing-icon { font-size: 2.5rem; margin-bottom: 5px; }
        .ing-text { font-weight: bold; color: #4b5563; font-size: 1rem; }

        /* Screens */
        .overlay-screen {
            position: absolute;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(255, 255, 255, 0.95);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 50;
            text-align: center;
            padding: 20px;
        }
        
        .title {
            font-size: 3rem;
            color: #d97706;
            text-shadow: 2px 2px 0 #fcd34d;
            margin-bottom: 10px;
        }

        .btn-start {
            background: #f59e0b;
            color: white;
            border: none;
            padding: 15px 40px;
            font-size: 1.5rem;
            border-radius: 50px;
            font-weight: bold;
            cursor: pointer;
            box-shadow: 0 5px 0 #b45309;
            transition: transform 0.1s;
            margin-top: 20px;
        }

        .btn-start:active {
            transform: translateY(5px);
            box-shadow: 0 0 0 #b45309;
        }

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

        /* Feedback */
        #feedback {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0);
            font-size: 4rem;
            font-weight: bold;
            z-index: 30;
            pointer-events: none;
            text-shadow: 3px 3px 0 white;
        }
        
        .feedback-pop { animation: popFade 1s forwards; }

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

        @keyframes dropIn {
            0% { transform: translateY(-100px); opacity: 0; }
            100% { transform: translateY(0); opacity: 1; }
        }
        
        @keyframes bounce {
            0%, 100% { transform: translateY(20px); }
            50% { transform: translateY(0px); }
        }

        @keyframes shake {
            0% { transform: translateX(0); }
            25% { transform: translateX(-10px); }
            75% { transform: translateX(10px); }
            100% { transform: translateX(0); }
        }

    </style>
</head>
<body>
<div id="game-screen">
    <div class="kitchen-bg"></div>
    <div class="counter-top"></div>

    <!-- HUD -->
    <div class="hud">
        <div class="bg-white px-3 py-1 rounded-full shadow border-2 border-orange-200">
            💰 <span id="score">0</span>
        </div>
        <div class="bg-white px-3 py-1 rounded-full shadow border-2 border-orange-200">
            🍽️ <span id="level">1/5</span>
        </div>
    </div>

    <!-- Gameplay Area -->
    <div id="customer-area">
        <div id="customer-char" class="customer">🤠</div>
    </div>

    <div id="order-bubble">
        <h3 class="text-sm text-gray-400 font-bold mb-1">ORDER #<span id="order-num">1</span></h3>
        <p class="question-text text-xl font-bold" id="question-text">Loading...</p>
    </div>

    <div id="feedback"></div>

    <!-- Interactive Area -->
    <div id="prep-area">
        <!-- Burger Visual -->
        <div style="flex-grow: 1; display: flex; justify-content: center; position: relative; width: 100%;">
            <div id="burger-stack"></div>
            <div class="plate"></div>
        </div>

        <h4 class="mb-3 text-gray-500 font-bold">Pilih bahan yang benar:</h4>
        
        <!-- Options -->
        <div class="ingredients-grid" id="options-container">
            <!-- Buttons injected by JS -->
        </div>
    </div>

    <!-- Start Screen -->
    <div id="start-screen" class="overlay-screen">
        <div class="title">English<br>Burger Master</div>
        <div class="text-6xl mb-4">🍔</div>
        <p class="text-gray-600 mb-6 font-bold max-w-xs">Layani pelanggan dengan melengkapi kalimat bahasa Inggris mereka!</p>
        <button class="btn-start" onclick="startGame()">OPEN!</button>
        <a href="index.php?game_id=5&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
    </div>

    <!-- Game Over Screen -->
    <div id="game-over-screen" class="overlay-screen hidden" style="display: none;">
        <div class="title" id="go-title">Great Job!</div>
        <div class="text-6xl mb-4" id="go-icon">👨‍🍳</div>
        <p class="text-xl text-gray-700 mb-2 font-bold">Total Earnings:</p>
        <div class="text-4xl text-green-600 font-bold mb-8">💰 <span id="final-score">0</span></div>
        <button class="btn-start" onclick="location.reload()">Main Lagi</button>
        <a href="index.php?game_id=5&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
    </div>
</div>

<script>
    // --- DATA SOAL ---
    let questions = [
        {
            text: "My mother _____ delicious food.",
            parts: ["cook", "cooks", "cooking", "cooked"],
            correct: 1, // cooks
            icon: "🥩" // Patty
        },
        {
            text: "An elephant is _____ than a cat.",
            parts: ["big", "bigger", "biggest", "more big"],
            correct: 1, // bigger
            icon: "🧀" // Cheese
        },
        {
            text: "We go to school _____ bus.",
            parts: ["on", "in", "by", "at"],
            correct: 2, // by
            icon: "🥬" // Lettuce
        },
        {
            text: "Yesterday, I _____ football.",
            parts: ["play", "plays", "playing", "played"],
            correct: 3, // played
            icon: "🍅" // Tomato
        },
        {
            text: "_____ is your name?",
            parts: ["What", "Where", "Who", "When"],
            correct: 0, // What
            icon: "🍳" // Egg
        }
    ];

    // Fetch Questions from DB
    async function fetchQuestions() {
        const urlParams = new URLSearchParams(window.location.search);
        const gameId = urlParams.get('game_id') || 5;
        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 = [];
                    const icons = ["🥩", "🧀", "🥬", "🍅", "🍳", "🥓", "🥒"];
                    
                    Object.keys(data).forEach((lvl, idx) => {
                        const q = data[lvl];
                        newQuestions.push({
                            text: q.q,
                            parts: q.options,
                            correct: q.correct,
                            icon: icons[idx % icons.length]
                        });
                    });
                    
                    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();

    const customers = ["🤠", "👩‍🚀", "🧛‍♀️", "🕵️‍♂️", "🧙‍♂️", "👮‍♀️", "🦸‍♂️"];
    
    // --- STATE ---
    let currentLevel = 0;
    let score = 0;
    let isProcessing = false;

    // --- DOM ELEMENTS ---
    const startScreen = document.getElementById('start-screen');
    const gameOverScreen = document.getElementById('game-over-screen');
    const customerChar = document.getElementById('customer-char');
    const orderBubble = document.getElementById('order-bubble');
    const questionText = document.getElementById('question-text');
    const optionsContainer = document.getElementById('options-container');
    const burgerStack = document.getElementById('burger-stack');
    const feedback = document.getElementById('feedback');
    const scoreEl = document.getElementById('score');
    const levelEl = document.getElementById('level');

    // --- GAME ENGINE ---

    function startGame() {
        startScreen.style.display = 'none';
        score = 0;
        currentLevel = 0;
        updateHUD();
        nextLevel();
    }

    function updateHUD() {
        scoreEl.innerText = score;
        levelEl.innerText = (currentLevel + 1) + "/5";
    }

    function nextLevel() {
        if (currentLevel >= questions.length) {
            endGame(true);
            return;
        }

        isProcessing = false;
        burgerStack.innerHTML = ''; // Clear burger
        
        // 1. Reset UI
        orderBubble.classList.remove('show');
        customerChar.classList.remove('active', 'happy', 'angry', 'leaving');
        customerChar.style.filter = '';
        
        // 2. Change Customer
        customerChar.innerText = customers[currentLevel % customers.length];
        
        // 3. Customer Enters
        setTimeout(() => {
            customerChar.classList.add('active');
            
            // 4. Show Question
            setTimeout(() => {
                showQuestion(currentLevel);
            }, 600);
        }, 500);
    }

    function showQuestion(index) {
        const q = questions[index];
        questionText.innerHTML = q.text.replace('_____', '<span class="text-blue-500 border-b-2 border-blue-500">?</span>');
        document.getElementById('order-num').innerText = index + 1;
        orderBubble.classList.add('show');

        // Render Options
        optionsContainer.innerHTML = '';
        
        // Add Bottom Bun first to stack visually (base)
        const baseBun = document.createElement('div');
        baseBun.className = 'ingredient-anim';
        baseBun.innerText = '🥯';
        burgerStack.appendChild(baseBun);

        q.parts.forEach((opt, i) => {
            const btn = document.createElement('button');
            btn.className = 'ingredient-btn';
            btn.innerHTML = `
                <span class="ing-icon">${q.icon}</span>
                <span class="ing-text">${opt}</span>
            `;
            btn.onclick = () => handleAnswer(i, q.correct, q.icon);
            optionsContainer.appendChild(btn);
        });
    }

    function handleAnswer(selectedIndex, correctIndex, icon) {
        if (isProcessing) return;
        isProcessing = true;

        // 1. Add Ingredient to Burger
        const ing = document.createElement('div');
        ing.className = 'ingredient-anim';
        ing.innerText = icon;
        burgerStack.appendChild(ing); // Add to stack

        // 2. Add Top Bun
        setTimeout(() => {
            const topBun = document.createElement('div');
            topBun.className = 'ingredient-anim';
            topBun.innerText = '🥯';
            burgerStack.appendChild(topBun);
        }, 200);

        // 3. Validate
        setTimeout(() => {
            if (selectedIndex === correctIndex) {
                // CORRECT
                showFeedback("DELICIOUS!", "text-green-500");
                score += 100;
                customerChar.classList.add('happy');
                
                // Update Question Text to show answer
                const q = questions[currentLevel];
                questionText.innerHTML = q.text.replace('_____', `<span class="text-green-600">${q.parts[correctIndex]}</span>`);

                setTimeout(() => {
                    currentLevel++;
                    updateHUD();
                    nextLevel();
                }, 2000);
            } else {
                // WRONG
                showFeedback("YUCK!", "text-red-500");
                customerChar.classList.add('angry');
                
                setTimeout(() => {
                    // Try again same level? Or Game Over?
                    // Let's make it forgiving: Try again but score penalty?
                    // Or just proceed with no points.
                    // For kids, let's proceed.
                    currentLevel++;
                    updateHUD();
                    nextLevel();
                }, 2000);
            }
        }, 800);
    }

    function showFeedback(text, colorClass) {
        feedback.innerText = text;
        feedback.className = `feedback-pop ${colorClass}`;
        // Reset animation
        setTimeout(() => {
            feedback.className = '';
            feedback.innerText = '';
        }, 1500);
    }

    function endGame(win) {
        gameOverScreen.style.display = 'flex';
        document.getElementById('final-score').innerText = score;
        
        const title = document.getElementById('go-title');
        if (score >= 400) {
            title.innerText = "Master Chef!";
            title.style.color = "#d97706";
        } else {
            title.innerText = "Good Job!";
            title.style.color = "#3b82f6";
        }
    }

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


