<script setup>
import { defineComponent, inject, provide, ref } from "vue";
import { Effect } from "effect";
import { useI18n } from "vue-i18n";
import { openModal } from "../../../../../composables/useOverlay";
import { getLocalizedText } from "../../../../../share/locale";
import { lookupFindBlock } from "../../../../config/utils/block-ref-cache";
import { injectCELContext, provideCELContext } from "../../../../../utils/cel-context";
import {
  EVENT_CHANNEL_KEY,
  createEventChannel,
  useEventChannel
} from "../../../../../share/event-bus";
import { FORM_STATE_KEY } from "../../../../form/utils/state";
import ShwfedActionDefinition from "../../../components/definition.vue";
import ShwfedSlotRenderer from "../../../../../share/slot-renderer.vue";
defineOptions({ name: "ShwfedModalLayoutActionRuntime" });
const props = defineProps({
  buttonId: { type: String, required: true },
  config: { type: null, required: true },
  buttonTitle: { type: null, required: false }
});
const { locale } = useI18n();
const configure = (_env) => {
};
const inheritedCelContext = injectCELContext();
const inheritedFormState = inject(FORM_STATE_KEY, void 0);
const outerEventChannel = useEventChannel();
const currentClose = ref(null);
const eventChannelNode = createEventChannel(
  props.buttonId,
  { close: () => Effect.sync(() => {
    currentClose.value?.();
  }) },
  outerEventChannel
);
const ModalBoundaryBridge = defineComponent({
  name: "ModalBoundaryBridge",
  setup(_, { slots }) {
    provideCELContext(inheritedCelContext);
    provide(EVENT_CHANNEL_KEY, eventChannelNode);
    if (inheritedFormState) provide(FORM_STATE_KEY, inheritedFormState);
    return () => slots.default?.();
  }
});
const findBlock = (type, compatibilityDate) => lookupFindBlock()?.(type, compatibilityDate);
const effect = Effect.gen(function* () {
  const title = getLocalizedText(props.config.modalTitle, locale.value) ?? getLocalizedText(props.buttonTitle, locale.value) ?? "";
  const { modal, close } = yield* openModal({
    title,
    width: props.config.modalWidth
  });
  currentClose.value = () => Effect.runSync(close());
  yield* modal;
  currentClose.value = null;
});
</script>

<template>
  <ShwfedActionDefinition
    :action-id="buttonId"
    :effect="effect"
  >
    <template #default>
      <div :style="config.modalMinHeight ? `min-height: ${config.modalMinHeight}` : void 0">
        <ModalBoundaryBridge>
          <ShwfedSlotRenderer
            :slot-value="config.slot"
            :configure="configure"
            :find-entry="findBlock"
          />
        </ModalBoundaryBridge>
      </div>
    </template>
  </ShwfedActionDefinition>
</template>
