<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(false) // Start hidden, wait for trigger

onMounted(() => {
  // Listen for toggle messages directly in the component
  chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'TOGGLE_SIDEBAR') {
      isVisible.value = !isVisible.value
    } else if (message.type === 'SHOW_INSIGHT') {
      isVisible.value = true
    }
  })

  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: '<path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/>'
      }))
      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.' }]
      }
    })
  })
}

const showProfileTip = ref(false)

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

  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)
      }
    }
  });
}
</script>

<template>
  <transition
    enter-active-class="transition duration-500 ease-out transform"
    enter-from-class="translate-x-full opacity-0 scale-95"
    enter-to-class="translate-x-0 opacity-100 scale-100"
    leave-active-class="transition duration-400 ease-in transform"
    leave-from-class="translate-x-0 opacity-100 scale-100"
    leave-to-class="translate-x-full opacity-0 scale-95"
  >
    <div v-if="isVisible" class="fixed right-6 top-1/2 -translate-y-1/2 w-[380px] max-h-[90vh] flex flex-col glass-card rounded-[24px] shadow-[0_32px_64px_rgba(0,0,0,0.5)] text-[#f8fafc] font-sans z-[2147483647] overflow-hidden border border-white/5 selection:bg-rose-500/30">
      
      <!-- Premium Header -->
      <div class="px-6 py-5 flex justify-between items-center bg-white/[0.02] border-b border-white/5">
        <div class="flex items-center gap-3">
          <div class="p-2 rounded-lg bg-rose-500/10 border border-rose-500/20">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" class="text-rose-500"><path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/></svg>
          </div>
          <div>
            <span class="text-sm font-bold tracking-tight block">InsightReply</span>
            <span class="text-[9px] text-zinc-500 uppercase tracking-[0.2em] font-bold">Spatial Copilot</span>
          </div>
        </div>
        <button @click="isVisible = false" class="p-2 rounded-full hover:bg-white/10 transition-apple group">
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-zinc-500 group-hover:text-white transition-apple"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>
      </div>

    <!-- Content -->
    <div class="p-6 flex-1 overflow-y-auto space-y-8 custom-scrollbar">
      
      <!-- Context Module -->
      <div v-if="tweetData" class="space-y-3">
        <h3 class="text-[10px] font-bold text-zinc-500 uppercase tracking-widest flex items-center gap-2 px-1">
          <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" class="text-rose-500"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
          Current Tweet
        </h3>
        <div class="bg-black/20 rounded-2xl p-4 border border-white/[0.03] relative group">
          <div class="text-[13px] text-zinc-400 leading-relaxed font-medium italic">
            "{{ tweetData.content }}"
          </div>
        </div>
      </div>

      <!-- Strategy Grid -->
      <div class="space-y-4">
        <h3 class="text-[10px] font-bold text-zinc-500 uppercase tracking-widest flex items-center gap-2 px-1">
          <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" class="text-rose-500"><path d="m16 4 4 4-4 4"/><path d="M20 8H4v12"/></svg>
          Generation Strategy
        </h3>
        <div class="grid grid-cols-1 gap-2.5">
          <button 
            v-for="s in strategies" 
            :key="s.id"
            @click="selectedStrategy = s.id"
            :class="[
              'flex items-center gap-4 p-4 rounded-2xl border transition-apple group text-sm font-semibold active:scale-[0.98]',
              selectedStrategy === s.id 
                ? 'bg-rose-500/10 border-rose-500/30 text-rose-50 text-white shadow-[0_8px_16px_rgba(136,19,55,0.15)]' 
                : 'bg-white/[0.02] border-white/5 hover:bg-white/[0.05] text-zinc-400'
            ]"
          >
            <div :class="['p-2 rounded-lg transition-apple', selectedStrategy === s.id ? 'bg-rose-500/20 text-rose-400' : 'bg-black/20 text-zinc-500 group-hover:text-zinc-300']">
              <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" v-html="s.icon"></svg>
            </div>
            <span class="flex-1 text-left tracking-tight">{{ s.label }}</span>
            <div v-if="selectedStrategy === s.id" class="w-2 h-2 rounded-full bg-rose-500 shadow-[0_0_8px_#f43f5e]"></div>
          </button>
        </div>
      </div>

      <!-- Result Module -->
      <div v-if="generatedReplies.length > 0" class="space-y-4 animate-in fade-in slide-in-from-bottom-4 duration-700">
        <h3 class="text-[10px] font-bold text-zinc-500 uppercase tracking-widest px-1">AI Suggestions</h3>
        
        <div v-for="(reply, idx) in generatedReplies" :key="idx" class="bg-white/[0.03] rounded-2xl p-5 border border-white/5 space-y-4 relative group hover:border-rose-500/20 transition-apple">
          <div class="flex justify-between items-center">
            <span class="text-[9px] font-bold text-rose-400 bg-rose-400/10 px-2.5 py-1 rounded-full uppercase tracking-widest">
              {{ reply.strategy || 'Insight' }}
            </span>
            <button @click="copyToClipboard(reply)" class="opacity-0 group-hover:opacity-100 transition-apple text-[10px] font-bold text-zinc-500 hover:text-white flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-white/5">
              <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>
              COPY
            </button>
          </div>
          <div class="text-[13px] leading-relaxed whitespace-pre-wrap text-zinc-200 font-medium tracking-tight">
            {{ reply.content }}
          </div>
        </div>
      </div>

    </div>

    <!-- Sticky Action Footer -->
    <div class="p-6 bg-white/[0.02] border-t border-white/5 space-y-4 shadow-[0_-12px_24px_rgba(0,0,0,0.2)]">
      <transition enter-active-class="transition duration-500 transform ease-out" enter-from-class="opacity-0 translate-y-4" enter-to-class="opacity-100 translate-y-0" leave-active-class="transition duration-300 transform ease-in" leave-from-class="opacity-100 translate-y-0" leave-to-class="opacity-0 translate-y-4">
        <div v-if="showProfileTip" class="bg-rose-500/10 border border-rose-500/20 text-rose-400 text-[11px] p-4 rounded-2xl flex gap-3 items-start relative font-medium leading-relaxed">
          <span class="text-base leading-none">✨</span>
          <p><strong>Optimize Conversion:</strong> Make sure your X Bio prominently features your product link!</p>
          <button @click="showProfileTip = false" class="absolute top-3 right-3 opacity-50 hover:opacity-100">✕</button>
        </div>
      </transition>

      <button 
        @click="generate"
        :disabled="isGenerating"
        class="w-full py-4 bg-gradient-to-br from-rose-600 to-rose-500 hover:from-rose-500 hover:to-rose-400 disabled:from-zinc-900 disabled:to-zinc-900 disabled:text-zinc-600 disabled:cursor-not-allowed text-white rounded-[20px] text-[15px] font-bold transition-all shadow-[0_12px_24px_rgba(136,19,55,0.25)] flex items-center justify-center gap-3 active:scale-[0.97]"
      >
        <div v-if="isGenerating" class="w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin"></div>
        <svg v-else xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-rose-100"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>
        {{ isGenerating ? 'AI Thinking...' : 'Generate Pro Reply' }}
      </button>
    </div>

  </div>
</template>

<style scoped>
.custom-scrollbar::-webkit-scrollbar {
  width: 4px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
}
.custom-scrollbar:hover::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
}
</style>
