<!--
@component

Select an option from a list, with search

Guided by https://www.w3.org/WAI/ARIA/apg/patterns/combobox/

```svelte
<SearchableSelect
  options={["Option 1", "Option 2", "Option 3"]}
  bind:value
/>
```
-->
<script lang="ts">
import type { ClassValue } from 'svelte/elements';

import { Floating, type FloatingStrategy, matchWidth } from '../floating';
import { Icon } from '../icon';
import { type InputState, InputStates } from '../input';
import { createHandleKey } from '../keyboard';
import { Progress } from '../progress';
import { uniqueId } from '../unique-id';
import { useNextFrame } from '../use-next-frame';
import {
  type DetailedOption,
  getSearchResults,
  optionDisplayValue,
  optionsToDetailedOptions,
  type SortOption,
  SortOptions,
} from './search';
import SelectInput from './select-input.svelte';

/** The options the user should be allowed to search and select from. */
export let options: (string | DetailedOption)[];

/** The value of the search input or the currently selected option, if any. */
export let value = '';

/** All selected values, if `multiple` is `true`. */
export let values: string[] = [];

/** The placeholder of the input. */
export let placeholder = '';

/** Optional id used in parent label `for` attribute */
export let id: string | undefined = undefined;

/**
 * Whether value must be constrained to `options` on change.
 * - `false` (Default) - any value may be selected
 * - `true` - value must be in `options`
 * - `Function` - value must be in `options` or pass the test function
 */
export let exclusive: boolean | ((value: string) => boolean) = false;

/** Controls whether or not we select the typed option when blurring */
export let selectOnBlur = true;

/** Multiple selections allowed. */
export let multiple: boolean | undefined = undefined;

/** Input is disabled. */
export let disabled = false;

/** Clearing the field resets to the last selected value rather than emitting an empty string. */
export let resetOnClear = false;

/** Clear the value on select rather than displaying the selected option. */
export let clearValueOnSelect = false;

/** The state of the select (info, warn, error, success), if any. */
export let state: InputState = InputStates.NONE;

/** Option sorting behavior. */
export let sort: SortOption = SortOptions.DEFAULT;

/**
 * When true, focusing the input shows the full option list until the user
 * types. The selected value is preserved; options only narrow once a search
 * term is entered. Pairs well with `sort="reduce"` so a populated field still
 * reveals every option on click rather than pre-filtering to the current value.
 */
export let showAllOnFocus = false;

/** Prefix to display with the arbitrary text option, if non-exclusive. */
export let otherOptionPrefix = '';

/** Error message ID, if any. */
export let errorID = '';

/** ID of the element that describes the SearchableSelect. */
export let describedBy: string | undefined = undefined;

/** Whether the data to populate the options is still loading.
 * If true, a loading indicator will be displayed instead of the options.
 */
export let isLoading = false;

/**
 * Notify the parent of a value change, after Enter key or blur.
 *
 * Only used if `multiple` is `false` (default)
 */
export let onChange: ((value: string) => unknown) | undefined = undefined;

/** Notify the parent of a value change, if `multiple` is `true` */
export let onMultiChange: ((values: string[]) => unknown) | undefined =
  undefined;

/** Notify the parent of focus. */
export let onFocus: ((event: FocusEvent) => unknown) | undefined = undefined;

/** Notify the parent of blur. */
export let onBlur: ((event: FocusEvent) => unknown) | undefined = undefined;

/**
 * The strategy for positioning the popup.
 *
 * Use `fixed` to break the menu out of the parent container
 * in the case where the parent container is also floating.
 */
export let floatingStrategy: FloatingStrategy | undefined = undefined;

/** Additional CSS classes to pass to the input container. */
let inputCx: ClassValue = '';
export { inputCx as cx };

/** Additional CSS classes to pass to the dropdown menu container. */
let menuCx: ClassValue = '';
export { menuCx };

