import { system, world } from "@minecraft/server";

const BLOOM_IDENTIFIER = "bunnystudios_rpg:bloom";
const CUBE_IDENTIFIER = "bunnystudios_rpg:cube";
const BOULDRAX_IDENTIFIER = "bunnystudios_rpg:bouldrax";
const TWIN_WOLF_IDENTIFIER = "bunnystudios_rpg:twin_wolf";
const DIMENSIONS = ["overworld", "nether", "the_end"];

// Bouldrax saldırı cooldown süreleri (tick cinsinden)
const BOULDRAX_ATTACK_COOLDOWNS = {
    1: 70,  // 2.5 saniye
    2: 152, // 6.6 saniye  
    3: 120  // 5 saniye
};

// Cube saldırı cooldown süreleri (tick cinsinden)
const CUBE_ATTACK_COOLDOWNS = {
    1: 150, // 8.5 saniye (5.5 + 3)
    2: 108, // 6.4 saniye (3.4 + 3)
    3: 105, // 6.25 saniye (3.25 + 3)
    4: 140  // 8 saniye (5 + 3)
};

// Bloom saldırı cooldown süreleri (tick cinsinden)
const BLOOM_ATTACK_COOLDOWNS = {
    1: 120, // 7 saniye (5 + 2)
    2: 200, // 10.75 saniye (8.75 + 2)
    3: 100, // 5.75 saniye (3.75 + 2)
    4: 175, // 9.75 saniye (7.75 + 2)
    5: 78,  // 4.9 saniye (2.9 + 2)
    6: 165, // 9.25 saniye (7.25 + 2)
    7: 148, // 8.4 saniye (6.4 + 2)
    8: 170  // 9.5 saniye (7.5 + 2)
};

// Twin Wolf saldırı cooldown süreleri (tick cinsinden)
const TWIN_WOLF_ATTACK_COOLDOWNS = {
    1: 74,  // 2.68 saniye
    2: 178  // 7.92 saniye
};

// Bloom'u en yakın oyuncuya döndürme fonksiyonu
function rotateBloomToNearestPlayer(bloom) {
    const players = world.getAllPlayers().filter(player => player.getGameMode() === "survival" || player.getGameMode() === "adventure");

    if (players.length === 0) return { player: null, distance: Infinity };

    let nearestPlayer = players[0];
    let minDistance = Number.MAX_VALUE;

    // En yakın oyuncuyu bul
    for (const player of players) {
        if (!player?.location || !bloom?.location) continue;

        const dx = player.location.x - bloom.location.x;
        const dy = player.location.y - bloom.location.y;
        const dz = player.location.z - bloom.location.z;
        const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);

        if (distance < minDistance) {
            minDistance = distance;
            nearestPlayer = player;
        }
    }

    if (minDistance > 32) return { player: null, distance: minDistance };

    // Rotasyon hesaplamaları
    const { x: playerX, y: playerY, z: playerZ } = nearestPlayer.location;
    const { x: bloomX, y: bloomY, z: bloomZ } = bloom.location;

    const deltaX = playerX - bloomX;
    const deltaY = playerY - bloomY;
    const deltaZ = playerZ - bloomZ;
    const length = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ);

    const xRot = -90 + Math.acos(deltaY / length) / Math.PI * 180;
    const yRot = -(Math.atan2(deltaX, deltaZ)) / Math.PI * 180;

    bloom.setRotation({ x: 0, y: yRot });
    return { player: nearestPlayer, distance: minDistance };
}

