<template>
  <!-- Floating toggle button -->
  <button class="chat-fab" @click="toggleOpen" :title="open ? '关闭' : '联系客服'" aria-label="联系客服">
    <Transition name="icon-flip" mode="out-in">
      <svg v-if="!open" key="chat" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
      </svg>
      <svg v-else key="close" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
        <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
      </svg>
    </Transition>
  </button>

  <!-- Chat panel -->
  <Transition name="chat-slide">
    <div v-if="open" class="chat-panel">
      <!-- Header -->
      <div class="chat-header">
        <div class="chat-header-avatar">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        </div>
        <div class="chat-header-info">
          <span class="chat-title">在线客服</span>
          <span class="chat-subtitle">有问题随时找我们</span>
        </div>
        <button class="chat-close-btn" @click="toggleOpen" title="关闭">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
      </div>

      <!-- Messages -->
      <div class="chat-messages" ref="messagesEl">
        <div v-if="loading" class="chat-status">
          <span class="loading-dots"><span>.</span><span>.</span><span>.</span></span>
        </div>
        <div v-else-if="messages.length === 0" class="chat-empty-state">
          <div class="chat-empty-icon">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.4"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
          </div>
          <p class="chat-empty-text">有任何疑问，欢迎留言！</p>
          <p class="chat-empty-sub">客服在线时会尽快回复您</p>
        </div>
        <template v-else>
          <div
            v-for="msg in messages"
            :key="msg.id"
            :class="['msg-row', msg.fromAdmin ? 'msg-row--admin' : 'msg-row--me']"
          >
            <div v-if="msg.fromAdmin" class="msg-avatar msg-avatar--admin">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
    </div>
            <div class="msg-body">
              <div class="msg-meta">
                <span class="msg-name">{{ msg.fromAdmin ? '客服' : '我' }}</span>
                <span class="msg-time">{{ formatTime(msg.sentAt) }}</span>
              </div>
              <div class="msg-content">{{ msg.content }}</div>
            </div>
            <div v-if="!msg.fromAdmin" class="msg-avatar msg-avatar--me">
              <img v-if="props.userAvatar" :src="props.userAvatar" class="avatar-img" />
              <span v-else>{{ (props.userName || '我').charAt(0) }}</span>
            </div>
          </div>
        </template>
      </div>

      <!-- Input -->
      <form class="chat-input-row" @submit.prevent="send">
        <input
          v-model="inputText"
          class="chat-input"
          placeholder="输入消息，Enter 发送…"
          maxlength="500"
          :disabled="sending"
          @keydown.enter.exact.prevent="send"
        />
        <button class="chat-send-btn" type="submit" :disabled="sending || !inputText.trim()">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2" fill="currentColor" stroke="none"/></svg>
        </button>
      </form>
      <p class="chat-error" v-if="error">{{ error }}</p>
    </div>
  </Transition>
</template>

<script setup>
import { ref, nextTick, onUnmounted } from 'vue'
import { fetchMyChatMessages, sendChatMessage } from '../shared/api.js'

const props = defineProps({
  userToken:  { type: String, required: true },
  userName:   { type: String, default: '我' },
  userAvatar: { type: String, default: '' }
})

const open = ref(false)
const messages = ref([])
const loading = ref(false)
const inputText = ref('')
const sending = ref(false)
const error = ref('')
const messagesEl = ref(null)

let pollTimer = null

const formatTime = (iso) => {
  if (!iso) return ''
  const d = new Date(iso)
  return d.toLocaleString('zh-CN', { hour12: false, month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}

const scrollBottom = async () => {
  await nextTick()
  if (messagesEl.value) {
    messagesEl.value.scrollTop = messagesEl.value.scrollHeight
  }
}

const loadMessages = async () => {
  try {
    messages.value = await fetchMyChatMessages(props.userToken)
    await scrollBottom()
  } catch {
    // 静默忽略轮询错误，避免频繁弹出错误提示
  }
}

const startPolling = () => {
  pollTimer = setInterval(loadMessages, 5000)
}

const stopPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
}

const toggleOpen = async () => {
  open.value = !open.value
  if (open.value) {
    loading.value = true
    await loadMessages()
    loading.value = false
    startPolling()
  } else {
    stopPolling()
  }
}

const send = async () => {
  const content = inputText.value.trim()
  if (!content || sending.value) return
  sending.value = true
  error.value = ''
  try {
    const msg = await sendChatMessage(props.userToken, content)
    if (msg) {
      messages.value.push(msg)
      inputText.value = ''
      await scrollBottom()
    }
  } catch (err) {
    error.value = err?.response?.data?.error || '发送失败，请稍后重试'
  } finally {
    sending.value = false
  }
}

onUnmounted(stopPolling)
</script>

<style scoped>
/* ── FAB button ── */
.chat-fab {
  position: fixed;
  right: 24px;
  bottom: 28px;
  z-index: 1200;
  width: 52px;
  height: 52px;
  border-radius: 50%;
  background: #2c2b2d;
  color: #fff;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 18px rgba(0, 0, 0, 0.28);
  transition: transform 0.2s, box-shadow 0.2s;
}

.chat-fab:hover {
  transform: scale(1.08);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.38);
}

/* ── Panel ── */
.chat-panel {
  position: fixed;
  right: 24px;
  bottom: 94px;
  z-index: 1200;
  width: 340px;
  height: 500px;
  display: flex;
  flex-direction: column;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.97);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  box-shadow: 0 16px 56px rgba(0, 0, 0, 0.16);
  border: 1px solid rgba(255, 255, 255, 0.6);
  overflow: hidden;
}

