<script>
    import { onMount } from "svelte";
    import "./ThemeToggle.css";

    let theme = "light";

    function applyTheme(t) {
        theme = t;
        try {
            document.documentElement.setAttribute("data-theme", t);
            localStorage.setItem("theme", t);
        } catch (e) {
            // ignore in SSR or restricted environments
        }
    }

    function toggle() {
        applyTheme(theme === "dark" ? "light" : "dark");
    }

    onMount(() => {
        try {
            const saved = localStorage.getItem("theme");
            if (saved) {
                applyTheme(saved);
                return;
            }
            const prefersDark =
                window.matchMedia &&
                window.matchMedia("(prefers-color-scheme: dark)").matches;
            applyTheme(prefersDark ? "dark" : "light");
        } catch (e) {
            // safe fallback
            applyTheme("light");
        }
    });
</script>

<button
    class="theme-toggle"
    on:click={toggle}
    aria-pressed={theme === "dark"}
    title="Toggle dark mode"
>
    {#if theme === "dark"}
        ○
    {:else}
        ●
    {/if}
</button>
