import { system, world, Entity, Player, ItemStack } from '@minecraft/server';
// Initialize a map to store hit counts for each entity
const entityHitCounts = new Map();
const tnt4 = [
    "hp1_mtnt:arrow_tnt",
    "hp1_mtnt:diamond_tnt",
    "hp1_mtnt:digger_tnt",
    "hp1_mtnt:frozen_tnt",
    "hp1_mtnt:mini_fortress_tnt",
    "hp1_mtnt:temple_tnt",
    "hp1_mtnt:buff_tnt",
    "hp1_mtnt:creeper_tnt",
    "hp1_mtnt:ender_portal_tnt",
    "hp1_mtnt:golem_tnt",
    "hp1_mtnt:lava_tnt",
    "hp1_mtnt:nether_portal_tnt",
    "hp1_mtnt:time_tnt",
    "hp1_mtnt:weather_tnt",
    "hp1_mtnt:zombie_tnt"
];

const tnt6 = [
    "hp1_mtnt:airstrike_tnt",
    "hp1_mtnt:double_tnt",
    "hp1_mtnt:radiation_tnt",
    "hp1_mtnt:stunning_tnt",
    "hp1_mtnt:tornado_tnt",
    "hp1_mtnt:meteorite_tnt",
    "hp1_mtnt:bedrock_tnt",
    "hp1_mtnt:freeze_tnt",
    "hp1_mtnt:mob_tnt",
    "hp1_mtnt:money_tnt",
    "hp1_mtnt:poison_tnt",
    "hp1_mtnt:ore_tnt",
    "hp1_mtnt:party_tnt",
    "hp1_mtnt:smoke_tnt"
];

const tnt8 = [
    "hp1_mtnt:blaze_tnt",
    "hp1_mtnt:lightning_storm_tnt",
    "hp1_mtnt:proximity_tnt",
    "hp1_mtnt:zero_gravity_tnt",
    "hp1_mtnt:blackhole_tnt",
    "hp1_mtnt:ghostly_tnt",
    "hp1_mtnt:red_eye_tnt",
    "hp1_mtnt:supersonic_tnt"
];

const tnt10 = [
    "hp1_mtnt:mega_tnt",
    "hp1_mtnt:wither_boss_tnt",
    "hp1_mtnt:warden_demolition_tnt"
];

