<template>
  <DialogRoot ref="naDialogRef" />
  <ActionSheet ref="naActionSheetRef" />
  <Toast ref="naToastRef" />
  <Notify ref="naNotifyRef" />
  <slot />
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { destroyCurrentRoot, setCurrentRoot } from './CommonRoot';
import Notify, { type NotifyInstance } from '../feedback/Notify.vue';
import Toast, { type ToastInstance } from '../feedback/Toast.vue';
import ActionSheet, { type ActionSheetRoot } from './ActionSheetRoot.vue';
import DialogRoot, { type DialogAlertRoot } from './DialogRoot.vue';

const naDialogRef = ref<DialogAlertRoot>();
const naToastRef = ref<ToastInstance>();
const naNotifyRef = ref<NotifyInstance>();
const naActionSheetRef = ref<ActionSheetRoot>();

export interface ICommonRoot {
  alert: DialogAlertRoot['alert'];
  confirm: DialogAlertRoot['confirm'];
  toast: ToastInstance['show'];
  closeToast: ToastInstance['close'];
  actionSheet: ActionSheetRoot['show'];
  notify: NotifyInstance['show'];
}

const commonRoot : ICommonRoot = {
  alert: (a) => naDialogRef.value!.alert(a),
  confirm: (a) => naDialogRef.value!.confirm(a),
  toast: (a) => naToastRef.value!.show(a),
  closeToast: () => naToastRef.value!.close(),
  actionSheet: (a) => naActionSheetRef.value!.show(a),
  notify: (a) => naNotifyRef.value!.show(a),
};

onMounted(() => {
  setCurrentRoot(commonRoot);
  (uni as any).$na = commonRoot;
});
onBeforeUnmount(() => {
  destroyCurrentRoot(commonRoot!);
});

defineExpose<ICommonRoot>(commonRoot);
</script>