<template>
  <div class="terminal-display" ref="containerRef">
    <div class="terminal-output" ref="outputRef"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import 'xterm/css/xterm.css'

const props = defineProps<{
  sessionId: string | null
}>()

const emit = defineEmits<{
  input: [data: string]
}>()

const containerRef = ref<HTMLElement | null>(null)
const outputRef = ref<HTMLElement | null>(null)
let terminal: Terminal | null = null
let fitAddon: FitAddon | null = null

onMounted(() => {
  terminal = new Terminal({
    theme: { background: '#1e1e1e' },
    cursorBlink: true,
  })
  
  fitAddon = new FitAddon()
  terminal.loadAddon(fitAddon)
  
  terminal.open(outputRef.value!)
  fitAddon.fit()
  
  // 用户输入
  terminal.onData((data) => {
    emit('input', data)
  })
})

onUnmounted(() => {
  terminal?.dispose()
})

function write(data: string) {
  terminal?.write(data)
}

function clear() {
  terminal?.clear()
}

defineExpose({ write, clear })
</script>

<style scoped>
.terminal-display {
  background: #1e1e1e;
  border-radius: 8px;
  overflow: hidden;
}

.terminal-output {
  padding: 12px;
  min-height: 400px;
}
</style>
