import { SettingsHandler } from "./settings";
// Track sponge state
const activeSponges = new Map();
const ignoredKeywords = new Set([
    "glass", "fence", "door", "trapdoor", "wall", "stairs", "slab", "iron_bars",
    "ladder", "pane", "leaves", "anvil", "chest", "shulker_box", "furnace", "crafting_table",
    "carrot", "potato", "wheat", "beetroot", "cactus", "melon", "pumpkin", "flower", "plant",
    "bamboo", "sugar_cane", "sapling", "torch", "vine", "mushroom", "kelp", "coral", "leaf_litter", "short_grass", "rose_bush", "tall_grass", "dead_bush", "fern", "sweet_berry_bush", "water"
]);
const directions = [
    { x: 1, y: 0, z: 0, face: "west" },
    { x: -1, y: 0, z: 0, face: "east" },
    { x: 0, y: 0, z: 1, face: "north" },
    { x: 0, y: 0, z: -1, face: "south" }
];
const SCAN_RADIUS = 15;
const TORCHES_PER_PULSE = 3;
const MAX_PULSES = 10;
const PARTICLE_STEP_SIZE = 0.5; // Reduced particle density
function spawnTrail(dim, from, to) {
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    const dz = to.z - from.z;
    const distance = Math.sqrt(dx ** 2 + dy ** 2 + dz ** 2);
    const steps = Math.ceil(distance / PARTICLE_STEP_SIZE);
    const arcHeight = 1;
    const drop = 0.5;
    for (let i = 0; i <= steps; i++) {
        const t = i / steps;
        const px = from.x + dx * t + 0.5;
        const pz = from.z + dz * t + 0.5;
        const baseY = from.y + dy * t;
        const arcY = arcHeight * Math.sin(Math.PI * t) * (1 - t);
        const py = baseY + arcY - drop * t + 0.5;
        dim.spawnParticle("wildphire_spg:yellow_trail_particle", { x: px, y: py, z: pz });
    }
}
function scanTorchSpots(dim, origin) {
    const spots = [];
    const radiusSq = SCAN_RADIUS * SCAN_RADIUS;
    // Scan the full radius for all valid spots
    for (let dx = -SCAN_RADIUS; dx <= SCAN_RADIUS; dx++) {
        for (let dy = -SCAN_RADIUS; dy <= SCAN_RADIUS; dy++) {
            for (let dz = -SCAN_RADIUS; dz <= SCAN_RADIUS; dz++) {
                if (dx * dx + dy * dy + dz * dz > radiusSq)
                    continue;
                const x = origin.x + dx;
                const y = origin.y + dy;
                const z = origin.z + dz;
                // Skip if it's the sponge block itself or below valid Y level
                if (dx === 0 && dy === 0 && dz === 0)
                    continue;
                if (y < -63 || y > 319)
                    continue; // Valid Y range check
                const base = dim.getBlock({ x, y, z });
                if (!base || base.typeId === "minecraft:air")
                    continue;
                // Fast keyword check
                const typeId = base.typeId;
                let isIgnored = false;
                for (const keyword of ignoredKeywords) {
                    if (typeId.includes(keyword)) {
                        isIgnored = true;
                        break;
                    }
                }
                if (isIgnored)
                    continue;
                // Check top torch only if not directly on sponge
                if (!(dx === 0 && dz === 0 && dy === -1)) {
                    const aboveY = y + 1;
                    if (aboveY >= -63 && aboveY <= 319) { // Valid Y range
                        const above = dim.getBlock({ x, y: aboveY, z });
                        if (above?.typeId === "minecraft:air") {
                            spots.push({ x, y: aboveY, z, face: "top" });
                        }
                    }
                }
                // Wall torches - check each direction
                for (const dir of directions) {
                    const sx = x + dir.x;
                    const sy = y + dir.y;
                    const sz = z + dir.z;
                    // Skip if torch would land on sponge block itself or outside valid Y level
                    if (sx === origin.x && sy === origin.y && sz === origin.z)
                        continue;
                    if (sy < -63 || sy > 319)
                        continue; // Valid Y range
                    const side = dim.getBlock({ x: sx, y: sy, z: sz });
                    if (side?.typeId === "minecraft:air") {
                        spots.push({ x: sx, y: sy, z: sz, face: dir.face });
                    }
                }
            }
        }
    }
    // Shuffle to randomize placement
    for (let i = spots.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [spots[i], spots[j]] = [spots[j], spots[i]];
    }
    return spots;
}
// 🔁 This is called every 20 ticks (1 second) for each sponge block
export function lightSpongePulse(block) {
    // Check if light sponge is enabled
    if (!SettingsHandler.isSpongeEnabled("lightSponge")) {
        const dim = block.dimension;
        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("§cLight Sponge is disabled in settings!");
        }
        return;
    }
    const dim = block.dimension;
    const origin = block.location;
    const key = `${origin.x}_${origin.y}_${origin.z}`;
    let sponge = activeSponges.get(key);
    if (!sponge) {
        const spots = scanTorchSpots(dim, origin);
        if (spots.length === 0)
            return;
        sponge = {
            placed: 0,
            pulsesRemaining: MAX_PULSES,
            spots
        };
        activeSponges.set(key, sponge);
    }
    if (sponge.pulsesRemaining <= 0 || sponge.placed >= 25 || sponge.spots.length === 0) {
        activeSponges.delete(key);
        dim.runCommand(`setblock ${origin.x} ${origin.y} ${origin.z} air destroy`);
        return;
    }
    let count = 0;
    while (count < TORCHES_PER_PULSE && sponge.spots.length > 0) {
        const spot = sponge.spots.pop();
        dim.runCommand(`setblock ${spot.x} ${spot.y} ${spot.z} minecraft:torch["torch_facing_direction"="${spot.face}"]`);
        spawnTrail(dim, origin, spot);
        sponge.placed++;
        count++;
    }
    sponge.pulsesRemaining--;
}
