<script lang="ts">
  import calendar_days_icon from "../assets/heroicons/20/solid/calendar-days.svg?raw";
  import document_text_icon from "../assets/heroicons/20/solid/document-text.svg?raw";
  import identification_icon from "../assets/heroicons/20/solid/identification.svg?raw";
  import { type FieldInfo } from "./field.svelte";
  import FieldDetails from "./field-details.svelte";

  type Props = {
    field: FieldInfo;
    index: number;
  };

  let { field = $bindable(), index }: Props = $props();

  const original_label_value = field.field.table_label;

  let type_indicator_element = $state<HTMLButtonElement | undefined>();
  let popover_element = $state<HTMLDivElement | undefined>();
  let name_value = $state(field.field.name);
  let label_value = $state(field.field.table_label ?? "");

  $effect(() => {
    field.field.table_label = label_value === "" ? undefined : label_value;
  });

  $effect(() => {
    popover_element?.addEventListener("toggle", handle_popover_toggle);
    return () => {
      popover_element?.removeEventListener("toggle", handle_popover_toggle);
    };
  });

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

  function handle_popover_toggle(ev: ToggleEvent) {
    if (ev.newState === "closed") {
      type_indicator_element?.focus();
      field.field.table_label = original_label_value;
      label_value = original_label_value ?? "";
    }
  }
</script>

<div
  aria-colindex={index}
  class="field-header__container"
  role="columnheader"
  style:width={`${field.field.table_width_px}px`}
>
  <div class="field-header__label">
    {field.field.table_label ?? field.field.name}
  </div>
  <div class="field-header__menu-container">
    <button
      bind:this={type_indicator_element}
      class="field-header__type-indicator"
      onclick={handle_type_indicator_element_click}
    >
      {#if field.field.presentation.t === "Text"}
        {@html document_text_icon}
      {:else if field.field.presentation.t === "Timestamp"}
        {@html calendar_days_icon}
      {:else if field.field.presentation.t === "Uuid"}
        {@html identification_icon}
      {/if}
    </button>
    <div
      bind:this={popover_element}
      class="field-header__popover"
      popover="auto"
    >
      <FieldDetails bind:name_value bind:label_value name_input_disabled />
    </div>
  </div>
</div>
