states.push({
	id: "sell",
	button: "Sell",
	action: "Haggling",
	duration: () => selectedItems.length * 100,
	step: () => selectedItems.length,
	requires: () => {
		if(selectedItems.length == 0) {
			receiveMessage({name:"[Merchant]", id:-1, style: ""}, "Please put your goods on display if you would like me to purchase them.");
			return false;
		}
		let salePrice = calculatePrice();
		let confirmSale = confirm(`Are you sure you want to sell these goods for ₩${salePrice}?`);
		return confirmSale;
	},
	start: () => {
		if(selectedItems.find(item => item.type == "contraband")) {
			receiveMessage({name:"[Merchant]", id:-1, style: ""}, "Oh my. This cargo is entirely against the rules. I will do you a favor and confiscate this before you run into trouble.");
			selectedItems = selectedItems.filter(item => item.type != "contraband");
			userData.inCargoHold = userData.inCargoHold.filter(item => item.type != "contraband");
		}
	},
	run: () => {
		selectedItems.forEach(item => {
			let index = userData.inCargoHold.indexOf(item);
			if(index > -1) {
				userData.inCargoHold.splice(index, 1);
				let returnedItem = sellItem(item);
				if(returnedItem){
					userData.inCargoHold.push(returnedItem);
				}
			}
		});
		receiveMessage({name:"[Merchant]", id:-1, style: ""}, "Pleasure doing business with you.");
	
		selectedItems = [];
	},
});

var marketMap = [
	{ type: "ironore", value: 1 },
	{ type: "silverore", value: 2 },
	{ type: "goldore", value: 5 },
	{ type: "platinumore", value: 10 },
	{ type: "rawdiamond", value: 100 },
	{ type: "iron", value: 10 },
	{ type: "silver", value: 20 },
	{ type: "gold", value: 50 },
	{ type: "platinum", value: 100 },
	{ type: "diamond", value: 1000 },
	{ type: "contraband", value: 17130 },
];

function calculatePrice() {
	return selectedItems.reduce((total, item) => {
		let marketRule = marketMap.find(market => market.type == item.type);
		if (!marketRule) {
			return total;
		}
		return total + marketRule.value;
	}, 0);
}

function sellItem(item) {
	let marketRule = marketMap.find(market => market.type == item.type);
	if (!marketRule) {
		return item;
	}
	userData.money += marketRule.value;
}