/**
 * BoostMedia AI Content Generator Admin - Usage & Costs Page
 *
 * Adapted from BoostBot's UsageDashboard for the BoostContent plugin.
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import {
  Sparkles,
  ShoppingCart,
  RefreshCw,
  Gift,
  CheckCircle,
  PartyPopper,
  Calendar,
  Zap,
} from 'lucide-react'
import { Header } from '../components/layout/Header'
import { Card, CardContent, Button, Badge, HelpTooltip } from '../components/common'
import { useCreditsStatus, usePricingCatalog, useCreateSubscription, useCancelSubscription } from '../hooks/useCredits'
import type { PricingPackage, PricingSubscription } from '../hooks/useCredits'
import { endpoints, getErrorMessage } from '../api/client'
import type { AffiliatePurchasePayload } from '../api/client'
import { SetupBanner } from '../components/onboarding/SetupBanner'
import { t, tf, getDateLocale } from '../lib/i18n'

const AFFILIATE_PENDING_SUBSCRIPTION_KEY = 'bmai_pending_affiliate_subscription'

interface PayPalApproveData {
  orderID?: string
}

interface PayPalButtonsInstance {
  render: (host: HTMLElement) => Promise<void>
}

interface PayPalNamespace {
  Buttons: (config: {
    onInit?: () => void
    style?: Record<string, string | number>
    createOrder?: () => Promise<string>
    onApprove?: (data: PayPalApproveData) => Promise<void>
    onCancel?: () => void
    onError?: (error: unknown) => void
  }) => PayPalButtonsInstance
}

function getPaypalWindow(): Window & { paypal?: PayPalNamespace } {
  return window as Window & { paypal?: PayPalNamespace }
}

function errorMessage(error: unknown, fallback: string): string {
  return getErrorMessage(error, fallback)
}

function currencySymbol(c?: string) {
  if (!c) return ''
  const u = c.toUpperCase()
  return u === 'ILS' ? '₪' : u === 'USD' ? '$' : `${u} `
}

function fmtPrice(amount: number, currency?: string) {
  return (currency || '').toUpperCase() === 'ILS'
    ? String(Math.round(amount))
    : amount.toFixed(2)
}

function discountPct(ppu: number, basePpu: number) {
  if (basePpu <= 0 || ppu >= basePpu) return 0
  return Math.round((1 - ppu / basePpu) * 100)
}

function loadPayPalSdk(clientId: string, currency: string): Promise<void> {
  return new Promise((resolve, reject) => {
    if (getPaypalWindow().paypal) { resolve(); return }
    const existing = document.getElementById('bc-paypal-sdk') as HTMLScriptElement | null
    if (existing) {
      existing.addEventListener('load', () => resolve(), { once: true })
      existing.addEventListener('error', () => reject(new Error('Failed to load PayPal SDK.')), { once: true })
      return
    }
    const paypalLocale = getDateLocale() === 'he-IL' ? 'he_IL' : 'en_US'
    const script = document.createElement('script')
    script.id = 'bc-paypal-sdk'
    script.src = `https://www.paypal.com/sdk/js?client-id=${encodeURIComponent(clientId)}&currency=${encodeURIComponent(currency)}&locale=${paypalLocale}&intent=capture`
    script.async = true
    script.onload = () => resolve()
    script.onerror = () => reject(new Error('Failed to load PayPal SDK.'))
    document.head.appendChild(script)
  })
}

/* ── Confetti Celebration ── */
const CONFETTI_COLORS = ['#10b981', '#06b6d4', '#6366f1', '#f59e0b', '#ec4899', '#8b5cf6', '#14b8a6']

function ConfettiCelebration({ active }: { active: boolean }) {
  const particles = useMemo(() =>
    Array.from({ length: 50 }, (_, i) => ({
      id: i,
      color: CONFETTI_COLORS[i % CONFETTI_COLORS.length],
      left: Math.random() * 100,
      delay: Math.random() * 1.2,
      duration: 2.5 + Math.random() * 2,
      size: 6 + Math.random() * 8,
      heightRatio: 0.4 + Math.random() * 0.6,
      rotate: Math.random() * 360,
      drift: (Math.random() - 0.5) * 120,
    })), [])

  if (!active) return null
  return (
    <div className="fixed inset-0 pointer-events-none z-[99999] overflow-hidden">
      {particles.map((p) => (
        <span key={p.id} className="absolute top-0 rounded-sm" style={{
          left: `${p.left}%`, width: p.size, height: p.size * p.heightRatio,
          backgroundColor: p.color, transform: `rotate(${p.rotate}deg)`,
          animation: `bc-confetti-fall ${p.duration}s ease-in ${p.delay}s forwards`,
          ['--drift' as string]: `${p.drift}px`,
        }} />
      ))}
      <style>{`@keyframes bc-confetti-fall { 0% { opacity:1; transform:translateY(-20px) translateX(0) rotate(0deg) scale(1); } 50% { opacity:1; } 100% { opacity:0; transform:translateY(100vh) translateX(var(--drift,0px)) rotate(720deg) scale(0.5); } }`}</style>
    </div>
  )
}