world.afterEvents.entityHitEntity.subscribe((res) => {
    const victim = res.hitEntity;
    const attacker = res.damagingEntity;
    attacker.runCommand('tag @e[family=tnt] add hp1_mtnt.tnt')

    // Check if the victim has the specific tag
    try {
        if (victim.hasTag("hp1_mtnt.tnt")) {
    
            // Get the current hit count for the victim or initialize it if not present
            let hitCount = entityHitCounts.get(victim.id) || 5;
    
            // Decrease the hit count
            hitCount--;
    
            // Update the hit count in the map
            entityHitCounts.set(victim.id, hitCount);
    
            // Log the current hit count
            if (hitCount > 0) {victim.runCommand('playanimation @s animation.hp1_mtnt.tnt.hit');}
            // Check if hit count reaches zero
            if (hitCount <= 0) {
                victim.runCommand('event entity @s meninggal');
            }
        }
    } catch (error) {
        
    }
});
world.afterEvents.entitySpawn.subscribe((Entity) => {
    const tnt = Entity.entity;
    // tagTntSizes(tnt);
});
world.afterEvents.entityDie.subscribe((entity) => {
    const victim = entity.deadEntity;
    // removeTntBarrier(victim);
});
world.afterEvents.itemUse.subscribe((event) => {
    const player = event.source;
    if (!event.itemStack) return;
    if (event.itemStack.typeId === `hp1_mtnt:remote`) {
        player.runCommand('event entity @e[family=tnt, r=500] remote_trigger');
    };
});
system.runInterval(() => {
    world.getDimension("overworld").runCommand(`effect @a[hasitem={item=hp1_mtnt:speed_boots, location=slot.armor.feet}] speed 3 10`);
    world.getDimension("overworld").getEntities().forEach(entity => {
        if(entity.typeId==="minecraft:villager"||entity.typeId==="minecraft:villager_v2") {
            entity.dimension.getEntities({type:"minecraft:item", maxDistance:2, location: entity.location}).forEach(items=>{
                const item = items.getComponent("item")
                if(item.itemStack.typeId==="hp1_mtnt:money") {
                    const dp = entity.getDynamicProperty('hp1_mtnt:villager_happy')
                    if(!dp) {
                        villagerHappy(entity)
                        items.remove()
                    }
                }
            })
        }
        if(entity.typeId==="hp1_mtnt:money_spawner") {
            entity.runCommand(`tp @s ~~15~`)
            entity.runCommand(`loot spawn ~~~ loot \"hp/mtnt/money\"`)
        }
        if(entity.typeId==="hp1_mtnt:proximity") {
            const dp = entity.getDynamicProperty('hp1_mtnt:proximity_start')
            if(!dp) {
                proximityEffect(entity)
            }
        }
        if(entity.typeId==="hp1_mtnt:horror_area") {
            horrorEffect(entity)
        }
        if(entity.typeId==="minecraft:item") {
            try {
                if(entity.getComponent("item").itemStack.typeId==="hp1_mtnt:money"){
                    if(entity.isOnGround && entity.getDynamicProperty("hp1_mtnt:is_on_ground")===undefined) {
                        entity.setDynamicProperty("hp1_mtnt:is_on_ground", true)
                        entity.runCommand(`playsound random.pop @a ~~~`)
                    }
                }
            } catch (error) {
                
            }
        }
        if(entity.typeId==="hp1_mtnt:obsidian_effect") {
            const dp = entity.getDynamicProperty("hp1_mtnt:initiated")
            if(!dp) {
                obsidianSummon(entity)
                entity.setDynamicProperty("hp1_mtnt:initiated", true)
            }
        }
        if(entity.typeId==="hp1_mtnt:bedrock_area") {
            const dp = entity.getDynamicProperty("hp1_mtnt:initiated")
            if(!dp) {
                explosionShaping(entity)
                //entity.setDynamicProperty("hp1_mtnt:initiated", true)
            }
        }
    });
})
function villagerHappy(entity) {
    entity.setDynamicProperty('hp1_mtnt:villager_happy', true)
    entity.runCommand(`playanimation @s animation.hp1_mtnt.villager_happy none 0.1`)
    entity.runCommand(`playsound mob.villager.yes @a ~~~`)
    entity.runCommand(`playsound hp1_mtnt.effect.chaching @a ~~~`)
    entity.runCommand(`particle hp1_mtnt:villager_happy ~~~`)
    entity.runCommand(`loot spawn ~~~ loot \"hp/mtnt/villager_happy\"`)
    const randomDelay = Math.random() * (20-5) + 5
    system.runTimeout(()=>{
        entity.setDynamicProperty('hp1_mtnt:villager_happy', false)
    }, randomDelay*20)
}
function proximityEffect(entity) {
    entity.setDynamicProperty('hp1_mtnt:proximity_start', true)
    const glitchAttack = entity.dimension.spawnEntity('hp1_mtnt:proximity_glitch', entity.location)
    system.runInterval(()=>{
        if (!glitchAttack.isValid()) return
        glitchAttack.runCommand(`spreadplayers ${entity.location.x} ${entity.location.z} 2 10 @s`);
        const block = entity.dimension.getBlock({x:glitchAttack.location.x,y:glitchAttack.location.y-2,z:glitchAttack.location.z});
        let blockId = block.typeId;
        const randHeight = Math.random(-2,2)
        glitchAttack.runCommand(`setblock ~~-2~ air`)
        glitchAttack.runCommand(`setblock ~~${randHeight}~ ${blockId}`)
    })
    const interval = system.runInterval(()=>{
        entity.dimension.getEntities({maxDistance:10, location:entity.location}).forEach(entities=>{
            const pitch = Math.random() * (1.2-0.8) + 0.8
            entities.runCommand(`spreadplayers ${entity.location.x} ${entity.location.z} 2 10 @s`)
            entities.dimension.spawnParticle("hp1_mtnt:proximity_effect", entities.location)
            entities.runCommand(`playsound hp1_mtnt.effect.hp.button @s ~~~ 1 ${pitch}`)
        })
    },0.3*20)
    system.runTimeout(()=>{
        system.clearRun(interval)
    },10*20)
}
function horrorEffect(entity) {
    const location = entity.location
    const players = entity.dimension.getPlayers({location:location,maxDistance:30}).forEach(player=>{
        const dp = player.getDynamicProperty("hp1_mtnt:jumpscare_otw")
        if(!dp||dp===undefined) {
            jumpscare(player)
        }
    })
    entity.remove()
}
function jumpscare(player) {
    player.setDynamicProperty('hp1_mtnt:jumpscare_otw', true)
    player.runCommand(`playsound hp1_mtnt.horror.ambient @s`)
    const randomDelay = Math.random() * (30-20) + 20
    system.runTimeout(()=>{
        jumpscareStart(player)
    }, randomDelay*20)
    player.addEffect('darkness', (randomDelay+5)*20, {showParticles: false})
}
function jumpscareStart(player) {
    player.setDynamicProperty('hp1_mtnt:jumpscare_otw', false)
    player.runCommand(`playsound hp1_mtnt.effect.jumpscare @s`)
    const jumpscare = player.dimension.spawnEntity('hp1_mtnt:horror_jumpscare', player.location)
    const range = 2
    const loc = {
        x:player.location.x+player.getViewDirection().x*range,
        y:player.location.y,
        z:player.location.z+player.getViewDirection().z*range
    }
    jumpscare.teleport(loc, {facingLocation:player.location})
    system.runTimeout(()=>{
        player.addEffect('slowness', 5*20, {showParticles:false, ampllifier:7})
        jumpscare.triggerEvent('hp1_mtnt:active')
        const plrFaceLoc = {
            x: jumpscare.location.x,
            y: jumpscare.location.y + 1,
            z: jumpscare.location.z
        }
        player.runCommand(`inputpermission set @s camera disabled`)
        player.runCommand(`inputpermission set @s movement disabled`)
        player.teleport(player.location, {facingLocation:plrFaceLoc})
        system.runTimeout(()=>{
            player.runCommand(`stopsound @s hp1_mtnt.horror.ambient`)
        },1*20)
        system.runTimeout(()=>{
            player.runCommand(`inputpermission set @s camera enabled`)
            player.runCommand(`inputpermission set @s movement enabled`)
            jumpscare.remove()

            const randomSecondJumpscare = Math.floor(Math.random() * (30 - 20) + 20)
            system.runTimeout(()=>{
                secondJumpscareStart(player)
            }, randomSecondJumpscare*20)
        },2*20)
    },1)
}
function secondJumpscareStart(player) {
    const jumpscare = player.dimension.spawnEntity('hp1_mtnt:horror_jumpscare', player.location)
    const range = 2
    const loc = {
        x:player.location.x+player.getViewDirection().x*range,
        y:player.location.y,
        z:player.location.z+player.getViewDirection().z*range
    }
    jumpscare.teleport(loc, {facingLocation:player.location})
    player.runCommand(`playsound hp1_mtnt.horror.jumpscare @s`)
    system.runTimeout(()=>{
        const facingLoc = {
            x: jumpscare.location.x,
            y: jumpscare.location.y + 1,
            z: jumpscare.location.z
        }
        player.addEffect('slowness', 1*20, {showParticles:false, ampllifier:7})
        player.teleport(player.location, {facingLocation:facingLoc})
        jumpscare.triggerEvent('hp1_mtnt:active2')
        system.runTimeout(()=>{
            jumpscare.remove()
        },1*20)
    }, 1)
}
function obsidianSummon(entity) {
    const radius = Math.random() * (10 - 5) + 5; // Radius acak antara 5 dan 10
    const baseLocation = entity.location; // Lokasi entitas
    const arahPenyebaran = [
        // Arah pancaran (atas, bawah, depan, belakang, kanan, kiri, dsb)
        {x: 0, y: 1, z: 0}, // Atas
        {x: 0, y: -1, z: 0}, // Bawah
        {x: 0, y: 0, z: 1}, // Depan
        {x: 0, y: 0, z: -1}, // Belakang
        {x: 1, y: 0, z: 0}, // Kanan
        {x: -1, y: 0, z: 0}, // Kiri
        {x: 0, y: 1, z: 1}, // Atas depan
        {x: 0, y: 1, z: -1}, // Atas belakang
        {x: 1, y: 1, z: 0}, // Atas kanan
        {x: -1, y: 1, z: 0}, // Atas kiri
        {x: 0, y: -1, z: 1}, // Bawah depan
        {x: 0, y: -1, z: -1}, // Bawah belakang
        {x: 1, y: -1, z: 0}, // Bawah kanan
        {x: -1, y: -1, z: 0}, // Bawah kiri
        {x: 1, y: 0, z: 1}, // Depan kanan
        {x: -1, y: 0, z: 1}, // Depan kiri
        {x: 1, y: 0, z: -1}, // Belakang kanan
        {x: -1, y: 0, z: -1}, // Belakang kiri
    ];

    // Loop untuk pancaran efek ledakan
    for (let i = 0; i < radius; i++) {
        arahPenyebaran.forEach(arah => {
            // Hitung posisi tujuan teleportasi
            const tujuanTP = {
                x: baseLocation.x + arah.x * i,
                y: baseLocation.y + arah.y * i,
                z: baseLocation.z + arah.z * i
            };

            // Teleport entitas ke posisi yang dihitung
            entity.runCommand(`tp @s ${tujuanTP.x} ${tujuanTP.y} ${tujuanTP.z}`);
            entity.runCommand(`setblock ~~~ obsidian`)
            if(!entity.dimension.getBlock(entity.location).isAir) {
                
            }
            
            // if (!entity.dimension.getBlock(tujuanTP).isAir) {
            //     entity.runCommand(`setblock ~~~ obsidian`);
            // }
        });
    }
}

