<script setup>
import { useEditor, EditorContent } from "@tiptap/vue-3";
import { StarterKit } from "@tiptap/starter-kit";
import { Underline } from "@tiptap/extension-underline";
import { TextStyle } from "@tiptap/extension-text-style";
import { Color } from "@tiptap/extension-color";
import { FontSize } from "tiptap-extension-font-size";
import { TextAlign } from "@tiptap/extension-text-align";
import { watch } from "vue";

const props = defineProps({
  modelValue: { type: String, default: "" },
  editable: { type: Boolean, default: true },
});
const emit = defineEmits(["update:modelValue", "focus", "blur"]);

const editor = useEditor({
  content: props.modelValue,
  editable: props.editable,
  extensions: [
    StarterKit,
    Underline,
    TextStyle,
    Color.configure({ types: ["textStyle"] }),
    FontSize.configure({ types: ["textStyle"] }),
    TextAlign.configure({ types: ["heading", "paragraph"] }),
  ],
  onUpdate: ({ editor }) => emit("update:modelValue", editor.getHTML()),
  onFocus: ({ editor }) => emit("focus", editor),
  onBlur: ({ editor }) => emit("blur", editor),
});

// Observa cambios en el contenido desde fuera
watch(
  () => props.modelValue,
  (newValue) => {
    if (editor.value && editor.value.getHTML() !== newValue) {
      editor.value.commands.setContent(newValue, false);
    }
  }
);

// Observa cambios en el estado 'editable' desde fuera
watch(
  () => props.editable,
  (isEditable) => {
    editor.value?.setEditable(isEditable);
  }
);

defineExpose({ editor });
</script>

<template>
  <EditorContent :editor="editor" />
</template>

<style scoped>
:deep(.ProseMirror) {
  padding: 0.5rem;
  outline: none;
  width: 100%;
  height: 100%;
  word-wrap: break-word;
}
/* Estilos para cuando NO es editable */
:deep(.ProseMirror[contenteditable="false"]) {
  cursor: default;
}
/* Estilos para cuando SÍ es editable */
:deep(.ProseMirror[contenteditable="true"]:focus) {
  outline: none;
  box-shadow: none;
}
/* Reglas generales que ya teníamos */
:deep(.ProseMirror span[style]) {
  display: inline !important;
}
:deep(.ProseMirror p) {
  margin: 0;
}
:deep(.ProseMirror ul),
:deep(.ProseMirror ol) {
  padding-left: 1.5rem;
}
:deep(p[style*="text-align: center"]) {
  text-align: center;
}
:deep(p[style*="text-align: right"]) {
  text-align: right;
}
:deep(p[style*="text-align: left"]) {
  text-align: left;
}
</style>
