import { resultSlot, liquidSlot, slotGen } from "./helpers.js";
import { cookTimeTotal } from "./helpers.js";
import { consumeItem, addResult } from "./helpers.js";

export default {
	name: "withering_dross",
	cookTime: cookTimeTotal,
	requiredTemp: "4",
	isValid: (inv, tempSlot) => {
		let boneSlot = -1, inkSlot = -1, witherRoseSlot = -1, wartSlot = -1;
		let filled = 0;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item) {
				filled++;
				if (item.typeId === "minecraft:bone" && boneSlot === -1) boneSlot = slot;
				else if (item.typeId === "minecraft:ink_sac" && inkSlot === -1) inkSlot = slot;
				else if (item.typeId === "minecraft:wither_rose" && witherRoseSlot === -1) witherRoseSlot = slot;
				else if (item.typeId === "minecraft:nether_wart" && wartSlot === -1) wartSlot = slot;
			}
		}
		const saltyFolly = inv.getItem(liquidSlot);
		const tankard = inv.getItem(slotGen);
		const result = inv.getItem(resultSlot);
		return boneSlot !== -1 && inkSlot !== -1 && witherRoseSlot !== -1 && wartSlot !== -1 &&
			   filled === 4 &&
			   saltyFolly && saltyFolly.typeId === "brewinandchewin:salty_folly" && saltyFolly.amount >= 1 &&
			   tankard && tankard.typeId === "brewinandchewin:tankard" && tankard.amount >= 1 &&
			   (!result || result.typeId === "brewinandchewin:withering_dross") &&
			   tempSlot && tempSlot.nameTag === "4";
	},
	onComplete: (inv, keg, overworld) => {
		let boneSlot = -1, inkSlot = -1, witherRoseSlot = -1, wartSlot = -1;
		for (let slot = 0; slot < 4; slot++) {
			const item = inv.getItem(slot);
			if (item && item.typeId === "minecraft:bone") boneSlot = slot;
			if (item && item.typeId === "minecraft:ink_sac") inkSlot = slot;
			if (item && item.typeId === "minecraft:wither_rose") witherRoseSlot = slot;
			if (item && item.typeId === "minecraft:nether_wart") wartSlot = slot;
		}
		if (boneSlot !== -1) consumeItem(inv, boneSlot, 1);
		if (inkSlot !== -1) consumeItem(inv, inkSlot, 1);
		if (witherRoseSlot !== -1) consumeItem(inv, witherRoseSlot, 1);
		if (wartSlot !== -1) consumeItem(inv, wartSlot, 1);
		
		const saltyFolly = inv.getItem(liquidSlot);
		if (saltyFolly) consumeItem(inv, liquidSlot, 1);
		
		const tankard = inv.getItem(slotGen);
		if (tankard) consumeItem(inv, slotGen, 1);
		
		addResult(inv, "brewinandchewin:withering_dross", 1);
		returnTaraToBuffer(inv, "brewinandchewin:tankard", 1);
		
		// Специальный XP для withering_dross
		const kegLoc = keg.location;
		const players = overworld.getPlayers({
			location: kegLoc,
			maxDistance: 5
		});
		if (players.length > 0) {
			overworld.spawnEntity("minecraft:xp_orb", {
				x: kegLoc.x + 0.5,
				y: kegLoc.y + 1,
				z: kegLoc.z + 0.5,
				amount: 2
			});
		}
	}
};
