function sendMessage(message) {
	if (window.webkit) {
		window.webkit.messageHandlers.messages.postMessage(message)
	} else if (typeof Android !== 'undefined' && Android.onJsCallback) {
		Android.onJsCallback(message)
	} else {
		console.error(`Neither webkit not Android was found to send  ${message}`)
		return false
	}
	return true
}

function closeWindow() {
	sendMessage('close')
}

function showDialog(dialogJson) {
	const dialogOptions = dialogJson
	const overlay = document.createElement('div')
	overlay.classList.add('overlay')
	document.body.appendChild(overlay)

	const dialog = document.createElement('dialog')
	dialog.classList.add('dialog')
	dialog.setAttribute('open', 'open')

	dialog.addEventListener('close', () => {
		document.body.removeChild(overlay)
	})

	const title = document.createElement('h2')
	title.textContent = dialogOptions.title
	title.classList.add('dialog-header')
	dialog.appendChild(title)

	const prompt = document.createElement('p')
	prompt.textContent = dialogOptions.prompt
	prompt.classList.add('dialog-text')
	dialog.appendChild(prompt)

	const buttonContainer = document.createElement('div')
	buttonContainer.classList.add('dialog-button-container')

	dialogOptions.buttons.forEach((buttonText) => {
		const button = document.createElement('button')
		button.classList.add('koala-button')
		button.textContent = buttonText
		button.addEventListener('click', () => {
			dialog.close()
			if (dialog.parentNode) {
				dialog.parentNode.removeChild(dialog);
			}
			sendMessage(
				JSON.stringify({
					action: 'dialog-button',
					button: buttonText,
					packId: dialogOptions.packId,
				})
			)
		})
		buttonContainer.appendChild(button)
	})

	dialog.appendChild(buttonContainer)
	overlay.appendChild(dialog)
}

function getImagePath(product) {
	return `packs/${product.productId}/pack.jpg`
}

function getAudioDemoPath(product) {
	return `packs/${product.productId}/pack.m4a`
}


function setPriceSpinnerVisible(visible) {
	const spinner = document.getElementById('price-spinner')
	if (!spinner) return
	spinner.style.display = visible ? 'block' : 'none'
}