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

const LIGHT_BLOCK = "minecraft:light_block";
const DIMENSIONS = ["overworld", "nether", "the_end"];
const TICK_INTERVAL = 5;

// Silah ve eşya sabitleri
const ITEMS = {
    FIRE_GAUNTLET: "bunnystudios_rpg:fire_gauntlet",
    ICE_GAUNTLET: "bunnystudios_rpg:ice_gauntlet",
    BOULDRAX_HAMMER: "bunnystudios_rpg:bouldrax_hammer",
    ELECTRIC_PLANT_STAFF: "bunnystudios_rpg:electric_plant_staff",
    FIRE_PLANT_STAFF: "bunnystudios_rpg:fire_plant_staff",
    ELECTRIC_GAUNTLET: "bunnystudios_rpg:electric_gauntlet",
    FROST_PLANT_STAFF: "bunnystudios_rpg:frost_plant_staff",
    ICE_WOLF_SWORD: "bunnystudios_rpg:ice_wolf_sword",
    PURPLE_WOLF_SWORD: "bunnystudios_rpg:purple_wolf_sword"
};


// Fire Bloom hasar sistemi
system.runInterval(() => {
    DIMENSIONS.forEach(dimensionId => {
        const dimension = world.getDimension(dimensionId);
        const fireBloomEntities = dimension.getEntities({
            type: "bunnystudios_rpg:fire_bloom_projectile"
        });

        fireBloomEntities.forEach(fireBloom => {
            const nearbyEntities = dimension.getEntities({
                location: fireBloom.location,
                maxDistance: 4,
                minDistance: 0,
                excludeFamilies: ["inanimate"],
                excludeTypes: ["item", "xp_orb", "bunnystudios_rpg:fire_bloom_projectile"]
            });

            const ownerId = fireBloom.getDynamicProperty("owner_id");
            nearbyEntities.forEach(entity => {
                if (entity.id !== ownerId) {
                    entity.setOnFire(2, true);
                    entity.applyDamage(2);
                } else {
                    fireBloom.teleport(entity.location)
                }
            });
        });
    });
}, 1);

// Frost Bloom hasar sistemi
system.runInterval(() => {
    DIMENSIONS.forEach(dimensionId => {
        const dimension = world.getDimension(dimensionId);
        const frostBloomEntities = dimension.getEntities({
            type: "bunnystudios_rpg:frost_bloom_projectile"
        });

        frostBloomEntities.forEach(frostBloom => {
            const spawnTime = frostBloom.getDynamicProperty("spawn_time");
            const hitCount = frostBloom.getDynamicProperty("hit_count") || 0;
            const timeSinceSpawn = Date.now() - spawnTime;

            if (timeSinceSpawn >= 250 && hitCount < 9) {
                const currentHitIndex = Math.floor((timeSinceSpawn - 250) / 250);

                if (currentHitIndex >= 0 && currentHitIndex < 9 && currentHitIndex === hitCount) {
                    let positions = [];
                    if (currentHitIndex === 0) positions = [{ x: -2, z: 0 }];
                    else if (currentHitIndex === 1) positions = [{ x: -1, z: -1 }];
                    else if (currentHitIndex === 2) positions = [{ x: 0, z: -2 }];
                    else if (currentHitIndex === 3) positions = [{ x: 1, z: -1 }];
                    else if (currentHitIndex === 4) positions = [{ x: 2, z: 0 }];
                    else if (currentHitIndex === 5) positions = [{ x: 1, z: 1 }];
                    else if (currentHitIndex === 6) positions = [{ x: 0, z: 2 }];
                    else if (currentHitIndex === 7) positions = [{ x: 0, z: 1 }];
                    else if (currentHitIndex === 8) positions = [{ x: -1, z: 1 }];

                    positions.forEach(pos => {
                        const blockLoc = {
                            x: Math.floor(frostBloom.location.x + pos.x),
                            y: Math.floor(frostBloom.location.y),
                            z: Math.floor(frostBloom.location.z + pos.z)
                        };

                        const nearbyEntities = dimension.getEntities({
                            location: blockLoc,
                            maxDistance: 1,
                            minDistance: 0,
                            excludeFamilies: ["inanimate"],
                            excludeTypes: ["item", "xp_orb", "bunnystudios_rpg:frost_bloom_projectile"]
                        });

                        const ownerId = frostBloom.getDynamicProperty("owner_id");
                        nearbyEntities.forEach(entity => {
                            if (entity.id !== ownerId) {
                                entity.addEffect("slowness", 60, { amplifier: 1, showParticles: true });
                                entity.applyDamage(10, { cause: 'freezing', damagingEntity: frostBloom });
                            }
                        });
                    });

                    frostBloom.setDynamicProperty("hit_count", hitCount + 1);
                }
            }
        });
    });
}, 1);


