'use client'

import { useQuery } from '@tanstack/react-query'
import { Zap, ArrowUpRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useLanguage } from '@/lib/i18n'
import Link from 'next/link'

interface QuotaData { remaining: number; limit: number; used: number }
interface UsageData { quotas: Record<string, QuotaData>; tier: string }

export function StarterPackBadge() {
  const { t } = useLanguage()

  const { data } = useQuery<UsageData>({
    queryKey: ['usage', 'current'],
    queryFn: async () => {
      const res = await fetch('/api/usage/current')
      if (!res.ok) throw new Error('Failed')
      return res.json()
    },
    staleTime: 5000,
  })

  if (!data) return null
  // Paid tiers do not need the badge; only BASIC (free) users see it
  const PAID_TIERS = ['PRO', 'BUSINESS', 'ENTERPRISE']
  if (PAID_TIERS.includes(data.tier)) return null

  const semanticQuota = data.quotas?.['semantic_search']
  if (!semanticQuota) return null

  const remaining = semanticQuota.remaining ?? 0
  const isCritical = remaining === 0
  const isWarning = remaining > 0 && remaining < 5

  return (
    <Link
      href="/pricing"
      className={cn(
        'flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-medium transition-colors',
        isCritical
          ? 'bg-destructive/10 text-destructive hover:bg-destructive/20'
          : isWarning
            ? 'bg-orange-500/10 text-orange-500 hover:bg-orange-500/20'
            : 'bg-muted text-muted-foreground hover:text-foreground hover:bg-muted/80'
      )}
    >
      <Zap className={cn('h-3.5 w-3.5', isWarning || isCritical ? 'animate-pulse' : '')} />
      <span>
        {isCritical
          ? t('onboarding.badge_upgrade')
          : t('onboarding.badge_credits', { count: remaining })
        }
      </span>
      {isCritical && <ArrowUpRight className="h-3 w-3 ml-auto" />}
    </Link>
  )
}
