<script lang="ts">
    import { browser } from '$app/environment';

    export let darkMode: boolean = true;

    function onThemeSwitch() {
        darkMode = !darkMode;

        localStorage.setItem('theme', darkMode ? 'dark' : 'light');

        darkMode
            ? document.documentElement.classList.add('dark')
            : document.documentElement.classList.remove('dark');
    }

    
    if (browser) {
        if (
            localStorage.theme === 'dark' ||
            (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)
        ) {
            document.documentElement.classList.add('dark');
            darkMode = true;
        } else {
            document.documentElement.classList.remove('dark');
            darkMode = false;
        }
    }
</script>

<style>
    input {
        display: none;
    }

    .switch {
        position: absolute;
        top: 0em;
        right: 0em;
        display: inline-block;
        width: 3.75em;
        height: 2.125em;
    }

    .slider {
        position: absolute;
        cursor: pointer;
        background-color: var(--bg-grad-4);
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        -webkit-transition: .4s;
        transition: .4s;
    }

    .slider:before {
        position: absolute;
        content: "";
        height: 80%;
        width: 45%;
        left: 4px;
        bottom: 4px;
        background-color: white;
        -webkit-transition: .4s;
        transition: .4s;
    }
    input:checked + .slider {
        background-color: var(--bg-grad-1);
    }

    input:checked + .slider:before {
        background: var(--bg);
    }

    input:checked + .slider:before {
        -webkit-transform: translateX(1.625em);
        -ms-transform: translateX(1.625em);
        transform: translateX(1.625em);
    }

    .slider.round {
        border-radius: 2.125em;
    }

    .slider.round:before {
        border-radius: 50%;
    }
</style>

<svelte:head>
    <link rel="stylesheet" href={`/themes/${darkMode ? 'dark' : 'light'}.css`} />
</svelte:head>


<div class="toggle-wrapper not-required">
    <label class="switch">
        <input type="checkbox" checked={darkMode} on:click={onThemeSwitch}>
        <span class="slider round"></span>
    </label>
</div>