<script lang="ts">
  import { run } from 'svelte/legacy';

  import settings, { type Settings } from '$stores/settings';

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

  interface Props {
    sectionBreak?: boolean;
    disabled?: boolean;
    text: string | (() => string);
    setting: SettingsBooleanKeys[keyof SettingsBooleanKeys];
    lineBreak?: boolean;
    onChange?: () => void;
    invert?: boolean;
    id?: string | null;
    children?: import('svelte').Snippet;
  }

  let {
    sectionBreak = false,
    disabled = false,
    text,
    setting,
    lineBreak = true,
    onChange = () => {
      return;
    },
    invert = false,
    id = null,
    children
  }: Props = $props();

  let checked = $state(false);
  run(() => {
    checked = setting ? (invert ? !$settings[setting] : $settings[setting]) : false;
  });
  let field = $derived(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>

{@render children?.()}

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

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