<svelte:options
  customElement={{
    props: {
      button_aria_label: { attribute: "button-aria-label" },
      button_class: { attribute: "button-class" },
      alignment: { attribute: "alignment" },
    },
    tag: "basic-dropdown",
  }}
/>

<script lang="ts">
  type Props = {
    alignment?: string;
    button_aria_label?: string;
    button_class?: string;
    on_toggle?(ev: ToggleEvent): void;
  };

  let {
    alignment,
    button_aria_label,
    button_class = "button--secondary",
    on_toggle,
  }: Props = $props();
  let popover_element: HTMLElement | undefined = $state();
  // 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)}`);

  let popover_left = $derived(
    alignment?.toLocaleLowerCase("en-US") === "right"
      ? "unset"
      : "anchor(left)",
  );
  let popover_right = $derived(
    alignment?.toLocaleLowerCase("en-US") === "right"
      ? "anchor(right)"
      : "unset",
  );

  $effect(() => {
    if (on_toggle) {
      popover_element?.addEventListener("toggle", on_toggle);
      return () => {
        popover_element?.removeEventListener("toggle", on_toggle);
      };
    }
  });
</script>

<button
  aria-label={button_aria_label}
  class={["basic-dropdown__button", button_class]}
  id="dropdown-button"
  onclick={() => {
    popover_element?.showPopover();
  }}
  style:anchor-name={anchor_name}
  type="button"
>
  <slot name="button-contents"></slot>
</button>
<div
  aria-labelledby="dropdown-button"
  bind:this={popover_element}
  class="basic-dropdown__popover"
  style:left={popover_left}
  style:position-anchor={anchor_name}
  style:right={popover_right}
  popover="auto"
>
  <slot name="popover"></slot>
</div>

<style lang="scss">
  @use "../../sass/main";
</style>
