const fireConfirmModal = (event) => {
	Swal.fire({ title: 'Wirklich löschen?', showCancelButton: true, cancelButtonText: 'Abbrechen', icon: 'warning', confirmButtonText: "Löschen", showCloseButton: true })
		.then((result) => { if (result.isConfirmed) { htmx.trigger(event.target, 'confirmed'); } });
}


document.querySelectorAll("button[hx-trigger='confirmed']").forEach((value) => value.addEventListener("click", fireConfirmModal));

document.addEventListener("htmx:afterSwap", () => {
	document.querySelectorAll("button[hx-trigger='confirmed']").forEach((value) => value.addEventListener("click", fireConfirmModal));
});

const getCurrentTheme = () => {
	let current = localStorage.getItem("theme");

	if (current == null) {
		current = document.documentElement.getAttribute("data-theme");
	}

	if (current === null) {
		if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
			current = "dark";
		} else {
			current = "light";
		}
	}

	return current;
}

const switchTheme = () => {
	const isCurrentlyLight = getCurrentTheme() === "light";

	document.documentElement.setAttribute("data-theme", isCurrentlyLight ? "dark" : "light");
	document.querySelector("#theme-switcher use").setAttribute("href", `/static/feather-sprite.svg#${isCurrentlyLight ? "sun" : "moon"}`)
	localStorage.setItem("theme", isCurrentlyLight ? "dark" : "light");
}

const observer = new MutationObserver((mutationList, observer) => {
	for (const mut of mutationList) {
		for (const node of mut.addedNodes) {
			if (node.className?.includes("navbar")) {
				console.log("found");
				document.getElementById("theme-switcher")?.addEventListener("click", switchTheme);
				document.querySelector("#theme-switcher use")?.setAttribute("href", `/static/feather-sprite.svg#${getCurrentTheme() === "light" ? "moon" : "sun"}`)
			}
		}
	}
});

observer.observe(document, { childList: true, subtree: true });


const isCurrentlyLight = getCurrentTheme() === "light";
document.documentElement.setAttribute("data-theme", isCurrentlyLight ? "light" : "dark");
document.querySelector("#theme-switcher use")?.setAttribute("href", `/static/feather-sprite.svg#${isCurrentlyLight ? "moon" : "sun"}`)
document.getElementById("theme-switcher")?.addEventListener("click", switchTheme);