const LIST_ID = uniqueId('combobox-list');
const SELECTED_ID = uniqueId('combobox-list-selected-item');
const CLOSED = 'closed';
const FOCUS_SEARCH = 'focus-search';
const FOCUS_ITEM = 'focus-item';
const PAGINATION_INCREMENT = 100;
const LOAD_MORE_INDEX_TRIGGER = 5;
const onNextFrame = useNextFrame();

type MenuState = typeof CLOSED | typeof FOCUS_SEARCH | typeof FOCUS_ITEM;

$: detailedOptions = optionsToDetailedOptions(options);
$: detailedOptionsMap = Object.fromEntries(
  detailedOptions.map((opt) => [opt.value, opt])
);

const optionElements: Record<string, HTMLElement> = {};

let inputElement: HTMLInputElement | undefined;
let containerElement: HTMLDivElement | undefined;
let listElement: HTMLUListElement | undefined;
let autoSelectIndex = -1;
let menuState: MenuState | undefined;
let numberDisplayed = PAGINATION_INCREMENT;

// searchValue is the value stored inside the search input field
// it is primarily updated reactively through a call to resetSearchValue when
// value changes (in handleSelect)
//
// It is also manually updated in edge cases like Escape or Blur
let searchValue = '';
// Tracks whether the user has typed since focusing. Used with showAllOnFocus to
// show the full list on focus and only narrow once a search term is entered.
let userIsSearching = false;
const resetSearchValue = (valueParam: string) => {
  resetDisplayCount();
  searchValue = clearValueOnSelect
    ? ''
    : optionDisplayValue(
        detailedOptionsMap[valueParam] ?? { value: valueParam }
      );
};
$: {
  void detailedOptionsMap;
  resetSearchValue(value);
}

// selectedSearchOption represents the value that was last selected (or the initial value)
$: selectedSearchOption = detailedOptionsMap[value];

$: effectiveSearchValue = showAllOnFocus && !userIsSearching ? '' : searchValue;
$: searchResults = getSearchResults(
  detailedOptions,
  effectiveSearchValue,
  sort
);
$: valueInSearch = searchResults.some(
  ({ option }) => optionDisplayValue(option) === searchValue
);
$: getOtherIsAllowed =
  typeof exclusive === 'function' ? exclusive : () => !exclusive;

$: otherOption =
  searchValue !== '' && !valueInSearch && getOtherIsAllowed(searchValue)
    ? {
        option: { value: searchValue, icon: 'plus' } as DetailedOption,
        priority: -1,
        highlight: undefined,
      }
    : undefined;

$: displayedOptions = searchResults.slice(0, numberDisplayed);
$: menuState =
  !menuState || (searchResults.length === 0 && !otherOption && !isLoading)
    ? CLOSED
    : menuState;

$: if (menuState === undefined || menuState === FOCUS_SEARCH) {
  let nextAutoSelectIndex = displayedOptions.findIndex(
    ({ priority }) => priority !== -1
  );
  // if we don't find any options with a non negative priority,
  // we set the nextAutoSelectIndex to the option that matches
  // the current search value. This is used so that when we blur
  // with a valid searchValue, we autoSelect the correct option
  if (nextAutoSelectIndex === -1) {
    nextAutoSelectIndex = displayedOptions.findIndex(
      ({ option }) => optionDisplayValue(option) === searchValue
    );
  }
  autoSelectIndex = nextAutoSelectIndex;
} else if (menuState === CLOSED) {
  autoSelectIndex = -1;
}

$: autoSelectOption = displayedOptions[autoSelectIndex] ?? otherOption;
$: isExpanded = menuState === FOCUS_SEARCH || menuState === FOCUS_ITEM;
$: activeOption = isExpanded ? autoSelectOption : undefined;
$: activeID = activeOption ? SELECTED_ID : undefined;
$: activeElement =
  activeOption && activeOption.option !== otherOption?.option
    ? optionElements[activeOption.option.value]
    : undefined;

const loadMoreOptions = () => {
  if (numberDisplayed < searchResults.length) {
    numberDisplayed += PAGINATION_INCREMENT;
  }
};

const resetDisplayCount = () => {
  numberDisplayed = PAGINATION_INCREMENT;
};

