let currentAudioSource = null
let currentButton = null
let currentContainer = null

function resetPlayingStyle() {
	if (currentButton !== null) {
		currentButton.parentNode.classList.remove('pause')
	}
}

function pausePlayer() {
	document.getElementById('audio-player').pause()
	resetPlayingStyle()
}

function startPlayer(container, src) {
	document.getElementById('audio-player').play()
	container.classList.add('pause')
	document.getElementById('audio-player').addEventListener('ended', () => {
		onAudioEnded()
	})
}

function storeState(container, src) {
	currentAudioSource = src
	currentButton = container.querySelector('.play-button')
	currentContainer = container
}

function togglePlayPause(container, src) {
	if (currentAudioSource === src) {
		if (document.getElementById('audio-player').paused) {
			startPlayer(container, src)
		} else {
			pausePlayer()
		}
	} else {
		if (!document.getElementById('audio-player').paused) {
			pausePlayer()
		}
		document.getElementById('audio-player').src = src
		startPlayer(container, src)
	}
	storeState(container, src)
}

function onAudioEnded() {
	resetPlayingStyle()
	currentAudioSource = null
	currentButton = null
	currentContainer = null
}