function explosionShaping(entity) {
    const baseLocation = entity.location;  // Lokasi awal entitas (titik pusat ledakan)
    const radius = 10; // Radius ledakan
    const numEntities = 40; // Jumlah entitas yang akan dipindahkan (bisa disesuaikan)

    for (let i = 0; i < numEntities; i++) {
        // Membuat arah acak (x, y, z) dalam radius tertentu untuk menghasilkan pancaran
        // Pilih arah acak dalam 3D
        const angleX = Math.random() * Math.PI * 2; // Arah acak untuk sumbu X
        const angleY = Math.random() * Math.PI * 2; // Arah acak untuk sumbu Y
        const angleZ = Math.random() * Math.PI * 2; // Arah acak untuk sumbu Z

        // Menghitung posisi x, y, z dalam radius dengan menggunakan trigonometri untuk memancarkan titik-titik
        const x = baseLocation.x + radius * Math.cos(angleX) * Math.sin(angleY);
        const y = baseLocation.y + radius * Math.sin(angleX) * Math.sin(angleY);
        const z = baseLocation.z + radius * Math.cos(angleY);

        // Teleport entitas ke posisi yang dihitung
        entity.teleport({x: x, y: y, z: z});

        // Menambahkan block di lokasi tersebut untuk menciptakan efek pancaran
        entity.dimension.spawnEntity("hp1_mtnt:obsidian_effect", entity.location)
    }
    entity.remove()
}
//Interval Section
system.runInterval(()=>{
    world.getDimension("overworld").getPlayers().forEach(player=>{
        if(player.getDynamicProperty("hp1_mtnt:jumpscare_otw")) {
            player.dimension.spawnParticle("hp1_mtnt:horror_ambient2", player.location)
        }
    })
},5*20)
system.runInterval(()=>{
    world.getDimension("overworld").getPlayers().forEach(player=>{
        if(player.getDynamicProperty("hp1_mtnt:jumpscare_otw")) {
            const randomX = Math.floor(Math.random() * 9) - 4;
            const randomZ = Math.floor(Math.random() * 9) - 4;
            player.runCommand(`particle hp1_mtnt:horror_ambient1 ~${randomX}~~${randomZ}`)

            const randomDistance = Math.random() * (10-5) + 5
            const randomSpread = Math.floor(Math.random() * 3) - 1;
            const randomHeight = Math.random() * (3-0) + 0
            let randomAmbient = {
                x: player.location.x + player.getViewDirection().x * randomDistance,
                y: player.location.y + randomHeight,
                z: player.location.z + player.getViewDirection().z * randomDistance
            }
            randomAmbient.x = randomSpread + randomAmbient.x
            randomAmbient.z = randomSpread + randomAmbient.z
            player.dimension.spawnEntity("hp1_mtnt:horror_ambient", randomAmbient)
        }
    })
},3*20)

