const STAGE_BY_MOD = Object.freeze({
	// feudal
	toms_storage: 'feudal',

	// steam
	bellsandwhistles: 'steam',
	sliceanddice: 'steam',

	// industrial
	immersiveengineering: 'industrial',

	// electronic
	pneumaticcraft: 'electronic',
	refinedstorage: 'electronic',
	railwaysnavigator: 'electronic',
	ae2: 'electronic',
	mekanism: 'electronic',
	mekanismgenerators: 'electronic',
	computercraft: 'electronic',

	// futuristic
	oritech: 'futuristic',
})

const BLOCK_BY_STAGE = Object.freeze({
	'minecraft:campfire':         'flint',
	'minecraft:furnace':          'flint',
	'minecraft:blast_furnace':    'iron',
	'minecraft:enchanting_table': 'feudal',

	// Oritech
	'oritech:assembler_block': 'electronic',
	'oritech:foundry_block':   'electronic',
	'oritech:machine_core_3':  'electronic',
	'oritech:machine_core_4':  'electronic',
	'oritech:machine_core_5':  'electronic',
	'oritech:machine_core_6':  'electronic',
	'oritech:machine_core_7':  'electronic',
})

const WHITELIST_BY_MOD = {
	oritech: Object.freeze({
		'oritech:assembler_block': true,
		'oritech:foundry_block': true,
		'oritech:machine_core_3': true,
		'oritech:machine_core_4': true,
		'oritech:machine_core_5': true,
		'oritech:machine_core_6': true,
		'oritech:machine_core_7': true,
	}),
	mekanism: Object.freeze({
		'mekanism:block_salt': true
	}),
	immersiveengineering: Object.freeze({
		'immersiveengineering:hemp': true,
		'immersiveengineering:crate': true,
		'immersiveengineering:alloy_smelter': true,
		'immersiveengineering:alloybrick': true,
		'immersiveengineering:wooden_barrel': true
	})
}

function GetItemModAndID(id) {
	const words = id.split(':')
	if (!words) return [];
	return [words[0], `${ words[0] }:${ words[1] }`];
}

function getStageByModOrBlockId(mod, id) {
	const wl = WHITELIST_BY_MOD[mod];

	// Whitelisted block → allow
	if (wl && wl[id]) {
		return undefined;
	}

	// Block-specific stage
	const blockStage = BLOCK_BY_STAGE[id];
	if (blockStage) {
		return blockStage;
	}

	// Mod-level stage
	return STAGE_BY_MOD[mod];
}

BlockEvents.rightClicked(event => {
	const player = event.player
	if (!player) return

	const block = event.block
	if (!block) return

	// Fucking String Object...
	const id = block.getId();
	if (!id) return

	const [mod, itemId] = GetItemModAndID(id)
	if (!mod) return

	// not gated → ignore
	const requiredStage = getStageByModOrBlockId(mod, itemId);
	if (!requiredStage) return

	// stage check → block interaction if missing
	if (!AStages.playerHasStage(requiredStage, player)) {
		player.tell(`§cYou may not interact with this block right now.`)
		event.cancel()
	}
})
