import { world, ItemStack, system, GameMode } from '@minecraft/server';
import { updateBlock } from '../utils/block';
import { consumeEquipped } from '../utils/item';

// Utils helpers
const Utils = {
  getPlayerEquipment(player) {
    return player.getComponent('equippable');
  },
  getSelectedItem(player) {
    const equip = this.getPlayerEquipment(player);
    return equip ? equip.getEquipment('Mainhand') : null;
  },
  consumeItem(player, item) {
    if (player.getGameMode() === GameMode.creative) return;
    const equip = this.getPlayerEquipment(player);
    consumeEquipped(equip, item);
  },
  setBlockState(block, stateName, value) {
    try {
      const newPerm = block.permutation.withState(stateName, value);
      block.setPermutation(newPerm);
    } catch (err) {
      updateBlock(block, { [stateName]: value });
    }
    if (stateName === 'peach:right' && value === '1') {
      Utils.scheduleRightDone(block);
    }
  },
  giveItem(player, id) {
    try {
      player.getComponent('inventory').container.addItem(new ItemStack(id));
    } catch (e) {}
  },
  playSound(block, sound) {
    try { block.dimension.playSound(sound, block.location); } catch (e) {}
  },
  spawnParticle(block, particle, offset = { x: 0, y: 0, z: 0 }) {
    try {
      const loc = block.location;
      block.dimension.spawnParticle(particle, {
        x: loc.x + 0.5 + offset.x,
        y: loc.y + 0.5 + offset.y,
        z: loc.z + 0.5 + offset.z
      });
    } catch (e) {}
  },
  randRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },
  scheduleRightDone(block) {
    try {
      if (block.permutation.getState('peach:right') !== '1') return;
      const delay = Utils.randRange(20, 30) * 50;
      system.runTimeout(() => {
        try {
          if (block.permutation.getState('peach:right') === '1') {
            Utils.setBlockState(block, 'peach:right', '2');
            Utils.spawnParticle(block, 'minecraft:campfire_smoke_particle', { x: 0, y: 0.4, z: 0 });
          }
        } catch (err) {}
      }, delay);
    } catch (e) {}
  }
};

