import { world, ItemStack } from '@minecraft/server';

/* ─── Item map ─────────────────────────────────────────────────────── */
const PLANT_ITEM = {
  'pu_biomes:enchanted_fallen_leaves' : 'pu_biomes:enchanted_fallen_leaves',
  'pu_biomes:orange_fallen_leaves'    : 'pu_biomes:orange_fallen_leaves',
  'pu_biomes:red_fallen_leaves'       : 'pu_biomes:red_fallen_leaves',
  'pu_biomes:sky_fallen_leaves'       : 'pu_biomes:sky_fallen_leaves',
  'pu_biomes:toxic_fallen_leaves'     : 'pu_biomes:toxic_fallen_leaves',
  'pu_biomes:redwood_fallen_leaves'     : 'pu_biomes:redwood_fallen_leaves',
  'pu_biomes:lunar_fallen_leaves'     : 'pu_biomes:lunar_fallen_leaves',
  'pu_biomes:violets'                 : 'pu_biomes:violets_item'
};
const BONE_MEAL = 'minecraft:bone_meal';
const MAX_GROW  = 3;

/* ─── helpers ──────────────────────────────────────────────────────── */
const itemFor = id => PLANT_ITEM[id];              //undefined if none
const isFertiliser = (blockId, itemId) =>
      itemId === BONE_MEAL || itemId === itemFor(blockId);

function consume(player, held, eq) {
  if (player.getGameMode() === 'creative') return;
  if (held.amount > 1) { held.amount--; eq.setEquipment('Mainhand', held); }
  else                 { eq.setEquipment('Mainhand', undefined); }
}

/* ─── component ────────────────────────────────────────────────────── */
world.beforeEvents.worldInitialize.subscribe(ev => {
  ev.blockComponentRegistry.registerCustomComponent('pu_biomes:fallenLeaves', {

    /* right‑click handler */
    onPlayerInteract(ev) {
      const { block, player } = ev;
      const eq   = player.getComponent('equippable');
      const held = eq.getEquipment('Mainhand');
      if (!held || !isFertiliser(block.typeId, held.typeId)) return;

      const growth = block.permutation.getState('pu_biomes:growth');
      const dropId = itemFor(block.typeId);        // may be undefined

      // Play sound effect
      player.playSound('place.pink_petals');

      // a) fully‑grown + bone‑meal   drop one item (if mapped) + particles
      if (held.typeId === BONE_MEAL && growth === MAX_GROW) {
        block.dimension.spawnParticle(
          'minecraft:crop_growth_emitter',
          { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 }
        );
        if (dropId) {
          block.dimension.spawnItem(
            new ItemStack(dropId, 1),
            { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 }
          );
        }
        consume(player, held, eq);
        ev.cancel = true;
        return;
      }

      // b) grow if stage < MAX_GROW
      if (growth < MAX_GROW) {
        block.setPermutation(
          block.permutation.withState('pu_biomes:growth', growth + 1)
        );
        if (held.typeId === BONE_MEAL) {
          block.dimension.spawnParticle(
            'minecraft:crop_growth_emitter',
            { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 }
          );
        }
        consume(player, held, eq);
        ev.cancel = true;
      }
    },

    /* break / drop handler */
    onPlayerDestroy({ block, dimension, destroyedBlockPermutation }) {
      const dropId = itemFor(block.typeId);
      if (!dropId) return;                         // no mapped item nothing

      const count  = destroyedBlockPermutation.getState('pu_biomes:growth') + 1;
      dimension.spawnItem(
        new ItemStack(dropId, count),
        { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 }
      );
    }
  });
});