<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { VueMonacoDiffEditor } from '@guolao/vue-monaco-editor'
import { useThemeStore } from '@/stores/theme'
import AiDiffToolbar from './AiDiffToolbar.vue'

const props = defineProps<{
  original: string
  modified: string
  loading: boolean
  error: string
  action: 'improve' | 'generate_acs' | 'expand'
  mode: 'inline' | 'modal'
}>()

const emit = defineEmits<{
  accept: []
  reject: []
}>()

const themeStore = useThemeStore()

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

const actionLabel = computed(() => {
  switch (props.action) {
    case 'improve': return 'Improve'
    case 'expand': return 'Expand'
    case 'generate_acs': return 'Generate ACs'
    default: return 'Improve'
  }
})

// Throttle modified prop to limit diff recomputation during streaming
const throttledModified = ref(props.modified)
let throttleTimer: ReturnType<typeof setTimeout> | null = null

watch(() => props.modified, (val) => {
  if (!props.loading) {
    // Not streaming — sync immediately
    throttledModified.value = val
    return
  }
  if (throttleTimer) return
  throttleTimer = setTimeout(() => {
    throttledModified.value = props.modified
    throttleTimer = null
  }, 150)
})

// Final sync when loading completes
watch(() => props.loading, (loading) => {
  if (!loading) {
    if (throttleTimer) {
      clearTimeout(throttleTimer)
      throttleTimer = null
    }
    throttledModified.value = props.modified
  }
})

const diffOptions = {
  readOnly: true,
  originalEditable: false,
  renderSideBySide: true,
  minimap: { enabled: false },
  wordWrap: 'on' as const,
  fontSize: 14,
  fontFamily: 'JetBrains Mono, monospace',
  scrollBeyondLastLine: false,
  automaticLayout: true,
}

function onKeydown(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    emit('reject')
  }
}

onMounted(() => {
  document.addEventListener('keydown', onKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', onKeydown)
  if (throttleTimer) clearTimeout(throttleTimer)
})
</script>

<template>
  <!-- Inline mode -->
  <div v-if="mode === 'inline'" class="border border-border-light dark:border-slate-700 rounded-lg overflow-hidden flex flex-col h-full" style="min-height: 500px">
    <AiDiffToolbar
      :action-label="actionLabel"
      :loading="loading"
      :error="error"
      compact
      @accept="emit('accept')"
      @reject="emit('reject')"
    />
    <!-- Diff editor -->
    <div v-if="!error || throttledModified" class="flex-1">
      <VueMonacoDiffEditor
        :original="original"
        :modified="throttledModified"
        :theme="editorTheme"
        :options="diffOptions"
        language="markdown"
        height="100%"
      />
    </div>
  </div>

  <!-- Modal mode -->
  <Teleport v-else to="body">
    <div class="fixed inset-0 z-50 flex items-center justify-center" @click.self="emit('reject')">
      <!-- Backdrop -->
      <div class="absolute inset-0 bg-black/50" @click="emit('reject')"></div>
      <!-- Card -->
      <div class="relative z-10 w-[90vw] max-w-6xl h-[80vh] bg-surface-light dark:bg-surface rounded-xl shadow-2xl flex flex-col overflow-hidden">
        <AiDiffToolbar
          :action-label="actionLabel"
          :loading="loading"
          :error="error"
          @accept="emit('accept')"
          @reject="emit('reject')"
        />
        <!-- Diff editor -->
        <div v-if="!error || throttledModified" class="flex-1">
          <VueMonacoDiffEditor
            :original="original"
            :modified="throttledModified"
            :theme="editorTheme"
            :options="diffOptions"
            language="markdown"
            height="100%"
          />
        </div>
      </div>
    </div>
  </Teleport>
</template>
