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

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

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

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

defineOptions({
  inheritAttrs: false
});

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

onMounted(async () => {
  await nextTick();
  const form = anchorRef.value?.closest?.("form");
  actionHost.value = form?.querySelector?.("[data-document-action-host]") || 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>
