<template>
  <div class="quill-editor-wrapper">
    <client-only>
      <QuillEditor
        ref="quillEditor"
        v-model:content="content"
        contentType="html"
        :options="editorOptions"
        :style="{ height: `${height + 50}px` }"
        @update:content="onContentChange"
      />
      <template #fallback>
        <textarea
          :value="modelValue"
          @input="$emit('update:modelValue', $event.target.value)"
          :placeholder="placeholder"
          :style="{ height: `${height}px` }"
          class="fallback-textarea"
        />
      </template>
    </client-only>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: Number,
    default: 400
  },
  placeholder: {
    type: String,
    default: '내용을 입력하세요'
  }
})

const emit = defineEmits(['update:modelValue'])

const quillEditor = ref(null)

const content = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const editorOptions = {
  theme: 'snow',
  placeholder: props.placeholder,
  modules: {
    toolbar: [
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      ['blockquote', 'code-block'],
      ['link', 'image', 'video'],
      ['clean']
    ]
  },
  formats: [
    'header', 'bold', 'italic', 'underline', 'strike',
    'color', 'background', 'font', 'align',
    'list', 'bullet', 'indent', 'blockquote', 'code-block',
    'link', 'image', 'video'
  ]
}

const onContentChange = (content) => {
  emit('update:modelValue', content)
}

watch(() => props.modelValue, (newValue) => {
  if (content.value !== newValue) {
    content.value = newValue
  }
})
</script>

<style scoped>
.quill-editor-wrapper {
  width: 100%;
}

.fallback-textarea {
  width: 100%;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.6;
  resize: vertical;
}

:deep(.ql-editor) {
  font-family: inherit;
  font-size: 14px;
  line-height: 1.6;
  min-height: 300px;
}

:deep(.ql-toolbar) {
  border-top: 1px solid #ddd;
  border-left: 1px solid #ddd;
  border-right: 1px solid #ddd;
  background-color: #f8f9fa;
}

:deep(.ql-container) {
  border-bottom: 1px solid #ddd;
  border-left: 1px solid #ddd;
  border-right: 1px solid #ddd;
  border-radius: 0 0 4px 4px;
}

:deep(.ql-toolbar:first-child) {
  border-radius: 4px 4px 0 0;
}
</style>