// Silah fonksiyonları
function bouldrax_hammer(player) {
    const { location, dimension, id } = player;
    player.runCommandAsync("camerashake add @a[r=10] 0.1 1.5 positional")
    player.runCommandAsync("playsound mob.irongolem.hit @a[r=20] ~~1~")
    dimension.getEntities({
        location,
        maxDistance: 5,
        excludeFamilies: ["inanimate"],
        excludeTypes: ["item", "xp_orb"]
    }).forEach(entity => {
        if (entity.id !== id) {
            entity.applyDamage(5);
            entity.applyKnockback(0, 0, 0, 0.5);
        }
    });

    // Parçacık efektleri
    for (let i = 1; i <= 5; i++) {
        if (i === 4) continue; // 4 numaralı parçacık yok
        dimension.spawnParticle(`bunnystudios_rpg:bouldrax_taunt_${i}`, location);
    }
}

function electric_plant_staff(player) {
    const { location, dimension, id } = player;
    player.runCommandAsync("playsound mob.wither.shoot @a[r=20] ~~1~ 0.5 0.5")

    dimension.getEntities({
        location,
        maxDistance: 10,
        excludeFamilies: ["inanimate"],
        excludeTypes: ["item", "xp_orb"]
    }).forEach(entity => {
        if (entity.id !== id) {
            dimension.spawnParticle("bunnystudios_rpg:frost_cube_spell_2_1", entity.location);
            entity.applyDamage(5);
            entity.applyKnockback(0, 0, 0, 0.25);
        }
    });
}

function fire_plant_staff(player) {
    const fireBloom = player.dimension.spawnEntity("bunnystudios_rpg:fire_bloom_projectile", player.location);
    fireBloom.setDynamicProperty("owner_id", player.id);
    player.runCommandAsync("playsound random.fizz @a[r=20] ~~1~")
    system.runTimeout(() => {
        player.runCommandAsync("playsound random.fizz @a[r=20] ~~1~")
        system.runTimeout(() => {
            player.runCommandAsync("playsound random.fizz @a[r=20] ~~1~")
            system.runTimeout(() => {
                player.runCommandAsync("playsound random.fizz @a[r=20] ~~1~")
                system.runTimeout(() => {
                    player.runCommandAsync("playsound random.fizz @a[r=20] ~~1~")
                    system.runTimeout(() => {
                        player.runCommandAsync("playsound random.fizz @a[r=20] ~~1~")
                        system.runTimeout(() => {
                            player.runCommandAsync("playsound random.fizz @a[r=20] ~~1~")
                        }, 30)
                    }, 30)
                }, 30)
            }, 30)
        }, 30)
    }, 30)
}

function frost_plant_staff(player) {
    const frostBloom = player.dimension.spawnEntity("bunnystudios_rpg:frost_bloom_projectile", player.location);
    frostBloom.setDynamicProperty("owner_id", player.id);
    frostBloom.setDynamicProperty("spawn_time", Date.now());
    frostBloom.setDynamicProperty("hit_count", 0);
    player.runCommandAsync("playsound mob.evocation_illager.cast_spell @a[r=20] ~~1~")
}

