<script setup lang="ts">
import { ref, computed } from 'vue'
import { VueMonacoEditor } from '@guolao/vue-monaco-editor'
import { useThemeStore } from '@/stores/theme'

const props = defineProps<{ modelValue: string; language?: string }>()
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()

const themeStore = useThemeStore()

const editorTheme = computed(() => {
  if (themeStore.mode === 'dark') return 'vs-dark'
  if (themeStore.mode === 'light') return 'vs'
  // System mode: check actual dark class
  return document.documentElement.classList.contains('dark') ? 'vs-dark' : 'vs'
})

const editorRef = ref<unknown>(null)

function onMount(editor: unknown) {
  editorRef.value = editor
}

function onChange(value: string | undefined) {
  if (value !== undefined) {
    emit('update:modelValue', value)
  }
}

defineExpose({ editor: editorRef })
</script>

<template>
  <div class="border border-border-light dark:border-slate-700 rounded-lg overflow-hidden h-full" style="min-height: 500px">
    <VueMonacoEditor
      :value="props.modelValue"
      :language="props.language || 'markdown'"
      :theme="editorTheme"
      :options="{
        minimap: { enabled: false },
        wordWrap: 'on',
        lineNumbers: 'on',
        fontSize: 14,
        fontFamily: 'JetBrains Mono, monospace',
        scrollBeyondLastLine: false,
        automaticLayout: true,
        tabSize: 2,
      }"
      height="100%"
      @mount="onMount"
      @change="onChange"
    />
  </div>
</template>
