<template>
  <div class="mt-8 max-md:mt-4">
    <div class="flex items-center gap-3 mb-3.5">
      <h3 class="text-lg font-bold text-apptext">用户消息</h3>
      <button
        class="px-3.5 py-1.5 rounded border border-white/35 bg-white/70 text-[13px] cursor-pointer text-apptext disabled:opacity-50"
        style="font-family: var(--font-serif);"
        @click="load" :disabled="loading"
      >刷新</button>
    </div>

    <div v-if="loading" class="py-6 text-center text-muted text-sm">加载中…</div>
    <div v-else-if="Object.keys(conversations).length === 0" class="py-6 text-center text-muted text-sm">暂无用户消息</div>

    <div v-else class="grid h-[520px] rounded-xl border border-white/35 overflow-hidden bg-white/40 shadow-[0_8px_24px_rgba(33,33,40,0.08)] max-md:grid-cols-1 max-md:grid-rows-[auto,1fr]" style="grid-template-columns: 200px 1fr;">
      <!-- Conversation list -->
      <div class="border-r border-white/35 overflow-y-auto bg-white/65 flex flex-col max-md:border-r-0 max-md:border-b max-md:overflow-x-auto max-md:overflow-y-hidden max-md:flex-row max-md:max-h-[72px] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        <div class="px-3.5 py-3 pb-2 text-[11px] font-bold tracking-[0.8px] uppercase text-muted border-b border-white/35 flex-shrink-0 max-md:hidden">对话列表</div>
        <div
          v-for="(msgs, account) in conversations"
          :key="account"
          class="flex items-center gap-2.5 px-3 py-2.5 cursor-pointer border-b border-white/50 last:border-b-0 transition-colors hover:bg-[rgba(217,168,120,0.08)] max-md:flex-col max-md:flex-shrink-0 max-md:items-center max-md:min-w-[70px] max-md:max-w-20 max-md:px-1.5 max-md:py-2 max-md:border-b-0 max-md:border-r max-md:border-white/35 max-md:text-center"
          :class="selectedAccount === account ? '!bg-[rgba(217,168,120,0.15)] border-l-[3px] border-accent pl-[9px] max-md:border-l-0 max-md:border-b-[2px] max-md:pl-1.5' : ''"
          @click="selectConv(account, msgs)"
        >
          <div class="w-[34px] h-[34px] rounded-full bg-[#e8e8e8] text-[#444] text-sm font-bold flex items-center justify-center flex-shrink-0 max-md:w-7 max-md:h-7 max-md:text-xs">
            {{ (getDisplayName(msgs) || account).slice(0, 1).toUpperCase() }}
          </div>
          <div class="flex-1 min-w-0 max-md:flex max-md:flex-col max-md:items-center">
            <div class="text-[13px] font-semibold text-apptext whitespace-nowrap overflow-hidden text-ellipsis max-md:text-[11px] max-md:max-w-16">{{ getDisplayName(msgs) || account }}</div>
            <div class="text-[11px] text-muted mt-0.5 whitespace-nowrap overflow-hidden text-ellipsis max-md:hidden">{{ latestMsg(msgs) }}</div>
          </div>
        </div>
      </div>

      <!-- Thread -->
      <div v-if="selectedAccount" class="flex flex-col overflow-hidden bg-white/30">
        <!-- Thread top -->
        <div class="flex items-center justify-between px-4 py-2.5 border-b border-white/35 bg-white/75 flex-shrink-0">
          <div class="flex items-center gap-2.5">
            <div class="w-8 h-8 rounded-full bg-[#e8e8e8] text-[#444] text-[13px] font-bold flex items-center justify-center flex-shrink-0">
              {{ (displayName || selectedAccount).slice(0, 1).toUpperCase() }}
            </div>
            <div class="flex flex-col gap-0">
              <span class="text-sm font-bold text-apptext leading-[1.2]">{{ displayName || selectedAccount }}</span>
              <span class="text-[11px] text-muted">{{ selectedAccount }}</span>
            </div>
          </div>
          <button
            class="px-3 py-1.5 rounded border border-[rgba(210,70,70,0.3)] bg-[rgba(210,70,70,0.06)] text-[#c04040] text-xs cursor-pointer whitespace-nowrap hover:bg-[rgba(210,70,70,0.14)] transition disabled:opacity-50"
            style="font-family: var(--font-serif);"
            @click="clearConv" :disabled="clearing"
          >清除记录</button>
        </div>

        <!-- Messages -->
        <div class="flex-1 overflow-y-auto px-4 py-4 flex flex-col gap-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden" ref="threadEl">
          <div
            v-for="msg in currentMessages"
            :key="msg.id"
            class="flex"
            :class="msg.fromAdmin ? 'justify-end' : 'justify-start'"
          >
            <div class="flex flex-col gap-0.5 max-w-[72%]" :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 ? '客服' : (msg.accountName || msg.accountId) }}</span>
                <span class="text-[10px] text-muted opacity-75">{{ formatTime(msg.sentAt) }}</span>
              </div>
              <div
                class="px-3.5 py-2.5 rounded-xl text-sm leading-[1.55] whitespace-pre-wrap break-words"
                :class="msg.fromAdmin
                  ? 'bg-[#2c2b2d] text-white rounded-br-[4px]'
                  : 'bg-white/85 text-apptext border border-white/35 rounded-bl-[4px]'"
              >{{ msg.content }}</div>
            </div>
          </div>
        </div>

        <!-- Reply input -->
        <form class="flex gap-2 px-3.5 py-2.5 border-t border-white/35 bg-white/70 flex-shrink-0" @submit.prevent="sendReply">
          <input
            v-model="replyText"
            class="flex-1 px-3 py-2 rounded-lg border border-white/35 text-sm bg-white/90 text-apptext outline-none focus:border-accent transition"
            style="font-family: var(--font-serif);"
            placeholder="输入回复内容…"
            maxlength="500"
            :disabled="replying"
          />
          <button
            class="px-[18px] py-2 rounded-lg bg-[#2c2b2d] text-white border-none cursor-pointer text-sm font-semibold disabled:opacity-45 disabled:cursor-default hover:not-disabled:opacity-80 transition"
            style="font-family: var(--font-serif);"
            type="submit" :disabled="replying || !replyText.trim()"
          >发送</button>
        </form>
        <p v-if="replyError" class="text-xs text-[#d64848] px-3.5 pb-2 text-right">{{ replyError }}</p>
      </div>

      <div v-else class="flex items-center justify-center text-muted text-sm bg-white/30">
        <div class="flex flex-col items-center gap-2.5">
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="opacity-30"><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>
          <p>选择左侧对话</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import { fetchAdminAllConversations, fetchAdminConversation, adminSendChatReply, adminClearConversation } from '../../shared/api.js'