function electric_gauntlet(player) {
    const rotation = player.getRotation();
    const location = player.location;
    player.runCommandAsync("playsound mob.shulker.shoot @a[r=20] ~~1~")
    player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 run summon bunnystudios_rpg:electro_cube_projectile ^^^5 facing ^^^10`);
    system.runTimeout(() => {
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^5 run damage @e[family=!inanimate,name=!${player.nameTag},r=4] 5`);
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^5 run particle bunnystudios_rpg:electro_cube_attack_1_1`);
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^5 run particle bunnystudios_rpg:electro_cube_attack_1_2`);
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^5 run particle bunnystudios_rpg:electro_cube_attack_1_3`);
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^5 run particle bunnystudios_rpg:electro_cube_attack_1_4`);
    }, 40);
}

function ice_wolf_sword(player) {
    const rotation = player.getRotation();
    const location = player.location;
    player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 run summon bunnystudios_rpg:twin_wolf_projectile ^^0.2^1 facing @s`);
    player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^1 run damage @e[family=!inanimate,name=!${player.nameTag},r=2] 5`);

    system.runTimeout(() => {
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^2 run damage @e[family=!inanimate,name=!${player.nameTag},r=2] 5`);
        player.runCommandAsync("playsound random.glass @a[r=10] ~ ~ ~ 1 0.5")
    }, 3);

    system.runTimeout(() => {
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^3 run damage @e[family=!inanimate,name=!${player.nameTag},r=2] 5`);
        player.runCommandAsync("playsound random.glass @a[r=10] ~ ~ ~ 1 0.5")
    }, 6);

    system.runTimeout(() => {
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^4 run damage @e[family=!inanimate,name=!${player.nameTag},r=2] 5`);
        player.runCommandAsync("playsound random.glass @a[r=10] ~ ~ ~ 1 0.5")
    }, 9);
    system.runTimeout(() => {
        player.runCommandAsync(`execute positioned ${location.x} ${location.y} ${location.z} rotated ${rotation.y} 0 positioned ^^^6 run damage @e[family=!inanimate,name=!${player.nameTag},r=2] 5`);
        player.runCommandAsync("playsound random.glass @a[r=10] ~ ~ ~ 1 0.5")
    }, 12);
}

function purple_wolf_sword(player) {
    const dir = player.getViewDirection();
    player.applyKnockback(dir.x, dir.z, 5, 0.4);
    player.runCommandAsync("playsound item.trident.throw @a[r=20] ~~1~")
    for (let time = 0; time < 16; time++) {
        system.runTimeout(() => {
            player.dimension.runCommandAsync(
                `damage @e[r=2,name=!${player.nameTag},x=${player.location.x},y=${player.location.y},z=${player.location.z}] 5 entity_attack entity @a[name=${player.nameTag}]`
            );
        }, time);

    }
}

// Işık bloğu yönetimi
function placeLightBlock(location) {
    const { x, y, z } = location;
    world.getDimension("overworld").runCommandAsync(
        `setblock ${Math.floor(x)} ${Math.floor(y)} ${Math.floor(z)} light_block ["block_light_level"=15] keep`
    ).catch(console.error);
}

function removeLightBlock(location) {
    const { x, y, z } = location;
    world.getDimension("overworld").runCommandAsync(
        `setblock ${Math.floor(x)} ${Math.floor(y)} ${Math.floor(z)} air`
    ).catch(console.error);
}

// Konum yönetimi
function setPreviousLocation(player, location) {
    player.setDynamicProperty("previous_location", JSON.stringify(location));
}

function getPreviousLocation(player) {
    const locationStr = player.getDynamicProperty("previous_location");
    return locationStr ? JSON.parse(locationStr) : null;
}

function areLocationsEqual(loc1, loc2) {
    return ["x", "y", "z"].every(coord =>
        Math.floor(loc1[coord]) === Math.floor(loc2[coord])
    );
}

function fire_gauntlet(player) {
    const playerLocation = player.location;
    const block = player.dimension.getBlock({
        x: Math.floor(playerLocation.x),
        y: Math.floor(playerLocation.y),
        z: Math.floor(playerLocation.z)
    });

    // Su veya lav bloğunda ise çalışmasın
    if (block?.typeId === "minecraft:water" || block?.typeId === "minecraft:lava") {
        return;
    }

    const previousLocation = getPreviousLocation(player);

    if (!previousLocation || !areLocationsEqual(previousLocation, playerLocation)) {
        if (previousLocation) removeLightBlock(previousLocation);
        removeLightBlock(playerLocation);
        placeLightBlock(playerLocation);
        setPreviousLocation(player, playerLocation);
    }

    ["fire_resistance", "strength"].forEach(effect => {
        player.addEffect(effect, 40, { amplifier: 0, showParticles: false });
    });
}

// Ana döngüler ve event dinleyiciler
system.runInterval(() => {
    world.getAllPlayers().forEach(player => {
        const holdItem = player.getComponent('equippable').getEquipment('Mainhand');
        if (!holdItem?.typeId) return;
        if (holdItem.typeId === ITEMS.FIRE_GAUNTLET) {
            fire_gauntlet(player);
        } else {
            const previousLocation = getPreviousLocation(player);
            if (previousLocation) removeLightBlock(previousLocation);
        }
    });
}, TICK_INTERVAL);

world.afterEvents.entityHitEntity.subscribe(({ damagingEntity: player, hitEntity: target }) => {
    if (player.typeId !== "minecraft:player") return;
    const holdItem = player.getComponent('equippable').getEquipment('Mainhand');
    if (holdItem?.typeId === ITEMS.ICE_GAUNTLET) {
        target.addEffect("slowness", 60, { amplifier: 1, showParticles: true });
        player.runCommandAsync("playsound random.glass @a[r=20] ~~1~")
    }
});

world.afterEvents.itemStartUse.subscribe(({ source: player, itemStack: item }) => {
    const weaponFunctions = {
        [ITEMS.BOULDRAX_HAMMER]: bouldrax_hammer,
        [ITEMS.ELECTRIC_PLANT_STAFF]: electric_plant_staff,
        [ITEMS.FIRE_PLANT_STAFF]: fire_plant_staff,
        [ITEMS.ELECTRIC_GAUNTLET]: electric_gauntlet,
        [ITEMS.FROST_PLANT_STAFF]: frost_plant_staff,
        [ITEMS.ICE_WOLF_SWORD]: ice_wolf_sword,
        [ITEMS.PURPLE_WOLF_SWORD]: purple_wolf_sword
    };


    const weaponFunction = weaponFunctions[item.typeId];
    if (weaponFunction) weaponFunction(player);


});




world.afterEvents.playerLeave.subscribe(({ player }) => {
    const previousLocation = getPreviousLocation(player);
    if (previousLocation) removeLightBlock(previousLocation);
});

// Buz yürüme sistemi
system.runInterval(() => {
    world.getAllPlayers().forEach(player => {
        const hasIceGauntlet = player.getComponent("equippable").getEquipment("Mainhand")?.typeId === ITEMS.ICE_GAUNTLET;
        if (!hasIceGauntlet) return;

        const { x: playerX, y: playerY, z: playerZ } = player.location;
        const dimension = world.getDimension("overworld");
        const radius = 5;

        for (let x = -radius; x <= radius; x++) {
            for (let z = -radius; z <= radius; z++) {
                if (Math.sqrt(x * x + z * z) > radius) continue;

                const block = dimension.getBlock({
                    x: Math.floor(playerX + x),
                    y: Math.floor(playerY - 1),
                    z: Math.floor(playerZ + z)
                });

                const blockAbove = dimension.getBlock({
                    x: Math.floor(playerX + x),
                    y: Math.floor(playerY),
                    z: Math.floor(playerZ + z)
                });

                if ((block?.typeId === "minecraft:water" || block?.typeId === "minecraft:frosted_ice") &&
                    blockAbove?.typeId !== "minecraft:water") {
                    block.setType("minecraft:frosted_ice");
                }
            }
        }
    });
}, 1);
