// Dash ability system - Double tap detection
import { world, system } from "@minecraft/server";

const DASH_STRENGTH = 2.5;
const DOUBLE_TAP_WINDOW = 8; // ticks untuk detect double tap
const DASH_COOLDOWN = 5; // ticks cooldown setelah dash
const MOVEMENT_THRESHOLD = 0.05;

// Map untuk track state setiap player
const playerStates = new Map();

function initPlayerState(player) {
    const name = player.name;
    if (!playerStates.has(name)) {
        playerStates.set(name, {
            forward: { lastTapTime: 0, prevMoving: false },
            backward: { lastTapTime: 0, prevMoving: false },
            left: { lastTapTime: 0, prevMoving: false },
            right: { lastTapTime: 0, prevMoving: false },
            lastDashTime: 0
        });
    }
    return playerStates.get(name);
}

function checkDoubleTap(player, state, direction, isMoving, angle, currentTick) {
    const dirState = state[direction];
    
    // Detect when movement STARTS (transition from not moving to moving)
    if (isMoving && !dirState.prevMoving) {
        const timeSinceLastTap = currentTick - dirState.lastTapTime;
        
        // Check if this is the second tap within the window
        if (timeSinceLastTap <= DOUBLE_TAP_WINDOW && dirState.lastTapTime !== 0) {
            // DOUBLE TAP DETECTED!
            // Cek apakah player memiliki tag shadowi
            if (player.hasTag("shadowi")) {
                return; // Tidak bisa dash jika memiliki tag shadowi
            }
            
            if (currentTick - state.lastDashTime >= DASH_COOLDOWN) {
                applyDash(player, angle, direction);
                state.lastDashTime = currentTick;
            }
        } else {
            // Reset tap time for new tap
            dirState.lastTapTime = currentTick;
        }
    }
    
    dirState.prevMoving = isMoving;
}

function applyDash(player, angleOffset, direction) {
    try {
        const rotation = player.getRotation();
        const yaw = (rotation.y + angleOffset) * (Math.PI / 180);
        
        const velocityX = -Math.sin(yaw) * DASH_STRENGTH;
        const velocityZ = Math.cos(yaw) * DASH_STRENGTH;
        
        // Map script events berdasarkan arah
        const scriptEventMap = {
            "forward": "no:forward5",
            "backward": "no:backward5",
            "right": "no:right5",
            "left": "no:left5"
        };
        
        // Run script event sesuai arah
        player.runCommand(`scriptevent ${scriptEventMap[direction]}`);
        
        // Play sound
        player.runCommand(`playsound items.dash @a[r=10]`);
        
        // Play animation based on direction
        if (direction === "forward") {
            player.playAnimation("animation.dash.forward");
        } else if (direction === "backward") {
            player.playAnimation("animation.dash.backward");
        } else if (direction === "right") {
            player.playAnimation("animation.dash.right");
        } else if (direction === "left") {
            player.playAnimation("animation.dash.left");
        }
        
    } catch (e) {
        world.sendMessage("Dash Error: " + String(e));
    }
}

export function initDashSystem() {
    system.runInterval(() => {
        const players = world.getAllPlayers();
        
        for (const player of players) {
            try {
                const state = initPlayerState(player);
                const velocity = player.getVelocity();
                const rotation = player.getRotation();
                
                // Use rotation.y for yaw (x is pitch, y is yaw)
                const yaw = rotation.y * (Math.PI / 180);
                
                // Forward/backward direction
                const forwardX = -Math.sin(yaw);
                const forwardZ = Math.cos(yaw);
                
                // Right/left direction (perpendicular)
                const rightX = -forwardZ;  // Perpendicular ke kanan
                const rightZ = forwardX;
                
                // Dot products for movement
                const forwardMovement = velocity.x * forwardX + velocity.z * forwardZ;
                const rightMovement = velocity.x * rightX + velocity.z * rightZ;
                
                const currentTick = system.currentTick;
                
                // Check each direction
                checkDoubleTap(player, state, "forward", forwardMovement > MOVEMENT_THRESHOLD, 0, currentTick);
                checkDoubleTap(player, state, "backward", forwardMovement < -MOVEMENT_THRESHOLD, 180, currentTick);
                checkDoubleTap(player, state, "right", rightMovement > MOVEMENT_THRESHOLD, 90, currentTick);
                checkDoubleTap(player, state, "left", rightMovement < -MOVEMENT_THRESHOLD, -90, currentTick);
                
            } catch (e) {
                world.sendMessage("Error: " + e);
            }
        }
    }, 1);
}
