function setAppliedMode(mode) {
	document.documentElement.dataset.appliedMode = mode;

	if (mode === "darkMode") {
		document
			.querySelector("meta[name='theme-color']")
			.setAttribute("content", "black");
	}
	else {
		document
			.querySelector("meta[name='theme-color']")
			.setAttribute("content", "hsl(48, 77%, 95%)");
	}
}

function setAppliedModeToSystem() {
	if (matchMedia("(prefers-color-scheme: dark)").matches) {
		setAppliedMode("darkMode")
	}
	else {
		setAppliedMode("lightMode")
	}
}

function selectMode(selectTag) {
	if (selectTag.options[selectTag.selectedIndex].text == "☀️ Light") {
		setAppliedMode("lightMode");
		if (typeof(Storage) !== "undefined") {
			localStorage.mode = "lightMode";
		}
	}
	else if (selectTag.options[selectTag.selectedIndex].text == "🌙 Dark") {
		setAppliedMode("darkMode");
		if (typeof(Storage) !== "undefined") {
			localStorage.mode = "darkMode";
		}
	}
	else {
		setAppliedModeToSystem();
		if (typeof(Storage) !== "undefined") {
			localStorage.mode = "system";
		}
	}
}

function setLightDarkSelect() {
	switch (localStorage.mode) {
		case "lightMode":
			document.getElementById("lightDarkSelect").selectedIndex = 0;
			break;
		case "darkMode":
			document.getElementById("lightDarkSelect").selectedIndex = 1;
			break;
		default:
			document.getElementById("lightDarkSelect").selectedIndex = 2;
			break;
	}
}

// on page load with default system mode
if (typeof(Storage) !== "undefined") { // check browser support for localStorage

	// Code for localStorage/sessionStorage.
	if (localStorage.mode) {
		if (localStorage.mode === "lightMode") {
			setAppliedMode("lightMode")
		}
		else if (localStorage.mode === "darkMode") {
			setAppliedMode("darkMode")
		}
		else {
			setAppliedModeToSystem()
		}
	}
	else {
		// initialize localStorage.mode with default value "system"
		localStorage.mode = "system"

		// checks system setting and matches
		setAppliedModeToSystem()
	}

	setLightDarkSelect();
}
else {
	setAppliedModeToSystem();
	document.getElementById("lightDarkSelect").selectedIndex = 2;
}