function PurchaseSuccessOverlay({ show, credits, onClose }: { show: boolean; credits: number; onClose: () => void }) {
  const onCloseRef = useRef(onClose)
  onCloseRef.current = onClose

  useEffect(() => {
    if (!show) return
    const timer = setTimeout(() => onCloseRef.current(), 6000)
    return () => clearTimeout(timer)
  }, [show])
  if (!show) return null
  return (
    <div className="fixed inset-0 z-[99998] flex items-center justify-center bg-black/30 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl p-8 max-w-sm mx-4 text-center animate-[bc-pop-in_0.4s_ease-out]" onClick={(e) => e.stopPropagation()}>
        <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-emerald-50 mb-4">
          <CheckCircle className="w-12 h-12 text-emerald-500" strokeWidth={1.5} />
        </div>
        <h3 className="text-2xl font-bold text-gray-900 mb-2 flex items-center justify-center gap-2">
          <PartyPopper className="w-6 h-6 text-amber-500" />
          {t('Purchase completed successfully!')}
          <PartyPopper className="w-6 h-6 text-amber-500" style={{ transform: 'scaleX(-1)' }} />
        </h3>
        <p className="text-gray-500 mb-1">
          <span className="text-emerald-600 font-bold text-lg">{credits.toLocaleString()}</span> {t('BoostCoin added to your account')}
        </p>
        <p className="text-sm text-gray-400 mb-5">{t('Invoice will be sent to your email from PayPal.')}</p>
        <Button variant="primary" onClick={onClose}>{t('Close')}</Button>
      </div>
      <style>{`@keyframes bc-pop-in { 0% { opacity:0; transform:scale(0.7) translateY(30px); } 60% { transform:scale(1.05) translateY(-5px); } 100% { opacity:1; transform:scale(1) translateY(0); } }`}</style>
    </div>
  )
}

/* ── Credit Slider ── */
function CreditSlider({ items, selectedIndex, onSelect }: {
  items: { id: string; label: string }[]
  selectedIndex: number
  onSelect: (i: number) => void
}) {
  if (items.length <= 1) return null
  return (
    <div className="py-4">
      <div className="text-xs text-bc-gray-400 text-center mb-2">{t('Choose BoostCoin amount')}</div>
      <div className="flex items-stretch bg-bc-gray-100 rounded-2xl p-1.5 gap-1.5">
        {items.map((item, i) => (
          <button key={item.id} type="button" onClick={() => onSelect(i)}
            className={`flex-1 py-3 px-2 rounded-xl text-sm transition-all duration-200 min-w-0 cursor-pointer ${
              i === selectedIndex
                ? 'bg-white text-bc-primary font-bold shadow-md ring-1 ring-bc-primary/20 border border-bc-primary/30'
                : 'bg-white/60 text-bc-gray-600 font-medium border border-bc-gray-200 hover:bg-white hover:shadow-sm'
            }`}
          >{item.label}</button>
        ))}
      </div>
    </div>
  )
}

