<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import Editor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight-all'
import 'prismjs/themes/prism-tomorrow.css'
import '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight.css'

const props = defineProps({
  modelValue: { type: String, default: '' },
  height: { type: String, default: '400px' },
  placeholder: { type: String, default: '' },
  initialEditType: { type: String, default: 'wysiwyg' }, // 'markdown' | 'wysiwyg'
})
const emit = defineEmits(['update:modelValue'])

// PC(Electron)는 Toast UI 에디터(위지윅·CodeMirror 모두)에서 한글 IME 첫 자음이 중복되는
// Chromium 버그가 있다(제목 등 일반 입력은 정상). → PC 에선 일반 textarea(네이티브 IME)로 입력받는다.
// 웹/모바일(APK)은 기존 Toast UI 위지윅 유지.
const isElectron = typeof navigator !== 'undefined' && /electron/i.test(navigator.userAgent)

// ===== PC: 일반 textarea (Vue v-model 이 IME 조합을 올바르게 처리) =====
const text = ref(props.modelValue || '')
if (isElectron) {
  watch(text, (v) => emit('update:modelValue', v))
  watch(
    () => props.modelValue,
    (v) => {
      if ((v || '') !== text.value) text.value = v || ''
    },
  )
}

// ===== 웹/APK: Toast UI 위지윅 =====
const el = ref(null)
let editor = null
let lastEmitted = props.modelValue || ''

onMounted(() => {
  if (isElectron) return
  editor = new Editor({
    el: el.value,
    height: props.height,
    initialEditType: props.initialEditType,
    hideModeSwitch: true,
    plugins: [codeSyntaxHighlight],
    initialValue: props.modelValue || '',
    placeholder: props.placeholder,
    usageStatistics: false,
    autofocus: false,
    events: {
      change: () => {
        lastEmitted = editor.getMarkdown()
        emit('update:modelValue', lastEmitted)
      },
    },
  })
})

watch(
  () => props.modelValue,
  (val) => {
    if (isElectron) return
    const v = val || ''
    if (v === lastEmitted) return
    if (editor && v !== editor.getMarkdown()) {
      lastEmitted = v
      editor.setMarkdown(v)
    }
  },
)

onBeforeUnmount(() => {
  editor?.destroy()
  editor = null
})
</script>

<template>
  <!-- PC(Electron): 일반 textarea — 한글 IME 정상 -->
  <textarea
    v-if="isElectron"
    v-model="text"
    class="md-textarea"
    :placeholder="placeholder"
    :style="{ height }"
  ></textarea>
  <!-- 웹/APK: Toast UI 에디터 -->
  <div v-else ref="el"></div>
</template>

<style scoped>
.md-textarea {
  width: 100%;
  box-sizing: border-box;
  padding: 0.75rem 0.9rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
  font-family: inherit;
  font-size: 0.95rem;
  line-height: 1.6;
  resize: vertical;
}
.md-textarea:focus {
  outline: none;
  border-color: hsla(160, 100%, 37%, 1);
}
</style>