// Her Bloom için ayrı saldırı kontrolü
function handleBloomAttack(bloom) {
    const { player: targetPlayer, distance } = rotateBloomToNearestPlayer(bloom);
    const currentTime = system.currentTick;
    const lastAttackTime = bloom.getDynamicProperty("lastAttackTime") || 0;
    const bloomPhase = bloom.getProperty("bunnystudios_rpg:phase");
    const isPhase = bloomPhase === 1;
    const isAttacking = bloom.getProperty("bunnystudios_rpg:attack") === 0;
    const lastAttackType = bloom.getDynamicProperty("lastAttackType") || 1;
    const canAttack = currentTime >= lastAttackTime + BLOOM_ATTACK_COOLDOWNS[lastAttackType];

    if (!targetPlayer || !isAttacking || !canAttack || isPhase) return;

    let attackType;
    if (distance <= 10) {
        // Yakın mesafe saldırıları
        if (bloomPhase === 2) {
            // Faz 2'de sadece 2 ve 4 numaralı saldırılar
            attackType = Math.random() < 0.5 ? 2 : 4;
        } else {
            // Normal fazda 1, 3 ve 5 numaralı saldırılar
            attackType = [1, 3, 5][Math.floor(Math.random() * 3)];
        }
    } else if (distance <= 16) {
        // Uzak mesafe saldırıları her zaman 7 veya 8
        attackType = Math.random() < 0.5 ? 7 : 8;
    } else if (distance <= 32) {
        // Uzak mesafe saldırıları her zaman 7 veya 8
        attackType = 8;
    }

    if (attackType) {
        bloom.runCommandAsync(`scriptevent bunnystudios_rpg:BloomAttack_${attackType}`);
        bloom.setDynamicProperty("lastAttackTime", currentTime);
        bloom.setDynamicProperty("lastAttackType", attackType);
    }
}

// Her Cube için ayrı saldırı kontrolü
function handleCubeAttack(cube) {
    const players = world.getAllPlayers().filter(player => player.getGameMode() === "survival" || player.getGameMode() === "adventure");
    if (players.length === 0) return;

    let nearestPlayer = null;
    let minDistance = Infinity;

    // En yakın oyuncuyu bul
    for (const player of players) {
        if (!player?.location || !cube?.location) continue;

        const dx = player.location.x - cube.location.x;
        const dy = player.location.y - cube.location.y;
        const dz = player.location.z - cube.location.z;
        const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);

        if (distance < minDistance) {
            minDistance = distance;
            nearestPlayer = player;
        }
    }

    if (minDistance > 12) return; // 12 blok mesafeden uzaksa saldırma

    const currentTime = system.currentTick;
    const lastAttackTime = cube.getDynamicProperty("lastAttackTime") || 0;
    const isAttacking = cube.getProperty("bunnystudios_rpg:attack") === 0;
    const lastAttackType = cube.getDynamicProperty("lastAttackType") || 1;
    const canAttack = currentTime >= lastAttackTime + CUBE_ATTACK_COOLDOWNS[lastAttackType];
    if (cube.getProperty("bunnystudios_rpg:phase") === 2) cube.triggerEvent("bunnystudios_rpg:movement_rage")

    if (!isAttacking || !canAttack) return;

    // Rastgele 1-4 arası saldırı seç
    const attackType = Math.floor(Math.random() * 4) + 1;

    cube.runCommandAsync(`scriptevent bunnystudios_rpg:CubeAttack_${attackType}`);
    cube.setDynamicProperty("lastAttackTime", currentTime);
    cube.setDynamicProperty("lastAttackType", attackType);
}

// Her Bouldrax için ayrı saldırı kontrolü
function handleBouldraxAttack(bouldrax) {
    const players = world.getAllPlayers().filter(player => player.getGameMode() === "survival" || player.getGameMode() === "adventure");
    if (players.length === 0) return;

    let nearestPlayer = null;
    let minDistance = Infinity;

    // En yakın oyuncuyu bul
    for (const player of players) {
        if (!player?.location || !bouldrax?.location) continue;

        const dx = player.location.x - bouldrax.location.x;
        const dy = player.location.y - bouldrax.location.y;
        const dz = player.location.z - bouldrax.location.z;
        const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);

        if (distance < minDistance) {
            minDistance = distance;
            nearestPlayer = player;
        }
    }

    if (!nearestPlayer) return;

    // Rotasyon hesaplamaları
    const { x: playerX, z: playerZ } = nearestPlayer.location;
    const { x: bouldraxX, z: bouldraxZ } = bouldrax.location;

    const deltaX = playerX - bouldraxX;
    const deltaZ = playerZ - bouldraxZ;

    const yRot = -(Math.atan2(deltaX, deltaZ)) / Math.PI * 180;
    bouldrax.setRotation({ x: 0, y: yRot });

    const currentTime = system.currentTick;
    const lastAttackTime = bouldrax.getDynamicProperty("lastAttackTime") || 0;
    const bouldraxPhase = bouldrax.getProperty("bunnystudios_rpg:phase");
    const isAttacking = bouldrax.getProperty("bunnystudios_rpg:attack") === 0;
    const lastAttackType = bouldrax.getDynamicProperty("lastAttackType") || 1;
    const canAttack = currentTime >= lastAttackTime + BOULDRAX_ATTACK_COOLDOWNS[lastAttackType];
    if (bouldraxPhase === 1) return;
    if (!isAttacking || !canAttack) return;

    // Mesafeye göre saldırı tipini belirle
    let attackType;
    if (minDistance <= 7) {
        const random = Math.random();
        if (random < 0.5) { // %60 şans ile attack 1
            attackType = 1;
        } else { // %40 şans ile attack 2 veya 3
            attackType = Math.random() < 0.5 ? 2 : 3;
        }
    } else {
        // 4 bloktan uzak mesafede sadece 2 veya 3 numaralı saldırı
        attackType = Math.random() < 0.5 ? 2 : 3;
    }

    bouldrax.runCommandAsync(`scriptevent bunnystudios_rpg:BouldraxAttack_${attackType}`);
    bouldrax.setDynamicProperty("lastAttackTime", currentTime);
    bouldrax.setDynamicProperty("lastAttackType", attackType);
}