/* ── Pricing Table ── */
function PricingTable({ rows, selectedIndex, onSelect }: {
  rows: { name: string; qty: number; price: string; perUnit: string; discount: number; popular?: boolean }[]
  selectedIndex: number
  onSelect: (i: number) => void
}) {
  return (
    <div className="overflow-x-auto rounded-lg border border-bc-gray-100 mt-4">
      <table className="w-full text-sm">
        <thead>
          <tr className="bg-bc-gray-50 text-bc-gray-500 text-xs">
            <th className="py-2.5 px-4 text-end font-semibold">{t('Package')}</th>
            <th className="py-2.5 px-4 text-end font-semibold">{t('Quantity')}</th>
            <th className="py-2.5 px-4 text-end font-semibold">{t('Price')}</th>
            <th className="py-2.5 px-4 text-end font-semibold">{t('Per Coin')}</th>
            <th className="py-2.5 px-4 text-end font-semibold">{t('Discount')}</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} onClick={() => onSelect(i)}
              className={`border-t border-bc-gray-50 cursor-pointer transition-colors duration-150 ${
                i === selectedIndex ? 'bg-bc-primary-light' : 'hover:bg-bc-gray-50'
              }`}
            >
              <td className="py-2.5 px-4 text-bc-gray-800 font-medium">
                <span className="inline-flex items-center gap-2">
                  {r.name}
                  {r.popular && <Badge variant="success">{t('Popular')}</Badge>}
                </span>
              </td>
              <td className="py-2.5 px-4 text-bc-gray-600">{r.qty.toLocaleString()} BoostCoin</td>
              <td className="py-2.5 px-4 text-bc-gray-600">{r.price}</td>
              <td className="py-2.5 px-4 text-bc-gray-600">{r.perUnit}</td>
              <td className="py-2.5 px-4">
                {r.discount > 0 ? (
                  <span className="text-green-600 font-semibold">{r.discount}%−</span>
                ) : (
                  <span className="text-bc-gray-300">—</span>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

/* ═══════════════════════════════════════════════════════
   UsagePage – Main Component
   ═══════════════════════════════════════════════════════ */

export default function UsagePage() {
  const credits = useCreditsStatus()
  const catalog = usePricingCatalog()
  const createSub = useCreateSubscription()
  const cancelSub = useCancelSubscription()
  const refetchCredits = credits.refetch
  const [cancelSuccess, setCancelSuccess] = useState(false)

  const [pkgIdx, setPkgIdx] = useState(0)
  const [subIdx, setSubIdx] = useState(0)
  const [paypalOpen, setPaypalOpen] = useState(false)
  const [paypalConfigLoading, setPaypalConfigLoading] = useState(false)
  const [paypalButtonsLoading, setPaypalButtonsLoading] = useState(false)
  const [paypalReady, setPaypalReady] = useState(false)
  const [paypalBusy, setPaypalBusy] = useState(false)
  const [paypalError, setPaypalError] = useState<string | null>(null)
  const [paypalConfig, setPaypalConfig] = useState<{ paypal_client_id: string; paypal_env: string } | null>(null)
  const [purchaseSuccess, setPurchaseSuccess] = useState<{ credits: number } | null>(null)
  const paypalHostRef = useRef<HTMLDivElement | null>(null)
  const pkgInit = useRef(false)
  const subInit = useRef(false)

  const packages = useMemo(
    () => [...(catalog.data?.packages || [])].sort((a, b) => a.credits - b.credits),
    [catalog.data?.packages]
  )

  const subs = useMemo(
    () => [...(catalog.data?.subscriptions || [])].sort((a, b) => a.price - b.price),
    [catalog.data?.subscriptions]
  )

  useEffect(() => {
    if (packages.length > 0 && !pkgInit.current) {
      pkgInit.current = true
      const i = packages.findIndex((p) => p.popular)
      setPkgIdx(i >= 0 ? i : Math.floor(packages.length / 2))
    }
  }, [packages])

  useEffect(() => {
    if (subs.length > 0 && !subInit.current) {
      subInit.current = true
      const i = subs.findIndex((s) => s.popular)
      setSubIdx(i >= 0 ? i : 0)
    }
  }, [subs])

  const sPkgI = Math.max(0, Math.min(pkgIdx, packages.length - 1))
  const selPkg: PricingPackage | null = packages[sPkgI] || null

  const sSubI = Math.max(0, Math.min(subIdx, subs.length - 1))
  const selSub: PricingSubscription | null = subs[sSubI] || null

  const cd = credits.data
  const freeTotal = cd?.credits?.free?.total ?? 0
  const freeUsed = cd?.credits?.free?.used ?? 0
  const freeRemaining = Math.max(0, freeTotal - freeUsed)
  const purchasedTotal = cd?.credits?.purchased?.total ?? cd?.boost_credits?.total ?? 0
  const purchasedUsed = cd?.credits?.purchased?.used ?? cd?.boost_credits?.used ?? 0
  const purchasedRemaining = Math.max(0, purchasedTotal - purchasedUsed)
  const subTotal = cd?.credits?.subscription?.total ?? 0
  const subUsed = cd?.credits?.subscription?.used ?? 0
  const subRemaining = Math.max(0, subTotal - subUsed)
  const subStatus = cd?.credits?.subscription?.status ?? 'none'
  const subRenewAt = cd?.credits?.subscription?.renew_at ?? null
  const dailyGenerated = cd?.daily_usage?.generated_today ?? cd?.daily_usage?.articles_generated ?? 0
  const dailyLimit = cd?.daily_usage?.limit ?? cd?.daily_usage?.article_limit ?? 1000
  const dailyRemaining = cd?.daily_usage?.remaining ?? cd?.daily_usage?.articles_remaining ?? Math.max(0, dailyLimit - dailyGenerated)
  const blocked = cd ? !cd.allowed : false

  const currency = catalog.data?.currency
  const sym = currencySymbol(currency)
  const coinBase = 1.0
  const selPkgDisc = selPkg ? discountPct(selPkg.price / selPkg.credits, coinBase) : 0

  const freePct = freeTotal > 0 ? Math.min(100, (freeRemaining / freeTotal) * 100) : 0
  const purchasedPct = purchasedTotal > 0 ? Math.min(100, (purchasedRemaining / purchasedTotal) * 100) : 0
  const subPct = subTotal > 0 ? Math.min(100, (subRemaining / subTotal) * 100) : 0
  const dailyPct = dailyLimit > 0 ? Math.min(100, (dailyGenerated / dailyLimit) * 100) : 0

  const renewLabel = subRenewAt
    ? new Date(subRenewAt).toLocaleDateString(getDateLocale(), { day: 'numeric', month: 'short' })
    : null

  const reportAffiliatePurchaseSafely = useCallback(async (payload: AffiliatePurchasePayload) => {
    try {
      await endpoints.reportAffiliatePurchase(payload)
    } catch (error) {
      // Affiliate reporting should not block a purchase that already succeeded.
      console.warn('BoostAffiliate purchase reporting failed', error)
    }
  }, [])

  /* ── PayPal inline purchase ── */
  const openPaypal = async () => {
    if (paypalOpen && !paypalBusy) { setPaypalOpen(false); return }
    setPaypalOpen(true)
    setPaypalError(null)
    if (paypalConfig || paypalConfigLoading) return
    setPaypalConfigLoading(true)
    try {
      const res = await endpoints.getPaypalConfig()
      setPaypalConfig(res.data as { paypal_client_id: string; paypal_env: string })
    } catch (e) {
      setPaypalError(errorMessage(e, t('Error loading PayPal')))
    } finally {
      setPaypalConfigLoading(false)
    }
  }

  useEffect(() => {
    if (!paypalOpen || !paypalConfig || !selPkg || !paypalHostRef.current) return
    let cancelled = false
    const host = paypalHostRef.current
    ;(async () => {
      try {
        setPaypalReady(false)
        setPaypalButtonsLoading(true)
        setPaypalError(null)
        await loadPayPalSdk(paypalConfig.paypal_client_id, (currency || 'USD').toUpperCase())
        if (cancelled) return
        const paypal = getPaypalWindow().paypal
        if (!paypal?.Buttons) throw new Error('PayPal SDK not available')
        if (!host) return
        host.innerHTML = ''
        const buttons = paypal.Buttons({
          onInit: () => { if (!cancelled) setPaypalReady(true) },
          style: { layout: 'vertical', color: 'gold', shape: 'rect', label: 'pay', height: 45 },
          createOrder: async () => {
            setPaypalBusy(true)
            const r = await endpoints.createPurchaseOrder(selPkg.id)
            const d = r.data as { order_id?: string }
            if (!d?.order_id) throw new Error('Failed to create order')
            return d.order_id
          },
          onApprove: async (data: { orderID?: string }) => {
            try {
              const oid = data?.orderID || ''
              if (!oid) throw new Error('Missing order ID')
              await endpoints.capturePurchaseOrder(oid)
              await reportAffiliatePurchaseSafely({
                amount: selPkg.price,
                currency: (currency || 'ILS').toUpperCase(),
                package_id: selPkg.id,
              })
              await new Promise((r) => setTimeout(r, 1200))
              await refetchCredits()
              if (!cancelled) { setPaypalOpen(false); setPurchaseSuccess({ credits: selPkg.credits }) }
            } catch (e) {
              if (!cancelled) setPaypalError(errorMessage(e, t('Purchase failed')))
            } finally {
              if (!cancelled) setPaypalBusy(false)
            }
          },
          onCancel: () => { if (!cancelled) setPaypalBusy(false) },
          onError: (err) => {
            if (!cancelled) { setPaypalBusy(false); setPaypalError(errorMessage(err, t('Payment error'))) }
          },
        })
        await buttons.render(host)
        if (!cancelled) setPaypalReady(true)
      } catch (e) {
        if (!cancelled) setPaypalError(errorMessage(e, t('Error loading PayPal')))
      } finally {
        if (!cancelled) setPaypalButtonsLoading(false)
      }
    })()
    return () => { cancelled = true; if (host) host.innerHTML = '' }
  }, [currency, paypalConfig, paypalOpen, refetchCredits, reportAffiliatePurchaseSafely, selPkg])

  const selSubDisc = selSub ? discountPct(selSub.price / selSub.allowance, coinBase) : 0

  /* ── Pricing table rows ── */
  const pkgRows = packages.map((p) => ({
    name: p.name,
    qty: p.credits,
    price: `${sym}${fmtPrice(p.price, currency)}`,
    perUnit: `${sym}${(p.price / p.credits).toFixed(3)}`,
    discount: discountPct(p.price / p.credits, coinBase),
    popular: p.popular,
  }))

  const subRows = subs.map((s) => ({
    name: s.name,
    qty: s.allowance,
    price: `${sym}${fmtPrice(s.price, currency)}`,
    perUnit: `${sym}${(s.price / s.allowance).toFixed(3)}`,
    discount: discountPct(s.price / s.allowance, coinBase),
    popular: s.popular,
  }))

  // Handle subscription return from PayPal
  useEffect(() => {
    let active = true

    void (async () => {
      const params = new URLSearchParams(window.location.search)
      if (params.get('bmai_subscription') !== 'success') return

      const raw = sessionStorage.getItem(AFFILIATE_PENDING_SUBSCRIPTION_KEY)
      if (raw) {
        try {
          const payload = JSON.parse(raw) as AffiliatePurchasePayload
          await reportAffiliatePurchaseSafely(payload)
        } catch (error) {
          console.warn('Failed to restore pending affiliate subscription payload', error)
        } finally {
          sessionStorage.removeItem(AFFILIATE_PENDING_SUBSCRIPTION_KEY)
        }
      }

      if (!active) return
      await refetchCredits()
      if (!active) return

      const cleanUrl = window.location.href.replace(/[?&]bmai_subscription=[^&#]+/, '')
      window.history.replaceState({}, '', cleanUrl)
    })()

    return () => {
      active = false
    }
  }, [refetchCredits, reportAffiliatePurchaseSafely])

  if (credits.loading && !cd) {
    return (
      <div className="min-h-screen">
        <Header title={t('Usage & Costs')} subtitle={t('BoostCoin — unified coins for content creation, images and AI')} />
        <div className="flex items-center justify-center p-12">
          <RefreshCw className="w-6 h-6 animate-spin text-bc-primary" />
          <span className="ms-3 text-bc-gray-600">{t('Loading usage data...')}</span>
        </div>
      </div>
    )
  }

  if (!credits.loading && credits.error && !cd) {
    return (
      <div className="min-h-screen">
        <Header title={t('Usage & Costs')} subtitle={t('BoostCoin — unified coins for content creation, images and AI')} />
        <div className="p-8 text-center">
          <div className="text-red-500 mb-2">{t('Failed to load credit information')}</div>
          <button onClick={refetchCredits} className="text-sm text-bc-primary hover:underline cursor-pointer">
            {t('Try again')}
          </button>
        </div>
      </div>
    )
  }

  if (!credits.loading && !cd) {
    return (
      <div className="min-h-screen">
        <Header title={t('Usage & Costs')} subtitle={t('BoostCoin — unified coins for content creation, images and AI')} />
        <div className="p-8 text-center">
          <div className="text-bc-gray-500">{t('Credit information unavailable')}</div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen">
      <Header
        title={t('Usage & Costs')}
        subtitle={t('BoostCoin — unified coins for content creation, images and AI')}
        helpContent={[
          t('View your BoostCoin balance — total, used, and remaining.'),
          t('Each article costs approximately 2-3 BoostCoins depending on research depth, images, and Copyscape checks.'),
          t('Purchase additional BoostCoins or manage your subscription here.'),
        ]}
      />

      <div className="p-6 space-y-6">

        {credits.refreshing && (
          <div className="text-xs text-bc-gray-400 text-center animate-pulse">{t('Refreshing...')}</div>
        )}

        <SetupBanner
          stepKey="usageSeen"
          icon={'\u{1F4B0}'}
          title={t('Meet your BoostCoin balance')}
          description={t('You received 60 free BoostCoins — enough to create your first articles. Here you can track usage, view costs, and purchase more coins when needed.')}
          nextLabel={t('Continue to Content Types')}
          nextPath="/post-types"
        />

        {/* Free Credits Card */}
        {freeTotal > 0 && (
          <Card className="border-emerald-200 bg-gradient-to-l from-emerald-50/60 to-white">
            <CardContent className="py-5">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2 text-sm text-bc-gray-500">
                  <Gift className="w-4 h-4 text-emerald-500" />
                  <span>{t('Free BoostCoin')}</span>
                  <HelpTooltip text={t('Free coins received when the plugin was installed. Used first before any other type. Cannot be replenished.')} />
                </div>
                <Badge variant="success">{t('Installation gift')}</Badge>
              </div>
              <div className="text-3xl font-bold text-bc-gray-800 tabular-nums">{freeRemaining.toLocaleString()}</div>
              <div className="mt-3">
                <div className="flex justify-between text-xs text-bc-gray-400 mb-1">
                  <span>{t('Used:')} {freeUsed.toLocaleString()}</span>
                  <span>{t('Total:')} {freeTotal.toLocaleString()}</span>
                </div>
                <div className="h-2 bg-bc-gray-100 rounded-full overflow-hidden">
                  <div className={`h-full rounded-full transition-all duration-500 ${freePct > 20 ? 'bg-emerald-500' : freePct > 0 ? 'bg-amber-500' : 'bg-red-500'}`}
                    style={{ width: `${freePct}%` }} />
                </div>
              </div>
              <p className="text-[11px] text-bc-gray-400 mt-2">
                {freeRemaining > 0
                  ? t('Used first before any other type. Identical to regular BoostCoin — same AI model and quality.')
                  : t('All free BoostCoin used. Consumption continues from subscription or purchased.')}
              </p>
            </CardContent>
          </Card>
        )}

        {/* Credit Balance Cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {/* Purchased Credits */}
          <Card>
            <CardContent className="py-5">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2 text-sm text-bc-gray-500">
                  <Sparkles className="w-4 h-4 text-bc-primary" />
                  <span>{t('Purchased BoostCoin')}</span>
                  <HelpTooltip text={t('Coins purchased via one-time payments. Never expire and accumulate over time. Used after free and subscription coins.')} />
                </div>
                <Badge variant="accent">{t('Accumulating')}</Badge>
              </div>
              <div className="text-3xl font-bold text-bc-gray-800 tabular-nums">{purchasedRemaining.toLocaleString()}</div>
              <div className="flex justify-between text-xs text-bc-gray-400 mb-1">
                <span>{t('Used:')} {purchasedUsed.toLocaleString()}</span>
                <span>{t('Total:')} {purchasedTotal.toLocaleString()}</span>
              </div>
              <div className="h-2 bg-bc-gray-100 rounded-full overflow-hidden">
                <div className={`h-full rounded-full transition-all duration-500 ${purchasedPct > 20 ? 'bg-bc-primary' : 'bg-red-500'}`}
                  style={{ width: `${purchasedPct}%` }} />
              </div>
              <p className="text-[11px] text-bc-gray-400 mt-2">{t('Never expire, accumulate over time')}</p>
            </CardContent>
          </Card>

          {/* Subscription Credits */}
          <Card>
            <CardContent className="py-5">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2 text-sm text-bc-gray-500">
                  <RefreshCw className="w-4 h-4 text-blue-500" />
                  <span>{t('Subscription BoostCoin')}</span>
                  <HelpTooltip text={t('Monthly coin allowance from your subscription. Resets each billing cycle — unused coins roll over into your purchased balance.')} />
                </div>
                {subStatus === 'active' ? <Badge variant="success">{t('Active')}</Badge>
                  : subStatus === 'paused' ? <Badge variant="warning">{t('Paused')}</Badge>
                  : subStatus === 'cancelled' ? <Badge variant="warning">{t('Cancelled')}</Badge>
                  : <Badge variant="default">{t('No subscription')}</Badge>
                }
              </div>
              <div className="text-3xl font-bold text-bc-gray-800 tabular-nums">
                {subStatus !== 'none' ? subRemaining.toLocaleString() : '—'}
              </div>
              <div className="mt-3">
                {subStatus !== 'none' ? (
                  <>
                    <div className="flex justify-between text-xs text-bc-gray-400 mb-1">
                      <span>{t('Used:')} {subUsed.toLocaleString()}</span>
                      <span>{t('Quota:')} {subTotal.toLocaleString()}</span>
                    </div>
                    <div className="h-2 bg-bc-gray-100 rounded-full overflow-hidden">
                      <div className={`h-full rounded-full transition-all duration-500 ${subPct > 20 ? 'bg-blue-500' : 'bg-red-500'}`}
                        style={{ width: `${subPct}%` }} />
                    </div>
                  </>
                ) : <div className="h-2" />}
              </div>
              <div className="flex items-center gap-2 mt-2">
                {renewLabel && (
                  <span className="text-[11px] text-bc-gray-400 flex items-center gap-1">
                    <Calendar className="w-3 h-3" />
                    {t('Renewal:')} {renewLabel}
                  </span>
                )}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="py-5">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2 text-sm text-bc-gray-500">
                  <Calendar className="w-4 h-4 text-violet-500" />
                  <span>{t('Daily article usage')}</span>
                  <HelpTooltip text={t('Each account can generate up to 1,000 articles per UTC day. Queued and completed jobs both count toward the limit.')} />
                </div>
                <Badge variant={dailyRemaining > 0 ? 'accent' : 'warning'}>
                  {dailyRemaining > 0 ? t('Available') : t('Limit reached')}
                </Badge>
              </div>
              <div className="text-3xl font-bold text-bc-gray-800 tabular-nums">{dailyRemaining.toLocaleString()}</div>
              <div className="flex justify-between text-xs text-bc-gray-400 mb-1">
                <span>{t('Generated today:')} {dailyGenerated.toLocaleString()}</span>
                <span>{t('Daily cap:')} {dailyLimit.toLocaleString()}</span>
              </div>
              <div className="h-2 bg-bc-gray-100 rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all duration-500 ${dailyRemaining > 0 ? 'bg-violet-500' : 'bg-red-500'}`}
                  style={{ width: `${dailyPct}%` }}
                />
              </div>
              <p className="text-[11px] text-bc-gray-400 mt-2">
                {t('Resets at midnight UTC. Large batch plans may stop early when the daily cap is reached.')}
              </p>
            </CardContent>
          </Card>
        </div>

        <p className="text-[11px] text-bc-gray-400 text-center -mt-2">
          {t('Consumption order: Subscription → Purchased (subscription coins are consumed first, unused balances roll over to purchased)')}
        </p>

        <div className="text-[11px] text-bc-gray-400 text-center -mt-1 space-y-0.5">
          <p>{t('Estimated rate: ~4-5 BoostCoins per article (~700 words, includes research, image, and plagiarism check).')}</p>
          <p>{t('~0.6 BoostCoins per 100 words (actual cost calculated after each generation)')}</p>
        </div>

        {/* Blocked warning */}
        {blocked && (
          <div className="p-4 rounded-xl border border-amber-200 bg-amber-50 text-amber-900 text-sm">
            <span className="font-semibold">{t('No BoostCoin available — ')}</span>
            {t('All BoostCoin used. Purchase a package to continue.')}
          </div>
        )}

        {/* One-Time Purchase */}
        <Card padding="none">
          <CardContent className="p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-9 h-9 rounded-bc bg-bc-primary-light flex items-center justify-center">
                <ShoppingCart className="w-5 h-5 text-bc-primary" />
              </div>
              <div>
                <h2 className="text-lg font-semibold text-bc-gray-800">{t('One-time purchase')}</h2>
                <p className="text-xs text-bc-gray-500">{t('Purchase BoostCoin that never expire')}</p>
              </div>
            </div>

            {catalog.loading ? (
              <div className="text-center py-10 text-bc-gray-400">{t('Loading packages...')}</div>
            ) : packages.length === 0 ? (
              <div className="text-center py-10 text-bc-gray-400">{t('No packages available right now')}</div>
            ) : (
              <>
                <CreditSlider
                  items={packages.map((p) => ({ id: p.id, label: p.credits.toLocaleString() }))}
                  selectedIndex={sPkgI}
                  onSelect={setPkgIdx}
                />

                {selPkg && (
                  <div className="flex flex-col items-center gap-2 py-2">
                    <div className="text-3xl font-extrabold text-bc-gray-800 tabular-nums">
                      {sym}{fmtPrice(selPkg.price, currency)}
                    </div>
                    <div className="flex items-center gap-3 text-sm text-bc-gray-500">
                      <span>{selPkg.credits.toLocaleString()} BoostCoin</span>
                      {selPkgDisc > 0 && (
                        <>
                          <span className="text-bc-gray-200">•</span>
                          <Badge variant="success">{selPkgDisc}{t('% discount')}</Badge>
                        </>
                      )}
                    </div>
                    <Button
                      size="lg"
                      className="mt-2 min-w-[180px]"
                      onClick={openPaypal}
                      disabled={paypalConfigLoading}
                      loading={paypalConfigLoading}
                      icon={<ShoppingCart className="w-4 h-4" />}
                    >
                      {t('Purchase')}
                    </Button>

                    {paypalOpen && (
                      <div className="w-full max-w-[420px] mt-3 border border-bc-gray-200 rounded-xl p-3 bg-bc-gray-50">
                        {(paypalConfigLoading || paypalButtonsLoading || !paypalReady) && !paypalError && (
                          <div className="flex items-center gap-2 text-sm text-bc-gray-500 mb-2">
                            <span className="inline-block w-4 h-4 border-2 border-bc-gray-300 border-t-bc-primary rounded-full animate-spin" />
                            <span>{t('Loading payment options...')}</span>
                          </div>
                        )}
                        {paypalError && (
                          <div className="mb-2 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
                            {paypalError}
                          </div>
                        )}
                        <div ref={paypalHostRef} className="min-h-[120px]" />
                        <div className="mt-2 flex items-center justify-between gap-2">
                          <p className="text-xs text-bc-gray-400">{t('Pay with PayPal account or credit card via PayPal.')}</p>
                          <button type="button" className="text-xs text-bc-gray-500 hover:text-bc-gray-700 border-none bg-transparent cursor-pointer"
                            onClick={() => { if (!paypalBusy) setPaypalOpen(false) }}>
                            {t('Close')}
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                <PricingTable rows={pkgRows} selectedIndex={sPkgI} onSelect={setPkgIdx} />

                <p className="text-xs text-bc-gray-400 mt-4 text-center">
                  {t('Purchased BoostCoin never expire and always accumulate. Coins are used for API calls to various AI models (content creation, images and more).')}
                </p>
              </>
            )}
          </CardContent>
        </Card>
        {/* Monthly Subscriptions */}
        {subs.length > 0 && (
          <Card padding="none">
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-9 h-9 rounded-bc bg-blue-50 flex items-center justify-center">
                  <RefreshCw className="w-5 h-5 text-blue-500" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-bc-gray-800">{t('Monthly Subscription')}</h2>
                  <p className="text-xs text-bc-gray-500">{t('Monthly BoostCoin allowance that resets each billing cycle')}</p>
                </div>
              </div>

              {(subStatus === 'active' || cancelSuccess) && (
                <div className="mb-4 p-3 rounded-lg border border-amber-200 bg-amber-50">
                  {cancelSuccess ? (
                    <div className="flex items-center gap-2 text-sm text-emerald-700">
                      <CheckCircle className="w-4 h-4" />
                      {t('Subscription cancelled successfully')}
                      {subRenewAt && (
                        <span className="text-xs text-bc-gray-500 ms-1">
                          — {tf('Active until %s', new Date(subRenewAt).toLocaleDateString(getDateLocale(), { day: 'numeric', month: 'long', year: 'numeric' }))}
                        </span>
                      )}
                    </div>
                  ) : (
                    <div className="flex items-center justify-between gap-3">
                      <span className="text-xs text-amber-600">
                        {t('You currently have an active subscription. You can cancel or change plans via PayPal.')}
                      </span>
                      <button
                        type="button"
                        onClick={async () => {
                          if (!confirm(
                            t('Are you sure you want to cancel your subscription?') + '\n\n' +
                            t('Your remaining BoostCoins will stay available until the end of the current billing period. Your plan will not renew.')
                          )) return
                          const ok = await cancelSub.cancel()
                          if (ok) {
                            setCancelSuccess(true)
                            credits.refetch()
                          }
                        }}
                        disabled={cancelSub.loading}
                        className="text-xs text-red-500 hover:text-red-700 bg-transparent border border-red-200 hover:border-red-300 rounded-bc px-3 py-1.5 cursor-pointer whitespace-nowrap transition-colors"
                      >
                        {cancelSub.loading ? t('Cancelling...') : t('Cancel Subscription')}
                      </button>
                    </div>
                  )}
                  {cancelSub.error && (
                    <div className="mt-2 text-xs text-red-600">{cancelSub.error}</div>
                  )}
                </div>
              )}

              <CreditSlider
                items={subs.map((s) => ({ id: s.id, label: s.allowance.toLocaleString() }))}
                selectedIndex={sSubI}
                onSelect={setSubIdx}
              />

              {selSub && (
                <div className="flex flex-col items-center gap-2 py-2">
                  <div className="text-3xl font-extrabold text-bc-gray-800 tabular-nums">
                    {sym}{fmtPrice(selSub.price, currency)}
                    <span className="text-base font-normal text-bc-gray-400 ms-1">/{t('month')}</span>
                  </div>
                  <div className="flex items-center gap-3 text-sm text-bc-gray-500">
                    <span>{tf('%s BoostCoin per month', selSub.allowance.toLocaleString())}</span>
                    {selSubDisc > 0 && (
                      <>
                        <span className="text-bc-gray-200">•</span>
                        <Badge variant="success">{selSubDisc}{t('% discount')}</Badge>
                      </>
                    )}
                  </div>
                  <Button
                    size="lg"
                    className="mt-2 min-w-[180px]"
                    onClick={async () => {
                      if (
                        subStatus === 'active' &&
                        !window.confirm(t('You already have an active subscription. This action may create an additional subscription. Continue?'))
                      ) {
                        return
                      }
                      const result = await createSub.create(selSub.id)
                      if (result?.approval_url) {
                        sessionStorage.setItem(AFFILIATE_PENDING_SUBSCRIPTION_KEY, JSON.stringify({
                          package_id: selSub.id,
                          amount: selSub.price,
                          currency: (currency || 'ILS').toUpperCase(),
                        }))
                        window.location.href = result.approval_url
                      }
                    }}
                    disabled={createSub.loading}
                    loading={createSub.loading}
                    icon={<Zap className="w-4 h-4" />}
                  >
                    {t('Subscribe')}
                  </Button>
                  {createSub.error && (
                    <div className="mt-2 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
                      {createSub.error}
                    </div>
                  )}
                </div>
              )}

              <PricingTable rows={subRows} selectedIndex={sSubI} onSelect={setSubIdx} />

              <p className="text-xs text-bc-gray-400 mt-4 text-center">
                {t('Subscription coins refresh each billing cycle. Unused subscription coins roll over into your purchased balance.')}
              </p>
            </CardContent>
          </Card>
        )}
      </div>

      <ConfettiCelebration active={purchaseSuccess !== null} />
      <PurchaseSuccessOverlay
        show={purchaseSuccess !== null}
        credits={purchaseSuccess?.credits ?? 0}
        onClose={() => setPurchaseSuccess(null)}
      />
    </div>
  )
}
