<template>
  <div class="border rounded bg-gray-900 text-gray-100">
    <div class="flex items-center justify-between px-3 py-1.5 border-b border-gray-700 text-xs">
      <span>
        日志 ·
        <span :class="connClass">{{ connText }}</span>
        <span
          v-if="exitText"
          class="text-gray-400"
        >
          · {{ exitText }}
        </span>
      </span>
      <NButton
        text
        size="tiny"
        class="!text-gray-300"
        @click="clear"
      >
        清屏
      </NButton>
    </div>
    <NScrollbar
      ref="scrollRef"
      :style="{ maxHeight: '360px' }"
    >
      <div class="p-3 font-mono text-xs leading-relaxed">
        <div
          v-for="l in logs"
          :key="l.id"
          :class="l.level === 'error' ? 'text-red-400' : 'text-gray-200'"
          class="whitespace-pre-wrap break-all"
        >
          {{ l.text }}
        </div>
        <div
          v-if="logs.length === 0"
          class="text-gray-500"
        >
          暂无日志（进程未运行或尚无输出）
        </div>
      </div>
    </NScrollbar>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { NScrollbar, NButton } from 'naive-ui'
import { useRunStream } from '@/composables/useRunStream'

const props = defineProps<{ profileId: string }>()

const { status, runStatus, exitCode, logs, clear } = useRunStream(props.profileId)

const scrollRef = ref<InstanceType<typeof NScrollbar> | null>(null)

// 新日志到达后自动滚到底部。
watch(
  () => logs.value.length,
  () => {
    nextTick(() => scrollRef.value?.scrollTo({ top: 999_999_999 }))
  },
)

const connText = computed(() => {
  switch (status.value) {
    case 'streaming':
      return '已连接'
    case 'connecting':
      return '连接中…'
    case 'error':
      return '连接异常'
    default:
      return '已断开'
  }
})
// 进程已停止/崩溃且带退出码时展示，例如「退出码 0」。
const exitText = computed(() =>
  exitCode.value !== null && (runStatus.value === 'stopped' || runStatus.value === 'crashed')
    ? `退出码 ${exitCode.value}`
    : '',
)
const connClass = computed(() =>
  status.value === 'streaming'
    ? 'text-green-400'
    : status.value === 'error'
      ? 'text-red-400'
      : 'text-gray-400',
)
</script>