const props = defineProps({ adminToken: { type: String, default: '' } })

const conversations = ref({})
const loading = ref(false)
const selectedAccount = ref('')
const currentMessages = ref([])
const displayName = ref('')
const replyText = ref('')
const replying = ref(false)
const replyError = ref('')
const clearing = ref(false)
const threadEl = ref(null)

let pollTimer = null

const formatTime = (iso) => {
  if (!iso) return ''
  return new Date(iso).toLocaleString('zh-CN', { hour12: false })
}

const getDisplayName = (msgs) => {
  if (!msgs || msgs.length === 0) return '未知用户'
  const userMsg = msgs.find((m) => !m.fromAdmin)
  return userMsg?.accountName || userMsg?.accountId || '未知用户'
}

const latestMsg = (msgs) => {
  if (!msgs || msgs.length === 0) return ''
  const last = msgs[msgs.length - 1]
  const prefix = last.fromAdmin ? '[客服] ' : ''
  return prefix + (last.content.length > 20 ? last.content.slice(0, 20) + '…' : last.content)
}

const scrollThreadBottom = async () => {
  await nextTick()
  if (threadEl.value) threadEl.value.scrollTop = threadEl.value.scrollHeight
}

const load = async () => {
  if (!props.adminToken) return
  loading.value = true
  try {
    conversations.value = await fetchAdminAllConversations(props.adminToken)
    if (selectedAccount.value) {
      currentMessages.value = conversations.value[selectedAccount.value] || []
      await scrollThreadBottom()
    }
  } finally { loading.value = false }
}

const selectConv = async (account, msgs) => {
  selectedAccount.value = account
  currentMessages.value = msgs || []
  displayName.value = getDisplayName(msgs)
  replyError.value = ''
  replyText.value = ''
  await scrollThreadBottom()
}

const sendReply = async () => {
  const content = replyText.value.trim()
  if (!content || replying.value) return
  replying.value = true
  replyError.value = ''
  try {
    const msg = await adminSendChatReply(props.adminToken, selectedAccount.value, content)
    if (msg) {
      currentMessages.value.push(msg)
      conversations.value[selectedAccount.value] = [...currentMessages.value]
      replyText.value = ''
      await scrollThreadBottom()
    }
  } catch (err) {
    replyError.value = err?.response?.data?.error || '发送失败'
  } finally { replying.value = false }
}

const clearConv = async () => {
  if (!selectedAccount.value || clearing.value) return
  if (!confirm(`确认清除与 ${selectedAccount.value} 的全部对话？`)) return
  clearing.value = true
  try {
    await adminClearConversation(props.adminToken, selectedAccount.value)
    delete conversations.value[selectedAccount.value]
    selectedAccount.value = ''
    currentMessages.value = []
  } catch { alert('清除失败，请重试') }
  finally { clearing.value = false }
}

onMounted(() => { load(); pollTimer = setInterval(load, 8000) })
onUnmounted(() => { if (pollTimer) clearInterval(pollTimer) })
</script>
