<svelte:options
  customElement={{
    props: {
      identifier_hints: { attribute: "identifier-hints", type: "Array" },
      initialValue: { attribute: "initial-value", type: "Object" },
    },
    shadow: "none",
    tag: "filter-menu",
  }}
/>

<script lang="ts">
  import { type PgExpressionAny } from "./expression.svelte";
  import ExpressionEditor from "./expression-editor.webc.svelte";

  type Props = {
    identifier_hints?: string[];
    initialValue?: PgExpressionAny | null;
  };

  let { identifier_hints = [], initialValue }: Props = $props();

  let popover_element = $state<HTMLDivElement | undefined>();
  let expr = $state<PgExpressionAny | undefined>(initialValue ?? undefined);

  function handle_toolbar_button_click() {
    popover_element?.togglePopover();
  }

  function handle_clear_button_click() {
    expr = undefined;
  }
</script>

<div class="toolbar__utilities">
  <div class="toolbar-item">
    <button
      class="toolbar-item__button"
      onclick={handle_toolbar_button_click}
      type="button"
    >
      Filter
    </button>
    <div bind:this={popover_element} class="toolbar-popover" popover="auto">
      <form action="set-filter" method="post">
        <ExpressionEditor bind:value={expr} {identifier_hints} />
        <div class="toolbar-popover__form-actions">
          <input
            name="filter_expression"
            type="hidden"
            value={JSON.stringify(expr)}
          />
          <button
            class="button--secondary"
            onclick={handle_clear_button_click}
            type="button"
          >
            Clear
          </button>
          <button class="button--primary" type="submit">Apply</button>
        </div>
      </form>
    </div>
  </div>
</div>
