<template>
  <div
    v-if="content || isStreaming"
    class="thinking-block"
    :class="{
      'thinking-block--expanded': expanded,
      'thinking-block--streaming': isStreaming,
      'thinking-block--loading': isLoading,
    }"
  >
    <div class="thinking-block__header" @click="toggle">
      <div class="thinking-block__title">
        <BulbOutlined class="thinking-block__icon" />
        <span class="thinking-block__label">{{ isLoading ? '正在思考…' : '思考过程' }}</span>
        <a-spin v-if="isStreaming" size="small" class="thinking-block__spinner" />
      </div>
      <div class="thinking-block__right">
        <span v-if="!isStreaming && content" class="thinking-block__meta">{{ summary }}</span>
        <RightOutlined
          :class="['thinking-block__expand', { 'thinking-block__expand--open': expanded }]"
        />
      </div>
    </div>
    <div v-if="expanded && content" class="thinking-block__content">
      <div
        ref="contentRef"
        class="thinking-block__text"
        :class="{ 'thinking-block__text--streaming': isStreaming }"
      >{{ content }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { BulbOutlined, RightOutlined } from '@ant-design/icons-vue'
import { Spin as ASpin } from 'ant-design-vue'

const props = defineProps<{
  content: string
  isStreaming?: boolean
}>()

// ponytail: content prop is already the accumulated stream (chatStream.ts:519),
// no extra truncation needed — rendering content directly gives token-by-token effect.
const isLoading = computed(() => !!props.isStreaming && !props.content)

// Streaming: expand by default to surface live tokens. Finished: collapsed summary bar.
const expanded = ref(props.isStreaming === true)
const contentRef = ref<HTMLElement | null>(null)
const scrollTopRef = ref(0)
const startTime = ref<Date | null>(null)

watch(
  () => props.content,
  (val) => {
    if (val && !startTime.value) {
      startTime.value = new Date()
    }
  },
  { immediate: true },
)

// Auto-collapse to summary bar when streaming finishes (true -> false).
watch(
  () => props.isStreaming,
  (now, prev) => {
    if (prev && !now && props.content) {
      expanded.value = false
    }
  },
)

const summary = computed(() => {
  const time = startTime.value
  const timeStr = time
    ? `${pad2(time.getHours())}:${pad2(time.getMinutes())}:${pad2(time.getSeconds())}`
    : ''
  return `${timeStr} · ${props.content.length} 字符`
})

function pad2(n: number): string {
  return String(n).padStart(2, '0')
}

function toggle(): void {
  // Preserve scroll position before collapsing (contentRef still mounted).
  if (expanded.value && contentRef.value) {
    scrollTopRef.value = contentRef.value.scrollTop
  }
  expanded.value = !expanded.value
  // Restore scroll position after expanding (DOM re-rendered via v-if).
  if (expanded.value) {
    nextTick(() => {
      if (contentRef.value) {
        contentRef.value.scrollTop = scrollTopRef.value
      }
    })
  }
}
</script>

<style scoped>
.thinking-block {
  border: 1px solid var(--border-color-split, #f0f0f0);
  border-radius: var(--radius-md, 8px);
  overflow: hidden;
  font-size: var(--font-sm, 13px);
  background: var(--bg-tertiary, #fafafa);
  margin-bottom: var(--space-2, 8px);
}

.thinking-block__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-2, 8px) var(--space-3, 12px);
  cursor: pointer;
  user-select: none;
  transition: background var(--transition-fast, 0.15s);
}

.thinking-block__header:hover {
  background: rgba(0, 0, 0, 0.02);
}

.thinking-block__title {
  display: flex;
  align-items: center;
  gap: var(--space-2, 8px);
}

.thinking-block__icon {
  font-size: 14px;
  color: var(--color-warning, #faad14);
}

.thinking-block__label {
  font-weight: var(--font-weight-medium, 500);
  color: var(--text-secondary, #666);
  font-size: var(--font-xs, 12px);
}

.thinking-block__spinner {
  margin-left: var(--space-1, 4px);
}

.thinking-block__right {
  display: flex;
  align-items: center;
  gap: var(--space-2, 8px);
}

.thinking-block__meta {
  color: var(--text-placeholder, #bfbfbf);
  font-size: var(--font-xs, 12px);
  font-variant-numeric: tabular-nums;
}

.thinking-block__expand {
  font-size: 10px;
  color: var(--text-placeholder, #bfbfbf);
  transition: transform var(--transition-fast, 0.15s);
}

.thinking-block__expand--open {
  transform: rotate(90deg);
}

.thinking-block__content {
  padding: var(--space-2, 8px) var(--space-3, 12px);
  border-top: 1px solid var(--border-color-split, #f0f0f0);
}

.thinking-block__text {
  color: var(--text-tertiary, #999);
  font-size: var(--font-xs, 12px);
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 300px;
  overflow-y: auto;
}

/* Streaming cursor: blinking caret at the tail of accumulated text. */
.thinking-block__text--streaming::after {
  content: '';
  display: inline-block;
  width: 7px;
  height: 1em;
  margin-left: 3px;
  background: var(--color-warning, #faad14);
  vertical-align: text-bottom;
  animation: thinking-block-blink 1s step-end infinite;
}

@keyframes thinking-block-blink {
  0%,
  50% {
    opacity: 1;
  }
  50.01%,
  100% {
    opacity: 0;
  }
}
</style>
