<script lang="ts">
import Spacer from "$lib/Layout/Spacer.svelte";
import settings, { type Settings } from "$stores/settings";

type BooleanSettingsKeys<T> = {
	[K in keyof T]: T[K] extends boolean ? K : never;
};
type SettingsBooleanKeys = BooleanSettingsKeys<Settings>;

export let sectionBreak = false;
export let disabled = false;
export let text: string | (() => string);
export let setting: SettingsBooleanKeys[keyof SettingsBooleanKeys];
export let lineBreak = true;
export let onChange: () => void = () => {
	return;
};
export let invert = false;
export let id: string | null = null;

$: checked = setting
	? invert
		? !$settings[setting]
		: $settings[setting]
	: false;
$: field = text instanceof Function ? text() : text;

// const toggler = (key: keyof Settings) => [
// 	() =>
// 		settings.update((s) => {
// 			(s[key] as boolean) = true;

// 			$settings = s;

// 			return s;
// 		}),
// 	() =>
// 		settings.update((s) => {
// 			(s[key] as boolean) = false;

// 			$settings = s;

// 			return s;
// 		})
// ];

const check = (
	e: Event & { currentTarget: EventTarget & HTMLInputElement },
): void => {
	const checked = (e.target as HTMLInputElement).checked;

	if (setting) {
		settings.setKey(setting, invert ? !checked : checked);
		onChange();
	}
};

const flip = () => {
	if (setting) $settings[setting] = !$settings[setting];
};
</script>

<input type="checkbox" onchange={check} bind:checked {id} />

<span
  onclick={flip}
  onkeydown={() => {
    return;
  }}
  role="button"
  tabindex="0"
>
  {#if disabled}
    <strike>
      {field}
    </strike>
  {:else}
    {field}
  {/if}
</span>

<slot />

{#if lineBreak}
  <br />
{/if}

{#if sectionBreak}
  <Spacer />
{/if}
