<script>

  export let value = [];

  export let size = undefined;

  export let placeholder = "";

  export let disabled = false;

  export let readonly = false;

  export let required = false;

  export let labelText = "";

  export let hideLabel = false;

  export let helperText = "";

  export let invalid = false;

  export let invalidText = "";

  export let warn = false;

  export let warnText = "";

  export let tagPlacement = "inline";

  export let delimiter = ",";

  export let addOnPaste = true;

  export let addOnBlur = false;

  export let normalize = (raw) => raw.trim();

  export let allowDuplicates = false;

  export let isDuplicate = (a, b) => a.toLowerCase() === b.toLowerCase();

  export let validate = () => true;

  export let max = undefined;

  export let removeTagText = "Remove";

  export let duplicateText = "This tag has already been added";

  export let requiredText = "Add at least one tag";

  export let invalidTagText = "This tag isn't valid";

  export let maxText = "You've reached the maximum number of tags";

  export let instructionsText =
    "Press Enter to add a tag. Press Backspace in an empty field to move to the tags, then Delete to remove one.";

  export let addedText = (tags, count) =>
    `${tags.length === 1 ? tags[0] : `${tags.length} tags`} added. ${count} ${count === 1 ? "tag" : "tags"}.`;

  export let removedText = (tag, count) =>
    `${tag} removed. ${count} ${count === 1 ? "tag" : "tags"}.`;

  export let id = uniqueId();

  export let name = undefined;

  export let ref = null;

  import { createEventDispatcher, getContext, tick } from "svelte";
  import { createStatusAnnouncer } from "../ListBox/menu-status.js";
  import Tag from "../Tag/Tag.svelte";
  import TagSet from "../TagSet/TagSet.svelte";
  import { FORM_SIZE_CONTEXT_KEY } from "../constants/context-keys.js";
  import EditOff from "../icons/EditOff.svelte";
  import WarningAltFilled from "../icons/WarningAltFilled.svelte";
  import WarningFilled from "../icons/WarningFilled.svelte";
  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 { isImeComposition } from "../utils/ime-composition.js";
  import {
    getLayoutDirection,
    resolveLayoutDirection,
  } from "../utils/layout-direction.js";
  import { normalizeFieldSize } from "../utils/size-aliases.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();

  const formSize = getContext(FORM_SIZE_CONTEXT_KEY);
  const layoutDirection = getLayoutDirection();
  $: effectiveSize = normalizeFieldSize(size ?? $formSize);
  $: tagSize =
    effectiveSize === "xs" || effectiveSize === "sm"
      ? effectiveSize
      : effectiveSize === "xl"
        ? "lg"
        : "default";

  // Restored when the owning form resets.
  const initialValue = value.slice();

  let rootRef = null;
  let fieldRef = null;
  let draft = "";
  let focused = false;
  let statusText = "";
  // Clears the region before each message, so a repeat is announced too.
  const announceStatus = createStatusAnnouncer((text) => (statusText = text));
  let rejectionText = "";

  $: interactive = !effectiveDisabled && !readonly;
  $: ({ showInvalid, showWarn } = resolveValidationVisibility({
    invalid: invalid || !!rejectionText,
    warn,
    disabled: effectiveDisabled,
    readonly,
  }));
  $: errorText = invalid ? invalidText : rejectionText;
  $: ({ helperId, errorId, warnId } = buildFieldIds(id));
  $: instructionsId = `instructions-${id}`;

  // `required` alone is satisfied by text that isn't a tag yet, and that
  // text isn't submitted.
  $: ref?.setCustomValidity(
    required && value.length === 0 && draft !== "" ? requiredText : "",
  );

  $: delimiterPattern =
    delimiter instanceof RegExp
      ? // `g` and `y` would make the paste check depend on `lastIndex`.
        new RegExp(delimiter.source, delimiter.flags.replace(/[gy]/g, ""))
      : new RegExp(
          (Array.isArray(delimiter) ? delimiter : [delimiter])
            .filter(Boolean)
            .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
            .join("|") || "$^",
        );

  // Rejoins rejected pieces that go back into the text input.
  $: joiner =
    typeof delimiter === "string"
      ? delimiter
      : Array.isArray(delimiter) && delimiter[0]
        ? delimiter[0]
        : ",";

  function split(text, pattern = delimiterPattern) {
    // `split` puts each capture group's text between the pieces; drop it.
    // An empty match has one entry per group, plus the match itself.
    const stride =
      new RegExp(`${pattern.source}|`, pattern.flags).exec("")?.length ?? 1;
    return text.split(pattern).filter((_, i) => i % stride === 0);
  }

  function reject(reason, tag, message) {
    rejectionText =
      reason === "duplicate"
        ? duplicateText
        : reason === "max"
          ? maxText
          : (message ?? "");
    dispatch("invalid", { value: tag, reason, message });
  }

  function addTags(raws, source) {
    const accepted = [];
    const rejected = [];

    for (const raw of raws) {
      const tag = normalize(raw);
      if (!tag) continue;

      if (
        !allowDuplicates &&
        [...value, ...accepted].some((existing) => isDuplicate(existing, tag))
      ) {
        reject("duplicate", tag);
        rejected.push(raw);
        continue;
      }

      if (max != null && value.length + accepted.length >= max) {
        reject("max", tag);
        rejected.push(raw);
        continue;
      }

      const result = validate(tag);
      if (result !== true) {
        reject(
          "validate",
          tag,
          (typeof result === "string" && result) || invalidTagText,
        );
        rejected.push(raw);
        continue;
      }

      if (!dispatch("add", { value: tag, source }, { cancelable: true })) {
        rejected.push(raw);
        continue;
      }

      accepted.push(tag);
    }

    if (accepted.length > 0) {
      if (rejected.length === 0) rejectionText = "";
      value = [...value, ...accepted];
      announceStatus(addedText(accepted, value.length));
      dispatch("change", value);
    }

    return rejected;
  }

  function setDraft(next) {
    draft = next;
    if (ref && ref.value !== next) ref.value = next;
  }

  function commitDraft(source) {
    if (!draft.trim()) return;
    const rejected = addTags([draft], source);
    setDraft(rejected[0] ?? "");
  }

  function handleTagClose({ detail }) {
    if (!interactive) return;
    const { index } = detail;
    const tag = value[index];
    if (tag === undefined) return;
    if (!dispatch("remove", { value: tag, index }, { cancelable: true })) {
      return;
    }

    const hadFocus = rootRef?.contains(document.activeElement);
    value = value.filter((_, i) => i !== index);
    rejectionText = "";
    announceStatus(removedText(tag, value.length));
    dispatch("change", value);

    // With no tag left to take focus, keep it in the field. `TagSet` moves
    // focus to a neighbouring tag otherwise.
    if (hadFocus && value.length === 0) tick().then(() => ref?.focus());
  }

  function focusTag(index) {
    const buttons = rootRef?.querySelectorAll(
      ".bx--tag__close-icon:not(:disabled)",
    );
    if (!buttons?.length) return;
     (
      buttons[index < 0 ? buttons.length + index : index]
    )?.focus();
  }

  function pointsToTags(key) {
    if (key !== "ArrowLeft" && key !== "ArrowRight") return false;
    const rtl = resolveLayoutDirection($layoutDirection, ref) === "rtl";
    return key === (rtl ? "ArrowRight" : "ArrowLeft");
  }

  function handleInputKeydown(event) {
    // Enter that commits an IME composition is not an add.
    if (isImeComposition(event) || !interactive) return;

    if (event.key === "Enter") {
      if (!draft.trim()) return;
      event.preventDefault();
      commitDraft("enter");
      return;
    }

    const atStart =
      ref?.selectionStart === 0 && ref?.selectionEnd === 0 && value.length > 0;

    // A held Backspace that just emptied the field must not run on into the
    // tags: only a fresh press moves there.
    if (event.key === "Backspace" && atStart && !event.repeat) {
      event.preventDefault();
      focusTag(-1);
    } else if (atStart && pointsToTags(event.key)) {
      event.preventDefault();
      focusTag(-1);
    } else if (event.key === "Home" && draft === "" && value.length > 0) {
      event.preventDefault();
      focusTag(0);
    }
  }

  function handleTagKeydown(event) {
    const target = event.target;
    if (!(target instanceof HTMLElement)) return;
    if (!target.matches(".bx--tag__close-icon")) return;

    const buttons = Array.from(
      rootRef?.querySelectorAll(".bx--tag__close-icon:not(:disabled)") ?? [],
    );
    const isLast = buttons[buttons.length - 1] === target;

    if (
      event.key === "Escape" ||
      event.key === "End" ||
      (isLast &&
        (event.key === "ArrowLeft" || event.key === "ArrowRight") &&
        !pointsToTags(event.key))
    ) {
      event.preventDefault();
      ref?.focus();
    }
  }

  function handleInput(event) {
    draft = event.currentTarget.value;
    rejectionText = "";
    // An IME's text isn't final until the composition ends, which
    // `handleCompositionEnd` splits.
    if (event.isComposing) return;
    // `handlePaste` let the browser paste as-is; don't split it here.
    if (!addOnPaste && event.inputType === "insertFromPaste") return;
    splitDraft();
  }

  function handleCompositionEnd(event) {
    draft = event.currentTarget.value;
    splitDraft();
  }

  function splitDraft() {
    if (!interactive) return;
    const parts = split(draft);
    if (parts.length < 2) return;
    // Everything before the last delimiter is complete; the rest is still
    // being typed. Rejected text goes back without the delimiter after it,
    // so the next keystroke doesn't split and reject it again.
    const rest = parts.pop() ?? "";
    // Writing the value moves the caret to the end; keep it as far from the
    // end as it was, for a delimiter typed mid-text.
    const fromEnd = draft.length - (ref?.selectionEnd ?? draft.length);
    const rejected = addTags(parts, "delimiter");
    const next = rejected.join(joiner) + rest;
    setDraft(next);
    const caret = Math.max(0, next.length - fromEnd);
    ref?.setSelectionRange(caret, caret);
  }

  function handlePaste(event) {
    if (!addOnPaste || !interactive || !ref) return;
    const text = event.clipboardData?.getData("text") ?? "";
    const pattern = new RegExp(
      `${delimiterPattern.source}|\\r?\\n`,
      delimiterPattern.flags,
    );
    if (!pattern.test(text)) return;

    event.preventDefault();
    const start = ref.selectionStart ?? draft.length;
    const end = ref.selectionEnd ?? draft.length;
    const combined = draft.slice(0, start) + text + draft.slice(end);
    const rejected = addTags(split(combined, pattern), "paste");
    setDraft(rejected.join(joiner));
  }

  function handleFocus() {
    focused = true;
  }

  function handleBlur() {
    focused = false;
    if (addOnBlur && interactive) commitDraft("blur");
  }

  function handleFieldClick(event) {
    if (!interactive) return;
    const target = event.target;
    if (
      target === fieldRef ||
      (target instanceof HTMLElement &&
        target.matches(".bx--tag-set, .bx--tag-set__space"))
    ) {
      ref?.focus();
    }
  }

  function tagSlotProps(tag) {
    return {
      filter: !readonly,
      disabled: effectiveDisabled,
      value: tag,
      title: removeTagText,
      maxWidth: "13rem",
    };
  }

  function handleFormReset() {
    value = initialValue.slice();
    setDraft("");
    rejectionText = "";
  }
