<template>
  <div class="tip-tap">
    <editor-content
      class="tip-tap__editor-wrapper"
      :editor="editor"
    />

    <toggle
      :bordered="false"
      :checked="isList"
      label="Als Liste formatieren"
      @input="toggleList"
    />
  </div>
</template>

<script lang="ts" setup>
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import BulletList from '@tiptap/extension-bullet-list';
import ListItem from '@tiptap/extension-list-item';
import { EditorContent, useEditor } from '@tiptap/vue-3';
import Toggle from '@/components/ui/Toggle.vue';
import { computed, watch } from 'vue';
import log from 'loglevel';
interface Value {
  text: string;
}
interface Props {
  value: Value;
}

const props = defineProps<Props>();
const emits = defineEmits(['input', 'change-text']);
const text = computed(() => props.value.text || '');

const editor = useEditor({
  editorProps: {
    attributes: {
      class: 'tip-tap__editor',
    },
  },
  content: text.value,
  extensions: [Document, Paragraph, Text, BulletList, ListItem],
  onUpdate: ({ editor }) => {
    log.debug('editor:onUpdate');
    const text = editor.getHTML();
    // emits('input', text);
    emits('change-text', text);
  },
});

// watch(text, (newText: string, _oldText: string) => {
watch(text, (newText: string) => {
  const isSame = editor.value?.getHTML() === newText;

  if (isSame) {
    return;
  }

  editor.value?.commands.setContent(newText, false);
});

const isList = computed(() => editor.value?.isActive('bulletList') || false);
const toggleList = () => {
  console.log('toggleList');
  editor.value?.chain().selectAll().toggleBulletList().run();
};
</script>

<style scoped lang="scss">
@import 'styles/helpers';

.tip-tap {
  &__editor-wrapper {
    margin-bottom: $medium-spacing;
  }

  :deep(.tip-tap__editor) {
    @include inputstyle;
    flex-direction: column;
    min-height: 150px;
  }

  :deep(ul) {
    padding-left: $medium-spacing;
    list-style: initial;
  }

  :deep(li) {
    @include inputfont;
  }

  :deep(div) {
    @include inputfont;
  }

  :deep(p) {
    @include inputfont;
  }
}
</style>