world.beforeEvents.worldInitialize.subscribe((initData) => {
  initData.blockComponentRegistry.registerCustomComponent('peach:teapot_logic', {
    onPlayerInteract: (e) => {
      try {
        const { player, block } = e;
        const selected = Utils.getSelectedItem(player);
        const id = selected?.typeId ?? '';
        const right = block.permutation.getState('peach:right');
        const recipe = block.permutation.getState('peach:recipe');
        const cups = block.permutation.getState('peach:cups');
        const cupsNum = parseInt(cups, 10);

        const matches = (suffix) => id === `peach:${suffix}` || id === `minecraft:${suffix}` || id.endsWith(suffix);

        // --- Estado inicial ---
        if (recipe === '0' && right === '0') {
          if (matches('potion')) {
            Utils.setBlockState(block, 'peach:recipe', '1');
            Utils.setBlockState(block, 'peach:cups', '4');
            Utils.consumeItem(player, selected);
            Utils.giveItem(player, 'minecraft:glass_bottle');
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
          if (matches('milk_bucket')) {
            Utils.setBlockState(block, 'peach:recipe', '2');
            Utils.setBlockState(block, 'peach:right', '1');
            Utils.setBlockState(block, 'peach:cups', '4');
            Utils.consumeItem(player, selected);
            Utils.giveItem(player, 'minecraft:bucket');
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
          if (matches('honey_bottle')) {
            Utils.setBlockState(block, 'peach:recipe', '3');
            Utils.setBlockState(block, 'peach:right', '1');
            Utils.setBlockState(block, 'peach:cups', '4');
            Utils.consumeItem(player, selected);
            Utils.giveItem(player, 'minecraft:glass_bottle');
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
        }

        // --- Recipe 1: base potion ---
        if (recipe === '1') {
          if (matches('collagen')) {
            Utils.setBlockState(block, 'peach:recipe', '12');
            Utils.consumeItem(player, selected);
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
          if (matches('tin_coffee_powder')) {
            Utils.setBlockState(block, 'peach:recipe', '4');
            Utils.setBlockState(block, 'peach:right', '1');
            Utils.consumeItem(player, selected);
            Utils.giveItem(player, 'peach:tin');
            Utils.playSound(block, 'extinguish.candle');
            return;
          }
        }

        // --- Recipe 12: collagen adicionado, agora aceita frutas ---
        if (recipe === '12') {
          if (matches('peach')) {
            Utils.setBlockState(block, 'peach:recipe', '9');
            Utils.setBlockState(block, 'peach:right', '1');
            Utils.consumeItem(player, selected);
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
          if (matches('orange')) {
            Utils.setBlockState(block, 'peach:recipe', '8');
            Utils.setBlockState(block, 'peach:right', '1');
            Utils.consumeItem(player, selected);
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
          if (matches('melon_slice')) {
            Utils.setBlockState(block, 'peach:recipe', '10');
            Utils.setBlockState(block, 'peach:right', '1');
            Utils.consumeItem(player, selected);
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
          if (matches('coconut_slice')) {
            Utils.setBlockState(block, 'peach:recipe', '11');
            Utils.setBlockState(block, 'peach:right', '1');
            Utils.consumeItem(player, selected);
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
        }

        // --- Milk recipes ---
        if (recipe === '2') {
          if (matches('tin_coffee_powder')) {
            Utils.setBlockState(block, 'peach:recipe', '6');
            Utils.consumeItem(player, selected);
            Utils.giveItem(player, 'peach:tin');
            Utils.playSound(block, 'extinguish.candle');
            return;
          }
          if (matches('chocolate_powder')) {
            Utils.setBlockState(block, 'peach:recipe', '7');
            Utils.consumeItem(player, selected);
            Utils.playSound(block, 'extinguish.candle');
            return;
          }
        }

        if (recipe === '7' && matches('tin_coffee_powder')) {
          Utils.setBlockState(block, 'peach:recipe', '5');
          Utils.consumeItem(player, selected);
          Utils.giveItem(player, 'peach:tin');
          Utils.playSound(block, 'extinguish.candle');
          return;
        }

        if (recipe === '6' && matches('chocolate_powder')) {
          Utils.setBlockState(block, 'peach:recipe', '5');
          Utils.consumeItem(player, selected);
          Utils.playSound(block, 'extinguish.candle');
          return;
        }

        // --- Entregas ---
        if (cupsNum > 1 && matches('cup') && right === '2') {
          const cupMap = {
            '2': 'peach:cup_milk',
            '3': 'peach:cup_honey',
            '4': 'peach:cup_coffee',
            '5': 'peach:cup_latte',
            '6': 'peach:cup_capuccino'
          };
          const giveId = cupMap[recipe];
          if (giveId) {
            Utils.setBlockState(block, 'peach:cups', String(cupsNum - 1));
            Utils.consumeItem(player, selected);
            Utils.giveItem(player, giveId);
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
        }

        if (cupsNum > 1 && recipe === '7' && matches('glass_bottle') && right === '2') {
          Utils.setBlockState(block, 'peach:cups', String(cupsNum - 1));
          Utils.consumeItem(player, selected);
          Utils.giveItem(player, 'peach:bottle_milk_chocolate');
          Utils.playSound(block, 'random.potion.brewed');
          return;
        }

        if (cupsNum === 1 && matches('cup') && right === '2') {
          const cupFinalMap = {
            '2': 'peach:cup_milk',
            '3': 'peach:cup_honey',
            '4': 'peach:cup_coffee',
            '5': 'peach:cup_latte',
            '6': 'peach:cup_capuccino'
          };
          const giveId = cupFinalMap[recipe];
          if (giveId) {
            Utils.setBlockState(block, 'peach:recipe', '0');
            Utils.setBlockState(block, 'peach:right', '0');
            Utils.setBlockState(block, 'peach:cups', '0');
            Utils.consumeItem(player, selected);
            Utils.giveItem(player, giveId);
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
        }

        if (cupsNum === 1 && recipe === '7' && matches('glass_bottle') && right === '2') {
          Utils.setBlockState(block, 'peach:recipe', '0');
          Utils.setBlockState(block, 'peach:right', '0');
          Utils.setBlockState(block, 'peach:cups', '0');
          Utils.consumeItem(player, selected);
          Utils.giveItem(player, 'peach:bottle_milk_chocolate');
          Utils.playSound(block, 'random.potion.brewed');
          return;
        }

        // --- Gelatinas: só após fervura ---
        if (right === '2' && matches('tin')) {
          const mapping = {
            '8': 'peach:tin_jello_o',
            '9': 'peach:tin_jello_p',
            '10': 'peach:tin_jello_w',
            '11': 'peach:tin_jello_c'
          };
          const out = mapping[recipe];
          if (out) {
            Utils.setBlockState(block, 'peach:recipe', '0');
            Utils.setBlockState(block, 'peach:right', '0');
            Utils.setBlockState(block, 'peach:cups', '0');
            Utils.consumeItem(player, selected);
            Utils.giveItem(player, out);
            Utils.playSound(block, 'random.potion.brewed');
            return;
          }
        }

      } catch (err) {}
    }
  });
});
