<script setup lang="ts">
import { ref, onMounted } from 'vue'

const props = defineProps<{
  tweetData?: {
    id: string;
    author: string;
    content: string;
    stats: {
      replies: string;
      retweets: string;
      likes: string;
    }
  }
}>()

const isVisible = ref(true)
const selectedStrategy = ref('Insightful')
const generatedReplies = ref<Array<{strategy: string, content: string}>>([])
const isGenerating = ref(false)

const defaultStrategies = [
  { id: 'Insightful', label: '认知升级型', icon: '🧠' },
  { id: 'Humorous', label: '幽默风趣型', icon: '😄' },
  { id: 'Professional', label: '专业严谨型', icon: '⚖️' },
  { id: 'Supportive', label: '共鸣支持型', icon: '❤️' },
  { id: 'Critical', label: '锐评批判型', icon: '🔥' },
  { id: 'Quote', label: '引用转发型', icon: '💬' }
]

const strategies = ref([...defaultStrategies])

onMounted(() => {
  chrome.runtime.sendMessage({ type: 'FETCH_CUSTOM_STRATEGIES' }, (response) => {
    if (response && response.success && response.data) {
      const customStrategies = response.data.map((s: any) => ({
        id: s.strategy_key,
        label: s.label,
        icon: '✨'
      }))
      strategies.value = [...defaultStrategies, ...customStrategies]
    }
  })
})

const generate = () => {
  if (!props.tweetData) return
  
  isGenerating.value = true
  generatedReplies.value = []
  
  chrome.storage.sync.get(['identity', 'language'], (res) => {
    let finalIdentity = res.identity ? String(res.identity) : 'Independent Developer / Founder'
    if (res.language && res.language !== 'auto') {
      const langStr = String(res.language)
      const langMap: Record<string, string> = { 'zh': 'Chinese (Simplified)', 'en': 'English' }
      finalIdentity += ` (CRITICAL: You MUST reply in ${langMap[langStr] || langStr})`
    }

    chrome.runtime.sendMessage({
      type: 'GENERATE_REPLY',
      payload: {
        tweetContent: props.tweetData!.content,
        strategy: selectedStrategy.value,
        identity: finalIdentity
      }
    }, (response) => {
      isGenerating.value = false
      if (response && response.success) {
        generatedReplies.value = response.data.replies || []
      } else if (response && response.error === 'unauthorized') {
        generatedReplies.value = [{ strategy: 'Auth Required', content: 'Connection required. Please log in first.' }]
        chrome.runtime.openOptionsPage()
      } else {
        generatedReplies.value = [{ strategy: 'Error', content: response?.error || 'Failed to generate reply. Please check your connection or API key.' }]
      }
    })
  })
}

const showProfileTip = ref(false)

const copyToClipboard = async (reply: any) => {
  navigator.clipboard.writeText(reply.content)
  showProfileTip.value = true
  setTimeout(() => { showProfileTip.value = false }, 7000)

  // Epic 13: Record generated reply for performance tracking telemetry
  if (!props.tweetData || !props.tweetData.id) return;

  chrome.storage.local.get(['jwt_token'], async (result) => {
    if (result.jwt_token) {
      try {
        const apiBase = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1'
        const token = result.jwt_token;
        await fetch(`${apiBase}/replies/record`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            tweet_id: props.tweetData?.id,
            strategy_type: reply.strategy || 'General',
            content: reply.content,
            language: 'en'
          })
        });
      } catch (err) {
        console.error('Failed to log telemetry:', err) // Non blocking telemetry
      }
    }
  });
}
</script>

