<!-- =============================================================================
// 企微IT智能服务台 — H5用户端对话区面板
// =============================================================================
// 说明：对话区主面板，包含：
//   1. 标题栏（IT智能服务台 + 坐席状态 + 🔔呼叫 + 主题切换）
//   2. 排查步骤（固定在消息区顶部，不随滚动消失）
//   3. 消息列表（自动滚动到底部）
//   4. 消息类型渲染：员工(右蓝) / 坐席(左白) / AI(左绿+AI标签) / 系统(居中灰)
//   5. 底部输入栏（工具栏+输入+发送+引导条）
// ============================================================================= -->

<template>
  <div class="chat-panel">
    <!-- 顶部标题栏 -->
    <div class="chat-panel__header">
      <div class="chat-panel__header-left">
        <span class="chat-panel__title">IT智能服务台</span>
        <!-- 坐席在线状态 -->
        <span v-if="store.agentOnline" class="chat-panel__status chat-panel__status--online">
          <span class="chat-panel__status-dot"></span>
          坐席在线
        </span>
        <span v-else class="chat-panel__status chat-panel__status--offline">
          <span class="chat-panel__status-dot"></span>
          坐席离线
        </span>
      </div>
      <div class="chat-panel__header-actions">
        <!-- 🔔 呼叫坐席按钮 -->
        <button
          v-if="store.canCallAgent"
          class="chat-panel__bell-btn"
          :disabled="!store.isLoggedIn || store.shaking"
          title="摇铃呼叫人工坐席"
          @click="showCallModal = true"
        >
          <span class="chat-panel__bell-icon">🔔</span>
          <span class="chat-panel__bell-text">呼叫</span>
        </button>
        <!-- 主题切换开关（☀️ 滑轨 🌙） -->
        <div
          class="theme-switch"
          :title="themeStore.currentTheme === 'light' ? '切换到深色模式' : '切换到浅色模式'"
          @click="themeStore.toggleTheme()"
        >
          <span class="switch-icon">☀️</span>
          <div class="switch-track">
            <div class="switch-thumb"></div>
          </div>
          <span class="switch-icon">🌙</span>
        </div>
      </div>
    </div>

    <!-- 排查步骤：固定在消息区顶部（标题栏下方、所有消息之上，不随滚动消失） -->
    <div v-if="store.troubleshootingSteps?.length" class="chat-panel__troubleshoot-fixed">
      <TroubleshootFlow />
    </div>

    <!-- 参与者横幅：当有被邀请参与者时显示（邀请功能 P0-09~P0-11） -->
    <div
      v-if="store.participants.length > 0"
      class="chat-panel__participant-banner"
      @click="store.toggleParticipantPanel()"
    >
      <span class="chat-panel__participant-icon">👥</span>
      <span class="chat-panel__participant-text">
        {{ store.joinedParticipantCount }}人已加入，共{{ store.participants.length }}人被邀请
      </span>
      <span
        class="chat-panel__participant-arrow"
        :class="{ 'chat-panel__participant-arrow--open': store.participantPanelVisible }"
      >▾</span>
    </div>

    <!-- 参与者面板（展开时显示） -->
    <div v-if="store.participantPanelVisible" class="chat-panel__participant-panel">
      <ParticipantList />
    </div>

    <!-- 消息列表区域（可滚动） -->
    <div ref="messageListRef" class="chat-panel__messages" @scroll="handleScroll">
      <!-- 未登录提示 -->
      <div v-if="!store.isLoggedIn" class="chat-panel__not-logged">
        <van-empty description="正在获取身份信息..." image="search" />
      </div>

      <!-- 无消息提示 -->
      <div v-else-if="store.messages.length === 0" class="chat-panel__empty">
        <div class="chat-panel__empty-icon">💬</div>
        <p class="chat-panel__empty-text">暂无消息</p>
        <p class="chat-panel__empty-hint">输入问题咨询，或 🔔 摇铃呼叫坐席</p>
      </div>

      <!-- 消息列表 -->
      <template v-else>
        <MessageBubble
          v-for="msg in store.messages"
          :key="msg.message_id"
          :msg="msg"
        />
      </template>
    </div>

    <!-- 底部输入栏 -->
    <InputBar />

    <!-- 呼叫坐席弹窗（描述问题 → AI确认 → 动画） -->
    <CallAgentModal
      :visible="showCallModal"
      @update:visible="showCallModal = $event"
      @call-success="handleCallSuccess"
    />

    <!-- 审批卡片弹窗（关键词触发） -->
    <ApprovalCardModal
      v-model="store.approvalCardVisible"
      :trigger-text="store.approvalCardTriggerText"
      @select="handleApprovalSelect"
    />
  </div>
