<script lang="ts">
  import { type EditorState } from "./editor-state.svelte";
  import { type FieldInfo } from "./field.svelte";

  type Props = {
    assignable_fields?: ReadonlyArray<FieldInfo>;
    editor_state: EditorState;
    field_info: FieldInfo;
  };

  let {
    assignable_fields = [],
    editor_state = $bindable(),
    field_info = $bindable(),
  }: Props = $props();

  let type_selector_menu_button_element = $state<
    HTMLButtonElement | undefined
  >();
  let type_selector_popover_element = $state<HTMLDivElement | undefined>();

  function handle_type_selector_menu_button_click() {
    type_selector_popover_element?.togglePopover();
  }

  function handle_type_selector_field_button_click(value: FieldInfo) {
    field_info = value;
    type_selector_popover_element?.hidePopover();
    type_selector_menu_button_element?.focus();
  }
</script>

<div class="datum-editor__container">
  {#if assignable_fields.length > 0}
    <div class="datum-editor__type-selector">
      <button
        bind:this={type_selector_menu_button_element}
        class="datum-editor__type-selector-menu-button"
        onclick={handle_type_selector_menu_button_click}
        type="button"
      >
        {field_info.field.presentation.t}
      </button>
      <div
        bind:this={type_selector_popover_element}
        class="datum-editor__type-selector-popover"
        popover="auto"
      >
        {#each assignable_fields as assignable_field_info}
          <button
            onclick={() =>
              handle_type_selector_field_button_click(assignable_field_info)}
            type="button"
          >
            {assignable_field_info.field.presentation.t}
          </button>
        {/each}
      </div>
    </div>
  {/if}
  <div class="datum-editor__content">
    {#if field_info.field.presentation.t === "Text" || field_info.field.presentation.t === "Uuid"}
      <input bind:value={editor_state.text_value} type="text" />
    {:else if field_info.field.presentation.t === "Timestamp"}
      <input bind:value={editor_state.date_value} type="date" />
      <input bind:value={editor_state.time_value} type="time" />
    {/if}
  </div>
</div>
