<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'

const STAGE_COLORS = { 1:'#3b82f6', 2:'#10b981', 3:'#f59e0b', 4:'#ec4899', 5:'#8b5cf6' }
const STAGE_NAMES  = { 1:'AWARENESS', 2:'INTEREST', 3:'CONSIDERATION', 4:'DECISION', 5:'RETENTION' }

// ── State ──────────────────────────────────────────────────
const messages       = ref([])
const chatInput      = ref('')
const isSending      = ref(false)
const currentStage   = ref(0)
const stageLog       = ref([])
const turnCount      = ref(0)
const deviceId       = ref('')
const convId         = ref('')
const historyList    = ref([])
const pipeline       = ref([])
const debugStage     = ref(null)
const messagesEnd    = ref(null)

// ── Device ID ─────────────────────────────────────────────
function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { const r=Math.random()*16|0; return (c==='x'?r:(r&0x3|0x8)).toString(16) }) }

function initDeviceId() {
  const KEY = 'canifa_lead_device_id'
  let id = localStorage.getItem(KEY)
  if (!id) { id = uuidv4(); localStorage.setItem(KEY, id) }
  deviceId.value = id
}

function initConvId() {
  const params = new URLSearchParams(window.location.search)
  let id = params.get('conversation_id') || localStorage.getItem('canifa_lead_last_conv') || uuidv4()
  convId.value = id
  localStorage.setItem('canifa_lead_last_conv', id)
  saveConvToList(id)
}

function saveConvToList(id) {
  let list = JSON.parse(localStorage.getItem('canifa_leadflow_histories') || '[]')
  list = list.filter(h => h.id !== id)
  list.unshift({ id, date: new Date().toLocaleString('vi-VN') })
  if (list.length > 20) list = list.slice(0, 20)
  localStorage.setItem('canifa_leadflow_histories', JSON.stringify(list))
  historyList.value = list
}

function newConversation() {
  const id = uuidv4()
  convId.value = id
  localStorage.setItem('canifa_lead_last_conv', id)
  messages.value = []; stageLog.value = []; pipeline.value = []; currentStage.value = 0; debugStage.value = null; turnCount.value = 0
  saveConvToList(id)
  const url = new URL(window.location)
  url.searchParams.set('conversation_id', id)
  window.history.replaceState({}, '', url)
}

function switchConv(id) {
  if (!id) { newConversation(); return }
  convId.value = id
  localStorage.setItem('canifa_lead_last_conv', id)
  messages.value = []; stageLog.value = []; pipeline.value = []; currentStage.value = 0; debugStage.value = null; turnCount.value = 0
  loadHistory(id)
  const url = new URL(window.location)
  url.searchParams.set('conversation_id', id)
  window.history.replaceState({}, '', url)
}

// ── History ───────────────────────────────────────────────
async function loadHistory(cId) {
  try {
    const r = await fetch(`/api/lead/history?conv_id=${cId}&limit=50`, { headers: { device_id: deviceId.value } })
    if (!r.ok) return
    const d = await r.json()
    const items = (d.data || []).slice().reverse()
    items.forEach(item => {
      if (item.is_human) {
        messages.value.push({ role: 'human', text: item.message || '' })
      } else {
        let text = item.message || '', ls = null, products = []
        try { const p = JSON.parse(text); if (p?.ai_response) { text = p.ai_response; ls = p.lead_stage; products = p.products || [] } } catch (_) {}
        messages.value.push({ role: 'ai', text, ls, products })
      }
    })
    scrollToBottom()
  } catch (_) {}
}

// ── Send ──────────────────────────────────────────────────
async function sendMessage() {
  const query = chatInput.value.trim()
  if (!query || isSending.value) return
  chatInput.value = ''; isSending.value = true; turnCount.value++

  messages.value.push({ role: 'human', text: query })
  messages.value.push({ role: 'typing' })
  scrollToBottom()

  try {
    const r = await fetch('/api/agent/chat-lead-flow', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ user_query: query, conversation_id: convId.value, device_id: deviceId.value })
    })
    const d = await r.json()
    messages.value = messages.value.filter(m => m.role !== 'typing')

    if (d.status === 'success') {
      const ls = d.lead_stage || {}
      messages.value.push({ role: 'ai', text: d.ai_response, ls, products: d.products || [] })
      pipeline.value = d.pipeline || []
      debugStage.value = { ...ls, timing: d.timing }
      if (ls.stage) {
        currentStage.value = ls.stage
        stageLog.value.push({ turn: turnCount.value, stage: ls.stage, query: query.slice(0, 40), name: STAGE_NAMES[ls.stage] })
      }
    } else {
      messages.value.push({ role: 'ai', text: '❌ ' + (d.message || 'Lỗi xử lý') })
    }
  } catch (e) {
    messages.value = messages.value.filter(m => m.role !== 'typing')
    messages.value.push({ role: 'ai', text: '❌ Lỗi kết nối: ' + e.message })
  } finally {
    isSending.value = false
    scrollToBottom()
  }
}

