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

<div class="switch">
    <Icon name="mdi:language-javascript" title="Theme switching needs JS to be enabled." data-theme-ph />
    <Icon name="mdi:white-balance-sunny" title="Switch to dark theme" data-theme-sun />
    <Icon name="mdi:weather-night" title="Switch to light theme" data-theme-moon />
</div>

<script>
    // Get and delete placeholder (JS is enabled)
    const placeHolder = document.querySelectorAll("[data-theme-ph]");
    placeHolder.forEach(e => e.remove());

    const moons = document.querySelectorAll("[data-theme-moon]");
    const suns = document.querySelectorAll("[data-theme-sun]");

    const current = document.documentElement.attributes.getNamedItem('data-theme')?.value ?? "dark";

    if (current === "dark") {
        moons.forEach(m => m.classList.add("selected"));
    } else {
        suns.forEach(s => s.classList.add("selected"));
    }

    const switchThemeDark = () => {
        document.dispatchEvent(new CustomEvent('set-theme', { detail: 'dark' }));
        moons.forEach(m => m.classList.remove("fadeOut"));
        moons.forEach(m => m.classList.add("fadeIn"));
        suns.forEach(s => s.classList.remove("fadeIn"));
        suns.forEach(s => s.classList.add("fadeOut"));
    }

    const switchThemeLight = () => {
        document.dispatchEvent(new CustomEvent('set-theme', { detail: 'light' }));
        moons.forEach(m => m.classList.remove("fadeIn"));
        moons.forEach(m => m.classList.add("fadeOut"));
        suns.forEach(s => s.classList.remove("fadeOut"));
        suns.forEach(s => s.classList.add("fadeIn"));
    }

    moons.forEach(m => m.addEventListener("click", switchThemeLight));
    suns.forEach(s => s.addEventListener("click", switchThemeDark));
</script>
<style lang="scss">
    .switch {
    position: relative;
    width: 1.5em;
    height: 1.5em;
    cursor: pointer;

    & > * {
        position: absolute;
        opacity: 0;
        transform: translate(0, 100%);
    }

    & > .selected {
        opacity: 1;
        transform: translate(0, 0);
    }

    .fadeOut {
        animation: fadeOut 0.2s ease-in-out;
        animation-fill-mode: forwards;
    }

    .fadeIn {
        animation: fadeIn 0.2s ease-in-out;
        animation-fill-mode: forwards;
    }

    .placeHolder {
        opacity: 1 !important;
        transform: translate(0, 0) !important;
    }
}

@keyframes fadeOut {
    from {
        opacity: 1;
        transform: translate(0, 0);
    }
    to {
        opacity: 0;
        transform: translate(0, -100%);
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translate(0, 100%);
    }
    to {
        opacity: 1;
        transform: translate(0, 0);
    }
}
</style>