<template>
  <div v-if="isVisible" class="fixed right-4 top-20 w-[360px] max-h-[85vh] flex flex-col bg-[#0A0A0A]/90 backdrop-blur-2xl border border-white/10 rounded-2xl shadow-2xl text-[#E5E5E5] font-sans z-[9999] overflow-hidden">
    
    <!-- Header -->
    <div class="p-4 border-b border-white/5 flex justify-between items-center bg-white/5">
      <div class="flex items-center gap-2">
        <div class="w-2 h-2 rounded-full bg-brand-primary animate-pulse"></div>
        <span class="text-sm font-medium tracking-wide">InsightReply AI</span>
      </div>
      <button @click="isVisible = false" class="text-zinc-500 hover:text-white transition-colors">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
      </button>
    </div>

    <!-- Content -->
    <div class="p-5 flex-1 overflow-y-auto space-y-6">
      
      <!-- Tweet Context (Small Preview) -->
      <div v-if="tweetData" class="bg-white/5 rounded-xl p-3 border border-white/5">
        <div class="text-[10px] text-zinc-500 mb-1 font-mono uppercase">Context</div>
        <div class="text-xs text-zinc-400 line-clamp-2 italic">" {{ tweetData.content }} "</div>
      </div>

      <!-- Strategy Selector -->
      <div class="space-y-3">
        <span class="text-xs font-semibold text-zinc-500 uppercase tracking-widest">Generation Strategy</span>
        <div class="grid grid-cols-1 gap-2">
          <button 
            v-for="s in strategies" 
            :key="s.id"
            @click="selectedStrategy = s.id"
            :class="[
              'flex items-center gap-3 p-3 rounded-xl border transition-all duration-200 text-sm group',
              selectedStrategy === s.id 
                ? 'bg-brand-primary/20 border-brand-primary text-white shadow-lg shadow-brand-primary/10' 
                : 'bg-white/5 border-transparent hover:bg-white/10 text-zinc-400'
            ]"
          >
            <span class="text-lg">{{ s.icon }}</span>
            <span class="flex-1 text-left">{{ s.label }}</span>
            <div v-if="selectedStrategy === s.id" class="w-1.5 h-1.5 rounded-full bg-brand-primary"></div>
          </button>
        </div>
      </div>

      <!-- Result Area -->
      <div v-if="generatedReplies.length > 0" class="space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-500">
        <div class="flex justify-between items-center">
          <span class="text-xs font-semibold text-zinc-500 uppercase tracking-widest">Assistant Suggestions</span>
        </div>
        
        <div v-for="(reply, idx) in generatedReplies" :key="idx" class="bg-[#171717] rounded-xl p-4 border border-white/10 space-y-3 relative group transition-all hover:bg-[#202020] hover:border-white/20">
          <div class="flex justify-between items-center">
            <span class="text-xs font-medium text-brand-primary bg-brand-primary/10 px-2 py-0.5 rounded-full">
              {{ reply.strategy || 'Suggestion' }}
            </span>
            <button @click="copyToClipboard(reply)" class="opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-zinc-400 hover:text-white flex items-center gap-1 cursor-pointer">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
              Copy
            </button>
          </div>
          <div class="text-sm leading-relaxed whitespace-pre-wrap text-[#E5E5E5]">
            {{ reply.content }}
          </div>
        </div>

      </div>

    </div>

    <!-- Footer Action -->
    <div class="p-4 bg-white/5 border-t border-white/5 flex flex-col gap-3">
      <transition enter-active-class="transition ease-out duration-300 transform" enter-from-class="opacity-0 translate-y-2" enter-to-class="opacity-100 translate-y-0" leave-active-class="transition ease-in duration-200 transform" leave-from-class="opacity-100 translate-y-0" leave-to-class="opacity-0 translate-y-2">
        <div v-if="showProfileTip" class="bg-blue-500/10 border border-blue-500/20 text-blue-400 text-[11px] p-2.5 rounded-lg flex gap-2 items-start relative pr-6">
          <span class="text-sm leading-none">💡</span>
          <p class="leading-relaxed"><strong>Optimze your conversion:</strong> Ensure your X Bio and Pinned Tweet clearly mention your product/link!</p>
          <button @click="showProfileTip = false" class="absolute top-2 right-2 text-blue-400/50 hover:text-blue-400">✕</button>
        </div>
      </transition>

      <button 
        @click="generate"
        :disabled="isGenerating"
        class="w-full py-3 bg-gradient-to-r from-violet-600 to-blue-600 hover:from-violet-500 hover:to-blue-500 disabled:from-zinc-800 disabled:to-zinc-800 disabled:text-zinc-500 disabled:cursor-not-allowed text-white rounded-xl text-sm font-semibold transition-all shadow-xl shadow-brand-primary/20 flex items-center justify-center gap-2"
      >
        <div v-if="isGenerating" class="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin"></div>
        {{ isGenerating ? 'AI Thinking...' : 'Generate High-Quality Reply' }}
      </button>
    </div>

  </div>
</template>

<style scoped>
/* 局部样式保证不溢出 */
::-webkit-scrollbar {
  width: 4px;
}
::-webkit-scrollbar-track {
  background: transparent;
}
::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.2);
}
</style>