// anytime dropdown closes, reset the display count to default state
$: {
  if (!isExpanded) {
    resetDisplayCount();
  }
}

const scrollIntoView = (element: HTMLElement | undefined): void => {
  if (typeof element?.scrollIntoView === 'function') {
    // NOTE(mc, 2024-06-17): do not scroll right away, or else we can accidentally
    // scroll the whole document instead of the element's containing `<ul>`
    onNextFrame(() => {
      element.scrollIntoView({ block: 'nearest', inline: 'nearest' });
    });
  }
};

$: scrollIntoView(menuState === FOCUS_ITEM ? activeElement : undefined);

const getSingleSelectedValue = (selectedOption: DetailedOption | undefined) => {
  if (selectedOption) {
    return selectedOption;
  }

  // Resolve the search text back to its option so detailed options (where
  // value !== label) commit their value, not their display label. Searches the
  // full result set so a selection outside the paginated window still resolves.
  const matchedOption = searchResults.find(
    ({ option }) => optionDisplayValue(option) === searchValue
  )?.option;
  if (matchedOption) {
    return matchedOption;
  }

  if (resetOnClear) {
    return { value };
  }

  return { value: '' };
};

const handleSingleSelect = (selectedOption: DetailedOption | undefined) => {
  const nextOption = getSingleSelectedValue(selectedOption);

  // we always set the menu state to closed even if the value is equal to the previous value
  // but we don't call onChange
  setMenuState(CLOSED);

  // we reset the search value here to the last selected option to ensure there is no mismatch
  // between what was actually selected vs what is in the search input
  resetSearchValue(nextOption.value);

  if (nextOption.value !== value) {
    value = clearValueOnSelect ? '' : nextOption.value;
    onChange?.(nextOption.value);
  }
};

// inputValue is the value of option that was selected (not the value in the search field)
const handleMultiSelect = (selectedOption: DetailedOption | undefined) => {
  if (!selectedOption) {
    return;
  }

  values = values.includes(selectedOption.value)
    ? values.filter((val) => val !== selectedOption.value)
    : [...values, selectedOption.value];

  value = '';
  searchValue = '';
  onMultiChange?.(values);
};

const handleSelect = (option: DetailedOption | undefined) => {
  if (disabled || menuState === CLOSED) {
    return;
  }

  if (multiple) {
    return handleMultiSelect(option);
  }

  handleSingleSelect(option);
};

const setMenuState = (nextMenuState: MenuState) => {
  menuState = disabled ? CLOSED : nextMenuState;
};

const handleInput = (event: Event) => {
  // update the searchValue on inputs to the search field
  const element = event.target as HTMLInputElement;
  searchValue = element.value;
  userIsSearching = true;
  setMenuState(FOCUS_SEARCH);
  // whenever typing, reset the number displayed
  resetDisplayCount();
  // When typing, scroll up because the best match is there
  if (searchValue.length > 0 && listElement) {
    listElement.scrollTop = 0;
  }
};

const handleFocus = (event: FocusEvent) => {
  userIsSearching = false;
  setMenuState(FOCUS_SEARCH);
  // Highlight the current text so the first keystroke replaces it instead of
  // editing the selected option's label.
  if (showAllOnFocus) {
    inputElement?.select();
  }
  onFocus?.(event);
};

const handleBlur = (event: FocusEvent) => {
  if (selectOnBlur) {
    handleSelect(autoSelectOption?.option);
  }

  resetSearchValue(value);
  setMenuState(CLOSED);
  onBlur?.(event);
};

const handleButtonClick = () => {
  setMenuState(isExpanded ? CLOSED : FOCUS_SEARCH);
  inputElement?.focus();
};

