<script setup>
import { ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Skeleton } from '@/components/ui/skeleton'

const DISABLE_AUTH = import.meta.env.VITE_DISABLE_AUTH === 'true'
const API = import.meta.env.VITE_API_BASE || 'http://localhost:5000'

let _clerkUser = ref(null)
if (!DISABLE_AUTH) {
  try {
    const { useUser } = await import('@clerk/vue')
    const { user } = useUser()
    _clerkUser = user
  } catch (_) {}
}
const user = _clerkUser

const stats = ref([
  { label: 'Tổng sản phẩm', value: null, delta: null, icon: `<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>`, color: '#f59e0b' },
  { label: 'Mô tả AI',      value: null, delta: null, icon: `<path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/>`, color: '#10b981' },
  { label: 'Chờ duyệt',    value: null, delta: null, icon: `<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>`, color: '#f97316' },
  { label: 'AI Phối đồ',   value: null, delta: null, icon: `<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>`, color: '#8b5cf6' },
])
const loading = ref(true)

onMounted(async () => {
  try {
    const r = await fetch(`${API}/api/product-desc/overview`)
    if (r.ok) {
      const d = await r.json()
      stats.value[0].value = d.total?.toLocaleString()
      stats.value[1].value = d.has_description?.toLocaleString()
      stats.value[2].value = d.pending_review?.toLocaleString()
      stats.value[3].value = d.has_ai_matches?.toLocaleString()
    }
  } catch (_) {}
  finally { loading.value = false }
})

const quickLinks = [
  {
    label: 'Ultra Description',
    path: '/product-desc',
    desc: 'AI sinh mô tả sản phẩm chuẩn SEO',
    badge: 'NEW',
    icon: `<path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/>`,
    color: '#f59e0b',
  },
  {
    label: 'Fashion Matches',
    path: '/fashion-matches',
    desc: 'AI phối đồ & scoring rules',
    badge: 'NEW',
    icon: `<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>`,
    color: '#ec4899',
  },
  {
    label: 'AI Data Analyst',
    path: '/ai-report',
    desc: 'Phân tích dữ liệu bằng ngôn ngữ tự nhiên',
    badge: 'NEW',
    icon: `<line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/>`,
    color: '#3b82f6',
  },
  {
    label: 'Live Monitor',
    path: '/live-monitor',
    desc: 'Giám sát chatbot & hệ thống realtime',
    badge: 'LIVE',
    icon: `<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>`,
    color: '#10b981',
  },
  {
    label: 'SQL Generator',
    path: '/ai-sql',
    desc: 'Text-to-SQL thông minh + HITL approval',
    badge: 'NEW',
    icon: `<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/>`,
    color: '#8b5cf6',
  },
  {
    label: 'Knowledge Graph',
    path: '/knowledge-graph',
    desc: 'Xem mạng lưới kiến thức AI',
    badge: null,
    icon: `<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>`,
    color: '#06b6d4',
  },
]
</script>

<template>
  <DashboardLayout>
    <div class="p-6 lg:p-8 space-y-8 max-w-[1200px]">

      <!-- ── Header ── -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold tracking-tight text-foreground">
            Xin chào, {{ user?.firstName || 'Admin' }} 👋
          </h1>
          <p class="text-sm text-muted-foreground mt-1">
            Canifa AI Admin Console · v3.0
          </p>
        </div>
        <div class="flex items-center gap-2 text-xs font-semibold px-3 py-1.5 rounded-full border border-emerald-200 bg-emerald-50 text-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-900/40">
          <span class="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
          Hệ thống Online
        </div>
      </div>

      <!-- ── KPI Stat Cards ── -->
      <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div v-for="(s, i) in stats" :key="i"
             class="rounded-xl border border-border bg-card p-5 hover:shadow-md transition-shadow relative overflow-hidden group">

          <!-- Subtle gradient bg on hover -->
          <div class="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity rounded-xl"
               :style="`background: linear-gradient(135deg, ${s.color}08 0%, transparent 80%);`" />

          <div class="relative flex items-start justify-between">
            <div>
              <p class="text-xs font-semibold uppercase tracking-widest text-muted-foreground mb-3">{{ s.label }}</p>
              <Skeleton v-if="loading" class="h-8 w-20 mb-1" />
              <p v-else class="text-3xl font-black tabular-nums text-foreground leading-none">
                {{ s.value ?? '—' }}
              </p>
            </div>
            <div class="w-10 h-10 rounded-lg flex items-center justify-center shrink-0"
                 :style="`background: ${s.color}18;`">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"
                   :style="`color: ${s.color};`" v-html="s.icon" />
            </div>
          </div>
        </div>
      </div>

      <!-- ── Quick Access Grid ── -->
      <div>
        <div class="flex items-center gap-3 mb-4">
          <p class="text-xs font-bold uppercase tracking-widest text-muted-foreground">Truy cập nhanh</p>
          <div class="flex-1 h-px bg-border" />
        </div>

        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
          <RouterLink
            v-for="link in quickLinks"
            :key="link.path"
            :to="link.path"
            class="group flex items-center gap-4 p-4 rounded-xl border border-border bg-card hover:border-transparent hover:shadow-lg hover:-translate-y-0.5 transition-all duration-200 relative overflow-hidden"
          >
            <!-- Gradient overlay on hover -->
            <div class="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity rounded-xl"
                 :style="`background: linear-gradient(135deg, ${link.color}10 0%, transparent 70%);`" />

            <!-- Icon -->
            <div class="relative w-10 h-10 rounded-lg flex items-center justify-center shrink-0 transition-transform group-hover:scale-110"
                 :style="`background: ${link.color}18;`">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"
                   :style="`color: ${link.color};`" v-html="link.icon" />
            </div>

            <!-- Text -->
            <div class="relative flex-1 min-w-0">
              <div class="flex items-center gap-2">
                <p class="text-sm font-semibold text-foreground truncate">{{ link.label }}</p>
                <span v-if="link.badge"
                      class="shrink-0 text-[9px] font-black px-1.5 py-0.5 rounded leading-none tracking-wider"
                      :style="link.badge === 'LIVE'
                        ? 'background: rgba(239,68,68,0.12); color: #ef4444;'
                        : `background: ${link.color}18; color: ${link.color};`">
                  {{ link.badge }}
                </span>
              </div>
              <p class="text-xs text-muted-foreground mt-0.5 truncate">{{ link.desc }}</p>
            </div>

            <!-- Arrow -->
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                 class="relative shrink-0 text-muted-foreground/30 group-hover:text-foreground/50 group-hover:translate-x-0.5 transition-all">
              <path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>
            </svg>
          </RouterLink>
        </div>
      </div>

      <!-- ── Footer info ── -->
      <div class="flex items-center gap-2 text-xs text-muted-foreground/50 pb-4">
        <span>Canifa AI Admin Console</span>
        <span>·</span>
        <span class="font-semibold" style="color: #f59e0b;">v3.0 Vue 3 + shadcn-vue</span>
        <span>·</span>
        <span>Powered by FastAPI × Gemini</span>
      </div>

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