</script>

<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
  use:fieldsetDisabled={(value) => (inDisabledFieldset = value)}
  bind:this={rootRef}
  class:bx--form-item={true}
  on:keydown={handleTagKeydown}
>
  {#if labelText || $$slots.labelChildren}
    <label
      for={id}
      class:bx--label={true}
      class:bx--visually-hidden={hideLabel}
      class:bx--label--disabled={effectiveDisabled}
    >
      <slot name="labelChildren">{labelText}</slot>
    </label>
  {/if}
  <!-- svelte-ignore a11y-click-events-have-key-events -->
  <!-- svelte-ignore a11y-no-static-element-interactions -->
  <div
    bind:this={fieldRef}
    data-invalid={showInvalid || undefined}
    data-warn={showWarn || undefined}
    class:bx--tag-input={true}
    class:bx--tag-input--xs={effectiveSize === "xs"}
    class:bx--tag-input--sm={effectiveSize === "sm"}
    class:bx--tag-input--xl={effectiveSize === "xl"}
    class:bx--tag-input--focused={focused}
    class:bx--tag-input--invalid={showInvalid}
    class:bx--tag-input--disabled={effectiveDisabled}
    class:bx--tag-input--readonly={readonly}
    class:bx--tag-input--status={readonly || showInvalid || showWarn}
    on:click={handleFieldClick}
  >
    {#if readonly}
      <EditOff class="bx--text-input__readonly-icon" />
    {:else if showInvalid}
      <WarningFilled class="bx--text-input__invalid-icon" />
    {:else if showWarn}
      <WarningAltFilled
        class="bx--text-input__invalid-icon bx--text-input__invalid-icon--warning"
      />
    {/if}
    <TagSet
      id="{id}-tags"
      class="bx--tag-input__tags"
      navigation="roving"
      multiline
      size={tagSize}
      on:close:tag={handleTagClose}
    >
      {#if tagPlacement === "inline"}
        {#each value as tag, index (index)}
          {@const props = tagSlotProps(tag)}
          <slot name="tag" {tag} {index} {props}>
            <Tag {...props}>{tag}</Tag>
          </slot>
        {/each}
      {/if}
      <input
        bind:this={ref}
        value={draft}
        use:formReset={handleFormReset}
        type="text"
        autocomplete="off"
        aria-invalid={showInvalid ? "true" : undefined}
        aria-errormessage={showInvalid && errorText ? errorId : undefined}
        disabled={effectiveDisabled}
        {id}
        placeholder={readonly && value.length > 0 ? undefined : placeholder}
        {readonly}
        required={required && value.length === 0}
        class:bx--tag-input__input={true}
        {...$$restProps}
        aria-describedby={joinDescribedBy(
          interactive && instructionsId,
          resolveStatusDescribedBy({
            showInvalid,
            showWarn,
            invalidText: errorText,
            warnText,
            helperText,
            errorId,
            warnId,
            helperId,
            includeErrorId: false,
          }),
          $$restProps["aria-describedby"],
        )}
        on:input={handleInput}
        on:compositionend={handleCompositionEnd}
        on:keydown={handleInputKeydown}
        on:keydown
        on:paste={handlePaste}
        on:focus={handleFocus}
        on:focus
        on:blur={handleBlur}
        on:blur
      />
    </TagSet>
  </div>
  {#if tagPlacement === "below" && value.length > 0}
    <TagSet
      id="{id}-tags-below"
      class="bx--tag-input__tags--below"
      navigation="roving"
      multiline
      size={tagSize}
      on:close:tag={handleTagClose}
    >
      {#each value as tag, index (index)}
        {@const props = tagSlotProps(tag)}
        <slot name="tag" {tag} {index} {props}>
          <Tag {...props}>{tag}</Tag>
        </slot>
      {/each}
    </TagSet>
  {/if}
  {#if !showInvalid && !showWarn && helperText}
    <div
      id={helperId}
      class:bx--form__helper-text={true}
      class:bx--form__helper-text--disabled={effectiveDisabled}
    >
      {helperText}
    </div>
  {/if}
  {#if showInvalid && errorText}
    <div class:bx--form-requirement={true} id={errorId} role="alert">
      {errorText}
    </div>
  {/if}
  {#if showWarn && warnText}
    <div class:bx--form-requirement={true} id={warnId}>{warnText}</div>
  {/if}
  {#if name}
    {#each value as tag, index (index)}
      <input type="hidden" {name} value={tag} disabled={effectiveDisabled} />
    {/each}
  {/if}
  <span id={instructionsId} class:bx--visually-hidden={true}
    >{instructionsText}</span
  >
  <!-- Always rendered (even while empty) so assistive tech registers the
       region before its text changes. -->
  <span role="status" aria-live="polite" class:bx--visually-hidden={true}
    >{statusText}</span
  >
</div>
