---
import { Icon } from "astro-icon/components";
---

<theme-toggle class="sticky top-0">
	<button
		class="sticky top-0 flex h-8 w-8 items-center justify-center rounded-lg drop-shadow-[0px_1.5px_1.5px_rgba(0,0,0,0.175)] hover:text-accent-two"
		type="button"
	>
		<span class="sr-only">Dark Theme</span>
		<Icon
			aria-hidden="true"
			class="absolute start-1/2 top-1/2 h-6 w-6 -translate-x-1/2 -translate-y-1/2 scale-100 opacity-100 transition-all dark:scale-0 dark:opacity-0"
			focusable="false"
			name="solar:sun-bold"
		/>
		<Icon
			aria-hidden="true"
			class="absolute start-1/2 top-1/2 h-6 w-6 -translate-x-1/2 -translate-y-1/2 scale-0 opacity-0 transition-all dark:scale-100 dark:opacity-100"
			focusable="false"
			name="solar:moon-bold"
		/>
	</button>
</theme-toggle>

<script>
	// Note that if you fire the theme-change event outside of this component, it will not be reflected in the button's aria-checked attribute. You will need to add an event listener if you want that.
	import { rootInDarkMode } from "@/utils/domElement";

	class ThemeToggle extends HTMLElement {
		connectedCallback() {
			const button = this.querySelector<HTMLButtonElement>("button")!;
			// Set aria role value
			button.setAttribute("role", "switch");
			button.setAttribute("aria-checked", String(rootInDarkMode()));

			// Button event
			button.addEventListener("click", () => {
				// Invert theme
				let themeChangeEvent = new CustomEvent("theme-change", {
					detail: {
						theme: rootInDarkMode() ? "light" : "dark",
					},
				});
				// Dispatch event -> ThemeProvider.astro
				document.dispatchEvent(themeChangeEvent);

				// Set the aria-checked attribute
				button.setAttribute("aria-checked", String(rootInDarkMode()));
			});
		}
	}

	customElements.define("theme-toggle", ThemeToggle);
</script>
