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

// === CONFIGURATION ===

// List of all animal families (expand as needed)
const ANIMAL_FAMILIES = [
    "animal",
    "axolotl",
    "bee",
    "cat",
    "chicken",
    "cow",
    "donkey",
    "fox",
    "frog",
    "goat",
    "horse",
    "llama",
    "mooshroom",
    "mule",
    "ocelot",
    "panda",
    "parrot",
    "pig",
    "polar_bear",
    "rabbit",
    "sheep",
    "sniffer",
    "strider",
    "turtle",
    "wolf"
    // Add more as needed
];

// List of really solid blocks (whitelist)
const SOLID_BLOCKS = [
    "aria_ah:grass",
    "aria_ah:dirt",
    "minecraft:stone",
    "minecraft:dirt",
    "minecraft:grass_block",
    "minecraft:sand",
    "minecraft:gravel",
    "minecraft:deepslate",
    "minecraft:cobblestone",
    "minecraft:andesite",
    "minecraft:diorite",
    "minecraft:granite",
    "minecraft:mycelium",
    "minecraft:podzol",
    "minecraft:clay",
    "minecraft:red_sand",
    // ...add more blocks as needed
];

// Weighted block config and state logic
const PLACEABLE_BLOCKS = [
    {
        id: "aria_ah:skeleton",
        weight: 12,
        randomStates: () => ({
            "aria_ah:type": Math.floor(Math.random() * 6),
            "minecraft:cardinal_direction": randomDirection()
        })
    },
    {
        id: "aria_ah:tombstone1",
        weight: 1,
        randomStates: () => ({
            "minecraft:cardinal_direction": randomDirection()
        })
    },
    {
        id: "aria_ah:tombstone2",
        weight: 1,
        randomStates: () => ({
            "minecraft:cardinal_direction": randomDirection()
        })
    },
    {
        id: "aria_ah:corpse",
        weight: 3,
        randomStates: () => ({
            "minecraft:cardinal_direction": randomDirection()
        })
    }
];

// Excluded bosses and flying mobs
const EXCLUDED_TYPEIDS = [
    "minecraft:wither",
    "minecraft:warden",
    "minecraft:ender_dragon",
    "minecraft:iron_golem",
    "minecraft:phantom"
    // Add more bosses if needed
];
const FLYING_TYPEIDS = [
    "minecraft:bat",
    "minecraft:parrot",
    "minecraft:bee",
    "minecraft:phantom",
    "minecraft:vex",
    "minecraft:ender_dragon"
    // Add more flying mobs if needed
];

// === HELPERS ===

// Scoreboard value fetcher
function getScoreboardValue(name) {
    try {
        const scoreboard = world.scoreboard.getObjective("aria_ah.corpse_mob");
        if (!scoreboard) return 0;
        const participants = scoreboard.getParticipants();
        for (const p of participants) {
            if (p.displayName === name) {
                return scoreboard.getScore(p);
            }
        }
    } catch (e) {}
    return 0;
}

