<template>
  <div class="h-full flex flex-col p-6 space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h2 class="text-2xl font-bold text-white tracking-tight flex items-center gap-2">
          🔥 Hot Opportunities
        </h2>
        <p class="text-zinc-400 mt-1">High-potential threads bubbling up from your monitoring radar</p>
      </div>
      
      <button 
        @click="loadHotTweets" 
        class="p-2 bg-white/5 border border-white/10 rounded-lg hover:bg-white/10 transition-colors"
        title="Refresh data"
      >
        <svg v-if="loading" class="w-5 h-5 text-white animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
        <span v-else>↻</span>
      </button>
    </div>

    <!-- Error State -->
    <div v-if="error" class="bg-red-500/10 border border-red-500/20 text-red-400 p-4 rounded-xl flex items-start gap-3">
      <span>⚠️</span>
      <p class="text-sm font-medium">{{ error }}</p>
    </div>

    <!-- Empty State -->
    <div v-else-if="!loading && tweets.length === 0" class="flex-1 flex flex-col items-center justify-center text-center p-8 bg-white/5 border border-white/10 rounded-2xl border-dashed">
      <div class="w-16 h-16 bg-white/5 rounded-full flex items-center justify-center mb-4">
        <span class="text-2xl opacity-50">🔭</span>
      </div>
      <h3 class="text-white font-medium mb-2">No hot tweets found</h3>
      <p class="text-sm text-zinc-400 max-w-sm">
        The scraper is running in the background. It takes some time and activity to build momentum heat scores. Check back later!
      </p>
    </div>

    <!-- List -->
    <div v-else class="grid gap-4 md:grid-cols-2">
      <div v-for="tweet in tweets" :key="tweet.id" class="p-5 bg-white/5 border border-white/10 hover:border-white/20 hover:bg-white/[0.07] transition-all rounded-xl relative group flex flex-col justify-between">
        
        <!-- Header -->
        <div class="flex justify-between items-start mb-3">
          <div class="flex flex-col">
            <span class="font-bold text-white tracking-wide">@{{ tweet.author_handle }}</span>
            <span class="text-[11px] text-zinc-500 font-mono">{{ new Date(tweet.posted_at).toLocaleString() }}</span>
          </div>
          <div class="flex items-center gap-1.5 bg-rose-500/10 text-rose-400 border border-rose-500/20 px-2 py-1 rounded text-xs font-bold font-mono">
            <span>🔥</span> {{ tweet.heat_score }}
          </div>
        </div>

        <!-- Body -->
        <p class="text-zinc-300 text-sm leading-relaxed mb-4 line-clamp-4">
          {{ tweet.content }}
        </p>

        <!-- Footer -->
        <div class="mt-auto flex items-center justify-between border-t border-white/5 pt-3">
          <div class="flex gap-4 text-xs text-zinc-400 font-mono">
            <span title="Replies">💬 {{ tweet.reply_count }}</span>
            <span title="Retweets">🔁 {{ tweet.retweet_count }}</span>
            <span title="Likes">❤️ {{ tweet.like_count }}</span>
          </div>
          
          <button 
            @click="openTweet(tweet.author_handle, tweet.x_tweet_id)"
            class="px-3 py-1.5 bg-blue-600 hover:bg-blue-500 text-white text-xs font-medium rounded-md transition-colors"
          >
            Reply on X ↗
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

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

const props = defineProps<{
  token: string
}>()

interface Tweet {
  id: string
  x_tweet_id: string
  author_handle: string
  content: string
  posted_at: string
  like_count: number
  retweet_count: number
  reply_count: number
  heat_score: number
}

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1'

const tweets = ref<Tweet[]>([])
const loading = ref(false)
const error = ref('')

const loadHotTweets = async () => {
  if (!props.token) {
    error.value = 'Unauthenticated. Please login.'
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    const response = await fetch(`${API_BASE}/tweets/hot`, {
      headers: {
        'Authorization': `Bearer ${props.token}`
      }
    })
    
    if (!response.ok) {
        throw new Error(`Failed to load hot opportunities (${response.status})`)
    }
    
    const data = await response.json()
    tweets.value = data || []
  } catch (err: any) {
    error.value = err.message || 'Network error while fetching tweets.'
  } finally {
    loading.value = false
  }
}

const openTweet = (handle: string, tweetId: string) => {
  // Construct the active twitter URL to trigger the context script sidebar there
  const url = `https://twitter.com/${handle}/status/${tweetId}`
  chrome.tabs.create({ url })
}

onMounted(() => {
  loadHotTweets()
})
</script>
