<script setup>
import { ref, reactive } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'

const STORAGE_KEY = 'competitor_research_vue'

const scoreColor = v => v >= 4 ? 'text-emerald-500' : v >= 3 ? 'text-amber-500' : 'text-destructive'

const DEFAULT_COMPETITORS = [
  { id: 'zalando', name: 'Zalando', url: 'https://zalando.co.uk', logo: '🟠', desc: 'E-commerce thời trang lớn nhất châu Âu — AI Shopping Assistant', strengths: ['Product card inline với hình ảnh', 'Follow-up questions cuối response', 'Hiểu context tốt', 'Response nhanh, streaming mượt'], weaknesses: ['Yêu cầu đăng nhập mới dùng được', 'Không hỗ trợ tiếng Việt'], lessons: ['Hiện product card inline thay vì list text dài', 'Thêm suggested follow-up questions', 'Cho phép mua ngay từ trong chat'], scores: { ux: 5, speed: 4, ai: 5, product: 5, overall: 5 } },
  { id: 'yame', name: 'YaMe.vn', url: 'https://yame.vn', logo: '🟡', desc: 'Đối thủ trực tiếp tại VN — AI styling theo số đo cơ thể', strengths: ['AI styling theo số đo cơ thể', 'Gợi ý mix đồ theo phong cách', 'Tiếng Việt tự nhiên'], weaknesses: ['Chậm hơn Canifa', 'Không có conversation context', 'Limited sản phẩm được recommend'], lessons: ['Thêm tính năng nhập số đo cơ thể', 'Gợi ý mix đồ (áo + quần + giày) theo set'], scores: { ux: 3, speed: 3, ai: 3, product: 4, overall: 3 } },
  { id: 'hm', name: 'H&M Chatbot', url: 'https://hm.com', logo: '🔴', desc: 'Fast fashion global — chatbot tư vấn cơ bản', strengths: ['Tích hợp trực tiếp trên app mobile', 'Phân loại intent tốt', 'Multi-language'], weaknesses: ['Chatbot khá cơ bản', 'Flow cứng, giống FAQ hơn chat'], lessons: ['Phân loại intent: mua / đổi trả / CSKH'], scores: { ux: 3, speed: 4, ai: 2, product: 2, overall: 3 } },
]

const DEFAULT_FINDINGS = [
  { id: 'f1', title: 'Product Card Inline là must-have', desc: 'Tất cả đối thủ đều hiện sản phẩm dạng card với hình ảnh trong chat. Canifa hiện tại chỉ list text.', apply: 'Thiết kế product card component với hình, tên, giá, nút "Mua ngay" trong chat response.' },
  { id: 'f2', title: 'Follow-up Questions tăng engagement', desc: 'Zalando gợi ý 2-3 câu hỏi tiếp theo để user không bị kẹt.', apply: 'Thêm trường "suggested_questions" vào response. Frontend hiện dạng chip có thể click.' },
  { id: 'f3', title: 'Speed là yếu tố số 1', desc: 'User không chịu đợi quá 3 giây. Canifa hiện tại ~4-6s.', apply: 'Optimize: streaming response, cache sản phẩm phổ biến, parallel tool calls.' },
]

const DEFAULT_IDEAS = [
  { id: 'i1', title: '🛒 Mua ngay trong chat', desc: 'User chọn size + màu ngay trong chat → add to cart → checkout.', priority: 'high', from: 'Zalando' },
  { id: 'i2', title: '📐 AI Size Advisor', desc: 'Nhập chiều cao + cân nặng → AI gợi ý size phù hợp.', priority: 'medium', from: 'YaMe' },
  { id: 'i3', title: '👗 Mix & Match Sets', desc: 'Thay vì recommend 1 sản phẩm, gợi ý cả "set đồ". Tăng giá trị đơn hàng.', priority: 'high', from: 'YaMe + Zalando' },
  { id: 'i4', title: '💬 Smart Chips', desc: 'Cuối mỗi response hiện 2-3 nút nhỏ: "Rẻ hơn?", "Màu khác?", "Size chart?"', priority: 'high', from: 'Zalando' },
]

