<template>
  <ActionSheet 
    v-bind="options"
    :show="show"
    @close="options?.onClose"
    @select="options?.onSelect"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import ActionSheet, { type ActionSheetProps } from './ActionSheet.vue';

export interface ActionSheetOptions extends Omit<ActionSheetProps, 'show'> {
  onSelect?: (index: number, name: string) => void;
  onClose?: () => void;
}
export interface ActionSheetRoot {
  show(options: ActionSheetOptions): Promise<number|undefined>;
}

const show = ref(false);
const options = ref<ActionSheetOptions>();

defineExpose<ActionSheetRoot>({
  show(_options: ActionSheetOptions) {
    show.value = true;
    options.value = _options;

    const onSelect = _options.onSelect;
    const onClose = _options.onClose;

    return new Promise<number|undefined>((resolve) => {
      _options.onClose = () => {
        show.value = false;
        onClose?.();
        resolve(undefined);
      };
      _options.onSelect = (i: number, n: string) => {
        show.value = false;
        onSelect?.(i, n);
        resolve(i);
      };
      options.value = _options;
      show.value = true;
    });
  },
})
</script>