<script lang="ts">
  import { onMount } from "svelte";
  import { writable } from "svelte/store";
  import IconSun from "~icons/tabler/Sun";
  import IconMoon from "~icons/tabler/Moon";

  let theme = writable("");

  $: if ($theme && "document" in globalThis) {
    document.documentElement.classList.remove("light", "dark");
    document.documentElement.classList.add($theme);
    localStorage.setItem("theme", $theme);
  }

  function toggleTheme() {
    theme.update((t) => (t === "light" ? "dark" : "light"));
  }

  onMount(() => {
    theme.set(localStorage.getItem("theme") || "dark");
  });
</script>

<button class="block w-6 h-6" on:click={toggleTheme} title="toggle dark mode">
  <IconMoon class="w-6 h-6 icon-tabler-moon" />
  <IconSun class="w-6 h-6 icon-tabler-sun" />
</button>

<style>
  button :global(path) {
    stroke-width: 1.5px !important;
  }

  button > :global(.icon-tabler-moon) {
    display: block;
  }

  button > :global(.icon-tabler-sun) {
    display: none;
  }

  :global(.dark .icon-tabler-moon) {
    display: none !important;
  }
  :global(.dark .icon-tabler-sun) {
    display: block !important;
  }
</style>
