<script>
    import "./Toggle.css";
    import { createEventDispatcher, onMount } from "svelte";

    export let checked = false;
    export let disabled = false;
    export let size = "md"; // 'sm' | 'md' | 'lg'
    export let ariaLabel = "Toggle";
    export let label = ""; // text to display next to toggle
    export let description = ""; // optional description text below

    const dispatch = createEventDispatcher();
    let btn;

    onMount(() => {
        const style = getComputedStyle(btn);
        if (!("checked" in $$props)) {
            const v = style.getPropertyValue("--toggle-default-checked").trim();
            if (v === "true" || v === "1") checked = true;
            else if (v === "false" || v === "0") checked = false;
        }
        if (!("disabled" in $$props)) {
            const d = style
                .getPropertyValue("--toggle-default-disabled")
                .trim();
            if (d === "true" || d === "1") disabled = true;
            else if (d === "false" || d === "0") disabled = false;
        }
    });

    function toggle() {
        if (disabled) return;
        checked = !checked;
        dispatch("change", { checked });
        dispatch("input", { checked });
    }
</script>

<button
    bind:this={btn}
    type="button"
    class="toggle {size} {checked ? 'on' : 'off'}"
    role="switch"
    aria-checked={checked}
    aria-label={label || ariaLabel}
    on:click={toggle}
    {disabled}
>
    <span class="track">
        <span class="knob"></span>
    </span>
    {#if label}
        <span class="toggle-label-wrapper">
            <span class="toggle-label">{label}</span>
            {#if description}
                <span class="toggle-description">{description}</span>
            {/if}
        </span>
    {/if}
</button>

<!--
Usage:
<Toggle bind:checked on:change={(e) => console.log(e.detail.checked)} />

CSS variables (scope to the element or a parent):
--toggle-default-checked: true | false
--toggle-default-disabled: true | false
--toggle-on-bg: color
--toggle-off-bg: color
--toggle-knob: color
--primary-color: used as fallback for on color
--toggle-width / --toggle-height can be overridden per size
-->
