import { BlockPermutation, system, world } from "@minecraft/server";
import { SettingsHandler } from "./settings";
const activeTntCountdowns = new Map();
function locationKey(loc) {
    return `${loc.x}_${loc.y}_${loc.z}`;
}
function getCountdownBar(ticksLeft) {
    const totalBars = 21;
    const progress = 10 - ticksLeft;
    let bar = "§cTNT Sponge Charging:§r\n     §7";
    for (let i = 0; i < totalBars; i++) {
        if (i < progress * 2.1) {
            if (i < 7)
                bar += "§c|"; // red
            else if (i < 14)
                bar += "§6|"; // orange
            else
                bar += "§e|"; // yellow
        }
        else {
            bar += "§7|"; // gray (unfilled)
        }
    }
    const percent = Math.floor((progress / 10) * 100);
    return bar + ` §8[§b${percent.toString().padStart(2, "0")}%§8]`;
}
export function tntSpongePulse(block) {
    // Check if TNT sponge is enabled
    if (!SettingsHandler.isSpongeEnabled("tntSponge")) {
        const dim = world.getDimension(block.dimension.id);
        dim.runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
        // Notify nearby players
        const nearbyPlayers = dim.getPlayers({ location: block.location, maxDistance: 10 });
        for (const player of nearbyPlayers) {
            player.sendMessage("§cTNT Sponge is disabled in settings!");
        }
        return;
    }
    const key = locationKey(block.location);
    if (activeTntCountdowns.has(key))
        return; // prevent duplicate countdowns
    world.getDimension(block.dimension.id).spawnParticle("wildphire_spg:explosion_idle_sponge_particle", {
        x: block.location.x + 0.5,
        y: block.location.y + 0.5,
        z: block.location.z + 0.5
    });
    let level = block.permutation.getAllStates()["wildphire_spg:tnt_charge"];
    if (level === undefined)
        level = 0;
    const dim = world.getDimension(block.dimension.id);
    const surroundingTNT = dim.getEntities({ location: block.location, type: "minecraft:tnt", maxDistance: 15 });
    if (surroundingTNT.length === 0)
        return;
    let tntCount = 0;
    for (const tnt of surroundingTNT) {
        tntCount++;
        dim.spawnParticle("minecraft:explosion", { x: tnt.location.x + 0.5, y: tnt.location.y, z: tnt.location.z + 0.5 });
        tnt.remove();
    }
    const newLevel = level + tntCount;
    if (newLevel >= 10) {
        activeTntCountdowns.set(key, true);
        let countdown = 10;
        const countdownTick = () => {
            const bar = getCountdownBar(countdown);
            dim.spawnParticle("wildphire_spg:fire_sponge_particle", {
                x: block.location.x + 0.5,
                y: block.location.y,
                z: block.location.z + 0.5
            });
            dim.runCommand(`title @a[r=35,x=${block.location.x},y=${block.location.y},z=${block.location.z}] actionbar ${bar}`);
            dim.playSound("note.bass", block.location);
            dim.spawnParticle("minecraft:basic_smoke_particle", {
                x: block.location.x + 0.5,
                y: block.location.y + 1,
                z: block.location.z + 0.5
            });
            if (countdown <= 0) {
                dim.runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air`);
                dim.createExplosion(block.location, 20, { causesFire: false, breaksBlocks: true });
                const createVerticalExplosions = (base, power) => {
                    for (let dy of [-5, 0, 5]) {
                        dim.createExplosion({ x: base.x, y: base.y + dy, z: base.z }, power, {
                            causesFire: false,
                            breaksBlocks: true
                        });
                    }
                };
                const faceOffsets = [
                    { x: 5, z: 0 }, { x: -5, z: 0 }, { x: 0, z: 5 }, { x: 0, z: -5 }
                ];
                for (const offset of faceOffsets) {
                    const faceLoc = {
                        x: block.location.x + offset.x,
                        y: block.location.y,
                        z: block.location.z + offset.z
                    };
                    createVerticalExplosions(faceLoc, 15);
                }
                const cornerOffsets = [
                    { x: 7, z: 7 }, { x: -7, z: 7 }, { x: 7, z: -7 }, { x: -7, z: -7 },
                    { x: 9, z: 9 }, { x: -9, z: 9 }, { x: 9, z: -9 }, { x: -9, z: -9 }
                ];
                for (const offset of cornerOffsets) {
                    const corner = {
                        x: block.location.x + offset.x,
                        y: block.location.y,
                        z: block.location.z + offset.z
                    };
                    createVerticalExplosions(corner, 10);
                }
                activeTntCountdowns.delete(key);
                return;
            }
            countdown--;
            system.runTimeout(countdownTick, 20);
        };
        countdownTick();
    }
    else {
        //spawn particle on block
        dim.spawnParticle("wildphire_spg:fire_sponge_particle", {
            x: block.location.x + 0.5,
            y: block.location.y + 1,
            z: block.location.z + 0.5
        });
        dim.runCommand(`title @a[r=35,x=${block.location.x},y=${block.location.y},z=${block.location.z}] actionbar §cTNT Sponge Charge:§e ${newLevel}§7/§610§r`);
        dim.playSound("random.fizz", block.location);
        block.setPermutation(BlockPermutation.resolve(block.typeId, { "wildphire_spg:tnt_charge": newLevel }));
    }
}
//need a function to remove the tnt sponge if its not fully charged it should return true if it cant be removed and false if it can be removed
export function removeTntSponge(block) {
    const key = locationKey(block.location);
    if (activeTntCountdowns.has(key)) {
        return true; // cannot remove if it's still charging
    }
    system.run(() => {
        world.getDimension(block.dimension.id).runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`);
    });
    return false; // successfully removed
}
