<script setup>
import { ref, computed, onMounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'

const MOCK_USERS = [
  { id: 1, name: 'Nguyễn Thị Lan', userId: 'CNF-20240156', gender: 'Nữ', age: 35, avatar_color: '#6366F1', location: 'Quận Cầu Giấy, Hà Nội', membership: 'VIP Gold', channels: ['Zalo OA', 'Web', 'Email'], aov: 485000, total_orders: 12, total_spent: 5820000, health_score: 82, rfm: { recency: 90, frequency: 75, monetary: 68 }, chatbot_insight: { USER: 'Nữ, 35 tuổi, mẹ bỉm sữa. Gu: basic, thoải mái, ưu tiên cotton organic.', TARGET: 'Con trai 5 tuổi, thích màu xanh navy và đỏ. Size 110-120cm.', GOAL: 'Mua quần áo trẻ em cho con đi học + đi chơi.', CONSTRAINS: 'Budget 300k-600k/bộ. Chỉ muốn cotton 100%. Size 5T-6T.', LATEST_PRODUCT_INTEREST: 'Áo thun bé trai Basic Cotton [6TS24B005] - Xanh navy', LAST_ACTION: 'Bot gợi ý 3 combo áo+quần bé trai dưới 500k.', SUMMARY_HISTORY: 'Hỏi áo thun bé trai → bot gợi ý → compare giá → hỏi combo deal' }, predictions: { next_purchase: 'Quần jean bé trai', next_purchase_conf: 78, churn_risk: 12, clv_6m: 2400000, next_visit_days: 3 }, segments: { purchase_likelihood: 'High', customer_value: 'VIP', lifecycle: 'Active Customer' }, next_best_actions: [{ icon: '📧', title: 'Gửi email BST Back-to-School', desc: 'Conf 85% — mua đồ cho con đi học', urgency: 'urgent' }, { icon: '🎁', title: 'Push combo "Mua 2 giảm 15%" trẻ em', desc: 'Tăng AOV', urgency: 'medium' }], purchase_timeline: [{ date: '22/03/2026', name: 'Áo thun bé trai x2', price: '498,000đ', icon: '👕', channel: 'Web' }, { date: '15/03/2026', name: 'Set quần áo bé trai', price: '459,000đ', icon: '👖', channel: 'Zalo' }], chatbot_history: [{ role: 'user', text: 'Cho mình xem áo thun cotton cho bé trai 5 tuổi' }, { role: 'bot', text: 'Dạ chị ơi, em có nhiều mẫu áo thun cotton bé trai size 5T (110cm). Giá từ 149k-249k.' }] },
  { id: 2, name: 'Trần Văn Minh', userId: 'CNF-20240089', gender: 'Nam', age: 42, avatar_color: '#059669', location: 'Quận 7, TP HCM', membership: 'Regular', channels: ['Zalo OA', 'Web'], aov: 720000, total_orders: 8, total_spent: 5760000, health_score: 61, rfm: { recency: 55, frequency: 50, monetary: 72 }, chatbot_insight: { USER: 'Nam, 42 tuổi, IT manager. Gu: smart casual, công sở.', TARGET: 'Bản thân + vợ (mua quà).', GOAL: 'Tìm áo sơ mi đi làm + quà sinh nhật cho vợ.', CONSTRAINS: 'Budget sơ mi 400k-600k. Quà vợ 500k-1tr. Size M nam, size S nữ.', LATEST_PRODUCT_INTEREST: 'Sơ mi Oxford Slim [8SM24S012] - Trắng', LAST_ACTION: 'Bot gợi ý 2 sơ mi + set quà cho vợ.', SUMMARY_HISTORY: 'Hỏi sơ mi → bot gợi ý Oxford → chuyển sang hỏi quà vợ' }, predictions: { next_purchase: 'Áo sơ mi', next_purchase_conf: 62, churn_risk: 25, clv_6m: 1800000, next_visit_days: 7 }, segments: { purchase_likelihood: 'Medium', customer_value: 'Regular', lifecycle: 'Active Customer' }, next_best_actions: [{ icon: '📧', title: 'Email BST Polo mùa hè mới', desc: 'Conf 70% — top category', urgency: 'medium' }, { icon: '🎁', title: 'Gợi ý set quà cho vợ', desc: 'Đã hỏi về quà sinh nhật', urgency: 'urgent' }], purchase_timeline: [{ date: '18/03/2026', name: 'Sơ mi Oxford Slim x2', price: '998,000đ', icon: '👔', channel: 'Web' }], chatbot_history: [{ role: 'user', text: 'Sơ mi nam công sở, size M, budget 500k?' }, { role: 'bot', text: 'Dạ anh, em gợi ý Sơ mi Oxford Slim (499k) và Sơ mi Linen (459k)!' }] },
  { id: 3, name: 'Lê Phương Anh', userId: 'CNF-20250012', gender: 'Nữ', age: 28, avatar_color: '#EC4899', location: 'Quận Hoàn Kiếm, Hà Nội', membership: 'VIP Platinum', channels: ['Zalo OA', 'Web', 'Email', 'SMS'], aov: 380000, total_orders: 22, total_spent: 8360000, health_score: 95, rfm: { recency: 95, frequency: 92, monetary: 78 }, chatbot_insight: { USER: 'Nữ, 28 tuổi, designer freelance. Gu: minimalist, neutral tones, oversized fit.', TARGET: 'Bản thân. Thích loungewear & đồ mặc nhà cao cấp.', GOAL: 'Mua set pyjama lụa + đồ WFH thoải mái.', CONSTRAINS: 'Budget 300k-500k/set. Chỉ muốn neutral colors (beige, trắng, xám). Size S.', LATEST_PRODUCT_INTEREST: 'Set Pyjama Lụa [7PJ24W003] - Beige', LAST_ACTION: 'Bot gửi link 3 set pyjama lụa neutral.', SUMMARY_HISTORY: 'Hỏi đồ mặc nhà → bot gợi ý cotton → khách muốn lụa → bot show 3 options → khách chọn beige' }, predictions: { next_purchase: 'Đồ mặc nhà lụa', next_purchase_conf: 91, churn_risk: 5, clv_6m: 3200000, next_visit_days: 1 }, segments: { purchase_likelihood: 'High', customer_value: 'VIP', lifecycle: 'Loyal Customer' }, next_best_actions: [{ icon: '🛒', title: 'Nhắc cart Pyjama Lụa Beige (450k)', desc: 'Added to cart 1 ngày trước', urgency: 'urgent' }, { icon: '📧', title: 'Email early access BST mới', desc: 'Loyal customer — cho xem trước 24h', urgency: 'low' }], purchase_timeline: [{ date: '23/03/2026', name: 'Set Pyjama Cotton', price: '279,000đ', icon: '👚', channel: 'Email' }, { date: '20/03/2026', name: 'Áo len cổ lọ oversized', price: '399,000đ', icon: '🧶', channel: 'Web' }], chatbot_history: [{ role: 'user', text: 'Có set đồ mặc nhà nào đang sale không?' }, { role: 'bot', text: 'Dạ chị ơi! Set Pyjama Cotton giảm 30% còn 279,000đ và set Pyjama Lụa giảm 20% còn 360,000đ ạ.' }] },
  { id: 4, name: 'Phạm Quốc Hùng', userId: 'CNF-20230445', gender: 'Nam', age: 38, avatar_color: '#D97706', location: 'Quận Bình Thạnh, TP HCM', membership: 'Premium', channels: ['Web'], aov: 1200000, total_orders: 5, total_spent: 6000000, health_score: 35, rfm: { recency: 25, frequency: 30, monetary: 85 }, chatbot_insight: { USER: 'Nam, 38 tuổi, giám đốc kinh doanh. Gu: premium, formal.', TARGET: 'Bản thân (đi meeting, event).', GOAL: 'Tìm blazer wool cho mùa đông.', CONSTRAINS: 'Budget 1tr-2tr. Size L. Chỉ muốn màu tối (đen, navy, charcoal).', LATEST_PRODUCT_INTEREST: 'Áo Blazer Wool [8BL24W001] - Navy', LAST_ACTION: 'Bot gợi ý Blazer Wool + quần âu. Khách abandoned cart 2 lần.', SUMMARY_HISTORY: 'Hỏi blazer premium → bot gợi ý → khách add cart → abandoned x2' }, predictions: { next_purchase: 'Áo khoác blazer', next_purchase_conf: 35, churn_risk: 68, clv_6m: 800000, next_visit_days: 21 }, segments: { purchase_likelihood: 'Low', customer_value: 'Premium', lifecycle: 'At-Risk' }, next_best_actions: [{ icon: '🚨', title: 'Win-back campaign URGENT', desc: '68% churn risk — không mua 82 ngày', urgency: 'urgent' }, { icon: '💸', title: 'Gửi voucher 200k cho blazer', desc: 'Abandoned cart x2 lần', urgency: 'urgent' }], purchase_timeline: [{ date: '05/01/2026', name: 'Sơ mi Oxford', price: '499,000đ', icon: '👔', channel: 'Web' }], chatbot_history: [{ role: 'user', text: 'Blazer wool nam, size L, navy?' }, { role: 'bot', text: 'Dạ anh, em có Blazer Wool Slim Fit (1,290,000đ) màu Navy, size L còn hàng!' }] },
  { id: 5, name: 'Đỗ Thanh Hà', userId: 'CNF-20260034', gender: 'Nữ', age: 20, avatar_color: '#7C3AED', location: 'Quận Đống Đa, Hà Nội', membership: 'New Member', channels: ['Zalo OA', 'Web', 'TikTok'], aov: 295000, total_orders: 3, total_spent: 885000, health_score: 72, rfm: { recency: 80, frequency: 35, monetary: 30 }, chatbot_insight: { USER: 'Nữ, 20 tuổi, sinh viên ĐH Kinh tế. Gu: trendy, GenZ, thích crop top & Y2K.', TARGET: 'Bản thân, mua đi chơi + đi học.', GOAL: 'Tìm áo crop top trendy, giá rẻ.', CONSTRAINS: 'Budget dưới 300k. Size XS/S. Thích pastel & màu neon.', LATEST_PRODUCT_INTEREST: 'Crop Top Ribbed [7CT24S005] - Hồng pastel', LAST_ACTION: 'Bot show 3 crop top dưới 200k. Khách thích Ribbed nhưng hết size XS.', SUMMARY_HISTORY: 'Hỏi crop top → bot list → thích ribbed → hết size → cân nhắc' }, predictions: { next_purchase: 'Áo crop top', next_purchase_conf: 82, churn_risk: 18, clv_6m: 1500000, next_visit_days: 2 }, segments: { purchase_likelihood: 'High', customer_value: 'New', lifecycle: 'New Customer' }, next_best_actions: [{ icon: '🛒', title: 'Nhắc cart Crop Top Ribbed 195k', desc: 'Viewed 5x, abandoned 1x', urgency: 'urgent' }, { icon: '📱', title: 'Push TikTok sale notification', desc: 'High TikTok engagement', urgency: 'medium' }], purchase_timeline: [{ date: '21/03/2026', name: 'Quần short kaki', price: '299,000đ', icon: '🩳', channel: 'Web' }], chatbot_history: [{ role: 'user', text: 'có áo croptop nào dưới 200k k 💀' }, { role: 'bot', text: 'Dạ chị, em có 3 mẫu Crop Top dưới 200k: Basic (149k), Ribbed (195k), và Henley (189k). Ribbed đang hot nhất ạ! 🔥' }] },
]

const users = ref([...MOCK_USERS])
const selectedId = ref(null)
const searchQuery = ref('')
const loading = ref(false)

const selectedUser = computed(() => users.value.find(u => u.id === selectedId.value))

const filteredUsers = computed(() => {
  const q = searchQuery.value.toLowerCase()
  if (!q) return users.value
  return users.value.filter(u => u.name.toLowerCase().includes(q) || u.userId.toLowerCase().includes(q))
})

const insightLayers = [
  { key: 'USER', icon: '👤', label: 'Người dùng', color: 'hsl(var(--chart-1))' },
  { key: 'TARGET', icon: '🎯', label: 'Đối tượng đích', color: 'hsl(var(--chart-2))' },
  { key: 'GOAL', icon: '🛒', label: 'Mục tiêu sắm', color: 'hsl(var(--chart-3))' },
  { key: 'CONSTRAINS', icon: '🔒', label: 'Ràng buộc', color: 'hsl(var(--destructive))' },
  { key: 'LATEST_PRODUCT_INTEREST', icon: '💎', label: 'Sp quan tâm', color: 'hsl(var(--chart-4))' },
  { key: 'LAST_ACTION', icon: '⚡', label: 'Bot Action', color: 'hsl(var(--chart-5))' },
  { key: 'SUMMARY_HISTORY', icon: '📝', label: 'Tóm tắt Flow', color: 'hsl(var(--muted-foreground))' },
]

function healthColor(score) {
  if (score >= 70) return 'text-emerald-500'
  if (score >= 40) return 'text-amber-500'
  return 'text-destructive'
}

function fmtMoney(n) { return Number(n || 0).toLocaleString('vi-VN') + 'đ' }

async function loadFromApi() {
  loading.value = true
  try {
    const r = await fetch('/api/user-insights/all')
    const d = await r.json()
    if (d.status === 'success' && d.insights?.length) {
      const extra = d.insights
        .filter(i => !users.value.find(u => u.userId === i.identity_key))
        .map((i, idx) => ({
          id: 1000 + idx, name: i.identity_key, userId: i.identity_key,
          gender: i.insight?.USER?.includes('Nữ') ? 'Nữ' : 'Nam', age: 0,
          avatar_color: ['#6366F1', '#059669', '#EC4899', '#D97706', '#7C3AED'][idx % 5],
          location: '—', membership: 'API User', channels: ['Chatbot'],
          aov: 0, total_orders: i.message_count || 0, total_spent: 0,
          health_score: 50, rfm: { recency: 50, frequency: 50, monetary: 50 },
          chatbot_insight: i.insight || {}, predictions: { next_purchase: '—', next_purchase_conf: 0, churn_risk: 50, clv_6m: 0, next_visit_days: 0 },
          segments: { purchase_likelihood: 'Unknown', customer_value: '—', lifecycle: '—' },
          next_best_actions: [], purchase_timeline: [], chatbot_history: [],
          _source: 'api'
        }))
      users.value = [...MOCK_USERS, ...extra]
    }
  } catch (_) {} finally { loading.value = false }
}

onMounted(loadFromApi)
</script>

<template>
  <DashboardLayout>
    <div class="h-[calc(100vh-theme(spacing.16))] flex flex-col p-6 max-w-[1400px] mx-auto gap-4">
      
      <!-- Top Header -->
      <div class="flex items-center justify-between shrink-0">
        <div>
          <h1 class="text-2xl font-bold tracking-tight text-foreground">User Insight & CDP</h1>
          <p class="text-sm text-muted-foreground mt-1">Phân tích hành vi & nhận diện khách hàng thông qua Chatbot</p>
        </div>
        <Button variant="outline" size="sm" @click="loadFromApi" :disabled="loading" class="gap-2">
          <span v-if="loading" class="w-3 h-3 border-2 border-current border-t-transparent animate-spin rounded-full"></span>
          {{ loading ? 'Đang đồng bộ...' : '🔄 Refresh API' }}
        </Button>
      </div>

      <Separator />

      <!-- Main Layout -->
      <div class="grid grid-cols-[320px_1fr] gap-6 flex-1 min-h-0">
        
        <!-- User list Sidebar -->
        <Card class="flex flex-col overflow-hidden bg-card/50">
          <CardHeader class="pb-3 border-b border-border/50">
            <CardTitle class="text-sm font-semibold flex items-center justify-between">
              Customer Profiles
              <Badge variant="secondary" class="font-normal text-[10px]">{{ filteredUsers.length }} users</Badge>
            </CardTitle>
            <Input v-model="searchQuery" placeholder="Tìm tên, user ID..." class="h-9 w-full shadow-none mt-2 text-xs" />
          </CardHeader>
          
          <ScrollArea class="flex-1 p-2">
            <div class="space-y-1">
              <div v-for="u in filteredUsers" :key="u.id"
                   @click="selectedId = u.id"
                   :class="['group flex items-center justify-between p-3 rounded-lg cursor-pointer transition-colors border border-transparent',
                     selectedId === u.id ? 'bg-primary/5 border-primary/20 shadow-sm' : 'hover:bg-accent/50 hover:border-border']">
                
                <div class="flex items-center gap-3 min-w-0">
                  <div class="w-10 h-10 rounded-full flex items-center justify-center text-primary-foreground text-xs font-bold shrink-0 shadow-sm transition-transform group-hover:scale-105"
                       :style="{ background: u.avatar_color }">
                    {{ u.name.split(' ').pop()[0] }}
                  </div>
                  <div class="flex-1 min-w-0 flex flex-col justify-center">
                    <p class="font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors">{{ u.name }}</p>
                    <div class="flex items-center gap-1.5 mt-0.5">
                      <p class="text-[10px] text-muted-foreground font-mono truncate">{{ u.userId }}</p>
                      <span v-if="u._source === 'api'" class="w-1.5 h-1.5 bg-emerald-500 rounded-full animate-pulse"></span>
                    </div>
                  </div>
                </div>

                <div class="flex flex-col items-end justify-center shrink-0 ml-3">
                  <p :class="['text-sm font-bold', healthColor(u.health_score)]">{{ u.health_score }}</p>
                  <p class="text-[9px] text-muted-foreground uppercase tracking-wider">Health</p>
                </div>
              </div>
            </div>
            
            <div v-if="!filteredUsers.length" class="text-center py-10 text-muted-foreground text-xs">
              Không tìm thấy khách hàng.
            </div>
          </ScrollArea>
        </Card>

        <!-- Right Detail Panel -->
        <div v-if="!selectedUser" class="flex flex-col items-center justify-center text-muted-foreground border border-dashed border-border rounded-xl bg-muted/10 h-full">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="opacity-20 mb-4"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
          <p class="font-medium text-foreground">Chưa chọn Profile</p>
          <p class="text-xs pt-1">Bấm vào một user ở danh sách để xem Insight & Predictions</p>
        </div>

        <Card v-else class="flex flex-col overflow-hidden">
          <ScrollArea class="flex-1">
            <!-- User Info Header -->
            <div class="p-6 border-b border-border bg-card/30">
              <div class="flex items-start justify-between gap-6">
                <!-- Left Details -->
                <div class="flex items-center gap-5">
                  <div class="w-20 h-20 rounded-full flex items-center justify-center text-primary-foreground text-3xl font-bold shadow-md shrink-0 ring-4 ring-background"
                       :style="{ background: selectedUser.avatar_color }">
                    {{ selectedUser.name.split(' ').pop()[0] }}
                  </div>
                  <div>
                    <div class="flex items-center gap-3">
                      <h2 class="text-xl font-bold text-foreground">{{ selectedUser.name }}</h2>
                      <Badge :variant="selectedUser.membership?.includes('VIP') ? 'default' : 'secondary'" class="text-[10px] uppercase font-bold tracking-wider">
                        {{ selectedUser.membership }}
                      </Badge>
                    </div>
                    <div class="flex items-center gap-2 mt-1">
                      <p class="text-xs font-mono text-muted-foreground bg-accent px-1.5 py-0.5 rounded">{{ selectedUser.userId }}</p>
                      <span class="text-muted-foreground text-xs">•</span>
                      <p class="text-xs text-muted-foreground">{{ selectedUser.gender }}, {{ selectedUser.age || '?' }} tuổi</p>
                    </div>
                    <p class="text-xs text-muted-foreground mt-1">{{ selectedUser.location }}</p>
                    <div class="flex gap-1.5 mt-2">
                      <Badge variant="outline" v-for="ch in selectedUser.channels" :key="ch" class="text-[9px] text-muted-foreground bg-background">{{ ch }}</Badge>
                    </div>
                  </div>
                </div>

                <!-- Right Micro-Stats -->
                <div class="grid grid-cols-3 gap-6 text-right">
                  <div>
                    <p class="text-2xl font-bold text-foreground">{{ selectedUser.total_orders }}</p>
                    <p class="text-[10px] text-muted-foreground uppercase font-medium tracking-wider">Đơn hàng</p>
                  </div>
                  <div>
                    <p class="text-2xl font-bold text-primary">{{ fmtMoney(selectedUser.aov).replace('đ','') }}<span class="text-base text-muted-foreground font-normal">đ</span></p>
                    <p class="text-[10px] text-muted-foreground uppercase font-medium tracking-wider">AOV</p>
                  </div>
                  <div>
                    <p :class="['text-2xl font-bold', healthColor(selectedUser.health_score)]">{{ selectedUser.health_score }}<span class="text-lg opacity-50">/100</span></p>
                    <p class="text-[10px] text-muted-foreground uppercase font-medium tracking-wider">Health</p>
                  </div>
                </div>
              </div>
            </div>

            <div class="p-6">
              <Tabs default-value="insight" class="w-full h-full flex flex-col">
                <TabsList class="grid w-full grid-cols-4 mb-6 bg-accent/50 p-1">
                  <TabsTrigger value="insight" class="text-xs">🧠 Chatbot Insight</TabsTrigger>
                  <TabsTrigger value="predictions" class="text-xs">🔮 Predictions</TabsTrigger>
                  <TabsTrigger value="actions" class="text-xs">⚡ Actions</TabsTrigger>
                  <TabsTrigger value="history" class="text-xs">💬 History</TabsTrigger>
                </TabsList>

                <!-- Chatbot Insight Tab -->
                <TabsContent value="insight" class="space-y-4">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Card v-for="layer in insightLayers" :key="layer.key"
                          v-if="selectedUser.chatbot_insight[layer.key] && !selectedUser.chatbot_insight[layer.key].includes('Chưa')"
                          class="overflow-hidden shadow-none border-l-4 rounded-xl hover:shadow-md transition-shadow"
                          :style="{ borderLeftColor: layer.color }">
                      <CardHeader class="p-4 pb-2 bg-gradient-to-r from-muted/30 to-transparent">
                        <CardTitle class="text-xs uppercase tracking-wider font-bold flex items-center gap-2" :style="{ color: layer.color }">
                          <span class="text-lg opacity-80">{{ layer.icon }}</span> {{ layer.label }}
                        </CardTitle>
                      </CardHeader>
                      <CardContent class="p-4 pt-0">
                        <p class="text-sm font-medium text-foreground leading-relaxed">{{ selectedUser.chatbot_insight[layer.key] }}</p>
                      </CardContent>
                    </Card>
                  </div>
                </TabsContent>

                <!-- Predictions Tab -->
                <TabsContent value="predictions" class="space-y-6">
                  <div class="grid grid-cols-3 gap-4">
                    <Card class="bg-primary/5 border-primary/20 shadow-sm pt-6 pb-4">
                      <CardContent class="text-center">
                        <p class="text-3xl font-black text-primary">{{ selectedUser.predictions.next_purchase_conf }}%</p>
                        <p class="text-xs font-semibold text-foreground mt-1">Mức độ mua tiếp</p>
                        <p class="text-xs text-muted-foreground mt-1 bg-background border border-border inline-block px-2 py-1 rounded-md">{{ selectedUser.predictions.next_purchase }}</p>
                      </CardContent>
                    </Card>
                    <Card :class="selectedUser.predictions.churn_risk > 50 ? 'bg-destructive/10 border-destructive/20' : 'bg-muted/30'" class="pt-6 pb-4 shadow-sm">
                      <CardContent class="text-center">
                        <p :class="['text-3xl font-black', selectedUser.predictions.churn_risk > 50 ? 'text-destructive' : 'text-amber-500']">{{ selectedUser.predictions.churn_risk }}%</p>
                        <p class="text-xs font-semibold text-foreground mt-1">Churn Risk</p>
                        <p class="text-[10px] text-muted-foreground mt-1 font-medium">Khả năng rời bỏ</p>
                      </CardContent>
                    </Card>
                    <Card class="bg-muted/30 shadow-sm pt-6 pb-4">
                      <CardContent class="text-center">
                        <p class="text-2xl font-black text-amber-600">{{ fmtMoney(selectedUser.predictions.clv_6m).replace('đ','') }}<span class="text-sm font-normal opacity-50">đ</span></p>
                        <p class="text-xs font-semibold text-foreground mt-1">CLV 6 tháng tới</p>
                        <p class="text-[10px] text-muted-foreground mt-1 font-medium">Bản đồ vòng lặp</p>
                      </CardContent>
                    </Card>
                  </div>

                  <div class="pt-4 border-t border-border">
                    <h3 class="text-sm font-semibold mb-4 text-foreground">Phân cụm / Segmentation</h3>
                    <div class="flex gap-4">
                      <div v-for="seg in [{ k: 'purchase_likelihood', label: 'Intent' }, { k: 'customer_value', label: 'Value' }, { k: 'lifecycle', label: 'Lifecycle' }]" :key="seg.k" class="flex-1 border border-border rounded-lg p-3 text-center bg-card">
                        <p class="text-[10px] uppercase font-bold tracking-wider text-muted-foreground mb-2">{{ seg.label }}</p>
                        <Badge :variant="selectedUser.segments[seg.k] === 'High' || selectedUser.segments[seg.k] === 'VIP' ? 'default' : 'secondary'" class="text-xs font-semibold w-full justify-center">
                          {{ selectedUser.segments[seg.k] }}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </TabsContent>

                <!-- Actions Tab -->
                <TabsContent value="actions" class="space-y-3 pt-2">
                  <div v-for="action in selectedUser.next_best_actions" :key="action.title"
                       :class="['flex items-start gap-4 p-4 border rounded-xl shadow-sm transition-colors',
                         action.urgency === 'urgent' ? 'border-destructive/30 bg-destructive/5 hover:border-destructive/50' : 'border-border bg-card hover:bg-accent/50']">
                    <div class="text-2xl shrink-0 mt-0.5 opacity-80">{{ action.icon }}</div>
                    <div class="flex-1 min-w-0">
                      <div class="flex items-center justify-between gap-2">
                        <p class="font-semibold text-foreground">{{ action.title }}</p>
                        <Badge v-if="action.urgency === 'urgent'" variant="destructive" class="text-[9px] h-4 py-0 uppercase">Urgent</Badge>
                      </div>
                      <p class="text-sm text-muted-foreground mt-1 leading-relaxed">{{ action.desc }}</p>
                    </div>
                    <Button variant="outline" size="sm" class="shrink-0 h-8 self-center">Thực thi</Button>
                  </div>
                  <div v-if="!selectedUser.next_best_actions?.length" class="text-center py-10 text-muted-foreground text-sm border border-dashed rounded-xl bg-muted/10">
                    Không có gợi ý hành động nào
                  </div>
                </TabsContent>

                <!-- History Tab -->
                <TabsContent value="history" class="space-y-6 pt-2">
                  <div class="border border-border rounded-xl p-4 bg-muted/10">
                    <h3 class="text-xs font-bold text-foreground uppercase tracking-wider mb-4 flex items-center gap-2">
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-primary"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>
                      Giao tiếp gần nhất
                    </h3>
                    <div class="space-y-3">
                      <div v-for="(msg, i) in selectedUser.chatbot_history" :key="i"
                           :class="['flex', msg.role === 'user' ? 'justify-end' : 'justify-start']">
                        <div :class="['max-w-[85%] rounded-2xl px-4 py-3 text-sm leading-relaxed shadow-sm',
                          msg.role === 'user' ? 'bg-primary text-primary-foreground rounded-tr-sm' : 'bg-card border border-border text-foreground rounded-tl-sm']">
                          {{ msg.text }}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div v-if="selectedUser.purchase_timeline?.length">
                    <h3 class="text-xs font-bold text-foreground uppercase tracking-wider mb-4 flex items-center gap-2">
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-muted-foreground"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                      Purchase Timeline
                    </h3>
                    <div class="border border-border rounded-xl bg-card overflow-hidden">
                      <div v-for="(p, idx) in selectedUser.purchase_timeline" :key="p.date"
                           :class="['flex items-center gap-4 p-4 hover:bg-accent/50 transition-colors', idx !== selectedUser.purchase_timeline.length - 1 ? 'border-b border-border' : '']">
                        <div class="w-10 h-10 rounded-full bg-accent flex items-center justify-center text-lg border border-border/50 shrink-0">{{ p.icon }}</div>
                        <div class="flex-1 min-w-0">
                          <p class="font-semibold text-sm text-foreground truncate">{{ p.name }}</p>
                          <div class="flex items-center gap-1 mt-0.5">
                            <span class="text-[10px] font-mono text-muted-foreground">{{ p.date }}</span>
                            <span class="text-muted-foreground text-[10px]">•</span>
                            <span class="text-[10px] bg-background border border-border px-1.5 rounded text-muted-foreground">{{ p.channel }}</span>
                          </div>
                        </div>
                        <p class="font-bold text-foreground tabular-nums shrink-0">{{ p.price }}</p>
                      </div>
                    </div>
                  </div>
                </TabsContent>
              </Tabs>
            </div>
          </ScrollArea>
        </Card>
      </div>

    </div>
  </DashboardLayout>
</template>
