<!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>Fruit Word Ninja - Zen Mode</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Bangers&family=Roboto:wght@400;700&display=swap');

        body {
            margin: 0;
            overflow: hidden;
            background-color: #3f2e26; /* Wood dark */
            font-family: 'Bangers', cursive;
            touch-action: none;
            user-select: none;
        }

        #game-container {
            position: relative;
            width: 100vw;
            height: 100vh;
            background: url('https://www.transparenttextures.com/patterns/wood-pattern.png'), radial-gradient(circle, #5d4037 0%, #3e2723 100%);
        }

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

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

        .hud {
            display: flex;
            justify-content: space-between;
            color: #fcd34d; /* Amber */
            text-shadow: 2px 2px 0 #78350f;
            font-size: 1.5rem;
        }

        /* Mission Banner */
        #mission-banner {
            position: absolute;
            top: 15%;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.6);
            padding: 10px 40px;
            border-radius: 50px;
            border: 4px solid #fcd34d;
            text-align: center;
            color: white;
            box-shadow: 0 10px 20px rgba(0,0,0,0.3);
            transition: transform 0.3s;
        }
        
        #mission-banner.pulse {
            animation: pulse 0.5s;
        }

        .mission-label {
            font-family: 'Roboto', sans-serif;
            font-size: 1rem;
            color: #fbbf24;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 2px;
        }

        .mission-target {
            font-size: 2.5rem;
            color: #fff;
            text-shadow: 3px 3px 0 #ef4444;
        }

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

        .btn-play {
            background: linear-gradient(to bottom, #84cc16, #4d7c0f);
            border: 4px solid #ecfccb;
            padding: 15px 50px;
            font-size: 2rem;
            font-family: 'Bangers', cursive;
            color: white;
            border-radius: 15px;
            cursor: pointer;
            box-shadow: 0 8px 0 #365314;
            transition: transform 0.1s;
            margin-top: 20px;
            text-shadow: 2px 2px 0 rgba(0,0,0,0.5);
        }

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

        .btn-back {
            color: #888;
            text-decoration: none;
            font-size: 14px;
            font-family: 'Roboto', sans-serif;
            margin-top: 15px;
        }
        .btn-back:hover { color: #ccc; }

        .hidden { display: none !important; }

        /* Floating Score */
        .float-score {
            position: absolute;
            font-size: 2rem;
            font-weight: bold;
            color: #fbbf24;
            pointer-events: none;
            animation: floatUp 1s forwards;
            text-shadow: 2px 2px 0 #000;
        }

        @keyframes floatUp {
            0% { transform: translateY(0) scale(1); opacity: 1; }
            100% { transform: translateY(-50px) scale(1.5); opacity: 0; }
        }
        
        @keyframes pulse {
            0% { transform: translateX(-50%) scale(1); }
            50% { transform: translateX(-50%) scale(1.1); }
            100% { transform: translateX(-50%) scale(1); }
        }
    </style>
</head>
<body>
<div id="game-container">
    <canvas id="gameCanvas"></canvas>

    <!-- HUD -->
    <div id="game-ui" class="ui-overlay hidden">
        <div class="hud">
            <div>SCORE: <span id="score-val">0</span></div>
            <div id="lives-display">❤️❤️❤️</div>
        </div>
        
        <div id="mission-banner">
            <div class="mission-label">MISSION</div>
            <div class="mission-target" id="mission-text">SLICE VERBS!</div>
        </div>
    </div>

    <!-- Start Screen -->
    <div id="start-screen" class="screen">
        <h1 class="text-6xl text-yellow-400 mb-2" style="text-shadow: 4px 4px 0 #b45309;">FRUIT WORD NINJA</h1>
        <p class="text-xl font-sans mb-8 text-gray-300 max-w-md">Mode Zen (Sangat Santai)</p>
        
        <div class="bg-white/10 p-4 rounded-lg mb-6 text-left text-sm font-sans">
            <p>🔪 <b>Cara Main:</b></p>
            <ul class="list-disc pl-5 mt-2 space-y-1">
                <li>Lihat Misi (contoh: "Potong KATA KERJA").</li>
                <li>Buah melayang <b>perlahan sekali</b>.</li>
                <li>Potong buah yang <b>BENAR</b>.</li>
                <li class="text-red-300 font-bold">AWAS: Jika jawaban BENAR jatuh, Nyawa -1!</li>
                <li>Hindari Bom! 💣</li>
            </ul>
        </div>

        <button class="btn-play" onclick="startGame()">START GAME</button>
        <a href="index.php?game_id=6&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
    </div>

    <!-- Game Over Screen -->
    <div id="end-screen" class="screen hidden">
        <h1 class="text-6xl text-red-500 mb-4" style="text-shadow: 4px 4px 0 #7f1d1d;">GAME OVER</h1>
        <div class="text-3xl mb-6">FINAL SCORE: <span id="final-score" class="text-yellow-400">0</span></div>
        <button class="btn-play" onclick="location.reload()">TRY AGAIN</button>
        <a href="index.php?game_id=6&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();

    // --- GAME DATA ---
    let rounds = [
        {
            rule: "SLICE VERBS (Kata Kerja)",
            type: "verb",
            correct: ["Run", "Eat", "Sleep", "Walk", "Play", "Swim", "Read", "Go"],
            wrong: ["Apple", "Blue", "Car", "Happy", "Cat", "House", "Slow"]
        },
        {
            rule: "SLICE NUMBERS (Angka)",
            type: "number",
            correct: ["One", "Ten", "Fifty", "Twelve", "Seven", "Zero", "Five"],
            wrong: ["Red", "Book", "Pen", "Eye", "Hand", "Dog", "Big"]
        },
        {
            rule: "SLICE ANIMALS (Hewan)",
            type: "animal",
            correct: ["Lion", "Cat", "Fish", "Bird", "Snake", "Cow", "Duck"],
            wrong: ["Table", "Chair", "Run", "Walk", "Red", "Green", "Sad"]
        },
        {
            rule: "SLICE COLORS (Warna)",
            type: "color",
            correct: ["Red", "Blue", "Green", "Pink", "Black", "White"],
            wrong: ["One", "Two", "Ear", "Nose", "Sing", "Dance", "Fast"]
        }
    ];

    // Fetch Questions from DB
    async function fetchQuestions() {
        const urlParams = new URLSearchParams(window.location.search);
        const gameId = urlParams.get('game_id') || 6;
        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 newRounds = [];
                    Object.keys(data).forEach(lvl => {
                        const q = data[lvl];
                        const correctAns = q.options[q.correct];
                        const wrongAns = q.options.filter((_, i) => i !== q.correct);
                        
                        newRounds.push({
                            rule: q.q, // The question becomes the "Rule" (e.g. "Slice the correct answer for...")
                            type: "custom",
                            correct: [correctAns], // Only one correct answer usually, but array expected
                            wrong: wrongAns
                        });
                    });
                    
                    if (newRounds.length > 0) {
                        rounds = newRounds;
                        console.log("Questions loaded from DB:", rounds);
                    }
                }
            }
        } catch (e) {
            console.error("Failed to fetch questions:", e);
        }
    }

    // Init Data
    fetchQuestions();

    const fruitColors = ["#ef4444", "#f97316", "#eab308", "#84cc16", "#3b82f6", "#a855f7"];
    
    // --- STATE ---
    let gameState = "MENU"; 
    let score = 0;
    let lives = 3;
    let currentRoundIdx = 0;
    let roundTimer = 0;
    const ROUND_DURATION = 800; 
    
    let fruits = [];
    let particles = [];
    let blade = [];
    let spawnTimer = 0;
    let spawnRate = 300; // 5 seconds per spawn (was 220)

    let isDragging = false;
    let lastPos = {x:0, y:0};

    // --- INPUT ---
    const handleStart = (x, y) => {
        isDragging = true;
        lastPos = {x, y};
        blade = [];
    };
    const handleMove = (x, y) => {
        if (!isDragging) return;
        blade.push({x, y, life: 1.0});
        checkSlice(lastPos.x, lastPos.y, x, y);
        lastPos = {x, y};
    };
    const handleEnd = () => { isDragging = false; };

    canvas.addEventListener('mousedown', e => handleStart(e.clientX, e.clientY));
    canvas.addEventListener('mousemove', e => handleMove(e.clientX, e.clientY));
    canvas.addEventListener('mouseup', handleEnd);
    
    canvas.addEventListener('touchstart', e => {
        e.preventDefault();
        handleStart(e.touches[0].clientX, e.touches[0].clientY);
    });
    canvas.addEventListener('touchmove', e => {
        e.preventDefault();
        handleMove(e.touches[0].clientX, e.touches[0].clientY);
    });
    canvas.addEventListener('touchend', handleEnd);

    // --- GAME ENGINE ---

    function startGame() {
        document.getElementById('start-screen').classList.add('hidden');
        document.getElementById('game-ui').classList.remove('hidden');
        score = 0;
        lives = 3;
        currentRoundIdx = 0;
        roundTimer = 0;
        fruits = [];
        blade = [];
        particles = [];
        spawnRate = 300; // Reset to Zen slow
        updateHUD();
        updateMissionDisplay();
        gameState = "PLAY";
        gameLoop();
    }

    function updateMissionDisplay() {
        const missionBox = document.getElementById('mission-banner');
        const text = document.getElementById('mission-text');
        text.innerText = rounds[currentRoundIdx].rule;
        missionBox.classList.remove('pulse');
        void missionBox.offsetWidth;
        missionBox.classList.add('pulse');
    }

    function spawnFruit() {
        const round = rounds[currentRoundIdx];
        
        // 50-50 Chance for Correct/Wrong
        const isCorrect = Math.random() > 0.5; 
        const list = isCorrect ? round.correct : round.wrong;
        const word = list[Math.floor(Math.random() * list.length)];
        
        const radius = 35 + Math.random() * 10;
        const x = Math.random() * (width - 100) + 50;
        const y = height + 50;
        
        // Physics - ZEN MODE (Feather light)
        const centerBias = (width/2 - x) * 0.0005; 
        const vx = (Math.random() - 0.5) * 0.5 + centerBias; // Almost perfectly vertical
        const vy = -(Math.random() * 1.0 + 3.0); // Very very soft push
        
        const isBomb = Math.random() > 0.9;
        
        fruits.push({
            x, y, vx, vy,
            radius,
            word,
            isCorrect,
            isBomb,
            color: isBomb ? '#111' : fruitColors[Math.floor(Math.random() * fruitColors.length)],
            rotation: 0,
            rotSpeed: (Math.random() - 0.5) * 0.005, // Almost still
            active: true
        });
    }

    function checkSlice(x1, y1, x2, y2) {
        for (let i = 0; i < fruits.length; i++) {
            let f = fruits[i];
            if (!f.active) continue;

            const midX = (x1 + x2) / 2;
            const midY = (y1 + y2) / 2;
            const dist = Math.hypot(f.x - midX, f.y - midY);

            if (dist < f.radius + 10) {
                sliceFruit(i, Math.atan2(y2-y1, x2-x1));
            }
        }
    }

    function sliceFruit(index, angle) {
        const f = fruits[index];
        f.active = false; 
        
        createParticles(f.x, f.y, f.color, 15);
        
        if (f.isBomb) {
            createFloatingText(f.x, f.y, "BOMB! -1 HP", "#ef4444");
            lives--;
            ctx.fillStyle = 'white';
            ctx.fillRect(0,0,width,height);
        } else if (f.isCorrect) {
            score += 10;
            createFloatingText(f.x, f.y, "+10", "#facc15");
        } else {
            score = Math.max(0, score - 5);
            createFloatingText(f.x, f.y, "SALAH! -5", "#9ca3af");
            lives--;
        }
        
        updateHUD();
        if (lives <= 0) gameOver();
    }
    
    function createFloatingText(x, y, text, color) {
        const el = document.createElement('div');
        el.className = 'float-score';
        el.innerText = text;
        el.style.left = x + 'px';
        el.style.top = y + 'px';
        el.style.color = color;
        document.getElementById('game-container').appendChild(el);
        setTimeout(() => el.remove(), 1000);
    }

    function createParticles(x, y, color, count) {
        for(let i=0; i<count; i++) {
            particles.push({
                x, y,
                vx: (Math.random() - 0.5) * 10,
                vy: (Math.random() - 0.5) * 10,
                life: 1.0,
                color: color,
                size: Math.random() * 5 + 2
            });
        }
    }

    function updateHUD() {
        document.getElementById('score-val').innerText = score;
        document.getElementById('lives-display').innerText = "❤️".repeat(Math.max(0, lives));
    }

    function gameOver() {
        gameState = "END";
        document.getElementById('game-ui').classList.add('hidden');
        document.getElementById('end-screen').classList.remove('hidden');
        document.getElementById('final-score').innerText = score;
    }

    // --- LOOP ---

    function gameLoop() {
        if (gameState !== "PLAY") return;

        ctx.clearRect(0, 0, width, height);

        // Spawn
        spawnTimer++;
        if (spawnTimer > spawnRate) {
            spawnFruit();
            spawnTimer = 0;
            // Cap speed: very strict cap, never gets fast
            if (spawnRate > 200) spawnRate -= 0.05; 
        }

        // Timer
        roundTimer++;
        if (roundTimer > ROUND_DURATION) {
            currentRoundIdx = (currentRoundIdx + 1) % rounds.length;
            updateMissionDisplay();
            roundTimer = 0;
            createFloatingText(width/2, height/2, "NEW ROUND!", "#fff");
        }

        // Blade
        if (blade.length > 0) {
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.lineWidth = 4;
            ctx.strokeStyle = '#fff';
            ctx.beginPath();
            ctx.moveTo(blade[0].x, blade[0].y);
            for(let i=1; i<blade.length; i++) ctx.lineTo(blade[i].x, blade[i].y);
            ctx.stroke();

            ctx.lineWidth = 10;
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
            ctx.stroke();
        }
        
        for(let i=blade.length-1; i>=0; i--) {
            blade[i].life -= 0.15;
            if(blade[i].life <= 0) blade.splice(i, 1);
        }

        // Fruits
        for (let i = fruits.length - 1; i >= 0; i--) {
            let f = fruits[i];
            
            f.x += f.vx;
            f.y += f.vy;
            f.vy += 0.002; // Almost ZERO gravity
            f.rotation += f.rotSpeed;

            ctx.save();
            ctx.translate(f.x, f.y);
            ctx.rotate(f.rotation);
            
            if (f.isBomb) {
                ctx.fillStyle = '#111';
                ctx.beginPath(); ctx.arc(0, 0, f.radius, 0, Math.PI*2); ctx.fill();
                ctx.fillStyle = '#fbbf24';
                ctx.fillRect(-5, -f.radius-5, 10, 10);
                ctx.fillStyle = '#ef4444';
                ctx.font = '20px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('💣', 0, 5);
            } else {
                ctx.fillStyle = f.color;
                ctx.beginPath(); ctx.arc(0, 0, f.radius, 0, Math.PI*2); ctx.fill();
                ctx.fillStyle = 'rgba(255,255,255,0.3)';
                ctx.beginPath(); ctx.arc(-10, -10, 10, 0, Math.PI*2); ctx.fill();
            }
            ctx.restore();

            ctx.save();
            ctx.translate(f.x, f.y);
            ctx.fillStyle = '#fff';
            ctx.font = 'bold 18px "Roboto"';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.shadowColor = 'black';
            ctx.shadowBlur = 4;
            ctx.fillText(f.word, 0, 0);
            ctx.shadowBlur = 0;
            ctx.restore();

            // Check OOB & PENALTY
            if (f.y > height + 100) {
                // If it was CORRECT and ACTIVE (not sliced), punish player
                if (f.active && f.isCorrect) {
                    lives--;
                    createFloatingText(f.x, height - 100, "TERLEWAT! -1", "#ef4444");
                    updateHUD();
                    if (lives <= 0) gameOver();
                }
                fruits.splice(i, 1);
            } else if (!f.active) {
                fruits.splice(i, 1);
            }
        }

        // Particles
        for (let i = particles.length - 1; i >= 0; i--) {
            let p = particles[i];
            p.x += p.vx;
            p.y += p.vy;
            p.vy += 0.5;
            p.life -= 0.03;
            
            ctx.globalAlpha = p.life;
            ctx.fillStyle = p.color;
            ctx.beginPath(); ctx.arc(p.x, p.y, p.size, 0, Math.PI*2); ctx.fill();
            ctx.globalAlpha = 1;
            
            if (p.life <= 0) particles.splice(i, 1);
        }

        requestAnimationFrame(gameLoop);
    }
</script>
</body>
</html>