const handleKeydown = createHandleKey({
  Enter: {
    handler: (event) => {
      if (menuState !== CLOSED) {
        handleSelect(autoSelectOption?.option);
        event.preventDefault();
      }
    },
    preventDefault: false,
  },
  ' ': {
    handler: (event) => {
      if (menuState === FOCUS_ITEM) {
        handleSelect(autoSelectOption?.option);
        event.preventDefault();
      }
    },
    preventDefault: false,
  },
  Escape: () => {
    // WAI: Dismisses the popup if it is visible. Optionally, if the popup is hidden before Escape is pressed, clears the combobox.
    if (menuState === CLOSED) {
      searchValue = '';
    } else {
      resetDisplayCount();
      setMenuState(CLOSED);
    }
  },
  ArrowDown: (event) => {
    if (event.altKey) {
      setMenuState(menuState === CLOSED ? FOCUS_SEARCH : FOCUS_ITEM);
    } else {
      setMenuState(FOCUS_ITEM);
      autoSelectIndex =
        autoSelectIndex < displayedOptions.length - 1 ? autoSelectIndex + 1 : 0;
      if (
        autoSelectIndex > displayedOptions.length - LOAD_MORE_INDEX_TRIGGER &&
        displayedOptions.length < searchResults.length
      ) {
        loadMoreOptions();
      }
    }
  },
  ArrowUp: () => {
    setMenuState(FOCUS_ITEM);
    autoSelectIndex =
      autoSelectIndex > 0 ? autoSelectIndex - 1 : displayedOptions.length - 1;
  },
  ArrowRight: {
    handler: () => setMenuState(FOCUS_SEARCH),
    preventDefault: false,
  },
  ArrowLeft: {
    handler: () => setMenuState(FOCUS_SEARCH),
    preventDefault: false,
  },
  Home: () => {
    setMenuState(FOCUS_SEARCH);
    inputElement?.setSelectionRange(0, 0);
  },
  End: () => {
    setMenuState(FOCUS_SEARCH);
    inputElement?.setSelectionRange(searchValue.length, searchValue.length);
  },
});

const onListScroll = (event: Event) => {
  const container = event.target as HTMLDivElement;
  if (container) {
    const offset =
      container.scrollHeight - container.clientHeight - container.scrollTop;

    if (offset < 200) {
      loadMoreOptions();
    }
  }
};
</script>

<SelectInput
  {state}
  {disabled}
  {placeholder}
  menuId={LIST_ID}
  isOpen={isExpanded}
  isFocused={menuState === FOCUS_ITEM ? false : undefined}
  {id}
  cx={[{ 'caret-transparent': menuState === FOCUS_ITEM }, inputCx]}
  icon={selectedSearchOption?.icon}
  aria-autocomplete="list"
  aria-multiselectable={multiple}
  aria-activedescendant={activeID}
  aria-errormessage={errorID}
  aria-describedby={describedBy}
  on:focus={handleFocus}
  on:blur={handleBlur}
  on:keydown={handleKeydown}
  on:input={handleInput}
  on:click={handleButtonClick}
  bind:inputElement
  bind:containerElement
  value={searchValue}
/>