function scrollToBottom() { setTimeout(() => { messagesEnd.value?.scrollIntoView({ behavior: 'smooth' }) }, 60) }

const QUICK = ['Tôi muốn mua áo đi làm', 'Shop có váy dự tiệc không?', 'Ngân sách 300k mua được gì?', 'Tư vấn phong cách mùa hè']

onMounted(() => { initDeviceId(); initConvId(); loadHistory(convId.value) })
</script>

<template>
  <DashboardLayout>
    <div class="flex h-[calc(100vh-56px)] overflow-hidden">

      <!-- Chat Panel (left 400px) -->
      <div class="w-[400px] shrink-0 flex flex-col border-r border-gray-100">

        <!-- Conv selector -->
        <div class="px-3 py-2 border-b bg-gray-50 flex items-center gap-2">
          <select class="flex-1 text-xs border border-gray-200 rounded-lg px-2 py-1 bg-white"
                  :value="convId" @change="switchConv($event.target.value)">
            <option value="">-- New Conversation --</option>
            <option v-for="h in historyList" :key="h.id" :value="h.id">{{ h.date }} ({{ h.id.slice(0,6) }}…)</option>
          </select>
          <Button size="sm" variant="outline" class="h-6 text-[10px] px-2" @click="newConversation">New</Button>
        </div>

        <!-- Stage progress bar -->
        <div class="flex items-center gap-1 px-3 py-2 border-b">
          <div v-for="i in 5" :key="i" class="flex items-center">
            <div :class="['w-6 h-6 rounded-full flex items-center justify-center text-[9px] font-black border-2 transition-all',
                          i <= currentStage ? 'border-transparent text-white' : 'border-gray-200 text-gray-400 bg-white']"
                 :style="i <= currentStage ? { background: STAGE_COLORS[i] } : {}">
              {{ i }}
            </div>
            <div v-if="i < 5" :class="['h-0.5 w-5 transition-all mx-0.5', i < currentStage ? 'bg-green-400' : 'bg-gray-200']"></div>
          </div>
          <span v-if="currentStage" class="ml-auto text-[10px] font-bold" :style="{ color: STAGE_COLORS[currentStage] }">
            {{ STAGE_NAMES[currentStage] }}
          </span>
        </div>

        <!-- Messages -->
        <div class="flex-1 overflow-y-auto p-3 space-y-2">
          <div v-for="(msg, i) in messages" :key="i" :class="['flex', msg.role === 'human' ? 'justify-end' : 'justify-start']">
            <!-- Human -->
            <div v-if="msg.role === 'human'"
                 class="max-w-[80%] bg-blue-600 text-white rounded-2xl rounded-tr-sm px-3 py-2 text-xs leading-relaxed">
              {{ msg.text }}
            </div>
            <!-- AI -->
            <div v-else-if="msg.role === 'ai'" class="max-w-[88%] space-y-1.5">
              <div v-if="msg.ls?.stage" class="flex items-center gap-1.5">
                <span class="text-[9px] font-bold px-2 py-0.5 rounded-full"
                      :style="{ background: (STAGE_COLORS[msg.ls.stage] || '#888') + '18', color: STAGE_COLORS[msg.ls.stage] || '#888' }">
                  Stage {{ msg.ls.stage }} · {{ msg.ls.tone_directive || '' }}
                </span>
              </div>
              <div class="bg-white border border-gray-100 rounded-2xl rounded-tl-sm px-3 py-2.5 text-xs text-gray-700 leading-relaxed shadow-sm">
                {{ msg.text }}
              </div>
              <!-- Inline product cards -->
              <div v-if="msg.products?.length" class="flex gap-1.5 overflow-x-auto pb-1">
                <div v-for="p in msg.products.slice(0, 5)" :key="p.sku"
                     class="shrink-0 w-24 bg-white border border-gray-100 rounded-xl overflow-hidden shadow-sm">
                  <img v-if="p.image" :src="p.image" class="w-full h-20 object-cover" @error="$event.target.style.display='none'" />
                  <div class="px-1.5 py-1">
                    <p class="text-[9px] text-gray-500 font-mono">{{ p.sku }}</p>
                    <p class="text-[10px] font-medium text-gray-800 truncate leading-tight">{{ p.name }}</p>
                    <p v-if="p.price" class="text-[10px] font-bold text-amber-600">{{ Number(p.price).toLocaleString() }}đ</p>
                  </div>
                </div>
              </div>
            </div>
            <!-- Typing -->
            <div v-else-if="msg.role === 'typing'" class="flex gap-1 px-3 py-2 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>
          </div>
          <div ref="messagesEnd"></div>
        </div>

        <!-- Quick chips -->
        <div class="px-3 py-1. flex flex-wrap gap-1">
          <button v-for="q in QUICK" :key="q"
                  @click="chatInput = q; sendMessage()"
                  class="text-[10px] bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full hover:bg-blue-100">{{ q }}</button>
        </div>

        <!-- Input -->
        <div class="p-3 border-t bg-gray-50">
          <div class="flex gap-2">
            <textarea v-model="chatInput" placeholder="Nhập tin nhắn..."
                      class="flex-1 text-xs border border-gray-200 rounded-xl px-3 py-2 resize-none min-h-[44px] focus:outline-none focus:border-blue-400"
                      @keydown.enter.prevent.exact="sendMessage"></textarea>
            <Button @click="sendMessage" :disabled="isSending || !chatInput.trim()"
                    class="self-end bg-blue-600 hover:bg-blue-700 h-9">
              {{ isSending ? '⏳' : '▶' }}
            </Button>
          </div>
          <p class="text-[9px] text-gray-400 mt-1 font-mono">device: {{ deviceId.slice(-8) }} · conv: {{ convId.slice(0, 8) }}…</p>
        </div>
      </div>

      <!-- Debug Panel (right) -->
      <div class="flex-1 overflow-hidden flex flex-col">
        <div class="px-4 py-2 border-b bg-gray-50">
          <h2 class="text-sm font-bold text-gray-700">🔬 Pipeline Debug</h2>
        </div>
        <div class="flex-1 overflow-y-auto p-4 space-y-4">

          <!-- Stage info -->
          <Card v-if="debugStage">
            <CardContent class="p-4 space-y-2">
              <div class="flex items-center gap-3 mb-2">
                <div class="w-10 h-10 rounded-xl flex items-center justify-center text-white font-black text-lg"
                     :style="{ background: STAGE_COLORS[debugStage.stage] || '#888' }">
                  {{ debugStage.stage }}
                </div>
                <div>
                  <p class="font-bold text-sm text-gray-800">{{ debugStage.stage_name || STAGE_NAMES[debugStage.stage] }}</p>
                  <p class="text-xs text-gray-400">{{ debugStage.tone_directive }}</p>
                </div>
                <div class="ml-auto text-right">
                  <p class="text-xs font-bold text-gray-600">{{ ((debugStage.confidence || 0) * 100).toFixed(0) }}%</p>
                  <p class="text-[9px] text-gray-400">confidence</p>
                </div>
              </div>
              <div class="h-1.5 bg-gray-100 rounded-full overflow-hidden">
                <div class="h-full rounded-full transition-all duration-500"
                     :style="{ width: ((debugStage.confidence || 0)*100)+'%', background: STAGE_COLORS[debugStage.stage] || '#888' }"></div>
              </div>
              <p v-if="debugStage.reasoning" class="text-xs text-gray-600 italic">{{ debugStage.reasoning }}</p>
              <div class="flex gap-3 text-xs text-gray-400 mt-1 pt-1 border-t">
                <span>Classifier: {{ debugStage.timing?.classifier_ms || '–' }}ms</span>
                <span>Stylist: {{ debugStage.timing?.stylist_ms || '–' }}ms</span>
                <span class="font-bold">Total: {{ debugStage.timing?.total_ms ? Math.round(debugStage.timing.total_ms) : '–' }}ms</span>
              </div>
            </CardContent>
          </Card>

          <!-- Pipeline steps -->
          <div v-if="pipeline.length" class="space-y-2">
            <p class="text-xs font-bold text-gray-500">Pipeline Steps</p>
            <div v-for="(step, i) in pipeline" :key="i"
                 v-if="step.step !== 'user'"
                 class="border border-gray-100 rounded-xl overflow-hidden">
              <div :class="['text-[10px] font-bold px-3 py-1.5 flex justify-between',
                             step.step === 'classifier' ? 'bg-blue-50 text-blue-700' :
                             step.step.includes('tool') ? 'bg-green-50 text-green-700' :
                             'bg-purple-50 text-purple-700']">
                <span>{{ step.step }}</span>
                <span v-if="step.elapsed_ms">{{ step.elapsed_ms }}ms</span>
              </div>
              <div class="px-3 py-2 text-[10px] text-gray-600 font-mono leading-relaxed whitespace-pre-wrap max-h-32 overflow-y-auto bg-white">
                {{ (step.content || '').slice(0, 400) }}
              </div>
            </div>
          </div>

          <!-- Stage log history -->
          <div v-if="stageLog.length" class="space-y-1">
            <p class="text-xs font-bold text-gray-500">Stage History</p>
            <div v-for="entry in [...stageLog].slice(-8).reverse()" :key="entry.turn"
                 class="flex items-center gap-2 text-xs py-1">
              <span class="text-gray-300 font-mono w-5">#{{ entry.turn }}</span>
              <span class="font-bold px-1.5 py-0.5 rounded text-[9px]"
                    :style="{ background: (STAGE_COLORS[entry.stage]||'#888')+'18', color: STAGE_COLORS[entry.stage] }">S{{ entry.stage }}</span>
              <span class="text-gray-600 truncate">{{ entry.query }}</span>
            </div>
          </div>

          <div v-if="!debugStage && !pipeline.length" class="flex flex-col items-center justify-center py-12 text-gray-400">
            <div class="text-4xl mb-2">🔬</div>
            <p class="text-xs">Pipeline trace sẽ hiện sau khi gửi tin nhắn</p>
          </div>
        </div>
      </div>
    </div>
  </DashboardLayout>
</template>
