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

const PARTICULA_ID = "pa:chimenea_hidrotermal";
const BLOQUE_ID = "pa:chimenea_hidrotermal";

// Guardamos timestamps o simplemente presencia; aquí guardamos presencia
const spawnedBlocks = new Set();

// Si ya había un intervalo activo (recarga), lo limpiamos
if (globalThis._chimeneaIntervalId !== undefined) {
    try { system.clearRun(globalThis._chimeneaIntervalId); } catch (e) {}
    globalThis._chimeneaIntervalId = undefined;
}

// Función principal
function spawnChimeneaParticles() {
    const players = world.getPlayers();
    if (!players || players.length === 0) return;

    for (const player of players) {
        const dim = player.dimension;
        const ploc = player.location;

        for (let dx = -1; dx <= 1; dx++) {
            for (let dy = -1; dy <= 1; dy++) {
                for (let dz = -1; dz <= 1; dz++) {
                    const bx = Math.floor(ploc.x) + dx;
                    const by = Math.floor(ploc.y) + dy;
                    const bz = Math.floor(ploc.z) + dz;
                    const key = `${dim.id}:${bx};${by};${bz}`;

                    const block = dim.getBlock({ x: bx, y: by, z: bz });

                    if (block && block.typeId === BLOQUE_ID) {
                        if (!spawnedBlocks.has(key)) {
                            // usar el centro del bloque para spawnParticle
                            const cx = bx + 0.5;
                            const cy = by + 0.5;
                            const cz = bz + 0.5;

                            try {
                                dim.spawnParticle(PARTICULA_ID, { x: cx, y: cy, z: cz });
                            } catch (err) {
                                // fallback a la API alternativa si existiera
                                try { dim.spawnParticle(PARTICULA_ID, { position: { x: cx, y: cy, z: cz } }); } catch(e){}
                            }

                            spawnedBlocks.add(key);
                        }
                    } else {
                        // si antes existía la entrada pero ya no hay bloque, limpiamos
                        if (spawnedBlocks.has(key)) spawnedBlocks.delete(key);
                    }
                }
            }
        }
    }
}

// Ejecutar cada 10 ticks (0.5s)
globalThis._chimeneaIntervalId = system.runInterval(spawnChimeneaParticles, 10);