<script lang="ts" setup>
type ChatRole = 'user' | 'assistant'

interface ChatMessage {
  id: string
  role: ChatRole
  content: string
  createdAt: number
}

const messages = ref<ChatMessage[]>([
  {
    id: 'm1',
    role: 'assistant',
    content:
      '欢迎来到企业文化 AI 助手。\n你可以直接输入：\n1) 帮我润色标题和内容\n2) 生成与内容匹配的标签\n3) 从候选标签里选主/副标签',
    createdAt: Date.now() - 1000 * 60 * 2,
  },
])

const input = ref('')
const sending = ref(false)

const canSend = computed(() => input.value.trim().length > 0 && !sending.value)

function uid() {
  return `${Date.now()}_${Math.random().toString(16).slice(2)}`
}

const handleSend = async () => {
  const text = input.value.trim()
  if (!text || sending.value) return

  sending.value = true

  const userMsg: ChatMessage = { id: uid(), role: 'user', content: text, createdAt: Date.now() }
  messages.value.push(userMsg)
  messages.value.push({
    id: uid(),
    role: 'assistant',
    content: '正在思考.......',
    createdAt: Date.now(),
  })
  scrollToBottom()

  const response = await fetch(`${import.meta.env.VITE_AI_API_URL}/api/chat`, {
    method: 'POST',
    body: JSON.stringify({ content: text }),
    headers: {
      'Content-Type': 'application/json',
    },
  })

  // 流式读取
  const reader = response.body?.getReader()
  if (!reader) return
  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    const content = new TextDecoder().decode(value)
    messages.value[messages.value.length - 1]!.content += content
    scrollToBottom()
  }
  input.value = ''
  sending.value = false
}

const scrollToBottom = () => {
  window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' })
}

onMounted(() => {
  scrollToBottom()
})
</script>

<template>
  <div class="min-h-screen bg-gradient-to-b flex flex-col">
    <div class="max-w-4xl mx-auto w-full px-4 pt-6 flex flex-col flex-1">
      <!-- 顶部说明 -->
      <div class="mb-4">
        <div class="flex items-center gap-3">
          <div
            class="w-11 h-11 rounded-2xl bg-gradient-to-br from-indigo-500 to-violet-500 shadow-lg shadow-indigo-200/40 flex items-center justify-center"
          >
            <span class="text-white font-bold">AI</span>
          </div>
          <div class="flex-1">
            <div class="text-lg font-semibold text-slate-900">企业文化 AI 助手</div>
            <div class="text-sm text-slate-500">
              先用假数据体验对话交互，后续可接你的 AI 后端接口
            </div>
          </div>
        </div>
      </div>

      <!-- 消息区（占满剩余高度） -->
      <el-card
        class="rounded-2xl border border-slate-200/70 bg-white shadow-sm flex-1 flex flex-col min-h-0"
      >
        <div
          ref="scrollEl"
          class="flex-1 overflow-auto p-4 pr-1 min-h-0"
          style="scrollbar-gutter: stable"
        >
          <div class="space-y-4">
            <div
              v-for="m in messages"
              :key="m.id"
              class="flex"
              :class="m.role === 'user' ? 'justify-end' : 'justify-start'"
            >
              <div
                class="max-w-[72%] whitespace-pre-wrap break-words rounded-2xl px-4 py-3 text-[15px] leading-relaxed shadow-sm"
                :class="
                  m.role === 'user' ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-800'
                "
              >
                {{ m.content }}
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 输入区（放在同一列容器内：宽度/边距对齐消息卡片） -->
      <div class="mt-auto sticky bottom-0 z-10 py-4 backdrop-blur">
        <div
          class="bg-white border border-slate-200/70 rounded-2xl shadow-sm px-3 py-3 flex gap-3 items-center"
        >
          <el-input
            v-model="input"
            type="textarea"
            :rows="2"
            resize="none"
            placeholder="输入你的问题，比如：润色标题和内容 / 生成标签 / 选取主副标签..."
            class="flex-1"
            @keyup.enter.exact.prevent="handleSend"
          />
          <el-button
            type="primary"
            :disabled="!canSend"
            :loading="sending"
            class="min-w-20 rounded-xl"
            @click="handleSend"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 让 Element Plus textarea 输入更接近你的卡片圆角与“聊天”风格 */
:deep(.el-input__wrapper) {
  border-radius: 16px !important;
  box-shadow: none !important;
}

:deep(.el-textarea__inner) {
  border-radius: 16px !important;
  padding: 10px 12px !important;
}
</style>
