<script setup lang="ts">
import { computed, watch, ref } from 'vue'
import MarkdownEditor from './MarkdownEditor.vue'
import Jeditor from './Jeditor.vue'
import HTML from './HTML.vue'
import Code from './Code.vue'

const props = defineProps<{ df: any; record: Record<string, any>; canEdit: boolean; ctx: any }>()

const contentType = ref(props.record.content_type || props.df.default_content_type || 'Jeditor')

watch(
  () => props.record.content_type,
  (newVal) => {
    contentType.value = newVal || props.df.default_content_type || 'Jeditor'
  }
)

const activeEditor = computed(() => {
  const ct = contentType.value
  if (!ct || ct === 'Jeditor' || ct === 'Rich Text') return Jeditor
  if (ct.includes('HTML')) return HTML
  if (ct === 'Code') return Code
  return MarkdownEditor
})

const isRichEditor = computed(() => {
  const ct = contentType.value
  return !ct || ct === 'Jeditor' || ct === 'Rich Text'
})

const editorProps = computed(() => ({
  df: props.df,
  modelValue: isRichEditor.value ? (props.record[props.df.fieldname] ?? '') : undefined,
  record: props.record,
  canEdit: props.canEdit,
  ctx: props.ctx,
}))

const editorEvents = computed(() =>
  isRichEditor.value
    ? { 'update:modelValue': (v: any) => { props.record[props.df.fieldname] = v } }
    : {}
)
</script>

<template>
  <component
    :is="activeEditor"
    v-bind="editorProps"
    v-on="editorEvents"
    :key="contentType"
  />
</template>