function loadData() {
  try {
    const s = localStorage.getItem(STORAGE_KEY)
    if (s) return JSON.parse(s)
  } catch (_) {}
  return { competitors: DEFAULT_COMPETITORS, findings: DEFAULT_FINDINGS, ideas: DEFAULT_IDEAS }
}

function saveData() { localStorage.setItem(STORAGE_KEY, JSON.stringify(data)) }

const data = reactive(loadData())
const tab = ref('competitors')
const showAddModal = ref(false)
const newComp = reactive({ name: '', url: '', desc: '', strengths: '', weaknesses: '', lessons: '', ux: 3, speed: 3, ai: 3, product: 3, overall: 3 })

function addCompetitor() {
  data.competitors.push({
    id: 'c_' + Date.now(), logo: '🔵',
    name: newComp.name, url: newComp.url, desc: newComp.desc,
    strengths: newComp.strengths.split('\n').filter(s => s.trim()),
    weaknesses: newComp.weaknesses.split('\n').filter(s => s.trim()),
    lessons: newComp.lessons.split('\n').filter(s => s.trim()),
    scores: { ux: +newComp.ux, speed: +newComp.speed, ai: +newComp.ai, product: +newComp.product, overall: +newComp.overall }
  })
  showAddModal.value = false; Object.assign(newComp, { name: '', url: '', desc: '' })
  saveData()
}

function deleteComp(id) { data.competitors = data.competitors.filter(c => c.id !== id); saveData() }

function addFinding() {
  const title = window.prompt('Finding title:')
  if (!title) return
  const desc = window.prompt('Mô tả:') || ''
  const apply = window.prompt('Áp dụng cho Canifa:') || ''
  data.findings.push({ id: 'f_' + Date.now(), title, desc, apply })
  saveData()
}

function addIdea() {
  const title = window.prompt('Idea title:')
  if (!title) return
  const desc = window.prompt('Mô tả:') || ''
  const from = window.prompt('Học từ đối thủ nào?') || ''
  const priority = window.prompt('Priority (high/medium/low):') || 'medium'
  data.ideas.push({ id: 'i_' + Date.now(), title, desc, from, priority })
  saveData()
}

const priColor = { high: 'destructive', medium: 'default', low: 'secondary' }
</script>