// Her Twin Wolf için ayrı saldırı kontrolü
function handleTwinWolfAttack(twinWolf) {
    const players = world.getAllPlayers().filter(player => player.getGameMode() === "survival" || player.getGameMode() === "adventure");
    if (players.length === 0) return;

    let nearestPlayer = null;
    let minDistance = Infinity;

    // En yakın oyuncuyu bul
    for (const player of players) {
        if (!player?.location || !twinWolf?.location) continue;

        const dx = player.location.x - twinWolf.location.x;
        const dy = player.location.y - twinWolf.location.y;
        const dz = player.location.z - twinWolf.location.z;
        const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);

        if (distance < minDistance) {
            minDistance = distance;
            nearestPlayer = player;
        }
    }

    if (minDistance > 16) return; // 16 blok mesafeden uzaksa saldırma

    const currentTime = system.currentTick;
    const lastAttackTime = twinWolf.getDynamicProperty("lastAttackTime") || 0;
    const isAttacking = twinWolf.getProperty("bunnystudios_rpg:attack") === 0;
    const lastAttackType = twinWolf.getDynamicProperty("lastAttackType") || 1;
    const attack1Count = twinWolf.getDynamicProperty("attack1Count") || 0;
    const canAttack = currentTime >= lastAttackTime + TWIN_WOLF_ATTACK_COOLDOWNS[lastAttackType];

    if (!isAttacking || !canAttack) return;

    let attackType;
    if (attack1Count >= 3) {
        attackType = 2;
        twinWolf.runCommandAsync("effect @s slowness 8 255 true");
        twinWolf.setDynamicProperty("attack1Count", 0);
    } else {
        if (minDistance < 7) {
            attackType = 1;
            twinWolf.setDynamicProperty("attack1Count", attack1Count + 1);
        }
    }

    twinWolf.runCommandAsync(`scriptevent bunnystudios_rpg:twinWolfAttack_${attackType}`);
    twinWolf.setDynamicProperty("lastAttackTime", currentTime);
    twinWolf.setDynamicProperty("lastAttackType", attackType);
}

// Ana döngü
system.runInterval(() => {
    DIMENSIONS.forEach(dimensionId => {
        const dimension = world.getDimension(dimensionId);
        const bloomEntities = dimension.getEntities({ type: BLOOM_IDENTIFIER });
        const cubeEntities = dimension.getEntities({ type: CUBE_IDENTIFIER });
        const bouldraxEntities = dimension.getEntities({ type: BOULDRAX_IDENTIFIER });
        const twinWolfEntities = dimension.getEntities({ type: TWIN_WOLF_IDENTIFIER });

        bloomEntities.forEach(bloom => {
            system.run(() => {
                handleBloomAttack(bloom);
            });
        });

        cubeEntities.forEach(cube => {
            system.run(() => {
                handleCubeAttack(cube);
            });
        });

        bouldraxEntities.forEach(bouldrax => {
            system.run(() => {
                handleBouldraxAttack(bouldrax);
            });
        });

        twinWolfEntities.forEach(twinWolf => {
            system.run(() => {
                handleTwinWolfAttack(twinWolf);
            });
        });
    });

}, 20);