</template>

<script setup lang="ts">
/**
 * ChatPanel 对话区面板
 * 包含标题栏、排查步骤（固定顶部）、消息列表和底部输入栏
 * 消息列表自动滚动到底部
 * 排查步骤固定在消息区顶部，不随消息滚动消失
 */

import { ref, watch, nextTick, onMounted } from 'vue'
import { useConversationStore } from '@/stores/conversation'
import { useThemeStore } from '@/stores/theme'
import MessageBubble from './MessageBubble.vue'
import InputBar from './InputBar.vue'
import CallAgentModal from './CallAgentModal.vue'
import ApprovalCardModal from './ApprovalCardModal.vue'
import TroubleshootFlow from './TroubleshootFlow.vue'
import ParticipantList from './ParticipantList.vue'

const store = useConversationStore()
const themeStore = useThemeStore()

/** 消息列表容器的 DOM 引用 */
const messageListRef = ref<HTMLElement | null>(null)

/** 是否显示「呼叫坐席」弹窗 */
const showCallModal = ref<boolean>(false)

/** 是否应该自动滚动到底部（用户手动上滚时暂停自动滚动） */
const shouldAutoScroll = ref<boolean>(true)

/**
 * 滚动到消息列表底部
 * 使用 nextTick 确保 DOM 更新后再滚动
 */