world.getDimension("overworld").getPlayers().forEach(player=>{
    player.setDynamicProperty('hp1_mtnt:jumpscare_otw', false)
})
// function tagTntSizes(entity) {
//     const tnt4 = [
//         "hp1_mtnt:arrow_tnt",
//         "hp1_mtnt:diamond_tnt",
//         "hp1_mtnt:digger_tnt",
//         "hp1_mtnt:frozen_tnt",
//         "hp1_mtnt:mini_fortress_tnt",
//         "hp1_mtnt:temple_tnt",
//         "hp1_mtnt:buff_tnt",
//         "hp1_mtnt:creeper_tnt",
//         "hp1_mtnt:ender_portal_tnt",
//         "hp1_mtnt:golem_tnt",
//         "hp1_mtnt:lava_tnt",
//         "hp1_mtnt:nether_portal_tnt",
//         "hp1_mtnt:time_tnt",
//         "hp1_mtnt:weather_tnt",
//         "hp1_mtnt:zombie_tnt"
//     ];

//     const tnt6 = [
//         "hp1_mtnt:airstrike_tnt",
//         "hp1_mtnt:double_tnt",
//         "hp1_mtnt:radiation_tnt",
//         "hp1_mtnt:stunning_tnt",
//         "hp1_mtnt:tornado_tnt",
//         "hp1_mtnt:meteorite_tnt",
//         "hp1_mtnt:bedrock_tnt",
//         "hp1_mtnt:freeze_tnt",
//         "hp1_mtnt:mob_tnt",
//         "hp1_mtnt:money_tnt",
//         "hp1_mtnt:poison_tnt",
//         "hp1_mtnt:ore_tnt",
//         "hp1_mtnt:party_tnt",
//         "hp1_mtnt:smoke_tnt"
//     ];

