<template>
  <Popover
    v-model:show="popoverVisible"
    :actions="actions"
    @select="onSelect"
  >
    <template
      v-if="hasDefault"
      v-slot:[slotName]
    >
      <div @click="popoverVisible = false">
        <slot />
      </div>
    </template>
    <template #reference>
      <slot name="reference" />
    </template>
  </Popover>
</template>

<script lang="ts">
export default {
  name: "WlPopover",
};
</script>

<script setup lang="ts">
import { Popover } from "vant";
import { PopoverAction } from "vant";
import { ref, watchEffect, useSlots, computed } from "vue";

type Props = {
  actions?: PopoverAction[];
  modelValue?: boolean;
};

const props = withDefaults(defineProps<Props>(), {
  actions: null,
  modelValue: false,
});

const slots = useSlots();

const hasDefault = ref(slots.default !== undefined);

const slotName = computed(() => (hasDefault.value ? "default" : "content"));

const emit = defineEmits<{
  (e: "update:modelValue", val: boolean);
  (e: "onSelect", val: PopoverAction);
}>();

const popoverVisible = ref(false);

const onTogglePopover = (bool) => {
  popoverVisible.value = bool;
  emit("update:modelValue", bool);
};

const onSelect = (val: PopoverAction) => {
  emit("onSelect", val);
  onTogglePopover(false);
};

watchEffect(() => {
  popoverVisible.value = props.modelValue;
});
</script>