/* ── Header ── */
.chat-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 13px 16px;
  background: #fff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
  flex-shrink: 0;
}

.chat-header-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  color: #555;
}

.chat-header-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1px;
}

.chat-title {
  font-size: 15px;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1.2;
}

.chat-subtitle {
  font-size: 11px;
  color: #888;
}

.chat-close-btn {
  background: rgba(0,0,0,0.1);
  border: none;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  color: #333;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.15s;
  flex-shrink: 0;
}

.chat-close-btn:hover {
  background: rgba(0,0,0,0.18);
}

/* ── Messages area ── */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 14px 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  scrollbar-width: none;
  background: #f8f6fb;
}

.chat-messages::-webkit-scrollbar {
  display: none;
}

/* Loading dots */
.chat-status {
  text-align: center;
  padding: 30px 0;
}

.loading-dots {
  font-size: 26px;
  color: var(--muted);
  letter-spacing: 4px;
}

.loading-dots span {
  animation: blink 1.2s infinite;
}

.loading-dots span:nth-child(2) { animation-delay: 0.2s; }
.loading-dots span:nth-child(3) { animation-delay: 0.4s; }

@keyframes blink {
  0%, 80%, 100% { opacity: 0.2; }
  40% { opacity: 1; }
}

/* Empty state */
.chat-empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  padding: 40px 20px;
}

.chat-empty-icon {
  color: var(--muted);
  margin-bottom: 4px;
}

.chat-empty-text {
  font-size: 14px;
  font-weight: 600;
  color: var(--text);
  margin: 0;
}

.chat-empty-sub {
  font-size: 12px;
  color: var(--muted);
  margin: 0;
}

/* Message rows */
.msg-row {
  display: flex;
  align-items: flex-end;
  gap: 7px;
}

.msg-row--me {
  flex-direction: row-reverse;
}

.msg-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  font-size: 11px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.msg-avatar--admin {
  background: #2c2b2d;
  color: #fff;
}

.msg-avatar--me {
  background: #e8e8e8;
  color: #444;
  overflow: hidden;
  width: 28px;
  height: 28px;
  min-width: 28px;
  min-height: 28px;
  border-radius: 50%;
}

.avatar-img {
  width: 28px;
  height: 28px;
  object-fit: cover;
  border-radius: 50%;
  display: block;
}

.msg-body {
  display: flex;
  flex-direction: column;
  gap: 3px;
  max-width: 76%;
}

.msg-row--me .msg-body {
  align-items: flex-end;
}

.msg-meta {
  display: flex;
  gap: 5px;
  align-items: baseline;
  padding: 0 3px;
}

.msg-name {
  font-size: 11px;
  font-weight: 600;
  color: var(--muted);
}

.msg-time {
  font-size: 10px;
  color: var(--muted);
  opacity: 0.7;
}

.msg-content {
  padding: 9px 13px;
  border-radius: 14px;
  font-size: 14px;
  line-height: 1.55;
  white-space: pre-wrap;
  word-break: break-word;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.msg-row--admin .msg-content {
  background: #fff;
  color: #1a1a1a;
  border-bottom-left-radius: 4px;
  border: 1px solid rgba(0,0,0,0.08);
}

.msg-row--me .msg-content {
  background: #2c2b2d;
  color: #fff;
  border-bottom-right-radius: 4px;
}

/* ── Input row ── */
.chat-input-row {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  border-top: 1px solid rgba(0,0,0,0.06);
  background: #fff;
  flex-shrink: 0;
}

.chat-input {
  flex: 1;
  padding: 9px 13px;
  border-radius: 999px;
  border: 1.5px solid rgba(180, 154, 203, 0.3);
  font-size: 14px;
  font-family: inherit;
  background: #f8f6fb;
  color: var(--text);
  outline: none;
  transition: border-color 0.2s;
}

.chat-input:focus {
  border-color: #aaa;
  background: #fff;
}

.chat-send-btn {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background: #2c2b2d;
  color: #fff;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: transform 0.15s, opacity 0.15s;
}

.chat-send-btn:disabled {
  opacity: 0.55;
  cursor: default;
  background: #888;
}

.chat-send-btn:not(:disabled):hover {
  transform: scale(1.08);
  opacity: 0.85;
}

.chat-error {
  font-size: 12px;
  color: #d64848;
  padding: 0 14px 8px;
  text-align: center;
}

/* ── Animations ── */
.chat-slide-enter-active,
.chat-slide-leave-active {
  transition: opacity 0.22s ease, transform 0.22s ease;
}

.chat-slide-enter-from,
.chat-slide-leave-to {
  opacity: 0;
  transform: translateY(20px) scale(0.96);
}

.icon-flip-enter-active,
.icon-flip-leave-active {
  transition: opacity 0.15s, transform 0.15s;
}

.icon-flip-enter-from,
.icon-flip-leave-to {
  opacity: 0;
  transform: rotate(90deg) scale(0.7);
}

@media (max-width: 600px) {
  .chat-panel {
    right: 8px;
    bottom: 80px;
    width: calc(100vw - 16px);
    height: 440px;
    border-radius: 16px;
  }

  .chat-fab {
    right: 16px;
    bottom: 20px;
  }
}
</style>
