<script setup>
import { ref } from "vue";
import Editor from "primevue/editor";

const props = defineProps({
  modelValue: { type: String, default: "" },
  label: { type: String, default: "" },
  disabled: { type: Boolean, default: false },
  placeholder: { type: String, default: "" },
  invalid: { type: Boolean, default: false },
  editorStyle: { type: String, default: "min-height: 200px" },
  /** When true, show a compact toolbar with only essential formatting. */
  minimal: { type: Boolean, default: false },
});

const emit = defineEmits(["update:modelValue"]);

const shellRef = ref(null);

function focusEditor(event) {
  if (props.disabled) return;
  if (!shellRef.value) return;
  const target = event?.target;
  if (target instanceof Element) {
    if (target.closest(".ql-toolbar")) return;
    if (target.closest(".ql-editor")) return;
  }
  const editable = shellRef.value.querySelector(".ql-editor");
  if (editable && typeof editable.focus === "function") {
    editable.focus();
  }
}
</script>

<template>
  <div class="flex flex-col gap-2 w-full">
    <label
      v-if="label"
      class="text-sm font-medium text-surface-700 dark:text-surface-200"
      @click="focusEditor"
      >{{ label }}</label
    >
    <div
      ref="shellRef"
      class="base-editor-shell border dark:border-surface-700 rounded-lg overflow-hidden focus-within:border-primary"
      style="border-width: 0.25px"
      :class="{
        'is-disabled': disabled,
        'is-invalid': invalid,
      }"
      @click="focusEditor($event)"
    >
      <Editor
        :model-value="modelValue"
        :readonly="disabled"
        :placeholder="placeholder"
        :class="{ 'opacity-60 pointer-events-none': disabled }"
        :editor-style="editorStyle"
        @update:model-value="emit('update:modelValue', $event)"
      >
        <template v-if="minimal" #toolbar>
          <span class="ql-formats">
            <button class="ql-bold" type="button" />
            <button class="ql-italic" type="button" />
          </span>
          <span class="ql-formats">
            <button class="ql-list" value="ordered" type="button" />
            <button class="ql-list" value="bullet" type="button" />
          </span>
          <span class="ql-formats">
            <button class="ql-clean" type="button" />
          </span>
        </template>
      </Editor>
    </div>
  </div>
</template>
