<template>
  <!-- Floating action button -->
  <button
    class="fixed right-6 bottom-7 z-[1200] w-[52px] h-[52px] rounded-full bg-[#2c2b2d] text-white border-none cursor-pointer flex items-center justify-center shadow-[0_4px_18px_rgba(0,0,0,0.28)] transition hover:scale-[1.08] hover:shadow-[0_6px_24px_rgba(0,0,0,0.38)] max-[600px]:right-4 max-[600px]:bottom-5"
    @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="fixed right-6 bottom-[94px] z-[1200] w-[340px] h-[500px] flex flex-col rounded-2xl bg-white/97 backdrop-blur-xl shadow-[0_16px_56px_rgba(0,0,0,0.16)] border border-white/60 overflow-hidden max-[600px]:right-2 max-[600px]:bottom-20 max-[600px]:w-[calc(100vw-16px)] max-[600px]:h-[440px]"
    >
      <!-- Header -->
      <div class="flex items-center gap-2.5 px-4 py-3.5 bg-white border-b border-black/[0.08] flex-shrink-0">
        <div class="w-9 h-9 rounded-full bg-[#f0f0f0] flex items-center justify-center flex-shrink-0 text-[#555]">
          <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="flex-1 flex flex-col gap-0">
          <span class="text-[15px] font-bold text-[#1a1a1a] leading-[1.2]">在线客服</span>
          <span class="text-[11px] text-[#888]">有问题随时找我们</span>
        </div>
        <button
          class="w-7 h-7 rounded-full bg-black/10 border-none text-[#333] cursor-pointer flex items-center justify-center transition hover:bg-black/[0.18] flex-shrink-0"
          @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 area -->
      <div
        class="flex-1 overflow-y-auto px-3 py-3.5 flex flex-col gap-3 bg-[#faf6f1] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
        ref="messagesEl"
      >
        <div v-if="loading" class="text-center py-8">
          <span class="text-[26px] text-muted tracking-[4px] loading-dots"><span>.</span><span>.</span><span>.</span></span>
        </div>
        <div v-else-if="messages.length === 0" class="flex flex-col items-center gap-1.5 py-10">
          <div class="text-muted mb-1">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="opacity-40"><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="text-sm font-semibold text-apptext m-0">有任何疑问，欢迎留言！</p>
          <p class="text-xs text-muted m-0">客服在线时会尽快回复您</p>
        </div>
        <template v-else>
          <div
            v-for="msg in messages"
            :key="msg.id"
            class="flex items-end gap-1.5"
            :class="msg.fromAdmin ? '' : 'flex-row-reverse'"
          >
            <!-- Avatar -->
            <div
              class="w-7 h-7 rounded-full text-[11px] font-bold flex items-center justify-center flex-shrink-0 overflow-hidden"
              :class="msg.fromAdmin ? 'bg-[#2c2b2d] text-white' : 'bg-[#e8e8e8] text-[#444]'"
            >
              <template v-if="!msg.fromAdmin">
                <img v-if="props.userAvatar" :src="props.userAvatar" class="w-7 h-7 object-cover rounded-full block" />
                <span v-else>{{ (props.userName || '我').charAt(0) }}</span>
              </template>
              <template v-else>
                <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>
              </template>
            </div>
            <!-- Bubble -->
            <div class="flex flex-col gap-0.5 max-w-[76%]" :class="msg.fromAdmin ? '' : 'items-end'">
              <div class="flex gap-1.5 items-baseline px-0.5">
                <span class="text-[11px] font-semibold text-muted">{{ msg.fromAdmin ? '客服' : '我' }}</span>
                <span class="text-[10px] text-muted opacity-70">{{ formatTime(msg.sentAt) }}</span>
              </div>
              <div
                class="px-3.5 py-2.5 text-sm leading-[1.55] whitespace-pre-wrap break-words shadow-[0_2px_8px_rgba(0,0,0,0.06)]"
                :class="msg.fromAdmin
                  ? 'bg-white text-[#1a1a1a] rounded-xl rounded-bl-[4px] border border-black/[0.08]'
                  : 'bg-[#2c2b2d] text-white rounded-xl rounded-br-[4px]'"
              >{{ msg.content }}</div>
            </div>
          </div>
        </template>
      </div>

      <!-- Input row -->
      <form class="flex items-center gap-2 px-3 py-2.5 border-t border-black/[0.06] bg-white flex-shrink-0" @submit.prevent="send">
        <input
          v-model="inputText"
          class="flex-1 px-3.5 py-2.5 rounded-full border border-[rgba(217,168,120,0.35)] text-sm bg-[#faf6f1] text-apptext outline-none transition focus:border-[#b8a090] focus:bg-white"
          style="font-family: var(--font-serif);"
          placeholder="输入消息，Enter 发送…"
          maxlength="500"
          :disabled="sending"
          @keydown.enter.exact.prevent="send"
        />
        <button
          class="w-[38px] h-[38px] rounded-full bg-[#2c2b2d] text-white border-none cursor-pointer flex items-center justify-center flex-shrink-0 transition disabled:opacity-55 disabled:cursor-default disabled:bg-[#888] hover:not-disabled:scale-[1.08] hover:not-disabled:opacity-85"
          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 v-if="error" class="text-xs text-[#d64848] px-3.5 pb-2 text-center">{{ 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 ''
  return new Date(iso).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 { /* silent */ }
}

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>
/* ── Animations that cannot be expressed in Tailwind utilities ── */
@keyframes blink {
  0%, 80%, 100% { opacity: 0.2; }
  40%            { opacity: 1;   }
}

.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; }

/* Chat panel slide */
.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 */
.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);
}
</style>
