<template>
  <div class="q-editor">
    <div ref="editorContainer"></div>
  </div>
</template>

<script>
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import Quill from "quill";
import "quill/dist/quill.snow.css";

export default {
  name: "QuillEditor",
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    options: {
      type: Object,
      default: () => ({
        theme: "snow",
        placeholder: "Start typing...",
        modules: {
          toolbar: [
            [{ font: [] }, { size: [] }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ color: [] }, { background: [] }],
            [{ script: 'sub' }, { script: 'super' }],
            [{ header: 1 }, { header: 2 }, 'blockquote', 'code-block'],
            [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
            [{ direction: 'rtl' }, { align: [] }],
            ['link', 'image', 'video', 'formula'],
            ['clean'], // remove formatting
          ],
        },
      }),
    },
  },
  emits: ["update:modelValue"],
  setup(props, { emit }) {
    const editorContainer = ref(null);
    let quillInstance = null;

    onMounted(() => {
      quillInstance = new Quill(editorContainer.value, props.options);

      quillInstance.root.innerHTML = props.modelValue;

      quillInstance.on("text-change", () => {
        emit("update:modelValue", quillInstance.root.innerHTML);
      });
    });

    watch(
        () => props.modelValue,
        (newValue) => {
          if (quillInstance && quillInstance.root.innerHTML !== newValue) {
            quillInstance.root.innerHTML = newValue;
          }
        }
    );

    onBeforeUnmount(() => {
      quillInstance = null;
    });

    return {
      editorContainer,
    };
  },
};
</script>