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

// Debug helper
function isDebugEnabled() {
    try {
        const scoreboard = world.scoreboard.getObjective("aria_ah.dev_mode");
        if (!scoreboard) return false;
        for (const p of scoreboard.getParticipants()) {
            if (p.displayName === "debug") {
                return scoreboard.getScore(p) === 1;
            }
        }
    } catch (e) {}
    return false;
}
function sendDebug(msg) {
    if (isDebugEnabled()) world.sendMessage(msg);
}

system.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.id !== "aria_ah:remove_items") return;
    const source = event.sourceEntity;
    if (!source || !source.isValid) return;

    // Parse parameters
    let [timeStr, radiusStr] = (event.message ?? "").split(" ");
    let delay = Math.max(0, parseFloat(timeStr) || 0); // seconds
    let radius = Math.max(1, parseInt(radiusStr) || 5);

    // Save location and dimension immediately!
    const { x, y, z } = source.location;
    const dimension = source.dimension;

    sendDebug(`§a[remove_items] Scheduled removal in ${delay}s, radius ${radius} at (${x}, ${y}, ${z})`);

    system.runTimeout(() => {
        const items = dimension.getEntities({
            type: "minecraft:item",
            location: { x, y, z },
            maxDistance: radius
        });
        let count = 0;
        for (const item of items) {
            item.remove();
            count++;
        }
        sendDebug(`§a[remove_items] Removed ${count} items at (${x}, ${y}, ${z}) radius ${radius}`);
    }, Math.floor(delay * 20));
});