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

const customGrassPlants = {
    'pu_biomes:horror_grass': [
        { id: 'pu_biomes:horror_moss_growth', chance: 0.4 },
        { id: 'pu_biomes:horror_moss_sprout', chance: 0.4 },
        { id: 'pu_biomes:horror_mossy_tree_bush', chance: 0.1 },
        { id: 'pu_biomes:horror_tree_bush', chance: 0.1 }
    ],
    'pu_biomes:red_grass': [
        { id: 'pu_biomes:red_bleeding_heart', chance: 0.1 },
        { id: 'pu_biomes:red_flower', chance: 0.1 },
        { id: 'pu_biomes:red_flowers', chance: 0.1 },
        { id: 'pu_biomes:red_flower', chance: 0.1 },
        { id: 'pu_biomes:red_green_bush', chance: 0.2 },
        { id: 'pu_biomes:red_large_green_bush', chance: 0.1 },
        { id: 'pu_biomes:red_rose_bush', chance: 0.2 },
        { id: 'pu_biomes:red_tree_bush', chance: 0.1 }
    ],
    'pu_biomes:sky_grass': [
        { id: 'pu_biomes:sky_big_bush', chance: 0.2 },
        { id: 'pu_biomes:sky_flower', chance: 0.1 },
        { id: 'pu_biomes:sky_tree_bush', chance: 0.1 },
        { id: 'pu_biomes:sky_growth', chance: 0.2 },
        { id: 'pu_biomes:sky_bush', chance: 0.2 }
    ],
    'pu_biomes:toxic_grass': [
        { id: 'pu_biomes:toxic_growth', chance: 0.3 },
        { id: 'pu_biomes:toxic_short_grass', chance: 0.3 },
        { id: 'pu_biomes:tall_toxic_lilys', chance: 0.1 },
        { id: 'pu_biomes:toxic_lilys', chance: 0.1 },
        { id: 'pu_biomes:toxic_sprouts', chance: 0.2 }
    ],
    'pu_biomes:enchanted_grass': [
        { id: 'pu_biomes:enchanted_bush', chance: 0.1 },
        { id: 'pu_biomes:enchanted_flower', chance: 0.1 },
        { id: 'pu_biomes:enchanted_grass_foliage', chance: 0.2 },
        { id: 'pu_biomes:enchanted_large_thick_bush', chance: 0.1 },
        { id: 'pu_biomes:enchanted_mushroom', chance: 0.2 },
        { id: 'pu_biomes:enchanted_thick_bush', chance: 0.1 },
        { id: 'pu_biomes:tall_enchanted_grass', chance: 0.1 },
        { id: 'pu_biomes:tall_enchanted_mushroom', chance: 0.1 }
    ],
    'pu_biomes:lunar_grass': [
        { id: 'pu_biomes:lunar_bell_flower', chance: 0.1 },
        { id: 'pu_biomes:lunar_big_bush', chance: 0.1 },
        { id: 'pu_biomes:lunar_bush', chance: 0.2 },
        { id: 'pu_biomes:lunar_flower', chance: 0.1 },
        { id: 'pu_biomes:lunar_lilac_petals', chance: 0.3 },
        { id: 'pu_biomes:tall_lunar_grass', chance: 0.2 },
        { id: 'pu_biomes:lunar_orchid', chance: 0.1 }
    ],
    'pu_biomes:orange_grass': [
        { id: 'pu_biomes:orange_big_bush', chance: 0.1 },
        { id: 'pu_biomes:orange_dried_bush', chance: 0.2 },
        { id: 'pu_biomes:orange_growth', chance: 0.2 },
        { id: 'pu_biomes:orange_tree_bush', chance: 0.1 },
        { id: 'pu_biomes:orange_orange_flower', chance: 0.1 },
        { id: 'pu_biomes:orange_big_bush', chance: 0.1 },
        { id: 'pu_biomes:orange_white_flower', chance: 0.1 },
        { id: 'pu_biomes:tall_orange_bush', chance: 0.1 },
        { id: 'pu_biomes:tall_orange_dried_bush', chance: 0.1 },
        { id: 'pu_biomes:orange_bush', chance: 0.2 }
    ]
};

// Weighted random plant picker
function getRandomPlant(plantList) {
    const roll = Math.random();
    let cumulative = 0;
    for (const plant of plantList) {
        cumulative += plant.chance;
        if (roll < cumulative) return plant.id;
    }
    return plantList[plantList.length - 1].id;
}

let lastProcessedTick = -1;

world.beforeEvents.playerInteractWithBlock.subscribe((eventData) => {
    const { block, itemStack, player } = eventData;

    if (!customGrassPlants[block.typeId]) return;
    if (!itemStack || itemStack.typeId !== 'minecraft:bone_meal') return;

    const currentTick = system.currentTick;
    if (currentTick === lastProcessedTick) return;
    lastProcessedTick = currentTick;

    const grassType = block.typeId;
    const plantList = customGrassPlants[grassType];

    system.run(() => {
        const origin = block.location;
        const dimension = block.dimension;

        const particleSpots = [];
        const plantableSpots = [];

        // 7x3x7 search area
        for (let dx = -3; dx <= 3; dx++) {
            for (let dy = -1; dy <= 1; dy++) {
                for (let dz = -3; dz <= 3; dz++) {
                    const pos = { x: origin.x + dx, y: origin.y + dy, z: origin.z + dz };
                    const base = dimension.getBlock(pos);
                    if (!base || base.typeId !== grassType) continue;

                    particleSpots.push(pos);

                    const above = dimension.getBlock({ x: pos.x, y: pos.y + 1, z: pos.z });
                    if (!above || above.typeId !== 'minecraft:air' || above.isLiquid) continue;

                    plantableSpots.push({ base, above });
                }
            }
        }

        // Limit and emit up to 12 particles
        const particlesToEmit = Math.min(12, particleSpots.length);
        for (let i = 0; i < particlesToEmit; i++) {
            const idx = Math.floor(Math.random() * particleSpots.length);
            const pos = particleSpots.splice(idx, 1)[0];
            dimension.spawnParticle('minecraft:crop_growth_emitter', {
                x: pos.x + 0.5,
                y: pos.y + 1,
                z: pos.z + 0.5,
            });
        }

        // Plant 1–6 random plants
        const plantsToPlace = Math.min(plantableSpots.length, Math.floor(Math.random() * 6) + 1);
        for (let i = 0; i < plantsToPlace; i++) {
            const idx = Math.floor(Math.random() * plantableSpots.length);
            const { above } = plantableSpots.splice(idx, 1)[0];
            const plant = getRandomPlant(plantList);
            above.setPermutation(BlockPermutation.resolve(plant));
        }

        // Consume bone meal
        if (player.getGameMode() !== 'creative') {
            const equipment = player.getComponent('equippable');
            const mainhand = equipment.getEquipment(EquipmentSlot.Mainhand);

            if (mainhand && mainhand.typeId === 'minecraft:bone_meal') {
                mainhand.amount--;
                if (mainhand.amount > 0) {
                    equipment.setEquipment(EquipmentSlot.Mainhand, mainhand);
                } else {
                    equipment.setEquipment(EquipmentSlot.Mainhand, undefined);
                }
            }
        }

        player.playSound('random.tick');
    });

    eventData.cancel = true;
});
