<script setup lang="ts">
import { ref, watch } from 'vue';

const props = defineProps<{
  modelValue?: string,
  type: 'arr' | 'obj'
}>()

const emits = defineEmits(["update:modelValue"])

const value = ref<object | unknown[]>({})

try {
  value.value = JSON.parse(props.modelValue as string)
} catch (error) {
  value.value = props.type === 'arr' ? [] : {}
}

// const value = ref(props.modelValue === undefined ? undefined : JSON.parse(props.modelValue))

const change = (v: unknown, k: any) => {
  //@ts-ignore
  value.value[k] = v
  // emits("update:modelValue", JSON.stringify(value.value))
  // console.log('change :>> ', value.value[k] = v);
}

watch(
  () => value.value,
  (val) => {
    // console.log('watch :>> ', val);
    emits("update:modelValue", JSON.stringify(val))
  },
  {
    deep: true,
  }
)

</script>

<template>
  <slot :value="value" :change="change"></slot>
</template>
