<!-- Reusable chat-with-pipeline component -->
<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'

const props = defineProps({
  apiUrl: { type: String, required: true },
  historyUrl: { type: String, default: null },
  clearUrl: { type: String, default: null },
  sessionId: { type: String, default: null },
  quickPrompts: { type: Array, default: () => [] },
  title: { type: String, default: 'Chat' },
  subtitle: { type: String, default: '' },
})

const chatInput = ref('')
const sending = ref(false)
const messages = ref([])
const pipeline = ref([])
const pathBadge = ref('')
const historyCount = ref(0)
const traceId = ref(null)
const timingInfo = ref('')
const messagesEnd = ref(null)

function md(text) {
  if (!text) return ''
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank" class="text-amber-600 underline">$1</a>')
    .replace(/`(.*?)`/g, '<code class="bg-gray-100 px-1 rounded text-xs font-mono">$1</code>')
    .replace(/^- (.*)/gm, '• $1')
    .replace(/\n/g, '<br>')
}

async function sendMsg() {
  const query = chatInput.value.trim()
  if (!query || sending.value) return
  chatInput.value = ''
  sending.value = true
  messages.value.push({ type: 'user', text: query })
  messages.value.push({ type: 'thinking' })
  await nextTick(); messagesEnd.value?.scrollIntoView({ behavior: 'smooth' })

  try {
    const token = localStorage.getItem('canifa_token')
    const body = { query }
    if (props.sessionId) body.session_id = props.sessionId
    const resp = await fetch(props.apiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...(token ? { 'Authorization': 'Bearer ' + token } : {}) },
      body: JSON.stringify(body)
    })
    const data = await resp.json()
    messages.value = messages.value.filter(m => m.type !== 'thinking')

    if (data.status === 'success') {
      const timing = data.timing || {}
      const wallMs = timing.wall_ms || timing.total_ms || data.elapsed_ms || '?'
      const metaParts = [`⏱ ${wallMs}ms`, data.agent_path, data.product_count ? `📦 ${data.product_count} SP` : null].filter(Boolean)

      messages.value.push({ type: 'ai', html: md(data.response), meta: metaParts.join(' · ') })

      // Product cards inline
      if (data.products?.length) {
        messages.value.push({ type: 'products', products: data.products.slice(0, 6) })
      }

      if (data.history_count !== undefined) historyCount.value = data.history_count
      if (data.trace_id) { traceId.value = data.trace_id }

      if (timing.wall_ms || timing.total_ms) {
        const parts = []
        if (timing.planner_ms) parts.push(`P:${timing.planner_ms}ms`)
        if (timing.responder_ms) parts.push(`R:${timing.responder_ms}ms`)
        parts.push(`T:${wallMs}ms`)
        timingInfo.value = parts.join(' | ')
      }

      if (data.pipeline?.length) {
        pipeline.value = data.pipeline
        pathBadge.value = `${data.agent_path || ''} · ${wallMs}ms`
      }
    } else {
      messages.value.push({ type: 'error', text: '❌ ' + (data.message || 'Lỗi') })
    }
  } catch (e) {
    messages.value = messages.value.filter(m => m.type !== 'thinking')
    messages.value.push({ type: 'error', text: '❌ Lỗi kết nối: ' + e.message })
  } finally {
    sending.value = false
    await nextTick(); messagesEnd.value?.scrollIntoView({ behavior: 'smooth' })
  }
}

async function clearChat() {
  if (props.clearUrl) {
    const token = localStorage.getItem('canifa_token')
    await fetch(props.clearUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...(token ? { 'Authorization': 'Bearer ' + token } : {}) },
      body: JSON.stringify({ query: '', session_id: props.sessionId })
    }).catch(() => {})
  }
  messages.value = []
  pipeline.value = []
  pathBadge.value = ''
  historyCount.value = 0
}

function sendQuick(text) { chatInput.value = text; sendMsg() }

function fmtPrice(n) { return n ? Number(n).toLocaleString('vi-VN') + '₫' : '' }

