'use client';

import { useState, useEffect, useCallback, useRef } 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, getActiveGateways, getAvailableCurrencies,
  startCheckout, startRazorpayCheckout, verifyRazorpayPayment,
  openCustomerPortal, listInvoices,
  BillingSubscription, BillingUsage, Plan, GatewayInfo, UnifiedInvoice as StripeInvoice
} from '@client/api/billing';
import { featureLabels } from '@shared/planFeatures';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';
import { toast } from 'sonner';

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

function currencySymbol(currency: string): string {
  try {
    return (0).toLocaleString('en', { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }).replace(/[\d\s,.]/g, '').trim();
  } catch {
    return currency + ' ';
  }
}

function loadRazorpayScript(): Promise<boolean> {
  return new Promise(resolve => {
    if (typeof window !== 'undefined' && (window as unknown as { Razorpay?: unknown }).Razorpay) {
      resolve(true);
      return;
    }
    const script = document.createElement('script');
    script.src = 'https://checkout.razorpay.com/v1/checkout.js';
    script.onload = () => resolve(true);
    script.onerror = () => resolve(false);
    document.body.appendChild(script);
  });
}

type Tab = 'overview' | 'plans' | '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%)',
};

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 { features: planFeatures, refresh: refreshPlanFeatures } = usePlanFeatures();
  const pollTimers = useRef<ReturnType<typeof setTimeout>[]>([]);
  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 [subscription, setSubscription] = useState<BillingSubscription | null>(null);
  const [usage, setUsage] = useState<BillingUsage | null>(null);
  const [plans, setPlans] = useState<Plan[]>([]);
  const [invoices, setInvoices] = useState<StripeInvoice[]>([]);
  const [loading, setLoading] = useState(true);
  const [invoicesLoading, setInvoicesLoading] = useState(false);
  const [gateways, setGateways] = useState<GatewayInfo[]>([]);
  const [selectedCurrency, setSelectedCurrency] = useState<string>('USD');
  const [gatewaysLoaded, setGatewaysLoaded] = useState(false);
  const [availableCurrencies, setAvailableCurrencies] = useState<string[]>([]);

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

  // Only show the red "trial ended" banner if the live subscription actually
  // confirms the trial/subscription is over. A stale ?reason=trial_expired
  // URL (e.g. from a transient middleware gate hiccup) must not flash the
  // banner to a user whose trial is still active.
  const subscriptionConfirmsExpired = !!subscription && (
    (subscription.status === 'trial' && subscription.trialEnd && new Date(subscription.trialEnd) < new Date()) ||
    subscription.status === 'inactive' ||
    subscription.status === 'cancelled'
  );
  const trialExpiredReason = trialExpiredReasonParam && subscriptionConfirmsExpired;

  // If the URL claims trial_expired but the live sub says otherwise, strip the
  // misleading param so a refresh comes back clean and no banner re-flashes.
  useEffect(() => {
    if (!loading && trialExpiredReasonParam && subscription && !subscriptionConfirmsExpired) {
      const url = new URL(window.location.href);
      url.searchParams.delete('reason');
      window.history.replaceState({}, '', url.pathname + (url.search ? url.search : '') + url.hash);
    }
  }, [loading, trialExpiredReasonParam, subscription, subscriptionConfirmsExpired]);

  useEffect(() => {
    const checkoutStatus = searchParams.get('checkout');
    if (checkoutStatus === 'success') {
      toast.success(t('billing.paymentSuccessful', 'Payment successful! Your subscription is now active.'));
      const featuresAtUpgrade = planFeatures.length;
      refreshPlanFeatures();
      let retries = 0;
      const MAX_RETRIES = 2;
      const POLL_INTERVAL_MS = 4000;
      const schedule = () => {
        if (retries >= MAX_RETRIES) return;
        retries++;
        const timer = setTimeout(() => {
          refreshPlanFeatures();
          if (planFeatures.length <= featuresAtUpgrade) {
            schedule();
          }
        }, POLL_INTERVAL_MS);
        pollTimers.current.push(timer);
      };
      schedule();
    } else if (checkoutStatus === 'cancelled') {
      toast.info(t('billing.checkoutCancelled', 'Checkout was cancelled. No charges were made.'));
    }
    return () => {
      pollTimers.current.forEach(clearTimeout);
      pollTimers.current = [];
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams]);

  useEffect(() => {
    async function init() {
      try {
        const [sub, usg, gws, currencies] = await Promise.all([
          getSubscription(), getUsage(), getActiveGateways(), getAvailableCurrencies(),
        ]);
        setSubscription(sub);
        setUsage(usg);
        setGateways(gws);
        const allCurrencies = [...new Set([...gws.map(g => g.currency), ...currencies])].sort();
        setAvailableCurrencies(allCurrencies);
        const initialCurrency = gws[0]?.currency ?? allCurrencies[0] ?? 'USD';
        setSelectedCurrency(initialCurrency);
        const pls = await fetchPlans(initialCurrency);
        setPlans(pls);
      } catch {
        toast.error(t('billing.failedToLoadData', 'Failed to load billing data'));
      } finally {
        setLoading(false);
        setGatewaysLoaded(true);
      }
    }
    init();
  }, [t]);

  useEffect(() => {
    if (!gatewaysLoaded) return;
    fetchPlans(selectedCurrency).then(setPlans).catch(() => {});
  }, [selectedCurrency, gatewaysLoaded]); // eslint-disable-line react-hooks/exhaustive-deps

  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]);

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

  const handleSelectPlanStripe = async (plan: Plan, cycle: 'monthly' | 'annual') => {
    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 handleSelectPlanRazorpay = async (plan: Plan, cycle: 'monthly' | 'annual') => {
    setCheckoutLoading(plan.id);
    try {
      const scriptLoaded = await loadRazorpayScript();
      if (!scriptLoaded) throw new Error('Failed to load payment gateway. Please try again.');
      const { subscriptionId, keyId, currency, planName } = await startRazorpayCheckout(plan.id, cycle);
      await new Promise<void>((resolve, reject) => {
        const options = {
          key: keyId,
          subscription_id: subscriptionId,
          name: 'RestroAgent',
          description: `${planName} — ${cycle} subscription`,
          currency,
          handler: async (response: { razorpay_subscription_id: string; razorpay_payment_id: string; razorpay_signature: string }) => {
            try {
              await verifyRazorpayPayment({
                razorpaySubscriptionId: response.razorpay_subscription_id,
                razorpayPaymentId: response.razorpay_payment_id,
                razorpaySignature: response.razorpay_signature,
              });
              toast.success(t('billing.paymentSuccessful', 'Payment successful! Your subscription is now active.'));
              resolve();
              window.location.href = '/billing?checkout=success';
            } catch (err) { reject(err); }
          },
          modal: { ondismiss: () => reject(new Error('__dismissed__')) },
        };
        const rzp = new (window as unknown as { Razorpay: new (opts: Record<string, unknown>) => { open(): void } }).Razorpay(options);
        rzp.open();
      });
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : 'Payment failed';
      if (msg !== '__dismissed__') toast.error(msg);
    } finally {
      setCheckoutLoading(null);
    }
  };

  const handleSelectPlan = async (plan: Plan, cycle: 'monthly' | 'annual' = billingCycle) => {
    const gw = gateways.find(g => g.currency === selectedCurrency) ?? gateways[0];
    if (gw?.id === 'razorpay') {
      await handleSelectPlanRazorpay(plan, cycle);
    } else {
      await handleSelectPlanStripe(plan, cycle);
    }
  };

  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 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: '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 activeCurrency = selectedCurrency;

  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))' }}>
                    {currencySymbol(activeCurrency)}{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))' }}>{currencySymbol(activeCurrency)}{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 flex-wrap 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">Save more</span>}
                </button>
              ))}
            </div>
            {availableCurrencies.length > 1 && (
              <>
                <span className="text-sm font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>·</span>
                <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>Currency:</span>
                <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  {availableCurrencies.map(cur => {
                    const isSelected = selectedCurrency === cur;
                    return (
                      <button
                        key={cur}
                        onClick={() => setSelectedCurrency(cur)}
                        className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all ${isSelected ? 'bg-white shadow-sm' : ''}`}
                        style={{ color: isSelected ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
                      >
                        {cur}
                      </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 effectiveMonthly = plan.effectivePriceMonthly ?? plan.priceMonthly;
              const effectiveAnnual = plan.effectivePriceAnnual ?? plan.priceAnnual;
              const annualPerMonth = effectiveAnnual > 0 ? Math.round(effectiveAnnual / 12) : Math.round(effectiveMonthly * 0.8);
              const displayPrice = billingCycle === 'annual' ? annualPerMonth : effectiveMonthly;
              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>
                    {plan.description && (
                      <p className="text-xs mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{plan.description}</p>
                    )}
                    <div className="flex items-end gap-1">
                      <span className="text-3xl font-bold" style={{ color }}>{currencySymbol(activeCurrency)}{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 {currencySymbol(activeCurrency)}{Math.max(0, Math.round(effectiveMonthly * 12 - (effectiveAnnual > 0 ? effectiveAnnual : annualPerMonth * 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 }} />
                        {featureLabels[f] ?? 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>
                  ) : gateways.length === 0 ? (
                    <button disabled className="w-full py-2.5 rounded-xl text-sm font-semibold opacity-60 cursor-not-allowed" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}>
                      Contact Support to Subscribe
                    </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 === '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>
      )}
    </>
  );
}