{#if isExpanded}
  <Floating
    placement="bottom-start"
    offset={4}
    referenceElement={containerElement}
    size={matchWidth}
    flip={{}}
    strategy={floatingStrategy}
    auto
  >
    <div
      class={[
        'border-gray-9 flex max-h-36 min-h-0 flex-col border bg-white shadow-sm',
        menuCx,
      ]}
    >
      <ul
        id={LIST_ID}
        role="listbox"
        class="min-h-0 grow flex-col overflow-y-auto"
        on:scroll={onListScroll}
        bind:this={listElement}
      >
        {#if isLoading}
          <li
            class="bg-light flex items-center justify-center gap-2 px-2.5 py-5"
          >
            <Progress />
            <span class="text-subtle-2 text-xs">Loading...</span>
          </li>
        {:else}
          {#each displayedOptions as { option, highlight } (option.value)}
            {@const isActive = activeOption?.option === option}
            {@const isSelected = multiple ? false : isActive}
            {@const isChecked = multiple
              ? values.includes(option.value)
              : undefined}
            {@const descriptionID = uniqueId('combobox-list-item-description')}
            <!-- Focus stays on combobox per WAI; key handlers on options not needed. -->
            <!-- svelte-ignore a11y_click_events_have_key_events -->
            <li
              role="option"
              id={isActive ? activeID : undefined}
              aria-selected={isSelected}
              aria-checked={isChecked}
              aria-describedby={descriptionID}
              aria-label={optionDisplayValue(option)}
              class={[
                'flex cursor-pointer items-center justify-start px-2.5 py-1.5',
                multiple ? 'pr-2.5 pl-2' : 'px-2.5',
                isActive ? 'bg-light' : 'hover:bg-light',
              ]}
              on:pointerdown|preventDefault
              on:mousedown|preventDefault
              on:click={() => handleSelect(option)}
              bind:this={optionElements[option.value]}
            >
              <div class="flex flex-row items-center gap-2">
                <!-- In all real cases, only one of these icons should should be active at once-->
                <!-- (multi with icon is not a designed use case yet) -->
                {#if multiple}
                  <Icon
                    cx={['my-0.5 shrink-0', !isChecked && 'text-gray-6']}
                    name={isChecked
                      ? 'checkbox-marked'
                      : 'checkbox-blank-outline'}
                  />
                {/if}
                {#if option.icon}
                  <Icon
                    cx={['text-gray-6 my-0.5 shrink-0']}
                    name={option.icon}
                  />
                {/if}
                <div class="flex flex-col text-xs wrap-anywhere">
                  <p>
                    {#if highlight !== undefined}
                      {@const [prefix, match, suffix] = highlight}
                      {prefix}<span class="bg-yellow-100">{match}</span>{suffix}
                    {:else}
                      {optionDisplayValue(option)}
                    {/if}
                  </p>
                  {#if option.description}
                    <p
                      id={descriptionID}
                      class=" text-subtle-2"
                    >
                      {option.description}
                    </p>
                  {/if}
                </div>
              </div>
            </li>
          {/each}
          <slot />
        {/if}
      </ul>

      <!-- svelte-ignore a11y_click_events_have_key_events -->
      {#if otherOption?.option && !isLoading}
        {@const option = otherOption?.option}
        {@const isActive = activeOption?.option === option}
        {@const isSelected = multiple ? false : isActive}
        {@const isChecked = multiple
          ? values.includes(option.value)
          : undefined}
        {@const descriptionID = uniqueId('combobox-list-item-description')}
        <li
          role="option"
          id={isActive ? activeID : undefined}
          data-testid="other-option"
          aria-selected={isSelected}
          aria-checked={isChecked}
          aria-describedby={descriptionID}
          aria-label={[otherOptionPrefix, optionDisplayValue(option)]
            .filter(Boolean)
            .join(' ')}
          class={[
            'border-light flex cursor-pointer items-center justify-start border-t px-2.5 py-1.5',
            multiple ? 'pr-2.5 pl-2' : 'px-2.5',
            isActive ? 'bg-light' : 'hover:bg-light',
          ]}
          on:pointerdown|preventDefault
          on:mousedown|preventDefault
          on:click={() => handleSelect(option)}
          bind:this={optionElements[option?.value]}
        >
          <div class="flex flex-row items-center gap-2">
            <!-- In all real cases, only one of these icons should should be active at once-->
            <!-- (multi with icon is not a designed use case yet) -->
            {#if multiple}
              <Icon
                cx={['my-0.5 shrink-0', !isChecked && 'text-gray-6']}
                name={isChecked ? 'checkbox-marked' : 'checkbox-blank-outline'}
              />
            {/if}
            {#if option.icon}
              <Icon
                cx={['text-gray-6 my-0.5 shrink-0']}
                name={option.icon}
              />
            {/if}
            <div class="flex flex-col text-xs wrap-anywhere">
              <p>
                {#if otherOptionPrefix}
                  {otherOptionPrefix} {optionDisplayValue(option)}
                {:else}
                  {optionDisplayValue(option)}
                {/if}
              </p>
              {#if option.description}
                <p
                  id={descriptionID}
                  class=" text-subtle-2"
                >
                  {option.description}
                </p>
              {/if}
            </div>
          </div>
        </li>
      {/if}
    </div>
  </Floating>
{/if}