onMounted(async () => {
  if (props.historyUrl && props.sessionId) {
    try {
      const token = localStorage.getItem('canifa_token')
      const res = await fetch(`${props.historyUrl}?session_id=${props.sessionId}`, {
        headers: token ? { 'Authorization': 'Bearer ' + token } : {}
      })
      const d = await res.json()
      if (d.status === 'success' && d.history?.length) {
        historyCount.value = d.count
        d.history.forEach(msg => {
          messages.value.push({ type: msg.role === 'user' ? 'user' : 'ai', text: msg.content, html: msg.role === 'user' ? null : md(msg.content) })
        })
      }
    } catch (e) {}
  }
})
</script>

<template>
  <div class="grid grid-cols-[1fr_340px] gap-5 h-[calc(100vh-140px)]">

    <!-- Chat panel -->
    <div class="flex flex-col">
      <!-- Quick prompts -->
      <div class="flex gap-2 flex-wrap mb-3" v-if="quickPrompts.length">
        <button v-for="q in quickPrompts" :key="q" @click="sendQuick(q)"
                class="px-3 py-1.5 bg-gray-50 hover:bg-amber-50 hover:border-amber-300 border border-gray-100 rounded-full text-xs text-gray-600 transition-colors">
          {{ q }}
        </button>
      </div>

      <!-- Badges -->
      <div v-if="historyCount || timingInfo || traceId" class="flex gap-2 mb-2 flex-wrap">
        <Badge v-if="historyCount" variant="secondary" class="text-[10px]">hist: {{ historyCount }}</Badge>
        <Badge v-if="timingInfo" variant="outline" class="text-[10px] font-mono">{{ timingInfo }}</Badge>
        <button v-if="traceId" @click="navigator.clipboard.writeText(traceId)"
                class="text-[10px] text-blue-500 hover:text-blue-700 border border-blue-200 px-2 py-0.5 rounded-full">
          🔍 {{ traceId.slice(0, 8) }}…
        </button>
        <button v-if="clearUrl || messages.length" @click="clearChat"
                class="text-[10px] text-red-400 hover:text-red-600 border border-red-200 px-2 py-0.5 rounded-full">
          🗑️ Clear
        </button>
      </div>

      <!-- Messages container -->
      <div class="flex-1 border border-gray-100 rounded-2xl bg-gray-50/50 overflow-y-auto p-4 space-y-3">
        <div v-if="!messages.length" class="flex flex-col items-center justify-center h-full text-gray-400">
          <div class="text-4xl mb-2">💬</div>
          <p class="text-sm">Nhập câu hỏi hoặc chọn prompt</p>
        </div>

        <template v-for="(msg, i) in messages" :key="i">
          <!-- Thinking -->
          <div v-if="msg.type === 'thinking'" class="flex gap-1 w-fit px-4 py-3 bg-white border border-gray-100 rounded-2xl shadow-sm">
            <span v-for="j in 3" :key="j" class="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce"
                  :style="{ animationDelay: j * 150 + 'ms' }"></span>
          </div>

          <!-- User -->
          <div v-else-if="msg.type === 'user'" class="flex justify-end">
            <div class="max-w-[75%] bg-amber-600 text-white px-4 py-2.5 rounded-2xl text-sm">{{ msg.text }}</div>
          </div>

          <!-- AI -->
          <div v-else-if="msg.type === 'ai'" class="flex justify-start">
            <div class="max-w-[80%] bg-white border border-gray-100 rounded-2xl px-4 py-3 shadow-sm">
              <div v-if="msg.html" class="text-sm leading-relaxed" v-html="msg.html"></div>
              <div v-else class="text-sm leading-relaxed">{{ msg.text }}</div>
              <p v-if="msg.meta" class="text-[10px] text-gray-400 mt-2 border-t border-gray-100 pt-1.5">{{ msg.meta }}</p>
            </div>
          </div>

          <!-- Product cards -->
          <div v-else-if="msg.type === 'products'" class="grid grid-cols-3 gap-2">
            <a v-for="p in msg.products" :key="p.sku"
               :href="p.url || '#'" target="_blank"
               class="border border-gray-100 bg-white rounded-xl overflow-hidden hover:border-amber-300 hover:shadow-sm transition-all no-underline">
              <img v-if="p.image" :src="p.image" :alt="p.name" class="w-full h-28 object-cover" />
              <div class="p-2">
                <p class="text-xs font-semibold text-gray-700 line-clamp-2 leading-tight">{{ p.name }}</p>
                <div class="flex items-center gap-1.5 mt-1">
                  <span class="text-xs font-bold text-amber-700">{{ fmtPrice(p.price) }}</span>
                  <span v-if="p.original_price > p.price" class="text-[10px] line-through text-gray-400">{{ fmtPrice(p.original_price) }}</span>
                  <span v-if="p.discount" class="text-[10px] bg-red-100 text-red-600 px-1 rounded">{{ p.discount }}</span>
                </div>
                <p class="text-[10px] text-gray-400 font-mono mt-0.5">{{ p.sku }}</p>
              </div>
            </a>
          </div>

          <!-- Error -->
          <div v-else-if="msg.type === 'error'" class="flex justify-start">
            <div class="max-w-[80%] bg-red-50 border border-red-100 text-red-700 px-4 py-2.5 rounded-2xl text-sm">
              {{ msg.text }}
            </div>
          </div>
        </template>
        <div ref="messagesEnd"></div>
      </div>

      <!-- Input -->
      <div class="flex gap-2 mt-3">
        <Input v-model="chatInput" :placeholder="`Hỏi ${title}...`"
               @keydown.enter="sendMsg" class="flex-1" />
        <Button @click="sendMsg" :disabled="sending || !chatInput.trim()">
          {{ sending ? '⏳' : 'Gửi' }}
        </Button>
      </div>
    </div>

    <!-- Pipeline sidebar -->
    <div class="flex flex-col">
      <div class="flex items-center justify-between mb-3">
        <h2 class="text-sm font-bold text-gray-700">🔧 Agent Pipeline</h2>
        <Badge v-if="pathBadge" variant="outline" class="text-[10px] font-mono">{{ pathBadge }}</Badge>
      </div>
      <Card class="flex-1 overflow-hidden">
        <CardContent class="p-0 h-full">
          <ScrollArea class="h-full p-3">
            <div v-if="!pipeline.length" class="text-center py-8 text-gray-400 text-xs">
              Pipeline sẽ hiện sau khi gửi tin nhắn
            </div>
            <div class="space-y-2">
              <div v-for="(step, i) in pipeline" :key="i"
                   :class="['border rounded-lg p-2.5 text-xs',
                     step.step === 'user' ? 'border-gray-200 bg-gray-50' :
                     step.step === 'planner' ? 'border-blue-200 bg-blue-50/50' :
                     step.step === 'tool_result' ? 'border-green-200 bg-green-50/50' :
                     'border-amber-200 bg-amber-50/50']">
                <p class="font-bold text-gray-600 mb-1">{{ step.label }}</p>
                <p v-if="step.content && step.step !== 'planner'" class="text-gray-600 line-clamp-3 text-[11px]">{{ step.content }}</p>
                <div v-if="step.tool_calls?.length">
                  <div v-for="tc in step.tool_calls" :key="tc.name" class="mt-1.5 space-y-0.5">
                    <div class="flex gap-1.5">
                      <span class="text-blue-600">🔧</span>
                      <span class="font-mono font-semibold">{{ tc.name }}</span>
                    </div>
                    <template v-for="(v, k) in (tc.args || {})" :key="k">
                      <div v-if="v !== null && v !== undefined && v !== ''" class="flex gap-1.5 pl-4 text-[10px]">
                        <span :class="k === 'reasoning' ? 'text-purple-500' : 'text-gray-400'">{{ k }}:</span>
                        <span class="font-mono" :class="k === 'reasoning' ? 'italic text-purple-600' : ''">
                          {{ Array.isArray(v) ? v.join(', ') : v }}
                        </span>
                      </div>
                    </template>
                  </div>
                </div>
                <details v-if="step.raw_json" class="mt-1.5">
                  <summary class="cursor-pointer text-blue-500 text-[10px] hover:text-blue-700">📋 Raw JSON</summary>
                  <pre class="bg-gray-900 text-green-300 rounded p-2 mt-1 text-[10px] overflow-auto max-h-32">{{ step.raw_json }}</pre>
                </details>
              </div>
            </div>
          </ScrollArea>
        </CardContent>
      </Card>
    </div>
  </div>
</template>
