import { useEffect, useState, useMemo, useRef } from 'react'
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  ReferenceArea,
  ReferenceLine,
} from 'recharts'
import {
  Sparkles,
  ShoppingCart,
  RefreshCw,
  Zap,
  TrendingDown,
  Calendar,
  BarChart3,
  Gift,
  PartyPopper,
  CheckCircle2,
} from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { formatCredits } from '@/utils/formatters'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { Badge } from '@/components/common/Badge'
import { PageLoading } from '@/components/common/Spinner'
import { apiClient } from '@/api/client'
import {
  useCreditsStatus,
  useCreditsUsageHistory,
  usePricingCatalog,
  useCreatePurchaseOrder,
  useCapturePurchaseOrder,
  useCreateSubscription,
} from '@/hooks/useUsage'
import { t, sprintf, isRtl } from '@/lib/i18n'

/* ═══════════════════════════════════════════════════════════════════════════
   Helpers
   ═══════════════════════════════════════════════════════════════════════════ */

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)
}

/** Format ISO date to DD/MM short label */
function shortDate(iso: string) {
  const [, m, d] = iso.split('-')
  return `${d}/${m}`
}

function loadPayPalSdk(clientId: string, currency: string): Promise<void> {
  return new Promise((resolve, reject) => {
    if ((window as any).paypal) {
      resolve()
      return
    }

    const existing = document.getElementById('bb-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 script = document.createElement('script')
    script.id = 'bb-paypal-sdk'
    script.src =
      'https://www.paypal.com/sdk/js?client-id=' +
      encodeURIComponent(clientId) +
      '&currency=' +
      encodeURIComponent(currency) +
      `&locale=${isRtl() ? 'he_IL' : 'en_US'}&intent=capture`
    script.async = true
    script.onload = () => resolve()
    script.onerror = () => reject(new Error('Failed to load PayPal SDK.'))
    document.head.appendChild(script)
  })
}

/* ═══════════════════════════════════════════════════════════════════════════
   ConfettiCelebration – lightweight CSS confetti burst on purchase success
   ═══════════════════════════════════════════════════════════════════════════ */

const CONFETTI_COLORS = ['#10b981', '#06b6d4', '#6366f1', '#f59e0b', '#ec4899', '#8b5cf6', '#14b8a6']
const CONFETTI_COUNT = 60

function ConfettiCelebration({ active }: { active: boolean }) {
  if (!active) return null
  return (
    <div className="fixed inset-0 pointer-events-none z-[99999] overflow-hidden">
      {Array.from({ length: CONFETTI_COUNT }).map((_, i) => {
        const color = CONFETTI_COLORS[i % CONFETTI_COLORS.length]
        const left = Math.random() * 100
        const delay = Math.random() * 1.2
        const duration = 2.5 + Math.random() * 2
        const size = 6 + Math.random() * 8
        const rotate = Math.random() * 360
        const drift = (Math.random() - 0.5) * 120
        return (
          <span
            key={i}
            className="absolute top-0 rounded-sm"
            style={{
              left: `${left}%`,
              width: size,
              height: size * (0.4 + Math.random() * 0.6),
              backgroundColor: color,
              transform: `rotate(${rotate}deg)`,
              animation: `bb-confetti-fall ${duration}s ease-in ${delay}s forwards`,
              ['--drift' as string]: `${drift}px`,
            }}
          />
        )
      })}
      <style>{`
        @keyframes bb-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
}) {
  useEffect(() => {
    if (!show) return
    const t = setTimeout(onClose, 6000)
    return () => clearTimeout(t)
  }, [show, onClose])

  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-[bb-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">
          <CheckCircle2 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('An invoice will be sent to your email from PayPal.')}</p>
        <Button size="sm" variant="primary" onClick={onClose}>
          {t('Close')}
        </Button>
      </div>
      <style>{`
        @keyframes bb-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>
  )
}

/* ═══════════════════════════════════════════════════════════════════════════
   CreditSlider – segmented control for discrete package selection
   ═══════════════════════════════════════════════════════════════════════════ */

function CreditSlider({
  items,
  selectedIndex,
  onSelect,
}: {
  items: { id: string; label: string }[]
  selectedIndex: number
  onSelect: (i: number) => void
}) {
  if (items.length === 0) return null

  if (items.length === 1) {
    return (
      <div className="flex justify-center py-4">
        <div className="bg-primary-50 text-primary-700 font-bold px-6 py-3 rounded-xl border border-primary-200 text-sm">
          {items[0].label} {t('BoostCoin')}
        </div>
      </div>
    )
  }

  return (
    <div className="py-4 select-none">
      <div className="text-xs text-gray-400 text-center mb-2">{t('Choose BoostCoin amount')}</div>
      <div className="flex items-stretch bg-gray-100 rounded-2xl p-1.5 gap-1.5">
        {items.map((item, i) => {
          const sel = i === selectedIndex
          return (
            <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
                ${sel
                  ? 'bg-white text-primary-600 font-bold shadow-md ring-1 ring-primary-200 border border-primary-200'
                  : 'bg-white/60 text-gray-600 font-medium border border-gray-200 hover:bg-white hover:text-gray-800 hover:border-gray-300 hover:shadow-sm'
                }
              `}
            >
              {item.label}
            </button>
          )
        })}
      </div>
    </div>
  )
}

/* ═══════════════════════════════════════════════════════════════════════════
   PricingTable – compact comparison table with selected-row highlight
   ═══════════════════════════════════════════════════════════════════════════ */

interface TableRow {
  name: string
  qty: number
  qtyLabel: string
  price: string
  perUnit: string
  discount: number
  popular?: boolean
}

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

/* ═══════════════════════════════════════════════════════════════════════════
   UsageDashboard – main page component
   ═══════════════════════════════════════════════════════════════════════════ */

export function UsageDashboard() {
  const [chartDays, setChartDays] = useState(30)
  const [pkgIdx, setPkgIdx] = useState(0)
  const [subIdx, setSubIdx] = useState(0)
  const [paypalInlineOpen, setPaypalInlineOpen] = useState(false)
  const [paypalConfigLoading, setPaypalConfigLoading] = useState(false)
  const [paypalButtonsLoading, setPaypalButtonsLoading] = useState(false)
  const [paypalButtonsReady, setPaypalButtonsReady] = useState(false)
  const [paypalFlowBusy, setPaypalFlowBusy] = 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 paypalButtonsHostRef = useRef<HTMLDivElement | null>(null)
  const pkgInit = useRef(false)
  const subInit = useRef(false)

  /* ── data hooks ── */
  const credits = useCreditsStatus()
  const usageHistory = useCreditsUsageHistory(chartDays)
  const catalog = usePricingCatalog()
  const createOrder = useCreatePurchaseOrder()
  const captureOrder = useCapturePurchaseOrder()
  const createSub = useCreateSubscription()
  const createOrderAsync = createOrder.mutateAsync
  const captureOrderAsync = captureOrder.mutateAsync
  const refetchCredits = credits.refetch

  /* ── PayPal one-time purchase return ── */
  useEffect(() => {
    const p = new URLSearchParams(window.location.search)
    if (p.get('bb_purchase') !== 'success') return
    const oid = p.get('token')
    if (!oid || captureOrder.isPending || captureOrder.isSuccess) return
    ;(async () => {
      try {
        await captureOrder.mutateAsync({ order_id: oid })

        const pkgRaw = sessionStorage.getItem('bb_purchase_pkg')
        let purchasedPkg: { credits?: number; name?: string; price?: number; currency?: string; id?: string } = {}
        if (pkgRaw) {
          try { purchasedPkg = JSON.parse(pkgRaw) } catch { /* ignore */ }
        }

        if (purchasedPkg.name && typeof window.gtag === 'function') {
          window.gtag('event', 'boostcoin_purchase', {
            send_to: 'G-4RR5QT255Z',
            event_category: 'purchase',
            event_label: purchasedPkg.name || purchasedPkg.id,
            value: purchasedPkg.price,
            currency: purchasedPkg.currency || 'USD',
            credits_amount: purchasedPkg.credits,
            package_id: purchasedPkg.id,
          })
        }

        await new Promise((r) => setTimeout(r, 2500))
        await credits.refetch()

        if (purchasedPkg.credits && purchasedPkg.credits > 0) {
          setPurchaseSuccess({ credits: purchasedPkg.credits })
        }

        sessionStorage.removeItem('bb_purchase_pkg')
      } catch (e: any) {
        alert(e?.message || t('Capture failed'))
      } finally {
        const u = new URL(window.location.href)
        u.searchParams.delete('bb_purchase')
        u.searchParams.delete('token')
        u.searchParams.delete('PayerID')
        window.history.replaceState({}, '', u.toString())
      }
    })()
  }, [captureOrder, credits])

  /* ── PayPal subscription return ── */
  useEffect(() => {
    const p = new URLSearchParams(window.location.search)
    if (p.get('bb_subscription') !== 'success') return
    ;(async () => {
      try {
        await new Promise((r) => setTimeout(r, 2500))
        await credits.refetch()
      } finally {
        const u = new URL(window.location.href)
        u.searchParams.delete('bb_subscription')
        u.searchParams.delete('subscription_id')
        u.searchParams.delete('ba_token')
        window.history.replaceState({}, '', u.toString())
      }
    })()
  }, [credits])

  /* ── Sorted packages & subscriptions ── */
  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.allowance - b.allowance),
    [catalog.data?.subscriptions],
  )

  /* ── Auto-select popular or middle package on first load ── */
  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 : Math.floor(subs.length / 2))
    }
  }, [subs])

  /* ── Safe indices ── */
  const sPkgI = Math.max(0, Math.min(pkgIdx, packages.length - 1))
  const sSubI = Math.max(0, Math.min(subIdx, subs.length - 1))

  /* ── Credits data ── */
  const cd = credits.data as any

  // Free credits (one-time grant on installation, consumed first)
  const freeTotal = cd?.credits?.free?.total ?? 0
  const freeUsed = cd?.credits?.free?.used ?? 0
  const freeRemaining = Math.max(0, freeTotal - freeUsed)

  // Purchased / accumulated coins (from unified BoostCoin wallet)
  const purchasedTotal = typeof cd?.boost_credits?.total === 'number' ? cd.boost_credits.total : 0
  const purchasedUsed = typeof cd?.boost_credits?.used === 'number' ? cd.boost_credits.used : 0
  const purchasedRemaining = Math.max(0, purchasedTotal - purchasedUsed)

  // Subscription credits (monthly allowance – resets each billing cycle)
  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 blocked = cd ? !cd.allowed : false
  const siteStatus = cd?.site_status

  const currency = catalog.data?.currency
  const sym = currencySymbol(currency)

  /* ── Discount calculations (unified base: 1 BoostCoin = ₪1) ── */
  const coinBase = 1.0
  const pkgBase = coinBase
  const subBase = coinBase
  // The base above is denominated in ILS, so the derived discount % is only
  // meaningful when the catalog is priced in ILS. Hide it for other currencies
  // to avoid showing bogus discounts (e.g. against a ₪1 base for USD prices).
  const showDiscounts = currency === 'ILS'

  const selPkg = packages[sPkgI] || null
  const selSub = subs[sSubI] || null
  const selPkgDisc = selPkg ? discountPct(selPkg.price / selPkg.credits, pkgBase) : 0
  const selSubDisc = selSub ? discountPct(selSub.price / selSub.allowance, subBase) : 0

  const openOneTimePurchaseInline = async () => {
    if (paypalInlineOpen && !paypalFlowBusy) {
      setPaypalInlineOpen(false)
      return
    }

    setPaypalInlineOpen(true)
    setPaypalError(null)

    if (paypalConfig || paypalConfigLoading) return

    setPaypalConfigLoading(true)
    try {
      const res = await apiClient.get<{ data: { paypal_client_id: string; paypal_env: string } }>(
        'purchases/paypal-config',
      )
      setPaypalConfig(res.data)
    } catch (e: any) {
      setPaypalError(e?.message || t('Failed to load PayPal'))
    } finally {
      setPaypalConfigLoading(false)
    }
  }

  useEffect(() => {
    if (!paypalInlineOpen || !paypalConfig || !selPkg || !paypalButtonsHostRef.current) return

    let cancelled = false

    ;(async () => {
      try {
        setPaypalButtonsReady(false)
        setPaypalButtonsLoading(true)
        setPaypalError(null)

        await loadPayPalSdk(paypalConfig.paypal_client_id, (currency || 'USD').toUpperCase())
        if (cancelled) return

        const paypal = (window as any).paypal
        if (!paypal || typeof paypal.Buttons !== 'function') {
          throw new Error('PayPal SDK is not available.')
        }

        const host = paypalButtonsHostRef.current
        if (!host) return
        host.innerHTML = ''

        const buttons = paypal.Buttons({
          onInit: () => {
            if (!cancelled) {
              setPaypalButtonsReady(true)
            }
          },
          style: {
            layout: 'vertical',
            color: 'gold',
            shape: 'rect',
            label: 'pay',
            height: 45,
          },
          createOrder: async () => {
            setPaypalFlowBusy(true)
            sessionStorage.setItem(
              'bb_purchase_pkg',
              JSON.stringify({
                id: selPkg.id,
                name: selPkg.name,
                price: selPkg.price,
                credits: selPkg.credits,
                currency: currency || 'USD',
              }),
            )
            const r = await createOrderAsync({ package_id: selPkg.id })
            if (!r?.order_id) throw new Error('Failed to create PayPal order.')
            return r.order_id
          },
          onApprove: async (data: { orderID?: string }) => {
            try {
              const orderId = data?.orderID || ''
              if (!orderId) throw new Error('Missing PayPal order ID.')
              await captureOrderAsync({ order_id: orderId })

              try {
                if (typeof window.gtag === 'function') {
                  window.gtag('event', 'boostcoin_purchase', {
                    send_to: 'G-4RR5QT255Z',
                    event_category: 'purchase',
                    event_label: selPkg.name || selPkg.id,
                    value: selPkg.price,
                    currency: currency || 'USD',
                    credits_amount: selPkg.credits,
                    package_id: selPkg.id,
                  })
                }
              } catch (_) {
                // Analytics errors must not break purchase success flow.
              }

              sessionStorage.removeItem('bb_purchase_pkg')
              await new Promise((r) => setTimeout(r, 1200))
              await refetchCredits()
              if (!cancelled) {
                setPaypalInlineOpen(false)
                setPurchaseSuccess({ credits: selPkg.credits })
              }
            } catch (e: any) {
              if (!cancelled) setPaypalError(e?.message || t('Purchase failed'))
            } finally {
              if (!cancelled) setPaypalFlowBusy(false)
            }
          },
          onCancel: () => {
            if (!cancelled) setPaypalFlowBusy(false)
          },
          onError: (err: any) => {
            if (!cancelled) {
              setPaypalFlowBusy(false)
              setPaypalError(err?.message || t('Payment failed. Please try again.'))
            }
          },
        })

        await buttons.render(host)
        if (!cancelled) {
          // Fallback guard in case onInit doesn't fire in edge cases.
          setPaypalButtonsReady(true)
        }
      } catch (e: any) {
        if (!cancelled) setPaypalError(e?.message || t('Failed to load PayPal'))
      } finally {
        if (!cancelled) setPaypalButtonsLoading(false)
      }
    })()

    return () => {
      cancelled = true
      if (paypalButtonsHostRef.current) {
        paypalButtonsHostRef.current.innerHTML = ''
      }
    }
  }, [
    paypalInlineOpen,
    paypalConfig,
    selPkg,
    currency,
    createOrderAsync,
    captureOrderAsync,
    refetchCredits,
  ])

  /* ── Table row data ── */
  const pkgRows: TableRow[] = packages.map((p) => ({
    name: p.name,
    qty: p.credits,
    qtyLabel: t('BoostCoin'),
    price: `${sym}${fmtPrice(p.price, currency)}`,
    perUnit: `${sym}${(p.price / p.credits).toFixed(3)}`,
    discount: discountPct(p.price / p.credits, pkgBase),
    popular: p.popular,
  }))

  const subRows: TableRow[] = subs.map((s) => ({
    name: s.name,
    qty: s.allowance,
    qtyLabel: sprintf(t('BoostCoin/%s'), t('month')),
    price: `${sym}${fmtPrice(s.price, currency)}/${t('month')}`,
    perUnit: `${sym}${(s.price / s.allowance).toFixed(3)}`,
    discount: discountPct(s.price / s.allowance, subBase),
    popular: s.popular,
  }))

  /* ── Chart data ── */
  const chartData = useMemo(() => {
    const daily = usageHistory.data?.daily || []
    // Build a lookup of actual data by date
    const lookup = new Map(daily.map((d) => [d.date, d]))

    // Generate ALL dates in the range (fill gaps with 0)
    const allDays: { date: string; fullDate: string; consumed: number; operations: number }[] = []
    const now = new Date()
    for (let i = chartDays - 1; i >= 0; i--) {
      const d = new Date(now)
      d.setDate(d.getDate() - i)
      const iso = d.toISOString().slice(0, 10)
      const entry = lookup.get(iso)
      allDays.push({
        fullDate: iso,
        date: shortDate(iso),
        consumed: entry?.consumed ?? 0,
        operations: entry?.operations ?? 0,
      })
    }

    // For 90 days, aggregate by week (every 7 days) to keep chart readable
    if (chartDays === 90) {
      const weekly: typeof allDays = []
      for (let i = 0; i < allDays.length; i += 7) {
        const chunk = allDays.slice(i, i + 7)
        const consumed = chunk.reduce((s, c) => s + c.consumed, 0)
        const operations = chunk.reduce((s, c) => s + c.operations, 0)
        // Use first day of the week as label
        weekly.push({
          fullDate: chunk[0].fullDate,
          date: shortDate(chunk[0].fullDate),
          consumed: Math.round(consumed * 100) / 100,
          operations,
        })
      }
      return weekly
    }

    return allDays
  }, [usageHistory.data?.daily, chartDays])

  /**
   * Compute week markers aligned to the Jewish calendar.
   * Lines & band boundaries are placed on Saturday (Shabbat = end of week).
   *
   * 1. Find every Saturday in the data → draw a thin vertical ReferenceLine.
   * 2. Between consecutive Saturdays (always exactly 7 days apart), draw
   *    alternating shaded ReferenceAreas so each band is uniform width.
   */
  const { saturdayLines, weekAreas } = useMemo(() => {
    if (chartData.length === 0 || chartDays === 90)
      return { saturdayLines: [] as string[], weekAreas: [] as { x1: string; x2: string }[] }

    // Collect indices of every Saturday (day 6) in the data.
    const saturdays: number[] = []
    for (let i = 0; i < chartData.length; i++) {
      if (new Date(chartData[i].fullDate + 'T12:00:00').getDay() === 6) {
        saturdays.push(i)
      }
    }

    // Vertical lines at every Saturday.
    const lines = saturdays.map((idx) => chartData[idx].date)

    // Shaded areas between consecutive Saturdays (exactly 7 days each).
    // Band edges align perfectly with the dashed Saturday lines.
    const areas: { x1: string; x2: string }[] = []
    for (let i = 0; i < saturdays.length - 1; i++) {
      if (i % 2 === 0) {
        areas.push({
          x1: chartData[saturdays[i]].date,
          x2: chartData[saturdays[i + 1]].date,
        })
      }
    }

    return { saturdayLines: lines, weekAreas: areas }
  }, [chartData, chartDays])

  const totalConsumed = usageHistory.data?.totals?.consumed ?? 0
  const totalOperations = usageHistory.data?.totals?.operations ?? 0

  /* ── Early returns ── */
  if (credits.isLoading) return <PageLoading />
  if (credits.isError) return <div className="text-red-500 p-4">{t('Error loading usage data')}</div>

  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 renewLabel = subRenewAt
    ? new Date(subRenewAt).toLocaleDateString(isRtl() ? 'he-IL' : 'en-US', { day: 'numeric', month: 'short' })
    : null

  return (
    <div className="space-y-6" data-wizard-id="credits-content">
      {/* ── Header ── */}
      <PageHeader
        title={t('Usage & Costs')}
        subtitle={t('BoostCoin – unified coins for conversations, indexing and RAG')}
      />

      {/* ══════════════════════════════════════════════════════════════════
         FREE CREDITS CARD (above the other two, consumed first)
         ══════════════════════════════════════════════════════════════════ */}
      {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-gray-500">
                <Gift className="w-4 h-4 text-emerald-500" />
                <span>{t('Free BoostCoin')}</span>
              </div>
              <Badge variant="success" size="sm">{t('Installation Gift')}</Badge>
            </div>
            <div className="text-3xl font-bold text-gray-900 tabular-nums">{formatCredits(freeRemaining)}</div>
            <div className="mt-3">
              <div className="flex justify-between text-xs text-gray-400 mb-1">
                <span>{t('Used:')} {formatCredits(freeUsed)}</span>
                <span>{t('Total:')} {formatCredits(freeTotal)}</span>
              </div>
              <div className="h-2 bg-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-gray-400 mt-2">
              {freeRemaining > 0
                ? t('Consumed first before any other type. Identical to regular BoostCoin — same AI model and same quality.')
                : t('All free BoostCoin have been used. Consumption continues from subscription or purchased.')}
            </p>
          </CardContent>
        </Card>
      )}

      {/* ══════════════════════════════════════════════════════════════════
         TWO CREDIT BALANCE CARDS
         RTL: Right = accumulated (purchased), Left = subscription
         ══════════════════════════════════════════════════════════════════ */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Purchased / Accumulated credits (RTL first = right) */}
        <Card>
          <CardContent className="py-5">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2 text-sm text-gray-500">
                <Sparkles className="w-4 h-4 text-primary-500" />
                <span>{t('Purchased BoostCoin')}</span>
              </div>
              <Badge variant="primary" size="sm">{t('Accumulative')}</Badge>
            </div>
            <div className="text-3xl font-bold text-gray-900 tabular-nums">{formatCredits(purchasedRemaining)}</div>
            <div className="mt-3">
              <div className="flex justify-between text-xs text-gray-400 mb-1">
                <span>{t('Used:')} {formatCredits(purchasedUsed)}</span>
                <span>{t('Total:')} {formatCredits(purchasedTotal)}</span>
              </div>
              <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all duration-500 ${
                    purchasedPct > 20 ? 'bg-primary-500' : 'bg-red-500'
                  }`}
                  style={{ width: `${purchasedPct}%` }}
                />
              </div>
            </div>
            <p className="text-[11px] text-gray-400 mt-2">{t('Never expire, accumulate over time')}</p>
          </CardContent>
        </Card>

        {/* Subscription credits (RTL second = left) */}
        <Card>
          <CardContent className="py-5">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2 text-sm text-gray-500">
                <RefreshCw className="w-4 h-4 text-blue-500" />
                <span>{t('Subscription BoostCoin')}</span>
              </div>
              {subStatus === 'active' ? (
                <Badge variant="success" size="sm">{t('Active')}</Badge>
              ) : subStatus === 'paused' ? (
                <Badge variant="warning" size="sm">{t('Paused')}</Badge>
              ) : subStatus === 'cancelled' ? (
                <Badge variant="danger" size="sm">{t('Cancelled')}</Badge>
              ) : (
                <Badge variant="default" size="sm">{t('No Subscription')}</Badge>
              )}
            </div>
            <div className="text-3xl font-bold text-gray-900 tabular-nums">
              {subStatus !== 'none' ? formatCredits(subRemaining) : '—'}
            </div>
            <div className="mt-3">
              {subStatus !== 'none' ? (
                <>
                  <div className="flex justify-between text-xs text-gray-400 mb-1">
                    <span>{t('Used:')} {formatCredits(subUsed)}</span>
                    <span>{t('Allowance:')} {formatCredits(subTotal)}</span>
                  </div>
                  <div className="h-2 bg-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-gray-400 flex items-center gap-1">
                  <Calendar className="w-3 h-3" />
                  {t('Renews:')} {renewLabel}
                </span>
              )}
              {subStatus === 'none' && (
                <span className="text-[11px] text-gray-400">{t('Reset monthly; no accumulation')}</span>
              )}
              {subStatus !== 'none' && !renewLabel && (
                <span className="text-[11px] text-gray-400">{t('Reset monthly; no accumulation')}</span>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* ── Consumption priority note ── */}
      <p className="text-[11px] text-gray-400 text-center -mt-2">
        {t('Consumption order: Free ← Subscription ← Purchased')} &nbsp;|&nbsp; {t('All BoostCoin types use the same AI model and quality')}
      </p>

      {/* ── Blocked / no-credits warning ── */}
      {blocked && (
        <div className="p-4 rounded-xl border border-amber-200 bg-amber-50 text-amber-900 text-sm">
          <span className="font-semibold">
            {siteStatus === 'disabled' ? t('Service is disabled — ') : t('No BoostCoin available — ')}
          </span>
          {siteStatus === 'disabled'
            ? t('This site has been disabled. Please contact support.')
            : t('All BoostCoin have been used. Purchase a package to continue.')}
        </div>
      )}

      {/* ══════════════════════════════════════════════════════════════════
         CREDIT USAGE CHART
         ══════════════════════════════════════════════════════════════════ */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between flex-wrap gap-3">
            <CardTitle className="flex items-center gap-2">
              <BarChart3 className="w-5 h-5 text-primary-500" />
              {t('BoostCoin Usage')}
            </CardTitle>
            <div className="flex items-stretch bg-gray-100/80 rounded-xl p-1 gap-0.5">
              {[
                { v: 7, l: t('7 days') },
                { v: 14, l: t('14 days') },
                { v: 30, l: t('30 days') },
                { v: 90, l: t('90 days') },
              ].map((opt) => (
                <button
                  key={opt.v}
                  type="button"
                  onClick={() => setChartDays(opt.v)}
                  className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all duration-150 border-none cursor-pointer ${
                    chartDays === opt.v
                      ? 'bg-white text-primary-600 shadow-sm'
                      : 'bg-transparent text-gray-500 hover:text-gray-700'
                  }`}
                >
                  {opt.l}
                </button>
              ))}
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {usageHistory.isLoading ? (
            <div className="text-center py-12 text-gray-400">{t('Loading usage data...')}</div>
          ) : usageHistory.isError ? (
            <div className="text-center py-12 text-red-400">
              {t('Error loading usage data. Please try again.')}
            </div>
          ) : chartData.length === 0 ? (
            <div className="text-center py-12 text-gray-400">
              <TrendingDown className="w-8 h-8 mx-auto mb-2 text-gray-300" />
              {t('No usage data for this period')}
            </div>
          ) : (
            <>
              {/* Summary stats */}
              <div className="flex items-center gap-6 mb-4 text-sm">
                <div>
                  <span className="text-gray-400">{t('Total consumed:')} </span>
                  <span className="font-semibold text-gray-900 tabular-nums">{Math.ceil(totalConsumed).toLocaleString()}</span>
                  <span className="text-gray-400"> {t('BoostCoin')}</span>
                </div>
                <div>
                  <span className="text-gray-400">{t('Operations:')} </span>
                  <span className="font-semibold text-gray-900 tabular-nums">{totalOperations.toLocaleString()}</span>
                </div>
              </div>

              {/* Chart – fixed height prevents ResponsiveContainer infinite-growth loop */}
              <div className="h-52 overflow-hidden">
                <ResponsiveContainer width="100%" height={208}>
                  <AreaChart data={chartData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
                    <defs>
                      <linearGradient id="gradCredits" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#6366f1" stopOpacity={0.2} />
                        <stop offset="95%" stopColor="#6366f1" stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                    {/* Alternating week bands (exactly 7 days each, Sun–Sat) */}
                    {weekAreas.map((band, i) => (
                      <ReferenceArea
                        key={`wa-${i}`}
                        x1={band.x1}
                        x2={band.x2}
                        fill="#6366f1"
                        fillOpacity={0.045}
                        strokeOpacity={0}
                      />
                    ))}
                    {/* Thin vertical lines at every Saturday (Shabbat) */}
                    {saturdayLines.map((d, i) => (
                      <ReferenceLine
                        key={`sl-${i}`}
                        x={d}
                        stroke="#cbd5e1"
                        strokeWidth={1}
                        strokeDasharray="4 3"
                      />
                    ))}
                    <XAxis
                      dataKey="date"
                      tick={{ fontSize: 11, fill: '#9ca3af' }}
                      tickLine={false}
                      axisLine={{ stroke: '#e5e7eb' }}
                      reversed
                    />
                    <YAxis
                      tick={{ fontSize: 11, fill: '#9ca3af' }}
                      tickLine={false}
                      axisLine={false}
                      width={45}
                    />
                    <Tooltip
                      contentStyle={{
                        background: '#fff',
                        border: '1px solid #e5e7eb',
                        borderRadius: '0.75rem',
                        fontSize: '0.8125rem',
                        direction: isRtl() ? 'rtl' : 'ltr',
                      }}
                      formatter={(value: number) => [`${Math.ceil(value).toLocaleString()} ${t('BoostCoin')}`, t('Consumed')]}
                      labelFormatter={(label: string) => label}
                    />
                    <Area
                      type="monotone"
                      dataKey="consumed"
                      stroke="#6366f1"
                      strokeWidth={2}
                      fill="url(#gradCredits)"
                      dot={false}
                      activeDot={{ r: 4, fill: '#6366f1' }}
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>

              {/* Category breakdown — merge related categories */}
              {(usageHistory.data?.categories?.length ?? 0) > 0 && (() => {
                const CATEGORY_MAP: Record<string, string> = {
                  'chat': t('Conversations'),
                  'chat:stream': t('Conversations'),
                  'chat:orchestrate': t('Conversations'),
                  'chat:execute:quick': t('Conversations'),
                  'chat:respond:quick': t('Conversations'),
                  'chat:respond:initial': t('Conversations'),
                  'chat:respond:followup': t('Conversations'),
                  'chat:respond:proactive': t('Conversations'),
                  'chat:summary': t('Conversations'),
                  'indexing': t('Indexing'),
                  'rag:rerank': t('Knowledge Retrieval'),
                  'rag:router': t('Knowledge Retrieval'),
                  'rag:prepare': t('Knowledge Retrieval'),
                  'rag:compress': t('Knowledge Retrieval'),
                  'rag:tools': t('Knowledge Retrieval'),
                  'raptor': t('Knowledge Retrieval'),
                  'autofill': t('Brand Card'),
                  'llm:quick': t('AI Features'),
                }
                const getDisplayCategory = (cat: string): string => {
                  if (CATEGORY_MAP[cat]) return CATEGORY_MAP[cat]
                  const parts = cat.split(':')
                  while (parts.length > 1) {
                    parts.pop()
                    const prefix = parts.join(':')
                    if (CATEGORY_MAP[prefix]) return CATEGORY_MAP[prefix]
                  }
                  return cat
                }
                const merged = new Map<string, number>()
                for (const cat of usageHistory.data!.categories) {
                  const label = getDisplayCategory(cat.category)
                  merged.set(label, (merged.get(label) ?? 0) + cat.consumed)
                }
                return (
                  <div className="flex flex-wrap gap-3 mt-4 pt-3 border-t border-gray-100">
                    {[...merged.entries()].map(([label, consumed]) => (
                      <div key={label} className="text-xs text-gray-500">
                        <span className="inline-block w-2 h-2 rounded-full bg-primary-400 me-1" />
                        {label}{' '}
                        <span className="font-medium text-gray-700">{Math.ceil(consumed).toLocaleString()}</span>
                      </div>
                    ))}
                  </div>
                )
              })()}
            </>
          )}
        </CardContent>
      </Card>

      {/* ═══════════════════════════════════════════════════════════════════
         ONE-TIME CREDIT PACKAGES
         ═══════════════════════════════════════════════════════════════════ */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <ShoppingCart className="w-5 h-5 text-primary-500" />
            {t('One-Time Purchase')}
          </CardTitle>
        </CardHeader>
        <CardContent>
          {catalog.isLoading ? (
            <div className="text-center py-10 text-gray-400">{t('Loading packages...')}</div>
          ) : catalog.isError ? (
            <div className="text-center py-10 text-red-400">
              {t('Error loading packages. Please try again.')}
            </div>
          ) : packages.length === 0 ? (
            <div className="text-center py-10 text-gray-400">{t('No packages available at this time')}</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-gray-900 tabular-nums">
                    {sym}
                    {fmtPrice(selPkg.price, currency)}
                  </div>
                  <div className="flex items-center gap-3 text-sm text-gray-500">
                    <span>{selPkg.credits.toLocaleString()} {t('BoostCoin')}</span>
                    {showDiscounts && selPkgDisc > 0 && (
                      <>
                        <span className="text-gray-200">•</span>
                        <Badge variant="success">{sprintf(t('%s%% discount'), String(selPkgDisc))}</Badge>
                      </>
                    )}
                  </div>
                  <Button
                    size="lg"
                    className="mt-2 min-w-[180px]"
                    onClick={openOneTimePurchaseInline}
                    disabled={paypalConfigLoading}
                    loading={paypalConfigLoading}
                  >
                    <ShoppingCart className="w-4 h-4 me-2" />
                    {t('Purchase')}
                  </Button>

                  {paypalInlineOpen && (
                    <div className="w-full max-w-[420px] mt-3 border border-gray-200 rounded-xl p-3 bg-gray-50/60">
                      {(paypalConfigLoading || paypalButtonsLoading || !paypalButtonsReady) && !paypalError && (
                        <div className="flex items-center gap-2 text-sm text-gray-500 mb-2">
                          <span className="inline-block w-4 h-4 border-2 border-gray-300 border-t-primary-500 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={paypalButtonsHostRef} className="min-h-[120px]" />

                      <div className="mt-2 flex items-center justify-between gap-2">
                        <p className="text-xs text-gray-400">
                          {t('You can pay with a PayPal account or credit card via PayPal.')}
                        </p>
                        <button
                          type="button"
                          className="text-xs text-gray-500 hover:text-gray-700 border-none bg-transparent cursor-pointer"
                          onClick={() => {
                            if (!paypalFlowBusy) setPaypalInlineOpen(false)
                          }}
                        >
                          {t('Close')}
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              )}

              <PricingTable
                rows={pkgRows}
                selectedIndex={sPkgI}
                onSelect={setPkgIdx}
                colLabel={t('Package')}
                showDiscount={showDiscounts}
              />

              <p className="text-xs text-gray-400 mt-4 text-center">
                {t('Purchased BoostCoin never expire and always accumulate. Coins are consumed for API calls to various AI models (conversations, indexing, RAG and more).')}
              </p>
            </>
          )}
        </CardContent>
      </Card>

      {/* ═══════════════════════════════════════════════════════════════════
         MONTHLY SUBSCRIPTIONS
         ═══════════════════════════════════════════════════════════════════ */}
      {(catalog.data?.subscriptions?.length ?? 0) > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <RefreshCw className="w-5 h-5 text-primary-500" />
              {t('Monthly Subscription')}
            </CardTitle>
            {subStatus === 'active' && (
              <div className="mt-2 text-xs text-amber-600 bg-amber-50 rounded-lg px-3 py-2">
                {t('You currently have an active subscription. You can cancel or change plans via PayPal.')}
              </div>
            )}
          </CardHeader>
          <CardContent>
            {subs.length === 0 ? (
              <div className="text-center py-10 text-gray-400">{t('No plans available at this time')}</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-gray-900 tabular-nums">
                      {sym}
                      {fmtPrice(selSub.price, currency)}
                      <span className="text-base font-normal text-gray-400 ms-1">/{t('month')}</span>
                    </div>
                    <div className="flex items-center gap-3 text-sm text-gray-500">
                      <span>{sprintf(t('%s BoostCoin per month'), selSub.allowance.toLocaleString())}</span>
                      {showDiscounts && selSubDisc > 0 && (
                        <>
                          <span className="text-gray-200">•</span>
                          <Badge variant="success">{sprintf(t('%s%% discount'), String(selSubDisc))}</Badge>
                        </>
                      )}
                    </div>
                    <Button
                      size="lg"
                      className="mt-2 min-w-[180px]"
                      onClick={async () => {
                        try {
                          if (
                            subStatus === 'active' &&
                            !window.confirm(
                              t('You already have an active subscription. This action may create an additional subscription. Continue?'),
                            )
                          ) {
                            return
                          }
                          const r = await createSub.mutateAsync({ package_id: selSub.id })
                          if (r?.approval_url) window.location.href = r.approval_url
                        } catch (e: any) {
                          alert(e?.message || t('Failed to create subscription'))
                        }
                      }}
                      disabled={createSub.isPending}
                      loading={createSub.isPending}
                    >
                      <Zap className="w-4 h-4 me-2" />
                      {t('Subscribe')}
                    </Button>
                  </div>
                )}

                <PricingTable
                  rows={subRows}
                  selectedIndex={sSubI}
                  onSelect={setSubIdx}
                  colLabel={t('Plan')}
                  showDiscount={showDiscounts}
                />

                <p className="text-xs text-gray-400 mt-4 text-center">
                  {t('Subscription BoostCoin reset each billing cycle; no accumulation.')}
                </p>
              </>
            )}
          </CardContent>
        </Card>
      )}

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