'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'next/navigation';
import {
  CreditCard, Download, Check, Zap, TrendingUp, MessageSquare,
  Phone, GitBranch, AlertCircle, Star, ChevronRight,
  Receipt, Shield, ArrowUpCircle, ArrowDownCircle, Loader2,
  ExternalLink, CheckCircle2, XCircle, X
} from 'lucide-react';
import {
  getSubscription, getUsage, listPlans as fetchPlans,
  startCheckout, openCustomerPortal, listInvoices, getPaymentMethod,
  createSetupIntent, updatePaymentMethod,
  BillingSubscription, BillingUsage, Plan, StripeInvoice, PaymentMethod
} from '@client/api/billing';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { toast } from 'sonner';
import { loadStripe } from '@stripe/stripe-js';
import { Elements, CardElement, useStripe, useElements } from '@stripe/react-stripe-js';

type TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;

async function resolveStripePublishableKey(): Promise<string | null> {
  const envKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;
  if (envKey) return envKey;
  try {
    const res = await fetch('/api/billing/stripe-config');
    if (res.ok) {
      const data = await res.json();
      if (data.publishableKey) return data.publishableKey as string;
    }
  } catch {}
  return null;
}

type Tab = 'overview' | 'plans' | 'payment' | 'invoices';

const usageIcons: Record<string, React.ReactNode> = {
  conversations: <MessageSquare size={16} />,
  voiceMinutes: <Phone size={16} />,
  branches: <GitBranch size={16} />,
  apiCalls: <Zap size={16} />,
};

const usageLabels: Record<string, string> = {
  conversations: 'AI Conversations',
  voiceMinutes: 'Voice Minutes',
  branches: 'Branches',
  apiCalls: 'API Calls',
};

const usageUnits: Record<string, string> = {
  conversations: 'conversations',
  voiceMinutes: 'minutes',
  branches: 'branches',
  apiCalls: 'calls',
};

const usageColors: Record<string, string> = {
  conversations: 'hsl(22, 89%, 48%)',
  voiceMinutes: 'hsl(210, 100%, 40%)',
  branches: 'hsl(142, 72%, 29%)',
  apiCalls: 'hsl(270, 60%, 50%)',
};

const limitKeys: Record<string, string> = {
  conversations: 'conversations_per_month',
  voiceMinutes: 'concurrent_voice_calls',
  branches: 'max_branches',
  apiCalls: 'api_calls_per_minute',
};

const planColors: Record<string, string> = {
  Starter: 'hsl(210, 100%, 40%)',
  Growth: 'hsl(142, 72%, 29%)',
  Pro: 'hsl(22, 89%, 48%)',
  Enterprise: 'hsl(231, 40%, 14%)',
};

const brandColors: Record<string, string> = {
  visa: '#1a1f71',
  mastercard: '#eb001b',
  amex: '#007bc1',
  discover: '#ff6600',
};

function UpdateCardForm({ clientSecret, onSuccess, onCancel, t }: { clientSecret: string; onSuccess: () => void; onCancel: () => void; t: TFn }) {
  const stripe = useStripe();
  const elements = useElements();
  const [saving, setSaving] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!stripe || !elements) return;
    setSaving(true);
    try {
      const cardElement = elements.getElement(CardElement);
      if (!cardElement) throw new Error(t('billing.cardElementNotMounted', 'Card element not mounted'));
      const { setupIntent, error } = await stripe.confirmCardSetup(clientSecret, {
        payment_method: { card: cardElement },
      });
      if (error) throw new Error(error.message ?? t('billing.cardSetupFailed', 'Card setup failed'));
      if (setupIntent?.payment_method) {
        await updatePaymentMethod(
          typeof setupIntent.payment_method === 'string'
            ? setupIntent.payment_method
            : setupIntent.payment_method.id
        );
      }
      toast.success(t('billing.paymentMethodUpdated', 'Payment method updated successfully'));
      onSuccess();
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('billing.failedToUpdatePaymentMethod', 'Failed to update payment method'));
    } finally {
      setSaving(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="p-3 rounded-xl border" style={{ backgroundColor: 'hsl(var(--background))', borderColor: 'hsl(var(--border))' }}>
        <CardElement options={{ style: { base: { fontSize: '14px', color: 'hsl(220, 9%, 80%)', '::placeholder': { color: 'hsl(220, 9%, 50%)' } } } }} />
      </div>
      <div className="flex gap-3">
        <button type="button" onClick={onCancel} className="flex-1 btn-secondary">{t('billing.cancel', 'Cancel')}</button>
        <button
          type="submit"
          disabled={!stripe || saving}
          className="flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-white disabled:opacity-70 transition-opacity hover:opacity-90"
          style={{ backgroundColor: 'hsl(var(--primary))' }}
        >
          {saving ? <Loader2 size={14} className="animate-spin" /> : <CreditCard size={14} />}
          {t('billing.saveCard', 'Save Card')}
        </button>
      </div>
    </form>
  );
}

