<script>

  export let size = "default";

  export let toggled = false;

  export let disabled = false;

  export let labelA = "Off";

  export let labelB = "On";

  export let labelText = "";

  export let hideLabel = false;

  export let id = uniqueId();

  export let readonly = false;

  export let readonlyText = "Read-only";

  export let invalid = false;

  export let invalidText = "";

  export let warn = false;

  export let warnText = "";

  export let helperText = "";

  export let name = undefined;

  export let form = undefined;

  export let value = "on";

  export let ref = null;

  import { createEventDispatcher } from "svelte";
  import WarningAltFilled from "../icons/WarningAltFilled.svelte";
  import WarningFilled from "../icons/WarningFilled.svelte";
  import { splitAriaNaming } from "../utils/aria-naming.js";
  import {
    buildFieldIds,
    joinDescribedBy,
    resolveStatusDescribedBy,
    resolveValidationVisibility,
  } from "../utils/field-status.js";
  import { fieldsetDisabled } from "../utils/fieldset-disabled.js";
  import { formReset } from "../utils/form-reset.js";
  import { uniqueId } from "../utils/unique-id.js";

  // A disabled `<fieldset>` around the component disables it too.
  let inDisabledFieldset = false;
  $: effectiveDisabled = disabled || inDisabledFieldset;

  const dispatch = createEventDispatcher();

  // A form reset restores the switch without a change event. Read the DOM
  // back, like the other form controls do. A read-only switch keeps its
  // state, so put the switch back instead of following the browser's
  // native-reset default.
  function handleFormReset() {
    if (!ref) return;
    if (readonly) {
      ref.checked = toggled;
      return;
    }
    toggled = ref.checked;
  }

  $: ({ showInvalid, showWarn } = resolveValidationVisibility({
    invalid,
    warn,
    disabled: effectiveDisabled,
    readonly,
  }));
  $: ({ helperId, errorId, readonlyId, warnId } = buildFieldIds(id));

  // Naming and description belong on the switch, not the wrapper.
  $: ({
    ariaLabel,
    ariaLabelledBy,
    ariaDescribedBy,
    rest: wrapperProps,
  } = splitAriaNaming($$restProps));
</script>

<div
  use:fieldsetDisabled={(value) => (inDisabledFieldset = value)}
  class:bx--form-item={true}
  class:bx--form-item--fit={true}
  class:bx--toggle--readonly={readonly}
  class:bx--toggle--invalid={showInvalid}
  class:bx--toggle--warning={showWarn}
  style:user-select="none"
  {...wrapperProps}
  on:click
  on:mouseover
  on:mouseenter
  on:mouseleave
>
  <input
    bind:this={ref}
    use:formReset={handleFormReset}
    role="switch"
    type="checkbox"
    class:bx--toggle-input={true}
    class:bx--toggle-input--small={size === "sm"}
    checked={toggled}
    aria-readonly={readonly || undefined}
    aria-invalid={showInvalid || undefined}
    aria-label={ariaLabel}
    aria-labelledby={ariaLabelledBy}
    aria-describedby={joinDescribedBy(
      readonly ? readonlyId : null,
      resolveStatusDescribedBy({
        showInvalid,
        showWarn,
        helperText,
        invalidText,
        warnText,
        errorId,
        warnId,
        helperId,
      }),
      ariaDescribedBy,
    )}
    on:click={(event) => {
      if (readonly) event.preventDefault();
    }}
    on:change={(event) => {
      if (readonly) return;
      // Read the input, not the Svelte state: the two disagree after a form
      // reset, and inverting stale state would undo the click.
      toggled = event.currentTarget.checked;
      dispatch("toggle", { toggled });
    }}
    on:change
    on:keydown={(event) => {
      if (event.key === "Enter") {
        event.preventDefault();
        // A held key repeats keydown; toggle once per press.
        if (!readonly && !event.repeat) ref?.click();
      }
    }}
    on:keyup
    on:focus
    on:blur
    disabled={effectiveDisabled}
    {id}
    {name}
    {form}
    {value}
  />
  <label
    aria-label={labelText || $$slots.labelChildren || ariaLabel !== undefined
      ? undefined
      : "Toggle"}
    for={id}
    class:bx--toggle-input__label={true}
  >
    {#if labelText || $$slots.labelChildren}
      <span class:bx--visually-hidden={hideLabel}>
        <slot name="labelChildren">{labelText}</slot>
      </span>
    {/if}
    <span
      class:bx--toggle__switch={true}
      style:margin-top={hideLabel ? 0 : undefined}
    >
      <!-- The state text is in flow: with none, render no spans, or their
        margin would widen an otherwise bare switch. -->
      {#if labelA || labelB || $$slots.labelA || $$slots.labelB}
        <span aria-hidden="true" class:bx--toggle__text--off={true}>
          <slot name="labelA">{labelA}</slot>
        </span>
        <span aria-hidden="true" class:bx--toggle__text--on={true}>
          <slot name="labelB">{labelB}</slot>
        </span>
      {/if}
    </span>
  </label>
  {#if readonly}
    <span id={readonlyId} class:bx--visually-hidden={true}>{readonlyText}</span>
  {/if}
  <div class:bx--toggle__validation-msg={true}>
    {#if showInvalid}
      <WarningFilled class="bx--toggle__invalid-icon" />
      {#if invalidText}
        <div id={errorId} class:bx--form-requirement={true} role="alert">
          {invalidText}
        </div>
      {/if}
    {:else if showWarn}
      <WarningAltFilled
        class="bx--toggle__invalid-icon bx--toggle__invalid-icon--warning"
      />
      {#if warnText}
        <div id={warnId} class:bx--form-requirement={true}>{warnText}</div>
      {/if}
    {/if}
  </div>
  {#if helperText && !showInvalid && !showWarn}
    <div
      id={helperId}
      class:bx--form__helper-text={true}
      class:bx--form__helper-text--disabled={effectiveDisabled}
    >
      {helperText}
    </div>
  {/if}
</div>
