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

const router = useRouter()

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(true)
const error = ref('')

const loadHotTweets = async () => {
  const token = localStorage.getItem('jwt_token')
  if (!token) {
    router.push('/login')
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    const response = await fetch(`${API_BASE}/tweets/hot`, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (response.status === 401) {
      localStorage.removeItem('jwt_token')
      router.push('/login')
      return
    }
    
    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) => {
  window.open(`https://twitter.com/${handle}/status/${tweetId}`, '_blank')
}

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

<template>
  <div class="max-w-[1400px] mx-auto space-y-8 animate-fade-in-up">
    <!-- Header -->
    <header class="flex justify-between items-end pb-4 border-b border-white/5">
      <div>
        <h1 class="text-3xl font-bold tracking-tight text-white flex items-center gap-3">
          🔥 Pipeline
          <span class="text-sm font-medium px-2.5 py-1 bg-brand-primary/20 text-brand-primary rounded-full">{{ tweets.length }} leads</span>
        </h1>
        <p class="text-zinc-500 mt-2">Prioritized X threads bubbling up from your monitoring radar.</p>
      </div>
      
      <button 
        @click="loadHotTweets" 
        class="px-4 py-2 bg-white/5 border border-white/10 text-white rounded-lg hover:bg-white/10 transition-colors flex items-center gap-2"
      >
        <span v-if="loading" class="animate-spin inline-block">↻</span>
        <span v-else>↻ Refresh</span>
      </button>
    </header>

    <!-- 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-12 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-xl text-white font-medium mb-2">No hot tweets found</h3>
      <p class="text-sm text-zinc-400 max-w-sm">
        The scraper is building radar momentum. Check back later to see rising opportunities.
      </p>
    </div>

    <!-- Pinterest Style Grid -->
    <div v-else class="columns-1 md:columns-2 lg:columns-3 xl:columns-4 gap-6 space-y-6">
      <div 
        v-for="tweet in tweets" 
        :key="tweet.id" 
        class="break-inside-avoid glass-panel p-5 relative group flex flex-col transition-all duration-300 hover:border-brand-primary/50 hover:shadow-[0_10px_40px_rgba(59,130,246,0.1)] hover:-translate-y-1"
      >
        <!-- Header -->
        <div class="flex justify-between items-start mb-4">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 rounded-full bg-gradient-to-br from-zinc-700 to-zinc-800 flex items-center justify-center font-bold text-white shadow-inner">
              {{ tweet.author_handle.charAt(0).toUpperCase() }}
            </div>
            <div class="flex flex-col">
              <span class="font-bold text-white tracking-wide text-sm">@{{ tweet.author_handle }}</span>
              <span class="text-[11px] text-zinc-500 font-mono">{{ new Date(tweet.posted_at).toLocaleDateString() }}</span>
            </div>
          </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-full text-xs font-bold font-mono shadow-sm">
            <span>🔥</span> {{ tweet.heat_score }}
          </div>
        </div>

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

        <!-- Footer -->
        <div class="mt-auto flex items-center justify-between border-t border-white/5 pt-4">
          <div class="flex gap-4 text-xs text-zinc-400 font-mono">
            <span title="Replies" class="flex items-center gap-1"><span class="opacity-50">💬</span> {{ tweet.reply_count }}</span>
            <span title="Retweets" class="flex items-center gap-1"><span class="opacity-50">🔁</span> {{ tweet.retweet_count }}</span>
            <span title="Likes" class="flex items-center gap-1"><span class="opacity-50">❤️</span> {{ tweet.like_count }}</span>
          </div>
          
          <button 
            @click="openTweet(tweet.author_handle, tweet.x_tweet_id)"
            class="px-4 py-1.5 bg-white/5 hover:bg-brand-primary text-white text-xs font-medium rounded-lg transition-all duration-300 border border-white/10 hover:border-transparent hover:shadow-lg hover:shadow-brand-primary/20"
          >
            Reply ↗
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
