import { world, system } from "@minecraft/server";
import { SettingsHandler } from "./settings";
const REDSTONE_ID = "minecraft:redstone_wire";
const EMP_RADIUS = 25;
const EMP_RADIUS_SQ = EMP_RADIUS * EMP_RADIUS;
const COUNTDOWN_TICKS = 100; // 5 seconds
const SIGNAL_PROP = "redstone_signal";
// Store pending EMP sponges
const pendingSponges = new Map();
// Helper to generate the colored bar
function getChargingBar(ticksLeft) {
    const totalBars = 50;
    const elapsed = COUNTDOWN_TICKS - ticksLeft;
    const yellowProgress = Math.floor((elapsed / 60) * totalBars);
    const orangeProgress = Math.floor((elapsed / 80) * totalBars);
    const redProgress = Math.floor((elapsed / 100) * totalBars);
    let bar = "§6Charging Redstone Sponge:§r\n ";
    for (let i = 0; i < totalBars; i++) {
        if (i < redProgress) {
            bar += "§c|"; // Red overwrites everything
        }
        else if (i < orangeProgress) {
            bar += "§6|"; // Orange overwrites yellow
        }
        else if (i < yellowProgress) {
            bar += "§e|"; // Yellow only
        }
        else {
            bar += "§7|"; // Uncharged
        }
    }
    const percent = Math.round((elapsed / COUNTDOWN_TICKS) * 100);
    bar += ` §8[§b${(percent + 2).toString().padStart(2, "0")}%§8]§r`;
    return bar;
}
system.runInterval(() => {
    if (pendingSponges.size === 0)
        return;
    for (const [key, data] of pendingSponges.entries()) {
        const { block } = data;
        const pos = block.location;
        // Show charging bar to nearby players
        if (data.ticksLeft % 2 === 0 && data.ticksLeft > 0) {
            const bar = getChargingBar(data.ticksLeft);
            for (const player of world.getPlayers()) {
                if (distanceSq(player.location, pos) <= EMP_RADIUS_SQ) {
                    player.onScreenDisplay.setActionBar(bar);
                }
            }
            // Only play sound/particle every 20 ticks (1 second)
            if (data.ticksLeft % 20 === 0) {
                world.getDimension(block.dimension.id).playSound("random.click", block.location);
                world.getDimension(block.dimension.id).spawnParticle("wildphire_spg:fire_sponge_particle", {
                    x: pos.x + 0.5,
                    y: pos.y - 0.5,
                    z: pos.z + 0.5
                });
            }
        }
        // Final message after countdown (on the 6th second, i.e., when ticksLeft === 0)
        if (data.ticksLeft === 0) {
            for (const player of world.getPlayers()) {
                if (distanceSq(player.location, pos) <= EMP_RADIUS_SQ) {
                    player.onScreenDisplay.setActionBar("§6Redstone has been EMP'd!");
                    world.getDimension(block.dimension.id).playSound("note.pling", block.location);
                    world.getDimension(block.dimension.id).playSound("random.explode", block.location);
                    world.getDimension(block.dimension.id).spawnParticle("wildphire_spg:redstone_sponge_particle", {
                        x: pos.x + 0.5,
                        y: pos.y,
                        z: pos.z + 0.5
                    });
                    player.runCommand(`camerashake add @s 0.1 0.5 positional`);
                }
            }
        }
        // Detonate
        if (data.ticksLeft <= 0) {
            runEMP(block);
            pendingSponges.delete(key);
        }
        else {
            data.ticksLeft--;
        }
    }
}, 1);
// Call this on sponge use
export function redstoneSponge(block) {
    // Check if redstone sponge is enabled
    if (!SettingsHandler.isSpongeEnabled("redstoneSponge")) {
        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("§cRedstone Sponge is disabled in settings!");
        }
        return;
    }
    const key = `${block.location.x}_${block.location.y}_${block.location.z}`;
    pendingSponges.set(key, { ticksLeft: COUNTDOWN_TICKS, block });
}
// Executes the EMP
function runEMP(block) {
    const dim = block.dimension;
    const origin = block.location;
    dim.spawnParticle("minecraft:flash", {
        x: origin.x + 0.5,
        y: origin.y + 1,
        z: origin.z + 0.5
    });
    for (let dx = -EMP_RADIUS; dx <= EMP_RADIUS; dx++) {
        for (let dy = -EMP_RADIUS; dy <= EMP_RADIUS; dy++) {
            for (let dz = -EMP_RADIUS; dz <= EMP_RADIUS; dz++) {
                const distSq = dx * dx + dy * dy + dz * dz;
                if (distSq > EMP_RADIUS_SQ)
                    continue;
                const x = origin.x + dx;
                const y = origin.y + dy;
                const z = origin.z + dz;
                // Skip positions below y -63 (world boundary)
                if (y < -63) {
                    continue;
                }
                const target = dim.getBlock({ x, y, z });
                if (!target || target.typeId !== REDSTONE_ID)
                    continue;
                dim.runCommand(`setblock ${x} ${y} ${z} air destroy`);
            }
        }
    }
    system.runTimeout(() => {
        dim.runCommand(`setblock ${origin.x} ${origin.y} ${origin.z} air destroy`);
    }, 20);
    // Destroy sponge
}
// Fast squared distance
function distanceSq(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;
    const dz = a.z - b.z;
    return dx * dx + dy * dy + dz * dz;
}
