function purchase(packId) {
	sendMessage(JSON.stringify({action: 'purchase', packId}))
}

function openPack(packId) {
	sendMessage(JSON.stringify({action: 'open-pack', packId}))
}

function getPackOwnership(packId) {
	sendMessage(JSON.stringify({action: 'is-owned', packId}))
}

function getPackPrice(packId) {
	sendMessage(JSON.stringify({action: 'get-price', packId}))
}

function purchaseFailed() {
	setPriceSpinnerVisible(false)
}

function updatePackOwnership(returnJson) {
	if (JSON.parse(returnJson).owned) {
		updatePrice('RESTORE PURCHASE')
		updatePurchaseStatus(JSON.parse(returnJson).packId)
	}
}

function escapeHtmlUsingParser(unsafe) {
	const parser = new DOMParser()
	const doc = parser.parseFromString(`<!doctype html><body>${unsafe}`, 'text/html')
	return doc.body.textContent || ''
}

function updatePackPrice(returnJson) {
	updatePrice('BUY ' + escapeHtmlUsingParser(JSON.parse(returnJson).price))
}

function updatePurchaseStatus(packId) {
	const productElement = document.querySelector(`div.product[data-product-id="${packId}"]`)
	if (productElement) {
		productElement.classList.add('purchased')
	}
	const priceElement = document.getElementById('buy-now')
	if (priceElement) {
		priceElement.classList.add('purchased')
	}
	setPriceSpinnerVisible(false)
	const packStatusElement = document.getElementById('pack-status')
	if (packStatusElement) {
		packStatusElement.classList.remove('unpurchased')
		packStatusElement.classList.add('purchased')
	}
	const goToPackElement = document.getElementById('go-to-pack')
	if (goToPackElement) {
		goToPackElement.style.display = 'flex'
	}
}

function updatePrice(price) {
	const priceElement = document.getElementById('price-value')
	if (priceElement) {
		priceElement.textContent = price
	}
}

function restorePurchases() {
	sendMessage(JSON.stringify({action: 'restore-purchases'}))
}
