const controls = document.querySelector(".controls");
const song = document.querySelector("iframe.song").contentWindow;

// Autoscroll
let scroll;
let scrollTimeout = 60;
const minTimeout = 10;
const maxTimeout = 120;
const scrollIncrement = 20;

function pageScroll() {
	song.scrollBy(0, 1);
	scroll = setTimeout(pageScroll, scrollTimeout);
}

function updateScrollSpeed() {
	if (controls.querySelector("#autoscroll").classList.contains("active")) {
		clearTimeout(scroll);
		scroll = setTimeout(pageScroll, scrollTimeout);
	}
}

controls.querySelector("#autoscroll-increase").addEventListener("click", () => {
	scrollTimeout = Math.max(minTimeout, scrollTimeout - scrollIncrement);
	updateScrollSpeed();
});

controls.querySelector("#autoscroll-decrease").addEventListener("click", () => {
	scrollTimeout = Math.min(maxTimeout, scrollTimeout + scrollIncrement);
	updateScrollSpeed();
});

controls.querySelector("#autoscroll").addEventListener("click", function() {
	this.classList.toggle("active");
	if (this.classList.contains("active")) {
		pageScroll();
	} else {
		clearTimeout(scroll);
	}
});

// Scaling
function pageScale(value) {
	if (value === 0) {
		song.document.body.style.transform = "scale(1)";
		return;
	}
	const currentScale =
		parseFloat(song.document.body.style.transform.split("scale(")[1]) || 1;
	song.document.body.style.transform = "scale(" + (currentScale + value) + ")";
}

controls
	.querySelector("#font-size-increase")
	.addEventListener("click", () => pageScale(0.1));
controls
	.querySelector("#font-size-decrease")
	.addEventListener("click", () => pageScale(-0.1));
controls
	.querySelector("#font-size-reset")
	.addEventListener("click", () => pageScale(0));

// Display the controls on JS-enabled browsers
window.addEventListener("load", () => (controls.classList.remove = "hidden"));
