<template>
  <vm-group-cascader
    :model-value="modelValue ?? ''"
    :tree="tree"
    :placeholder="placeholder ?? crudLabel('pickFilePath')"
    :clearable="clearable"
    :editable="editable"
    :disabled="disabled"
    @update:model-value="(v) => emit('update:modelValue', v)"
  />
</template>

<script setup lang="ts">
import { crudLabel } from '../crud/style'
import { ref, onMounted, onUnmounted } from 'vue'
import {
  listViewsTree,
  VIEWS_RESCAN_EVENT,
} from '../lib/module'
import type { ViewsTreeNode } from '../../../typings/admin/vome/module'
defineOptions({ name: 'vm-view-path-picker' })

withDefaults(
  defineProps<{
    modelValue?: string | null
    placeholder?: string
    clearable?: boolean
    editable?: boolean
    disabled?: boolean
  }>(),
  {
    placeholder: undefined,
    clearable: true,
    editable: true,
  },
)

const emit = defineEmits<{
  'update:modelValue': [v: string]
}>()

const tree = ref<ViewsTreeNode[]>([])

function rescan() {
  tree.value = listViewsTree()
}

onMounted(() => {
  rescan()
  window.addEventListener(VIEWS_RESCAN_EVENT, rescan)
})

onUnmounted(() => {
  window.removeEventListener(VIEWS_RESCAN_EVENT, rescan)
})

// 打开选择器前再扫一次（配合 HMR 事件）
defineExpose({ rescan })
</script>