async function scrollToBottom(): Promise<void> {
  await nextTick()
  if (messageListRef.value && shouldAutoScroll.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

/**
 * 处理滚动事件
 * 如果用户滚动到接近底部，恢复自动滚动
 * 如果用户向上滚动离开底部，暂停自动滚动
 */
function handleScroll(): void {
  if (!messageListRef.value) return
  const { scrollTop, scrollHeight, clientHeight } = messageListRef.value
  // 距离底部 100px 以内时恢复自动滚动
  shouldAutoScroll.value = scrollHeight - scrollTop - clientHeight < 100
}

/** 呼叫成功回调：刷新会话状态 */
function handleCallSuccess(): void {
  store.fetchCurrentConversation()
}

/** 处理审批选项选择 */
function handleApprovalSelect(option: any): void {
  console.log('[ChatPanel] 选择审批:', option)
  store.closeApprovalCard()
}

// 监听消息列表变化，自动滚动到底部
watch(
  () => store.messages.length,
  () => {
    scrollToBottom()
  }
)

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
/* 对话区面板容器 */
.chat-panel {
  display: flex;
  flex-direction: column;
  height: 100dvh;
  background-color: var(--bg-primary);
}

/* 兼容不支持 dvh 的浏览器 */
@supports not (height: 100dvh) {
  .chat-panel {
    height: 100vh;
  }
}

/* 顶部标题栏 */
.chat-panel__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
  flex-shrink: 0;
}

/* 标题栏左侧 */
.chat-panel__header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 标题文字 */
.chat-panel__title {
  font-size: 17px;
  font-weight: 600;
  color: var(--text-primary);
}

/* 坐席在线状态 */
.chat-panel__status {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.chat-panel__status--online {
  background-color: var(--color-success-soft, rgba(34, 197, 94, 0.1));
  color: var(--color-success, #22c55e);
}

.chat-panel__status--offline {
  background-color: var(--bg-tertiary);
  color: var(--text-tertiary);
}

.chat-panel__status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

.chat-panel__status--online .chat-panel__status-dot {
  background-color: var(--color-success, #22c55e);
  animation: pulse-dot 2s ease-in-out infinite;
}

.chat-panel__status--offline .chat-panel__status-dot {
  background-color: var(--text-tertiary);
}

@keyframes pulse-dot {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 标题栏右侧操作区 */
.chat-panel__header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 🔔 呼叫坐席按钮（标题栏） */
.chat-panel__bell-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 20px;
  border: 1px solid var(--color-warning, #FF9800);
  background: linear-gradient(135deg, #FFF8E1, #FFE082);
  cursor: pointer;
  transition: all 0.2s ease;
  font-family: inherit;
  font-size: 13px;
  font-weight: 500;
  color: #E65100;
  animation: bell-idle 2s ease-in-out infinite;
  -webkit-tap-highlight-color: transparent;
  outline: none;
}

.chat-panel__bell-btn:hover:not(:disabled) {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(255, 152, 0, 0.4);
  animation: bell-ring 0.5s ease-in-out;
}

.chat-panel__bell-btn:active:not(:disabled) {
  transform: scale(0.95);
}

.chat-panel__bell-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  animation: none;
}

.chat-panel__bell-icon {
  font-size: 16px;
  line-height: 1;
}

.chat-panel__bell-text {
  font-size: 12px;
}

/* 静止时轻微摇摆 */
@keyframes bell-idle {
  0%, 100% { transform: rotate(0); }
  25% { transform: rotate(-3deg); }
  75% { transform: rotate(3deg); }
}

/* 悬停时快速摇铃 */
@keyframes bell-ring {
  0%, 100% { transform: rotate(0) scale(1.05); }
  15% { transform: rotate(-10deg) scale(1.05); }
  30% { transform: rotate(8deg) scale(1.05); }
  45% { transform: rotate(-6deg) scale(1.05); }
  60% { transform: rotate(4deg) scale(1.05); }
  75% { transform: rotate(-2deg) scale(1.05); }
  90% { transform: rotate(1deg) scale(1.05); }
}

/* 排查步骤：固定在消息区顶部 */
.chat-panel__troubleshoot-fixed {
  flex-shrink: 0;
  border-bottom: 1px solid var(--border-color);
}

/* 参与者横幅：点击可展开/收起参与者面板 */
.chat-panel__participant-banner {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 16px;
  background-color: var(--accent-soft, rgba(59, 130, 246, 0.06));
  border-bottom: 1px solid var(--border-color);
  cursor: pointer;
  transition: background-color 0.15s;
  flex-shrink: 0;
  -webkit-tap-highlight-color: transparent;
}

.chat-panel__participant-banner:hover {
  background-color: var(--accent-soft, rgba(59, 130, 246, 0.12));
}

.chat-panel__participant-icon {
  font-size: 14px;
  line-height: 1;
}

.chat-panel__participant-text {
  flex: 1;
  font-size: 12px;
  color: var(--accent);
  font-weight: 500;
}

.chat-panel__participant-arrow {
  font-size: 12px;
  color: var(--accent);
  transition: transform 0.2s;
}

.chat-panel__participant-arrow--open {
  transform: rotate(180deg);
}

/* 参与者面板（展开时显示 ParticipantList） */
.chat-panel__participant-panel {
  flex-shrink: 0;
  border-bottom: 1px solid var(--border-color);
  background-color: var(--bg-secondary);
  max-height: 240px;
  overflow-y: auto;
}

/* 消息列表区域 */
.chat-panel__messages {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
  -webkit-overflow-scrolling: touch;
}

/* 未登录提示 */
.chat-panel__not-logged {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

/* 无消息空状态 */
.chat-panel__empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 16px;
}

/* 空状态图标 */
.chat-panel__empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

/* 空状态提示文字 */
.chat-panel__empty-text {
  font-size: 15px;
  color: var(--text-tertiary);
  margin-bottom: 8px;
}

/* 空状态辅助提示 */
.chat-panel__empty-hint {
  font-size: 12px;
  color: var(--text-placeholder);
  text-align: center;
}
</style>
