<template>
  <div class="tw:space-y-2">
    <textarea
      ref="textareaRef"
      class="form-control"
      :placeholder="placeholder"
    ></textarea>
  </div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from "vue";

const props = defineProps({
  placeholder: {
    type: String,
    default: "",
  },
  height: {
    type: Number,
    default: 240,
  },
});

const model = defineModel({
  type: String,
  default: "",
});

const textareaRef = ref(null);
const summernoteInstance = ref(null);

const getJQuery = () => window.$ || window.jQuery;

const normalizeTelegramHtml = (html = "") => {
  const withoutEmptyParagraphs = html.replace(/<p><br><\/p>/gi, "<br>");
  const withoutParagraphs = withoutEmptyParagraphs
    .replace(/<p>/gi, "")
    .replace(/<\/p>/gi, "<br>");

  return withoutParagraphs.replace(/(?:<br>\s*)+$/i, "").trim();
};

const makeSpoilerButton = ($) => (context) => {
  const ui = $.summernote.ui;
  return ui
    .button({
      contents: '<i class="fa fa-eye-slash"></i>',
      tooltip: "Спойлер (Telegram)",
      click() {
        const selectedText = context.invoke("editor.getSelectedText") || "";
        const content = selectedText || "spoiler";
        context.invoke(
          "editor.pasteHTML",
          `<span class="tg-spoiler">${content}</span>`
        );
      },
    })
    .render();
};

onMounted(() => {
  const $ = getJQuery();
  if (!$ || !textareaRef.value) {
    console.warn("[RichTextEditor] jQuery или textarea недоступны");
    return;
  }

  const $el = $(textareaRef.value);

  $el.summernote({
    height: props.height,
    placeholder: props.placeholder,
    shortcuts: false,
    dialogsInBody: true,
    disableResizeEditor: true,
    buttons: {
      spoiler: makeSpoilerButton($),
    },
    toolbar: [
      ["font", ["bold", "underline", "italic", "strikethrough", "clear"]],
      ["para", ["ul", "ol", "paragraph"]],
      ["insert", ["link", "spoiler"]],
      ["view", ["fullscreen", "codeview", "help"]],
    ],
    callbacks: {
      onChange(contents) {
        const normalized = normalizeTelegramHtml(contents ?? "");
        if (normalized !== contents) {
          $el.summernote("code", normalized);
          return;
        }
        model.value = normalized;
      },
      onKeydown(e) {
        if (e.keyCode === 13) {
          e.preventDefault();
          $el.summernote("pasteHTML", "<br>");
        }
      },
    },
  });

  if (model.value) {
    $el.summernote("code", normalizeTelegramHtml(model.value));
  }

  summernoteInstance.value = $el;
});

watch(
  model,
  (value) => {
    const instance = summernoteInstance.value;
    if (!instance) {
      return;
    }
    const normalized = normalizeTelegramHtml(value || "");
    const current = normalizeTelegramHtml(instance.summernote("code"));
    if (current !== normalized) {
      instance.summernote("code", normalized);
    }
  }
);

onBeforeUnmount(() => {
  if (summernoteInstance.value) {
    summernoteInstance.value.summernote("destroy");
    summernoteInstance.value = null;
  }
});
</script>