//     const tnt8 = [
//         "hp1_mtnt:blaze_tnt",
//         "hp1_mtnt:lightning_storm_tnt",
//         "hp1_mtnt:proximity_tnt",
//         "hp1_mtnt:zero_gravity_tnt",
//         "hp1_mtnt:blackhole_tnt",
//         "hp1_mtnt:ghostly_tnt",
//         "hp1_mtnt:red_eye_tnt",
//         "hp1_mtnt:supersonic_tnt"
//     ];

//     const tnt10 = [
//         "hp1_mtnt:mega_tnt",
//         "hp1_mtnt:wither_boss_tnt",
//         "hp1_mtnt:warden_demolition_tnt"
//     ];
    
//     for (const typeId of tnt4) {
//         if (entity.typeId === typeId) {
//             entity.runCommand('tag @s add hp1_mtnt.tnt4');
//             //entity.runCommand('say Size 4 TNT Added');
//             entity.runCommand('structure load hp_mtnt:hp1_tnt4_barrier ~-2~~-2');
//             entity.runCommand('execute @a[r=2] ~~~ tp @s ~~6~');
//         }
//     };
    
//     for (const typeId of tnt6) {
//         if (entity.typeId === typeId) {
//             entity.runCommand('tag @s add hp1_mtnt.tnt6');
//             //entity.runCommand('say Size 6 TNT Added');
//             entity.runCommand('structure load hp_mtnt:hp1_tnt6_barrier ~-3~~-3');
//             entity.runCommand('execute @a[r=3] ~~~ tp @s ~~8~');
//         }
//     };
    
