<template>
  <div class="relative" :class="{ small: small }">
    <FormFieldLabel
      class="-ml-1 mt-[44px] pointer-events-none z-[1]"
      :is-placeholder="!modelValue && !isFocused"
      title-offset-top="-60px"
    >
      {{ label }}
    </FormFieldLabel>
    <CKEditorComponent
      v-model="internalValue"
      :editor="TextEditor"
      @blur="isFocused = false"
      @focus="isFocused = true"
    />
    <div v-if="readonly" class="disabled-overlay"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import FormFieldLabel from '../FormFieldLabel.vue'
import { TextEditor } from './ckeditor/htmlEditors'
import CKEditor from '@ckeditor/ckeditor5-vue'

const {
  modelValue,
  label = '',
  small = false,
  readonly = false,
} = defineProps<{
  modelValue: string | number | null | undefined
  label?: string
  small?: boolean
  readonly?: boolean
}>()

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

const CKEditorComponent = CKEditor.component

const internalValue = ref(
  typeof modelValue === 'number'
    ? modelValue.toString()
    : modelValue !== null
    ? modelValue
    : ''
)
watch(internalValue, (n) => emit('update:modelValue', n))

const isFocused = ref(false)
</script>

<style>
.small .ck .ck .ck-content {
  min-height: 107px;
}
</style>

<style scoped lang="scss">
.disabled-overlay {
  position: absolute;
  inset: 0;
  background: #f3f5f6;
  opacity: 0.5;
}
</style>