export default function CustomerBillingPage() {
  const { t, currentLang } = useLanguage();
  usePageHeader(t('billing.title', 'Billing & Subscription'), t('billing.subtitle', 'Manage your plan, usage, and payment details'));
  const searchParams = useSearchParams();
  const [activeTab, setActiveTab] = useState<Tab>('overview');
  const [billingCycle, setBillingCycle] = useState<'monthly' | 'annual'>('monthly');
  const [checkoutLoading, setCheckoutLoading] = useState<string | null>(null);
  const [portalLoading, setPortalLoading] = useState(false);
  const [cancelLoading, setCancelLoading] = useState(false);
  const [showCancelDialog, setShowCancelDialog] = useState(false);
  const [showUpdateCard, setShowUpdateCard] = useState(false);
  const [setupClientSecret, setSetupClientSecret] = useState<string | null>(null);
  const [setupLoading, setSetupLoading] = useState(false);

  const [subscription, setSubscription] = useState<BillingSubscription | null>(null);
  const [usage, setUsage] = useState<BillingUsage | null>(null);
  const [plans, setPlans] = useState<Plan[]>([]);
  const [invoices, setInvoices] = useState<StripeInvoice[]>([]);
  const [paymentMethod, setPaymentMethod] = useState<PaymentMethod | null>(null);
  const [loading, setLoading] = useState(true);
  const [invoicesLoading, setInvoicesLoading] = useState(false);
  const [paymentLoading, setPaymentLoading] = useState(false);
  const [stripePromise, setStripePromise] = useState<ReturnType<typeof loadStripe> | null>(null);

  useEffect(() => {
    resolveStripePublishableKey().then(pk => {
      if (pk) setStripePromise(loadStripe(pk));
    });
  }, []);

  const trialExpiredReason = searchParams.get('reason') === 'trial_expired';
  const featureNotIncludedReason = searchParams.get('reason') === 'feature_not_included';

  useEffect(() => {
    const checkoutStatus = searchParams.get('checkout');
    if (checkoutStatus === 'success') {
      toast.success(t('billing.paymentSuccessful', 'Payment successful! Your subscription is now active.'));
    } else if (checkoutStatus === 'cancelled') {
      toast.info(t('billing.checkoutCancelled', 'Checkout was cancelled. No charges were made.'));
    }
  }, [searchParams, t]);

  useEffect(() => {
    Promise.all([getSubscription(), getUsage(), fetchPlans()])
      .then(([sub, usg, pls]) => {
        setSubscription(sub);
        setUsage(usg);
        setPlans(pls);
      })
      .catch(() => toast.error(t('billing.failedToLoadData', 'Failed to load billing data')))
      .finally(() => setLoading(false));
  }, [t]);

  const loadInvoices = useCallback(async () => {
    setInvoicesLoading(true);
    try {
      const data = await listInvoices();
      setInvoices(data);
    } catch {
      toast.error(t('billing.failedToLoadInvoices', 'Failed to load invoices'));
    } finally {
      setInvoicesLoading(false);
    }
  }, [t]);

  const loadPaymentMethod = useCallback(async () => {
    setPaymentLoading(true);
    try {
      const pm = await getPaymentMethod();
      setPaymentMethod(pm);
    } catch {
      toast.error(t('billing.failedToLoadPaymentMethod', 'Failed to load payment method'));
    } finally {
      setPaymentLoading(false);
    }
  }, [t]);

  useEffect(() => {
    if (activeTab === 'invoices' && invoices.length === 0) loadInvoices();
  }, [activeTab, invoices.length, loadInvoices]);

  useEffect(() => {
    if (activeTab === 'payment') loadPaymentMethod();
  }, [activeTab, loadPaymentMethod]);

  const handleSelectPlan = async (plan: Plan, cycle: 'monthly' | 'annual' = billingCycle) => {
    setCheckoutLoading(plan.id);
    try {
      const url = await startCheckout(plan.id, cycle);
      try {
        const parsed = new URL(url);
        if (parsed.protocol !== 'https:' || !(parsed.hostname === 'stripe.com' || parsed.hostname.endsWith('.stripe.com'))) {
          throw new Error('Untrusted checkout URL');
        }
        window.location.href = url;
      } catch {
        throw new Error('Invalid checkout URL');
      }
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : t('billing.failedToStartCheckout', 'Failed to start checkout');
      toast.error(msg);
    } finally {
      setCheckoutLoading(null);
    }
  };

  const handleUpgradePlan = async () => {
    const sorted = [...plans].sort((a, b) => a.priceMonthly - b.priceMonthly);
    const nextPlan = sorted.find(p => p.priceMonthly > planPrice);
    if (nextPlan) {
      await handleSelectPlan(nextPlan, 'monthly');
    } else {
      setActiveTab('plans');
    }
  };

  const handleManagePayment = async () => {
    setPortalLoading(true);
    try {
      const url = await openCustomerPortal();
      window.location.href = url;
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : t('billing.failedToOpenPortal', 'Failed to open payment portal');
      toast.error(msg);
    } finally {
      setPortalLoading(false);
    }
  };

  const handleCancelSubscription = async () => {
    setCancelLoading(true);
    try {
      const url = await openCustomerPortal();
      setShowCancelDialog(false);
      window.location.href = url;
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : t('billing.failedToOpenCancelPortal', 'Failed to open cancellation portal');
      toast.error(msg);
    } finally {
      setCancelLoading(false);
    }
  };

  const handleOpenUpdateCard = async () => {
    if (!stripePromise) {
      toast.error(t('billing.stripeNotConfigured', 'Stripe is not configured. Please contact your administrator.'));
      return;
    }
    setSetupLoading(true);
    try {
      const secret = await createSetupIntent();
      setSetupClientSecret(secret);
      setShowUpdateCard(true);
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('billing.failedToStartCardUpdate', 'Failed to start card update'));
    } finally {
      setSetupLoading(false);
    }
  };

  const tabs: { key: Tab; label: string; icon: React.ReactNode }[] = [
    { key: 'overview', label: t('billing.tabOverview', 'Overview'), icon: <TrendingUp size={15} /> },
    { key: 'plans', label: t('billing.tabPlans', 'Plans'), icon: <Star size={15} /> },
    { key: 'payment', label: t('billing.tabPayment', 'Payment Methods'), icon: <CreditCard size={15} /> },
    { key: 'invoices', label: t('billing.tabInvoices', 'Invoices'), icon: <Receipt size={15} /> },
  ];

  if (loading) {
    return (
      <>
        <div className="flex items-center justify-center py-20 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Loader2 size={20} className="animate-spin" /> {t('billing.loadingData', 'Loading billing data…')}
        </div>
      </>
    );
  }

  const planName = subscription?.planName ?? t('billing.noPlan', 'No Plan');
  const planPrice = subscription?.priceMonthly ?? 0;
  const planLimits = subscription?.limits ?? {};
  const planColor = planColors[planName] ?? 'hsl(var(--primary))';
  const memberSince = subscription ? new Date(subscription.createdAt).toLocaleDateString(currentLang, { month: 'short', year: 'numeric' }) : '—';
  const isPastDue = subscription?.status === 'past_due';

  const usageEntries = usage ? [
    { key: 'conversations', used: usage.conversations, label: t('billing.usageConversations', 'AI Conversations'), unit: t('billing.unitConversations', 'conversations') },
    { key: 'voiceMinutes', used: usage.voiceMinutes, label: t('billing.usageVoiceMinutes', 'Voice Minutes'), unit: t('billing.unitMinutes', 'minutes') },
    { key: 'branches', used: usage.branches, label: t('billing.usageBranches', 'Branches'), unit: t('billing.unitBranches', 'branches') },
    { key: 'apiCalls', used: usage.apiCalls, label: t('billing.usageApiCalls', 'API Calls'), unit: t('billing.unitCalls', 'calls') },
  ] : [];

  const isTrialActive = subscription?.status === 'trial' && subscription?.trialEnd && new Date(subscription.trialEnd) > new Date();
  const trialDaysLeft = isTrialActive && subscription?.trialEnd
    ? Math.ceil((new Date(subscription.trialEnd).getTime() - Date.now()) / (1000 * 60 * 60 * 24))
    : 0;

  return (
    <>
      {trialExpiredReason && (
        <div className="rounded-2xl p-6 mb-6 border-2" style={{ backgroundColor: 'hsl(0 84% 60% / 0.06)', borderColor: 'hsl(0 84% 60% / 0.4)' }}>
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0" style={{ backgroundColor: 'hsl(0 84% 60% / 0.12)' }}>
              <XCircle size={24} className="text-red-500" />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-bold mb-1 text-red-600">{t('billing.trialEndedTitle', 'Your 14-day free trial has ended')}</h3>
              <p className="text-sm mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('billing.trialEndedDesc', 'To continue using RestroAgent, please choose a plan below. All your data is safe and will be restored once you subscribe.')}
              </p>
              <button
                onClick={() => setActiveTab('plans')}
                className="btn-primary flex items-center gap-2"
              >
                <ArrowUpCircle size={15} /> {t('billing.viewPlansSubscribe', 'View Plans & Subscribe')}
              </button>
            </div>
          </div>
        </div>
      )}

      {featureNotIncludedReason && (
        <div className="rounded-2xl p-6 mb-6 border-2" style={{ backgroundColor: 'hsl(25 95% 53% / 0.06)', borderColor: 'hsl(25 95% 53% / 0.4)' }}>
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0" style={{ backgroundColor: 'hsl(25 95% 53% / 0.12)' }}>
              <ArrowUpCircle size={24} style={{ color: 'hsl(25, 95%, 53%)' }} />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-bold mb-1" style={{ color: 'hsl(25, 95%, 53%)' }}>{t('billing.featureNotIncludedTitle', 'Feature not included in your plan')}</h3>
              <p className="text-sm mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('billing.featureNotIncludedDesc', 'The feature you tried to access requires a higher plan. Upgrade your subscription to unlock it.')}
              </p>
              <button
                onClick={() => setActiveTab('plans')}
                className="btn-primary flex items-center gap-2"
              >
                <ArrowUpCircle size={15} /> {t('billing.viewPlansUpgrade', 'View Plans & Upgrade')}
              </button>
            </div>
          </div>
        </div>
      )}

      {isTrialActive && !trialExpiredReason && (
        <div className="flex items-center gap-3 p-4 rounded-xl mb-5 border" style={{ backgroundColor: 'hsl(210 100% 40% / 0.07)', borderColor: 'hsl(210 100% 40% / 0.3)' }}>
          <Star size={18} style={{ color: 'hsl(210, 100%, 40%)' }} className="flex-shrink-0" />
          <div className="flex-1">
            <p className="text-sm font-semibold" style={{ color: 'hsl(210, 100%, 40%)' }}>{t('billing.freeTrialActive', 'Free trial active')}</p>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('billing.trialDaysRemaining', '{{days}} day{{plural}} remaining · Trial ends {{date}}', {
                days: trialDaysLeft,
                plural: trialDaysLeft !== 1 ? 's' : '',
                date: new Date(subscription!.trialEnd!).toLocaleDateString(currentLang, { month: 'long', day: 'numeric', year: 'numeric' })
              })}
            </p>
          </div>
          <button onClick={() => setActiveTab('plans')} className="btn-secondary text-sm flex items-center gap-1.5 flex-shrink-0">
            <ArrowUpCircle size={14} /> {t('billing.upgrade', 'Upgrade')}
          </button>
        </div>
      )}

      {isPastDue && (
        <div className="flex items-center gap-3 p-4 rounded-xl mb-5 border" style={{ backgroundColor: 'hsl(0 84% 60% / 0.08)', borderColor: 'hsl(0 84% 60% / 0.3)' }}>
          <AlertCircle size={18} className="text-red-500 flex-shrink-0" />
          <div>
            <p className="text-sm font-semibold text-red-600">{t('billing.paymentPastDue', 'Payment past due')}</p>
            <p className="text-xs text-red-500 mt-0.5">{t('billing.paymentFailedDesc', 'Your last payment failed. Please update your payment method to avoid service interruption.')}</p>
          </div>
          <button onClick={handleManagePayment} disabled={portalLoading} className="ml-auto flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-white bg-red-500 hover:bg-red-600 transition-colors flex-shrink-0">
            {portalLoading ? <Loader2 size={12} className="animate-spin" /> : <CreditCard size={12} />}
            {t('billing.updatePayment', 'Update Payment')}
          </button>
        </div>
      )}

      <div className="flex gap-1 p-1 rounded-xl mb-6 w-fit" style={{ backgroundColor: 'hsl(var(--muted))' }}>
        {tabs.map(t => (
          <button
            key={t.key}
            onClick={() => setActiveTab(t.key)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === t.key ? 'bg-white shadow-sm' : ''}`}
            style={{ color: activeTab === t.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
          >
            {t.icon} {t.label}
          </button>
        ))}
      </div>

      {activeTab === 'overview' && (
        <div className="space-y-5">
          <div className="card p-6" style={{ borderLeft: `4px solid ${planColor}` }}>
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 rounded-xl flex items-center justify-center" style={{ backgroundColor: `${planColor}20` }}>
                  <Shield size={22} style={{ color: planColor }} />
                </div>
                <div>
                  <div className="flex items-center gap-2 mb-0.5">
                    <span className="text-lg font-bold" style={{ color: 'hsl(var(--foreground))' }}>{planName} Plan</span>
                    {subscription?.status === 'active' && (
                      <span className="px-2 py-0.5 rounded-full text-xs font-semibold text-white" style={{ backgroundColor: 'hsl(142, 72%, 29%)' }}>{t('billing.statusActive', 'Active')}</span>
                    )}
                    {subscription?.status === 'trial' && (
                      <span className="px-2 py-0.5 rounded-full text-xs font-semibold text-white" style={{ backgroundColor: 'hsl(210, 100%, 40%)' }}>{t('billing.statusTrial', 'Trial')}</span>
                    )}
                    {isPastDue && (
                      <span className="px-2 py-0.5 rounded-full text-xs font-semibold text-white bg-red-500">{t('billing.pastDue', 'Past Due')}</span>
                    )}
                    {subscription?.status === 'cancelled' && (
                      <span className="px-2 py-0.5 rounded-full text-xs font-semibold text-white" style={{ backgroundColor: 'hsl(var(--muted-foreground))' }}>{t('billing.statusCancelled', 'Cancelled')}</span>
                    )}
                  </div>
                  <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    ${planPrice}/month
                    {subscription?.currentPeriodEnd && ` · ${t('billing.nextBilling', 'Next billing')}: ${new Date(subscription.currentPeriodEnd).toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' })}`}
                  </p>
                </div>
              </div>
              <div className="flex gap-2 flex-wrap">
                <button onClick={handleUpgradePlan} disabled={checkoutLoading !== null} className="btn-primary flex items-center gap-2">
                  {checkoutLoading !== null ? <Loader2 size={15} className="animate-spin" /> : <ArrowUpCircle size={15} />} Upgrade Plan
                </button>
                {subscription?.stripeSubscriptionId && (
                  <button onClick={handleManagePayment} disabled={portalLoading} className="btn-secondary flex items-center gap-2">
                    {portalLoading ? <Loader2 size={14} className="animate-spin" /> : <CreditCard size={14} />}
                    Manage
                  </button>
                )}
                {subscription?.stripeSubscriptionId && subscription.status === 'active' && (
                  <button
                    onClick={() => setShowCancelDialog(true)}
                    className="flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-medium border transition-colors"
                    style={{ color: 'hsl(0, 84%, 60%)', borderColor: 'hsl(0, 84%, 60% / 0.4)', backgroundColor: 'transparent' }}
                  >
                    <X size={14} /> Cancel Plan
                  </button>
                )}
              </div>
            </div>
          </div>

          <div>
            <h3 className="text-sm font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>Usage This Month</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {usageEntries.map(item => {
                const limitKey = limitKeys[item.key];
                const limit = planLimits[limitKey] ?? 0;
                const pct = limit <= 0 ? 0 : Math.round((item.used / limit) * 100);
                const isWarning = pct >= 80;
                const isCritical = pct >= 95;
                const color = usageColors[item.key];
                return (
                  <div key={item.key} className="card p-5">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ backgroundColor: `${color}15`, color }}>
                          {usageIcons[item.key]}
                        </div>
                        <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{usageLabels[item.key]}</span>
                      </div>
                      {isCritical && <AlertCircle size={16} className="text-red-500" />}
                      {isWarning && !isCritical && <AlertCircle size={16} className="text-amber-500" />}
                    </div>
                    <div className="flex items-end justify-between mb-2">
                      <span className="text-xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>
                        {limit <= 0 ? '∞' : item.used.toLocaleString()}
                      </span>
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {limit <= 0 ? 'Unlimited' : `of ${limit.toLocaleString()} ${usageUnits[item.key]}`}
                      </span>
                    </div>
                    {limit > 0 && (
                      <>
                        <div className="w-full h-2 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                          <div
                            className="h-full rounded-full transition-all"
                            style={{ width: `${Math.min(pct, 100)}%`, backgroundColor: isCritical ? 'hsl(0, 84%, 60%)' : isWarning ? 'hsl(38, 92%, 50%)' : color }}
                          />
                        </div>
                        <div className="flex justify-between mt-1.5">
                          <span className="text-xs font-medium" style={{ color: isCritical ? 'hsl(0, 84%, 60%)' : isWarning ? 'hsl(38, 92%, 50%)' : 'hsl(var(--muted-foreground))' }}>
                            {pct}% used
                          </span>
                        </div>
                      </>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div className="card p-5">
              <p className="text-xs font-semibold uppercase tracking-wider mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.currentPlan', 'Current Plan')}</p>
              <p className="text-2xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>${planPrice.toFixed(2)}/mo</p>
              <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{planName}</p>
            </div>
            <div className="card p-5">
              <p className="text-xs font-semibold uppercase tracking-wider mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.status', 'Status')}</p>
              <p className="text-sm font-semibold capitalize" style={{ color: isPastDue ? 'hsl(0, 84%, 60%)' : 'hsl(var(--foreground))' }}>{subscription?.status ?? '—'}</p>
              <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.subscriptionStatus', 'Subscription status')}</p>
            </div>
            <div className="card p-5">
              <p className="text-xs font-semibold uppercase tracking-wider mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.memberSince', 'Member Since')}</p>
              <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{memberSince}</p>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'plans' && (
        <div className="space-y-5">
          <div className="flex items-center gap-3">
            <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>Billing Cycle:</span>
            <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              {(['monthly', 'annual'] as const).map(c => (
                <button
                  key={c}
                  onClick={() => setBillingCycle(c)}
                  className={`px-4 py-1.5 rounded-lg text-sm font-medium capitalize transition-all ${billingCycle === c ? 'bg-white shadow-sm' : ''}`}
                  style={{ color: billingCycle === c ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
                >
                  {c}
                  {c === 'annual' && <span className="ml-1.5 text-xs font-bold text-green-600">-20%</span>}
                </button>
              ))}
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
            {plans.map(plan => {
              const color = planColors[plan.name] ?? 'hsl(var(--primary))';
              const displayPrice = billingCycle === 'annual' ? Math.round(plan.priceMonthly * 0.8) : plan.priceMonthly;
              const isCurrent = plan.name === planName;
              const isUpgrade = plan.priceMonthly > planPrice;
              const isLoading = checkoutLoading === plan.id;

              return (
                <div
                  key={plan.id}
                  className={`card p-6 relative flex flex-col ${plan.name === 'Pro' ? 'ring-2' : ''}`}
                  style={plan.name === 'Pro' ? { '--tw-ring-color': color } as React.CSSProperties : {}}
                >
                  {plan.name === 'Pro' && (
                    <div className="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 rounded-full text-xs font-bold text-white" style={{ backgroundColor: color }}>
                      Most Popular
                    </div>
                  )}
                  {isCurrent && (
                    <div className="absolute -top-3 right-4 px-3 py-1 rounded-full text-xs font-bold text-white" style={{ backgroundColor: 'hsl(142, 72%, 29%)' }}>
                      Current Plan
                    </div>
                  )}

                  <div className="mb-4">
                    <h3 className="text-lg font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{plan.name}</h3>
                    <div className="flex items-end gap-1">
                      <span className="text-3xl font-bold" style={{ color }}>${displayPrice}</span>
                      <span className="text-sm mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>/mo</span>
                    </div>
                    {billingCycle === 'annual' && (
                      <p className="text-xs text-green-600 font-medium mt-0.5">Save ${(plan.priceMonthly - displayPrice) * 12}/year</p>
                    )}
                  </div>

                  {Object.keys(plan.limits ?? {}).length > 0 && (
                    <div className="grid grid-cols-2 gap-1.5 mb-4">
                      {plan.limits.conversations_per_month != null && (
                        <div className="px-2 py-1.5 rounded-lg text-xs" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                          <span className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                            {plan.limits.conversations_per_month === 0 ? '∞' : plan.limits.conversations_per_month.toLocaleString()}
                          </span>
                          <span className="block" style={{ color: 'hsl(var(--muted-foreground))' }}>Chats/mo</span>
                        </div>
                      )}
                      {plan.limits.api_calls_per_minute != null && (
                        <div className="px-2 py-1.5 rounded-lg text-xs" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                          <span className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                            {plan.limits.api_calls_per_minute === 0 ? '∞' : plan.limits.api_calls_per_minute}
                          </span>
                          <span className="block" style={{ color: 'hsl(var(--muted-foreground))' }}>API calls/min</span>
                        </div>
                      )}
                      {plan.limits.concurrent_voice_calls != null && (
                        <div className="px-2 py-1.5 rounded-lg text-xs" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                          <span className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                            {plan.limits.concurrent_voice_calls === 0 ? '∞' : plan.limits.concurrent_voice_calls}
                          </span>
                          <span className="block" style={{ color: 'hsl(var(--muted-foreground))' }}>Voice calls</span>
                        </div>
                      )}
                      {plan.limits.max_branches != null && (
                        <div className="px-2 py-1.5 rounded-lg text-xs" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                          <span className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                            {plan.limits.max_branches === 0 ? '∞' : plan.limits.max_branches}
                          </span>
                          <span className="block" style={{ color: 'hsl(var(--muted-foreground))' }}>Branches</span>
                        </div>
                      )}
                    </div>
                  )}

                  <ul className="space-y-2 mb-6 flex-1">
                    {plan.features.map(f => (
                      <li key={f} className="flex items-center gap-2 text-sm" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                        <Check size={14} style={{ color, flexShrink: 0 }} />
                        {f}
                      </li>
                    ))}
                  </ul>

                  {isCurrent ? (
                    <button disabled className="w-full py-2.5 rounded-xl text-sm font-semibold opacity-50 cursor-not-allowed" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}>
                      Current Plan
                    </button>
                  ) : (
                    <button
                      onClick={() => handleSelectPlan(plan)}
                      disabled={isLoading}
                      className="w-full py-2.5 rounded-xl text-sm font-bold text-white flex items-center justify-center gap-2 transition-opacity hover:opacity-90 disabled:opacity-70"
                      style={{ backgroundColor: color }}
                    >
                      {isLoading ? (
                        <Loader2 size={15} className="animate-spin" />
                      ) : (
                        <>
                          {isUpgrade ? <ArrowUpCircle size={15} /> : <ArrowDownCircle size={15} />}
                          {isUpgrade ? 'Upgrade' : 'Downgrade'}
                        </>
                      )}
                    </button>
                  )}
                </div>
              );
            })}
          </div>

          <p className="text-xs text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>
            Plan changes take effect immediately. Prorated charges apply for upgrades. Downgrades apply at next billing cycle.
          </p>
        </div>
      )}

      {activeTab === 'payment' && (
        <div className="max-w-2xl space-y-4">
          <div className="flex items-center justify-between mb-2">
            <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.paymentMethods', 'Payment Methods')}</h3>
            {!showUpdateCard && (
              <button
                onClick={handleOpenUpdateCard}
                disabled={setupLoading}
                className="btn-primary flex items-center gap-2"
              >
                {setupLoading ? <Loader2 size={14} className="animate-spin" /> : <CreditCard size={14} />}
                {paymentMethod ? t('billing.updateCard', 'Update Card') : t('billing.addCard', 'Add Card')}
              </button>
            )}
          </div>

          {showUpdateCard && setupClientSecret ? (
            <div className="card p-5">
              <h4 className="text-sm font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>
                {paymentMethod ? t('billing.updatePaymentCard', 'Update Payment Card') : t('billing.addPaymentCard', 'Add Payment Card')}
              </h4>
              <Elements stripe={stripePromise} options={{ clientSecret: setupClientSecret }}>
                <UpdateCardForm
                  clientSecret={setupClientSecret}
                  t={t}
                  onSuccess={() => {
                    setShowUpdateCard(false);
                    setSetupClientSecret(null);
                    loadPaymentMethod();
                  }}
                  onCancel={() => {
                    setShowUpdateCard(false);
                    setSetupClientSecret(null);
                  }}
                />
              </Elements>
            </div>
          ) : paymentLoading ? (
            <div className="flex justify-center py-10">
              <Loader2 size={20} className="animate-spin" style={{ color: 'hsl(var(--muted-foreground))' }} />
            </div>
          ) : paymentMethod ? (
            <div className="card p-5 flex items-center gap-4">
              <div className="w-12 h-8 rounded flex items-center justify-center text-white text-xs font-bold" style={{ backgroundColor: brandColors[paymentMethod.brand] ?? '#333' }}>
                {paymentMethod.brand.toUpperCase().slice(0, 4)}
              </div>
              <div className="flex-1">
                <p className="text-sm font-semibold capitalize" style={{ color: 'hsl(var(--foreground))' }}>
                  {paymentMethod.brand} ending in {paymentMethod.last4}
                </p>
                <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  Expires {String(paymentMethod.expMonth).padStart(2, '0')}/{paymentMethod.expYear}
                </p>
              </div>
              <button
                onClick={handleOpenUpdateCard}
                disabled={setupLoading}
                className="btn-secondary flex items-center gap-1.5 text-sm"
              >
                {setupLoading ? <Loader2 size={14} className="animate-spin" /> : <ChevronRight size={14} />}
                Update
              </button>
            </div>
          ) : (
            <div className="text-center py-12 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <CreditCard size={32} className="mx-auto mb-3 opacity-30" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.noPaymentMethodsOnFile', 'No payment methods on file')}</p>
              <p className="text-xs mt-1 mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.clickAddCardAbove', 'Click "Add Card" above to save a payment method')}</p>
            </div>
          )}

          <div className="flex items-center gap-2 p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            <Shield size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Payment methods are securely managed by Stripe. We never store your card details.</span>
          </div>
        </div>
      )}

      {activeTab === 'invoices' && (
        <div>
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.invoiceHistory', 'Invoice History')}</h3>
          </div>

          {invoicesLoading ? (
            <div className="flex justify-center py-16">
              <Loader2 size={24} className="animate-spin" style={{ color: 'hsl(var(--muted-foreground))' }} />
            </div>
          ) : invoices.length === 0 ? (
            <div className="text-center py-16 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <Receipt size={32} className="mx-auto mb-3 opacity-30" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.noInvoicesYet', 'No invoices yet')}</p>
              <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.invoicesWillAppear', 'Invoices will appear here once your first billing cycle completes')}</p>
            </div>
          ) : (
            <div className="rounded-2xl overflow-hidden border" style={{ borderColor: 'hsl(var(--border))' }}>
              <table className="w-full text-sm">
                <thead>
                  <tr style={{ backgroundColor: 'hsl(var(--muted))' }}>
                    <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.colInvoice', 'Invoice')}</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.colDate', 'Date')}</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.colAmount', 'Amount')}</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.status', 'Status')}</th>
                    <th className="text-right px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.colDownload', 'Download')}</th>
                  </tr>
                </thead>
                <tbody>
                  {invoices.map((inv, i) => (
                    <tr key={inv.id} style={{ borderTop: i > 0 ? '1px solid hsl(var(--border))' : 'none' }}>
                      <td className="px-4 py-3" style={{ color: 'hsl(var(--foreground))' }}>
                        <span className="font-mono text-xs">{inv.number ?? inv.id.slice(-8).toUpperCase()}</span>
                      </td>
                      <td className="px-4 py-3" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {new Date(inv.createdAt).toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' })}
                      </td>
                      <td className="px-4 py-3 font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                        {inv.currency} {inv.amount.toFixed(2)}
                      </td>
                      <td className="px-4 py-3">
                        {inv.status === 'paid' ? (
                          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold text-white" style={{ backgroundColor: 'hsl(142, 72%, 29%)' }}>
                            <CheckCircle2 size={11} /> Paid
                          </span>
                        ) : inv.status === 'open' ? (
                          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold text-white" style={{ backgroundColor: 'hsl(38, 92%, 50%)' }}>
                            <AlertCircle size={11} /> Open
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}>
                            <XCircle size={11} /> {inv.status ?? 'Unknown'}
                          </span>
                        )}
                      </td>
                      <td className="px-4 py-3 text-right">
                        {inv.pdfUrl ? (
                          <a href={inv.pdfUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs font-medium hover:opacity-80" style={{ color: 'hsl(var(--primary))' }}>
                            <Download size={13} /> PDF
                          </a>
                        ) : inv.hostedUrl ? (
                          <a href={inv.hostedUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs font-medium hover:opacity-80" style={{ color: 'hsl(var(--primary))' }}>
                            <ExternalLink size={13} /> View
                          </a>
                        ) : (
                          <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>—</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {showCancelDialog && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
          <div className="w-full max-w-md rounded-2xl p-6 shadow-xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <div className="flex items-start gap-4 mb-5">
              <div className="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0" style={{ backgroundColor: 'hsl(0 84% 60% / 0.1)' }}>
                <XCircle size={20} className="text-red-500" />
              </div>
              <div>
                <h3 className="text-base font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>Cancel your plan?</h3>
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  Your subscription will remain active until the end of the current billing period. After that, your account will revert to the free tier and access to paid features will be removed.
                </p>
              </div>
            </div>
            <div className="flex gap-3">
              <button
                onClick={() => setShowCancelDialog(false)}
                className="flex-1 btn-secondary"
              >
                Keep Plan
              </button>
              <button
                onClick={handleCancelSubscription}
                disabled={cancelLoading}
                className="flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-white bg-red-500 hover:bg-red-600 transition-colors disabled:opacity-70"
              >
                {cancelLoading ? <Loader2 size={15} className="animate-spin" /> : <X size={15} />}
                Yes, Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
