<!--
@component

TODO: Can this component be removed?
-->
<script lang="ts">
  type CssClass = string | (string | false | null | undefined)[];

  type Props = {
    completions: string[];
    popover_class?: CssClass;
    search_input_class?: CssClass;
    search_input_element?: HTMLInputElement;
    search_value: string;
    value: string;
  };

  let {
    completions,
    popover_class,
    search_input_class,
    search_input_element = $bindable(),
    search_value = $bindable(),
    value = $bindable(),
  }: Props = $props();

  let focused = $state(false);
  let popover_element = $state<HTMLDivElement | undefined>();
  // Hacky workaround because as of September 2025 implicit anchor association
  // is still pretty broken, at least in Firefox.
  let anchor_name = $state(`--anchor-${Math.floor(Math.random() * 1000000)}`);

  function handle_component_focusin() {
    focused = true;
    popover_element?.showPopover();
  }

  function handle_component_focusout() {
    focused = false;
    setTimeout(() => {
      // TODO: There's still an edge case, where a click with a
      // mousedown-to-mouseup duration greater than the delay here will cause
      // the popover to hide.
      if (!focused) {
        popover_element?.hidePopover();
      }
    }, 250);
  }
</script>

<!--
Wrapping both the search input and the popover in a container element allows us
to capture 
-->
<div
  class="combobox__container"
  onfocusin={handle_component_focusin}
  onfocusout={handle_component_focusout}
  style:anchor-name={anchor_name}
>
  <input
    bind:this={search_input_element}
    bind:value={search_value}
    class={search_input_class}
    oninput={() => {
      popover_element?.showPopover();
    }}
    onkeydown={(ev) => {
      if (ev.key === "Escape") {
        popover_element?.hidePopover();
      }
    }}
    type="text"
  />
  <div
    bind:this={popover_element}
    class={popover_class ?? "combobox__popover"}
    popover="manual"
    role="listbox"
    style:position-anchor={anchor_name}
  >
    {#each completions as completion}
      <button
        aria-selected={value === completion}
        class="combobox__completion"
        onclick={() => {
          value = completion;
          search_input_element?.focus();
          popover_element?.hidePopover();
        }}
        role="option"
        type="button"
      >
        {completion}
      </button>
    {/each}
  </div>
</div>

<style lang="scss">
  .combobox {
    &__popover {
      &:popover-open {
        // @include globals.popover;

        left: anchor(left);
        position: absolute;
        top: anchor(bottom);
      }
    }

    &__completion {
      // @include globals.reset-button;

      display: block;
      padding: 0.5rem;
      font-weight: normal;
      text-align: left;
      width: 100%;

      &:hover,
      &:focus {
        background: #0000001f;
      }
    }
  }
</style>
