<template>
  <div class="social-inbox-page">
    <!-- Header -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          <span class="icon">📥</span>
          Social Inbox
        </h1>
        <p class="page-subtitle">Comments & DMs từ Facebook, Instagram, TikTok → AI Learning Loop</p>
      </div>
      <div class="header-actions">
        <button class="btn-refresh" @click="loadData" :disabled="loading">
          <span v-if="loading">⏳</span>
          <span v-else>🔄</span>
          Refresh
        </button>
      </div>
    </div>

    <!-- Stats Cards -->
    <div class="stats-grid" v-if="stats">
      <div class="stat-card total">
        <div class="stat-icon">💬</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">Tổng Messages</div>
        </div>
      </div>
      <div class="stat-card positive">
        <div class="stat-icon">🟢</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.by_sentiment?.positive || 0 }}</div>
          <div class="stat-label">Positive</div>
        </div>
      </div>
      <div class="stat-card negative">
        <div class="stat-icon">🔴</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.by_sentiment?.negative || 0 }}</div>
          <div class="stat-label">Negative</div>
        </div>
      </div>
      <div class="stat-card neutral">
        <div class="stat-icon">⚪</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.by_sentiment?.neutral || 0 }}</div>
          <div class="stat-label">Neutral</div>
        </div>
      </div>
      <div class="stat-card rate" :class="{ 'danger': stats.negative_rate > 30 }">
        <div class="stat-icon">📊</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.negative_rate }}%</div>
          <div class="stat-label">Negative Rate</div>
        </div>
      </div>
    </div>

    <!-- Filters -->
    <div class="filter-bar">
      <div class="filter-tabs">
        <button
          v-for="p in ['all', 'facebook', 'instagram', 'tiktok']"
          :key="p"
          class="filter-tab"
          :class="{ active: selectedPlatform === p }"
          @click="selectPlatform(p)"
        >
          <span>{{ platformIcon(p) }}</span>
          {{ p.charAt(0).toUpperCase() + p.slice(1) }}
          <span class="badge" v-if="platformCount(p) > 0">{{ platformCount(p) }}</span>
        </button>
      </div>
      <div class="sentiment-tabs">
        <button
          v-for="s in ['all', 'positive', 'negative', 'neutral']"
          :key="s"
          class="sentiment-tab"
          :class="[s, { active: selectedSentiment === s }]"
          @click="selectSentiment(s)"
        >
          {{ sentimentIcon(s) }} {{ s }}
        </button>
      </div>
    </div>

    <!-- Test Sentiment Tool -->
    <div class="sentiment-tester">
      <div class="tester-header" @click="showTester = !showTester">
        <span>🧪 Test Sentiment Analysis</span>
        <span>{{ showTester ? '▲' : '▼' }}</span>
      </div>
      <div class="tester-body" v-if="showTester">
        <textarea
          v-model="testText"
          placeholder="Nhập text tiếng Việt hoặc tiếng Anh để test..."
          class="tester-input"
          rows="2"
        />
        <button class="btn-analyze" @click="testSentiment">Phân Tích</button>
        <div class="tester-result" v-if="testResult">
          <span class="result-label" :class="testResult.label">{{ sentimentIcon(testResult.label) }} {{ testResult.label }}</span>
          <span class="result-score">Pos: {{ testResult.pos_score }} | Neg: {{ testResult.neg_score }}</span>
          <div class="result-keywords" v-if="testResult.matched_positive?.length">
            ✅ <span>{{ testResult.matched_positive.join(', ') }}</span>
          </div>
          <div class="result-keywords neg" v-if="testResult.matched_negative?.length">
            ❌ <span>{{ testResult.matched_negative.join(', ') }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Messages Feed -->
    <div class="messages-section">
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>Đang tải messages...</p>
      </div>

      <div v-else-if="messages.length === 0" class="empty-state">
        <div class="empty-icon">📭</div>
        <p>Chưa có social messages nào.</p>
        <p class="empty-hint">Kết nối Facebook/Instagram/TikTok webhook để bắt đầu nhận feedback.</p>
      </div>

      <div v-else class="messages-list">
        <div
          v-for="msg in messages"
          :key="`${msg.platform}-${msg.received_at}`"
          class="message-card"
          :class="msg.sentiment"
        >
          <div class="message-header">
            <div class="sender-info">
              <span class="platform-badge" :class="msg.platform">
                {{ platformIcon(msg.platform) }} {{ msg.platform }}
              </span>
              <span class="message-type-badge">{{ msg.message_type }}</span>
              <strong class="sender-name">@{{ msg.sender_name }}</strong>
            </div>
            <div class="message-meta">
              <span class="sentiment-badge" :class="msg.sentiment">
                {{ sentimentIcon(msg.sentiment) }} {{ msg.sentiment }}
              </span>
              <span class="time">{{ formatTime(msg.received_at) }}</span>
            </div>
          </div>
          <div class="message-body">{{ msg.body }}</div>
          <div class="message-footer" v-if="msg.post_id">
            <span class="post-id">Post: {{ msg.post_id }}</span>
          </div>
        </div>
      </div>

      <!-- Pagination -->
      <div class="pagination" v-if="total > limit">
        <button @click="prevPage" :disabled="offset === 0">← Trước</button>
        <span>{{ Math.floor(offset / limit) + 1 }} / {{ Math.ceil(total / limit) }}</span>
        <button @click="nextPage" :disabled="offset + limit >= total">Tiếp →</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'

const API_BASE = import.meta.env.VITE_API_URL || ''

const loading = ref(false)
const messages = ref([])
const stats = ref(null)
const total = ref(0)
const limit = ref(50)
const offset = ref(0)
const selectedPlatform = ref('all')
const selectedSentiment = ref('all')
const showTester = ref(false)
const testText = ref('')
const testResult = ref(null)

const platformIcon = (p) => ({ all: '🌐', facebook: '📘', instagram: '📸', tiktok: '🎵' }[p] || '💬')
const sentimentIcon = (s) => ({ all: '🔍', positive: '🟢', negative: '🔴', neutral: '⚪' }[s] || '⚪')

const platformCount = (p) => {
  if (!stats.value || p === 'all') return 0
  return stats.value.by_platform?.[p]?.total || 0
}

const formatTime = (iso) => {
  if (!iso) return ''
  const d = new Date(iso)
  return d.toLocaleString('vi-VN', { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit' })
}

const selectPlatform = (p) => { selectedPlatform.value = p; offset.value = 0; loadMessages() }
const selectSentiment = (s) => { selectedSentiment.value = s; offset.value = 0; loadMessages() }

const loadMessages = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams({ limit: limit.value, offset: offset.value })
    if (selectedPlatform.value !== 'all') params.append('platform', selectedPlatform.value)
    if (selectedSentiment.value !== 'all') params.append('sentiment', selectedSentiment.value)
    const res = await fetch(`${API_BASE}/api/social/messages?${params}`)
    const data = await res.json()
    messages.value = data.messages || []
    total.value = data.total || 0
  } catch (e) {
    console.error('Failed to load messages:', e)
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const res = await fetch(`${API_BASE}/api/social/messages/stats`)
    stats.value = await res.json()
  } catch (e) {
    console.error('Failed to load stats:', e)
  }
}

const loadData = async () => {
  await Promise.all([loadMessages(), loadStats()])
}

const testSentiment = async () => {
  if (!testText.value.trim()) return
  try {
    const res = await fetch(`${API_BASE}/api/social/messages/analyze`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text: testText.value }),
    })
    testResult.value = await res.json()
  } catch (e) {
    console.error('Sentiment test failed:', e)
  }
}

