<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: "",
    },
    limit: {
      type: Number,
      default: 1000,
    },
    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", () => {
        const text = quillInstance.getText().trim();
        const words = text.split(/\s+/).filter(Boolean);

        if (words.length > props.limit) {

          let charIndex = 0
          let wordCount = 0

          while (wordCount < props.limit && charIndex < text.length) {
            if (/\s/.test(text[charIndex])) {
              wordCount++
            }
            charIndex++
          }

          quillInstance.deleteText(charIndex, quillInstance.getLength())
        }

        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>