<script>
    import { onMount } from "svelte";
    import "./ThemeToggle.css";
    import { applyTheme as persistTheme, getSavedTheme } from "../../lib/theme";

    let theme = "light";

    function setTheme(t) {
        theme = t;
        persistTheme(t);
    }

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

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

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