const prevPage = () => { offset.value = Math.max(0, offset.value - limit.value); loadMessages() }
const nextPage = () => { offset.value += limit.value; loadMessages() }

onMounted(loadData)
</script>

<style scoped>
.social-inbox-page { padding: 24px; max-width: 1200px; margin: 0 auto; font-family: 'Inter', sans-serif; }

.page-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px; }
.page-title { font-size: 1.8rem; font-weight: 700; color: #1a1a2e; margin: 0; }
.page-title .icon { margin-right: 8px; }
.page-subtitle { color: #666; margin: 4px 0 0; font-size: 0.9rem; }

.btn-refresh { background: #4f46e5; color: white; border: none; padding: 8px 16px; border-radius: 8px; cursor: pointer; font-size: 0.9rem; transition: all 0.2s; }
.btn-refresh:hover { background: #4338ca; transform: translateY(-1px); }
.btn-refresh:disabled { opacity: 0.6; cursor: not-allowed; }

/* Stats */
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; margin-bottom: 24px; }
.stat-card { background: white; border-radius: 12px; padding: 16px; display: flex; gap: 12px; align-items: center; box-shadow: 0 2px 8px rgba(0,0,0,0.08); border-left: 4px solid #e5e7eb; }
.stat-card.positive { border-color: #22c55e; }
.stat-card.negative { border-color: #ef4444; }
.stat-card.neutral { border-color: #9ca3af; }
.stat-card.total { border-color: #6366f1; }
.stat-card.rate { border-color: #f59e0b; }
.stat-card.rate.danger { border-color: #ef4444; background: #fef2f2; }
.stat-icon { font-size: 1.5rem; }
.stat-value { font-size: 1.6rem; font-weight: 700; color: #1a1a2e; }
.stat-label { font-size: 0.75rem; color: #888; }

/* Filters */
.filter-bar { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; margin-bottom: 20px; background: white; padding: 12px 16px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
.filter-tabs, .sentiment-tabs { display: flex; gap: 6px; }
.filter-tab, .sentiment-tab { padding: 6px 14px; border-radius: 20px; border: 1px solid #e5e7eb; background: white; cursor: pointer; font-size: 0.85rem; transition: all 0.2s; display: flex; align-items: center; gap: 6px; }
.filter-tab:hover, .sentiment-tab:hover { background: #f5f5f5; }
.filter-tab.active { background: #4f46e5; color: white; border-color: #4f46e5; }
.sentiment-tab.positive.active { background: #22c55e; color: white; border-color: #22c55e; }
.sentiment-tab.negative.active { background: #ef4444; color: white; border-color: #ef4444; }
.sentiment-tab.neutral.active { background: #9ca3af; color: white; border-color: #9ca3af; }
.sentiment-tab.all.active { background: #4f46e5; color: white; border-color: #4f46e5; }
.badge { background: #ef4444; color: white; border-radius: 10px; padding: 1px 7px; font-size: 0.75rem; }

/* Sentiment Tester */
.sentiment-tester { background: white; border-radius: 12px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); overflow: hidden; }
.tester-header { padding: 12px 16px; cursor: pointer; display: flex; justify-content: space-between; font-weight: 600; font-size: 0.9rem; color: #4f46e5; background: #f0f0ff; }
.tester-body { padding: 16px; display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-start; }
.tester-input { flex: 1; min-width: 200px; border: 1px solid #e5e7eb; border-radius: 8px; padding: 10px; font-size: 0.9rem; resize: vertical; }
.btn-analyze { background: #6366f1; color: white; border: none; padding: 10px 18px; border-radius: 8px; cursor: pointer; white-space: nowrap; }
.tester-result { width: 100%; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 10px; background: #f9fafb; border-radius: 8px; }
.result-label { font-weight: 700; padding: 4px 12px; border-radius: 20px; font-size: 0.9rem; }
.result-label.positive { background: #dcfce7; color: #16a34a; }
.result-label.negative { background: #fee2e2; color: #dc2626; }
.result-label.neutral { background: #f3f4f6; color: #6b7280; }
.result-score { font-size: 0.85rem; color: #666; }
.result-keywords { font-size: 0.82rem; color: #555; }
.result-keywords.neg { color: #dc2626; }

/* Messages */
.messages-section { margin-top: 8px; }
.messages-list { display: flex; flex-direction: column; gap: 12px; }
.message-card { background: white; border-radius: 12px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); border-left: 4px solid #e5e7eb; transition: transform 0.15s; }
.message-card:hover { transform: translateY(-2px); box-shadow: 0 4px 16px rgba(0,0,0,0.1); }
.message-card.positive { border-color: #22c55e; }
.message-card.negative { border-color: #ef4444; }
.message-card.neutral { border-color: #d1d5db; }

.message-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; flex-wrap: wrap; gap: 8px; }
.sender-info { display: flex; align-items: center; gap: 8px; }
.platform-badge { font-size: 0.78rem; padding: 2px 10px; border-radius: 12px; font-weight: 600; }
.platform-badge.facebook { background: #e7f0fd; color: #1877f2; }
.platform-badge.instagram { background: #fde7f5; color: #e1306c; }
.platform-badge.tiktok { background: #e7faf5; color: #00c4cc; }
.message-type-badge { font-size: 0.75rem; background: #f3f4f6; padding: 2px 8px; border-radius: 10px; color: #666; }
.sender-name { font-weight: 600; font-size: 0.9rem; }
.message-meta { display: flex; align-items: center; gap: 8px; }
.sentiment-badge { font-size: 0.78rem; padding: 2px 10px; border-radius: 12px; font-weight: 600; }
.sentiment-badge.positive { background: #dcfce7; color: #16a34a; }
.sentiment-badge.negative { background: #fee2e2; color: #dc2626; }
.sentiment-badge.neutral { background: #f3f4f6; color: #6b7280; }
.time { font-size: 0.78rem; color: #aaa; }
.message-body { font-size: 0.95rem; color: #333; line-height: 1.5; }
.post-id { font-size: 0.75rem; color: #bbb; margin-top: 6px; }

/* Empty / Loading */
.empty-state, .loading-state { text-align: center; padding: 60px 20px; color: #888; }
.empty-icon { font-size: 3rem; margin-bottom: 12px; }
.empty-hint { font-size: 0.85rem; color: #aaa; }
.spinner { width: 36px; height: 36px; border: 3px solid #e5e7eb; border-top-color: #6366f1; border-radius: 50%; animation: spin 0.8s linear infinite; margin: 0 auto 12px; }
@keyframes spin { to { transform: rotate(360deg); } }

/* Pagination */
.pagination { display: flex; justify-content: center; align-items: center; gap: 16px; margin-top: 20px; }
.pagination button { padding: 8px 20px; border-radius: 8px; border: 1px solid #e5e7eb; background: white; cursor: pointer; }
.pagination button:disabled { opacity: 0.4; cursor: not-allowed; }
</style>
