<template>
  <span ref="anchorRef" class="warehouse-document-action-anchor" aria-hidden="true"></span>

  <Teleport :to="actionHost" :disabled="!actionHost">
    <div
      class="warehouse-document-action-bar warehouse-document-action-bar--shared"
      :class="{ 'warehouse-document-action-bar--with-state': $slots.state }"
      @click.capture="handleActionClick"
    >
      <div v-if="$slots.state" class="warehouse-document-action-state">
        <slot name="state" />
      </div>

      <div class="warehouse-document-action-buttons">
        <slot />
      </div>
    </div>
  </Teleport>
</template>

<script setup>
import { nextTick, onMounted, ref } from "vue";

const anchorRef = ref(null);
const actionHost = ref(null);

onMounted(async () => {
  await nextTick();
  actionHost.value = anchorRef.value
    ?.closest?.("form")
    ?.querySelector?.("[data-warehouse-document-action-host]") || null;
});

function handleActionClick(event) {
  const target = event.target;
  const submitter = target?.closest?.("button[type='submit'], input[type='submit']");
  if (!submitter || submitter.disabled) {
    return;
  }
  const form = anchorRef.value?.closest?.("form");
  if (!form) {
    return;
  }
  event.preventDefault();
  form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
}
</script>