//     for (const typeId of tnt8) {
//         if (entity.typeId === typeId) {
//             entity.runCommand('tag @s add hp1_mtnt.tnt8');
//             //entity.runCommand('say Size 8 TNT Added');
//             entity.runCommand('structure load hp_mtnt:hp1_tnt8_barrier ~-4~~-4');
//             entity.runCommand('execute @a[r=4] ~~~ tp @s ~~10~');
//         }
//     };
    
//     for (const typeId of tnt10) {
//         if (entity.typeId === typeId) {
//             entity.runCommand('tag @s add hp1_mtnt.tnt10');
//             //entity.runCommand('say Size 10 TNT Added');
//             entity.runCommand('structure load hp_mtnt:hp1_tnt10_barrier ~-5~~-5');
//             entity.runCommand('execute @a[r=5] ~~~ tp @s ~~12~');
//         }
//     }
// };
// function removeTntBarrier(entity) {
//     const tnt4 = [
//         "hp1_mtnt:arrow_tnt",
//         "hp1_mtnt:diamond_tnt",
//         "hp1_mtnt:digger_tnt",
//         "hp1_mtnt:frozen_tnt",
//         "hp1_mtnt:mini_fortress_tnt",
//         "hp1_mtnt:temple_tnt",
//         "hp1_mtnt:buff_tnt",
//         "hp1_mtnt:creeper_tnt",
//         "hp1_mtnt:ender_portal_tnt",
//         "hp1_mtnt:golem_tnt",
//         "hp1_mtnt:lava_tnt",
//         "hp1_mtnt:nether_portal_tnt",
//         "hp1_mtnt:time_tnt",
//         "hp1_mtnt:weather_tnt",
//         "hp1_mtnt:zombie_tnt"
//     ];

//     const tnt6 = [
//         "hp1_mtnt:airstrike_tnt",
//         "hp1_mtnt:double_tnt",
//         "hp1_mtnt:radiation_tnt",
//         "hp1_mtnt:stunning_tnt",
//         "hp1_mtnt:tornado_tnt",
//         "hp1_mtnt:meteorite_tnt",
//         "hp1_mtnt:bedrock_tnt",
//         "hp1_mtnt:freeze_tnt",
//         "hp1_mtnt:mob_tnt",
//         "hp1_mtnt:money_tnt",
//         "hp1_mtnt:poison_tnt",
//         "hp1_mtnt:ore_tnt",
//         "hp1_mtnt:party_tnt",
//         "hp1_mtnt:smoke_tnt"
//     ];

//     const tnt8 = [
//         "hp1_mtnt:blaze_tnt",
//         "hp1_mtnt:lightning_storm_tnt",
//         "hp1_mtnt:proximity_tnt",
//         "hp1_mtnt:zero_gravity_tnt",
//         "hp1_mtnt:blackhole_tnt",
//         "hp1_mtnt:ghostly_tnt",
//         "hp1_mtnt:red_eye_tnt",
//         "hp1_mtnt:supersonic_tnt"
//     ];

//     const tnt10 = [
//         "hp1_mtnt:mega_tnt",
//         "hp1_mtnt:wither_boss_tnt",
//         "hp1_mtnt:warden_demolition_tnt"
//     ];
    
//     for (const typeId of tnt4) {
//         if (entity.typeId === typeId) {
//             entity.runCommand('fill ~-2~~-2 ~2~5~2 air');
//             //entity.runCommand('say Size 4 TNT Removed');
//         }
//     };
    
//     for (const typeId of tnt6) {
//         if (entity.typeId === typeId) {
//             entity.runCommand('fill ~-3~~-3 ~3~6~3 air');
//             //entity.runCommand('say Size 6 TNT Removed');
//         }
//     };
    
//     for (const typeId of tnt8) {
//         if (entity.typeId === typeId) {
//             entity.runCommand('fill ~-4~~-4 ~4~8~4 air');
//             //entity.runCommand('say Size 8 TNT Removed');
//         }
//     };
    
//     for (const typeId of tnt10) {
//         if (entity.typeId === typeId) {
//             entity.runCommand('fill ~-5~~-5 ~5~10~5 air');
//             //entity.runCommand('say Size 10 TNT Removed');
//         }
//     }
// };