var knownStations = []

function goToStation(station) {
	var url = new URL(window.location.href)
	url.pathname = 'view-station.html'
	url.searchParams.set('station', station)
	url.searchParams.set('date', new Date().toISOString())
	window.location.href = url.toString()
}

function searchNormalize(str) {
	return str
		.toLowerCase()
		.replaceAll('ă', 'a')
		.replaceAll('â', 'a')
		.replaceAll('î', 'i')
		.replaceAll('ș', 's')
		.replaceAll('ț', 't')
} 

var focusedElement = null

var _rebuildDebounce = null
var _rebuildRequested = false
function rebuildSuggestions() {
	if (_rebuildDebounce !== null) {
		_rebuildRequested = true
		return
	}
	
	_rebuildRequested = false
	_rebuildDebounce = 123

	var suggestionsArea = document.getElementById('suggestionsArea')
	while (suggestionsArea.childNodes.length > 0) {
		suggestionsArea.childNodes[0].remove()
	}

	var stationNameInput = document.getElementById('stationName')
	var stationName = searchNormalize(stationNameInput.value.trim())

	var suggestions = []
	if (!stationName) {
		suggestions = knownStations.slice()
	}
	else {
		for (var i = 0; i < knownStations.length; i++) {
			if (!searchNormalize(knownStations[i].name).includes(stationName)) {
				continue
			}
			suggestions.push(knownStations[i])
		}
		suggestions.sort((s1, s2) => {
			var s1n = searchNormalize(s1.name);
			var s2n = searchNormalize(s2.name);

			if (s1n.indexOf(stationName) != s2n.indexOf(stationName)) {
				return s1n.indexOf(stationName) - s2n.indexOf(stationName);
			}

			if (s1.stoppedAtBy.length != s2.stoppedAtBy.length) {
				return s2.stoppedAtBy.length - s1.stoppedAtBy.length;
			}

			return s1.name.localeCompare(s2.name);
		})
	}

	var foundInput = false
	suggestions.forEach(function (suggestion, index) {
		if (stationName == searchNormalize(suggestion.name)) {
			foundInput = true
		}
		var suggestionLi = document.createElement('li')
		suggestionsArea.appendChild(suggestionLi)

		setTimeout(function () {
			suggestionLi.classList.add('items')
			suggestionLi.tabIndex = index + 1
			suggestionLi.style.padding = '2px 0'

			function onAction(e) {
				goToStation(suggestion.name)
			}
			suggestionLi.addEventListener('click', onAction)
			suggestionLi.addEventListener('keypress', function (e) {
				if (e.key == 'Enter') {
					onAction(e)
				}
			})
			suggestionLi.addEventListener('focus', function (e) {
				focusedElement = suggestionLi
			})

			var stationNameP = document.createElement('p')
			suggestionLi.appendChild(stationNameP)

			stationNameP.textContent = suggestion.name
			stationNameP.classList.add('pri', 'stationName')

			// var trainCompanyP = document.createElement('p')
			// suggestionLi.appendChild(trainCompanyP)

			// trainCompanyP.textContent = suggestion.company
			// trainCompanyP.classList.add('thi')
		}, 0)
	})
	if (!foundInput && stationName) {
		var suggestionLi = document.createElement('li')
		suggestionsArea.appendChild(suggestionLi)

		suggestionLi.classList.add('items')
		suggestionLi.tabIndex = suggestions.length + 2
		suggestionLi.style.padding = '2px 0'

		function onAction(e) {
			goToStation(stationNameInput.value.trim())
		}
		suggestionLi.addEventListener('click', onAction)
		suggestionLi.addEventListener('keypress', function (e) {
			if (e.key == 'Enter') {
				onAction(e)
			}
		})
		suggestionLi.addEventListener('focus', function (e) {
			focusedElement = suggestionLi
		})

		var stationNameP = document.createElement('p')
		suggestionLi.appendChild(stationNameP)

		stationNameP.textContent = stationNameInput.value.trim()
		stationNameP.classList.add('pri', 'stationName')
	}

	setTimeout(function () {
		_rebuildDebounce = null
		if (_rebuildRequested) {
			rebuildSuggestions()
		}
	}, 500)
}

function lsk() {
	document.getElementById('stationName').focus()
}

function csk() {
	if (focusedElement == null) {
		return
	}

	if (focusedElement.id === 'stationName') {
		goToTrain(document.activeElement.value.trim())
	}
	else {
		focusedElement.click()
	}
}

window.addEventListener('load', function (e) {
	var stationName = document.getElementById('stationName')
	stationName.addEventListener('input', function (e) {
		rebuildSuggestions()
	})
	stationName.addEventListener('focus', function (e) {
		focusedElement = stationName
		document.getElementsByClassName('lsk')[0].textContent = ''
		document.getElementsByClassName('csk')[0].textContent = 'Search'
	})
	stationName.addEventListener('blur', function (e) {
		document.getElementsByClassName('lsk')[0].textContent = 'Search'
		document.getElementsByClassName('csk')[0].textContent = 'Select'
	})
	stationName.addEventListener('keypress', function (e) {
		if (e.key == 'Enter') {
			goToStation(stationName.value.trim())
		}
	})

	document.querySelectorAll('.lsk').forEach(function (lskElem) {
		lskElem.addEventListener('click', function (e) {
			lsk()
		})
	})
	document.querySelectorAll('.csk').forEach(function (cskElem) {
		cskElem.addEventListener('click', function (e) {
			csk()
		})
	})
	document.body.addEventListener('keydown', function (e) {
		if (e.key == 'SoftLeft') {
			lsk()
		}
		else if (e.key == 'Enter') {
			csk()
		}
	})

	fetch('https://scraper.infotren.dcdev.ro/v3/stations')
		.then(function (response) {
			return response.json()
		})
		.then(function (response) {
			knownStations = response
			knownStations.sort(function(a, b) { return b.stoppedAtBy.length - a.stoppedAtBy.length })
		})
		.then(function () {
			rebuildSuggestions()
		})
})