<script lang="ts">
	import type { IconProps } from "@lucide/svelte";
	import type { Component } from "svelte";
	import Switch from "$lib/components/ui/switch/switch.svelte";
	import { Label } from "$lib/components/ui/label";
	import { eventTarget } from "$lib/services/localStore.svelte";

	let {
		icon: Icon,
		text,
		onchange,
		disabled,
		localStorageKey,
		value = $bindable(
			localStorageKey
				? localStorage.getItem(localStorageKey) === "true"
				: false,
		),
	}: {
		icon?: Component<IconProps>;
		text: string;
		onchange?: () => void;
		disabled?: boolean;
		value?: boolean;
		localStorageKey?: string;
	} = $props();
</script>

<div class="flex">
	<Label style="width: 100%;" for="settings-toggle">
		{#if Icon}
			<Icon />
		{/if}
		{text}
	</Label>
	<Switch
		{disabled}
		bind:checked={value}
		onCheckedChange={() => {
			if (onchange) onchange();
			if (localStorageKey) {
				localStorage.setItem(localStorageKey, value ? "true" : "false");
				eventTarget.dispatchEvent(
					new CustomEvent("localStorageChanged", {
						detail: { key: localStorageKey, value },
					}),
				);
			}
		}}
		id="settings-toggle"
	/>
</div>