// Dynamic allowed family logic
function isAllowedFamily(entity) {
    const allowAnimal = getScoreboardValue("animal");
    const allowMob = getScoreboardValue("mob");
    const allowMonster = getScoreboardValue("monster");

    if (allowMob) {
        return entity.matches({ families: ["mob"] });
    } else if (allowAnimal) {
        for (const fam of ANIMAL_FAMILIES) {
            if (entity.matches({ families: [fam] })) {
                return true;
            }
        }
        return false;
    } else if (allowMonster) {
        if (entity.matches({ families: ["mob"] })) {
            for (const fam of ANIMAL_FAMILIES) {
                if (entity.matches({ families: [fam] })) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    return false;
}

function isSolidBlock(block) {
    return block && block.isValid && SOLID_BLOCKS.includes(block.typeId);
}

function randomDirection() {
    const directions = ["north", "south", "east", "west"];
    return directions[Math.floor(Math.random() * directions.length)];
}

// Weighted random block picker
function randomPlaceableBlock() {
    const totalWeight = PLACEABLE_BLOCKS.reduce((sum, b) => sum + b.weight, 0);
    let r = Math.random() * totalWeight;
    for (const block of PLACEABLE_BLOCKS) {
        if (r < block.weight) return block;
        r -= block.weight;
    }
    return PLACEABLE_BLOCKS[0];
}

// Debug message helpers
function debugGreen(msg) { world.sendMessage(`§a[DEBUG] ${msg}`); }
function debugRed(msg) { world.sendMessage(`§c[DEBUG] ${msg}`); }

// Exclude bosses, phantoms, and flying mobs
function isExcludedEntity(entity) {
    if (EXCLUDED_TYPEIDS.includes(entity.typeId)) return true;
    if (FLYING_TYPEIDS.includes(entity.typeId)) return true;
    try {
        if (entity.getComponent("minecraft:can_fly")) return true;
    } catch (e) {}
    return false;
}

// === MAIN EVENT ===

system.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.id !== "aria_ah:corpse_mob") return;
    const entity = event.sourceEntity;
    if (!entity || !entity.isValid) {
        //debugRed("Kein gültiges Entity gefunden.");
        return;
    }
    if (!isAllowedFamily(entity)) {
        //debugRed("Entity gehört nicht zu einer erlaubten Familie (laut Scoreboard).");
        return;
    }
    if (isExcludedEntity(entity)) {
        //debugRed(`Entity ${entity.typeId} ist Boss, Phantom oder fliegendes Mob und wird ignoriert.`);
        return;
    }

    const pos = entity.location;
    const center = { x: Math.floor(pos.x), y: Math.floor(pos.y), z: Math.floor(pos.z) };
    const dim = entity.dimension;

    //debugGreen(`Suche Platz für Block um (${center.x}, ${center.y}, ${center.z})`);

    let foundPos = null;

    // 1. Try directly under the entity (1x1)
    const blockAt = dim.getBlock(center);
    const blockBelow = blockAt?.below();
    if (
        blockAt && blockAt.isAir &&
        blockBelow && isSolidBlock(blockBelow)
    ) {
        foundPos = center;
        //debugGreen(`Direkt unter Entity gefunden: (${center.x}, ${center.y}, ${center.z}) auf ${blockBelow.typeId}`);
    } else {
        //debugRed(`Direkt unter Entity keine gültige Position (${center.x}, ${center.y}, ${center.z})`);
        // 2. Try 3x3 area (excluding center)
        for (let dx = -1; dx <= 1; dx++) {
            for (let dz = -1; dz <= 1; dz++) {
                if (dx === 0 && dz === 0) continue;
                const placePos = { x: center.x + dx, y: center.y, z: center.z + dz };
                const blockAt3x3 = dim.getBlock(placePos);
                const blockBelow3x3 = blockAt3x3?.below();
                if (
                    blockAt3x3 && blockAt3x3.isAir &&
                    blockBelow3x3 && isSolidBlock(blockBelow3x3)
                ) {
                    foundPos = placePos;
                    //debugGreen(`Gefundene Position im 3x3: (${placePos.x}, ${placePos.y}, ${placePos.z}) auf ${blockBelow3x3.typeId}`);
                    break;
                } else {
                    //debugRed(`Keine gültige Position bei (${placePos.x}, ${placePos.y}, ${placePos.z})`);
                }
            }
            if (foundPos) break;
        }
    }

    if (foundPos) {
        const blockConfig = randomPlaceableBlock();
        const blockType = blockConfig.id;
        const states = blockConfig.randomStates();

        //debugGreen(`Platziere Block ${blockType} mit States ${JSON.stringify(states)} bei (${foundPos.x}, ${foundPos.y}, ${foundPos.z})`);

        const permutation = BlockPermutation.resolve(blockType, states);

        const block = dim.getBlock(foundPos);
        if (block) block.setPermutation(permutation);
    } else {
        //debugRed("Keine passende Stelle für Block gefunden, platziere nichts.");
    }

    // --- Sound and particles ---
    if (Math.random() < 0.7) {
        dim.runCommand(`playsound aria_ah.dead_breath @a ${pos.x} ${pos.y} ${pos.z} 5 1`);
        //debugGreen("Sound aria_ah.dead_breath abgespielt.");
    } else {
        //debugGreen("Sound aria_ah.dead_breath wurde nicht abgespielt (Zufall).");
    }
    dim.runCommand(`particle aria_ah:dark_fog_gray ${pos.x} ${pos.y} ${pos.z}`);
    dim.runCommand(`particle aria_ah:dark_fog_ground_gray ${center.x} ${center.y} ${center.z}`);
    if (world.scoreboard.getObjective("aria_ah.general").getScore("vv_active")) {
        dim.runCommand(`particle aria_ah:death_gray_vv ${center.x} ${center.y} ${center.z}`);
        dim.runCommand(`particle aria_ah:death_gray_vv ${center.x} ${center.y} ${center.z}`);
    } else {
        dim.runCommand(`particle aria_ah:death_gray ${center.x} ${center.y} ${center.z}`);
        dim.runCommand(`particle aria_ah:death_gray ${center.x} ${center.y} ${center.z}`);
    }

    //debugGreen(`Entferne Entity (${entity.typeId}) an (${center.x}, ${center.y}, ${center.z})`);
    entity.remove();
});