<template>
  <DashboardLayout>
    <div class="p-6 md:p-8 max-w-[1400px] mx-auto min-h-screen">
      <!-- Header -->
      <div class="mb-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div>
          <h1 class="text-3xl font-bold tracking-tight text-foreground">Competitor Research</h1>
          <p class="text-sm text-muted-foreground mt-1">Nghiên cứu đối thủ, tổng hợp insight và đề xuất</p>
        </div>
      </div>

      <!-- Add Competitor Modal -->
      <div v-if="showAddModal" class="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm transition-all duration-200">
        <Card class="w-full max-w-lg shadow-lg border-border">
          <CardHeader class="pb-4 border-b border-border">
            <CardTitle>Thêm đối thủ mới</CardTitle>
          </CardHeader>
          <CardContent class="p-6 space-y-4">
            <div class="grid grid-cols-2 gap-4">
              <div class="space-y-1.5">
                <label class="text-xs font-medium text-foreground">Tên đối thủ</label>
                <Input v-model="newComp.name" placeholder="Ví dụ: ASOS" class="h-9" />
              </div>
              <div class="space-y-1.5">
                <label class="text-xs font-medium text-foreground">URL</label>
                <Input v-model="newComp.url" placeholder="https://..." class="h-9" />
              </div>
            </div>
            
            <div class="space-y-1.5">
              <label class="text-xs font-medium text-foreground">Mô tả ngắn</label>
              <textarea v-model="newComp.desc" placeholder="Đặc điểm nổi bật..." class="w-full flex min-h-[60px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring resize-none" />
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="space-y-1.5">
                <label class="text-xs font-medium text-foreground">Điểm mạnh</label>
                <textarea v-model="newComp.strengths" placeholder="Mỗi dòng 1 điểm..." class="w-full flex min-h-[60px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring resize-none" />
              </div>
              <div class="space-y-1.5">
                <label class="text-xs font-medium text-foreground">Điểm yếu</label>
                <textarea v-model="newComp.weaknesses" placeholder="Mỗi dòng 1 điểm..." class="w-full flex min-h-[60px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring resize-none" />
              </div>
            </div>

            <div class="space-y-1.5">
              <label class="text-xs font-medium text-foreground">Bài học áp dụng</label>
              <textarea v-model="newComp.lessons" placeholder="Bài học cho Canifa..." class="w-full flex min-h-[60px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring resize-none" />
            </div>

            <div class="pt-4 flex gap-3">
              <Button @click="addCompetitor" class="flex-1">Lưu thông tin</Button>
              <Button variant="outline" @click="showAddModal = false" class="flex-1">Hủy</Button>
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs v-model="tab" class="w-full">
        <TabsList class="mb-6 bg-muted/50 p-1 w-max grid grid-cols-3">
          <TabsTrigger value="competitors" class="px-6 rounded-md">🏢 Đối thủ ({{ data.competitors.length }})</TabsTrigger>
          <TabsTrigger value="findings" class="px-6 rounded-md">💡 Findings ({{ data.findings.length }})</TabsTrigger>
          <TabsTrigger value="ideas" class="px-6 rounded-md">🎯 Ideas ({{ data.ideas.length }})</TabsTrigger>
        </TabsList>

        <!-- Competitors Tab -->
        <TabsContent value="competitors" class="space-y-4">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold text-foreground">Hồ sơ đối thủ</h2>
            <Button size="sm" @click="showAddModal = true" class="shadow-sm">
              <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="mr-2"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
              Thêm đối thủ
            </Button>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
            <Card v-for="c in data.competitors" :key="c.id" class="flex flex-col group hover:border-primary/30 transition-colors">
              <CardContent class="p-6 flex-1 flex flex-col">
                <div class="flex items-start gap-4 mb-4">
                  <div class="w-12 h-12 rounded-xl bg-accent flex items-center justify-center text-2xl shrink-0 border border-border shadow-sm">
                    {{ c.logo }}
                  </div>
                  <div class="flex-1 min-w-0">
                    <p class="font-bold text-base text-foreground truncate">{{ c.name }}</p>
                    <a :href="c.url" target="_blank" class="text-xs text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-max">
                      {{ new URL(c.url).hostname }}
                      <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" x2="21" y1="14" y2="3"/></svg>
                    </a>
                  </div>
                  <button @click="deleteComp(c.id)" class="opacity-0 group-hover:opacity-100 p-1.5 rounded-md hover:bg-destructive/10 hover:text-destructive text-muted-foreground transition-all shrink-0">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
                  </button>
                </div>
                
                <p class="text-sm text-foreground/80 mb-6 flex-1 leading-relaxed">{{ c.desc }}</p>
                
                <div class="space-y-5">
                  <div>
                    <h4 class="text-[10px] font-bold text-emerald-600 uppercase tracking-wider mb-2 flex items-center gap-1.5">
                      <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                      Điểm mạnh
                    </h4>
                    <ul class="space-y-1.5">
                      <li v-for="s in c.strengths" :key="s" class="text-xs text-muted-foreground flex items-start gap-2">
                        <span class="text-emerald-500 mt-0.5">•</span> <span class="leading-snug">{{ s }}</span>
                      </li>
                    </ul>
                  </div>

                  <div>
                    <h4 class="text-[10px] font-bold text-destructive uppercase tracking-wider mb-2 flex items-center gap-1.5">
                      <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                      Điểm yếu
                    </h4>
                    <ul class="space-y-1.5">
                      <li v-for="w in c.weaknesses" :key="w" class="text-xs text-muted-foreground flex items-start gap-2">
                        <span class="text-destructive mt-0.5">•</span> <span class="leading-snug">{{ w }}</span>
                      </li>
                    </ul>
                  </div>

                  <div class="p-3 bg-primary/5 border border-primary/10 rounded-lg">
                    <h4 class="text-[10px] font-bold text-primary uppercase tracking-wider mb-2 flex items-center gap-1.5">
                      <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
                      Bài học áp dụng
                    </h4>
                    <ul class="space-y-1.5">
                      <li v-for="l in c.lessons" :key="l" class="text-xs text-foreground font-medium flex items-start gap-2">
                        <span class="opacity-50 mt-0.5">→</span> <span class="leading-snug">{{ l }}</span>
                      </li>
                    </ul>
                  </div>
                </div>

                <!-- Scores Footer -->
                <div class="mt-6 pt-4 border-t border-border grid grid-cols-5 gap-2">
                  <div v-for="(v, k) in c.scores" :key="k" class="text-center flex flex-col justify-end">
                    <p :class="['text-lg font-black leading-none mb-1', scoreColor(v)]">{{ v }}</p>
                    <p class="text-[9px] text-muted-foreground uppercase font-semibold tracking-wider truncate">{{ k }}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <!-- Findings Tab -->
        <TabsContent value="findings" class="space-y-4">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold text-foreground">Key Findings</h2>
            <Button size="sm" variant="outline" @click="addFinding" class="shadow-sm">Thêm giả thuyết</Button>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card v-for="f in data.findings" :key="f.id" class="group">
              <CardContent class="p-5 flex flex-col h-full">
                <div class="flex items-start justify-between mb-3">
                  <h3 class="font-bold text-sm text-foreground flex items-center gap-2">
                    <span class="text-primary text-base">🔍</span>
                    {{ f.title }}
                  </h3>
                  <button @click="data.findings = data.findings.filter(x => x.id !== f.id); saveData()" class="opacity-0 group-hover:opacity-100 p-1 rounded-md hover:bg-destructive/10 hover:text-destructive text-muted-foreground transition-all shrink-0">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
                  </button>
                </div>
                <p class="text-sm text-muted-foreground leading-relaxed mb-4 flex-1">{{ f.desc }}</p>
                <div v-if="f.apply" class="mt-auto bg-primary/10 border border-primary/20 rounded-md p-3 text-sm text-primary font-medium flex items-start gap-2">
                  <span class="mt-0.5">💡</span>
                  <p class="leading-relaxed">{{ f.apply }}</p>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <!-- Ideas Tab -->
        <TabsContent value="ideas" class="space-y-4">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold text-foreground">Actionable Ideas</h2>
            <Button size="sm" variant="outline" @click="addIdea" class="shadow-sm">Đề xuất Idea</Button>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            <Card v-for="idea in data.ideas" :key="idea.id" class="group hover:border-primary/40 transition-colors">
              <CardContent class="p-5">
                <div class="flex items-start gap-3 justify-between">
                  <div class="space-y-2 flex-1">
                    <div class="flex items-start justify-between">
                      <h3 class="font-semibold text-foreground text-base pr-4">{{ idea.title }}</h3>
                      <button @click="data.ideas = data.ideas.filter(x => x.id !== idea.id); saveData()" class="opacity-0 group-hover:opacity-100 p-1.5 rounded-md hover:bg-destructive/10 hover:text-destructive text-muted-foreground transition-all -mt-1 -mr-1">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
                      </button>
                    </div>
                    
                    <div class="flex flex-wrap items-center gap-2">
                      <Badge :variant="priColor[idea.priority] || 'secondary'" class="text-[10px] uppercase font-bold tracking-wider leading-none py-1 shadow-none">
                        {{ idea.priority }}
                      </Badge>
                      <Badge variant="outline" class="text-[10px] text-muted-foreground font-mono bg-transparent">
                        Ref: {{ idea.from }}
                      </Badge>
                    </div>

                    <p class="text-sm text-muted-foreground leading-relaxed pt-2 border-t border-border/50 mt-4">{{ idea.desc }}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
        
      </Tabs>
    </div>
  </DashboardLayout>
</template>
