import axios from 'axios';
import {
  AlertCircle,
  BarChart3,
  CheckCircle2,
  Download,
  Globe,
  HelpCircle,
  Info,
  Key,
  Minus,
  Plus,
  Sparkles,
  Users,
} from 'lucide-react';
import { toast } from 'sonner';

import React, { useEffect, useRef, useState } from 'react';

import { Head, Link, router, usePage } from '@inertiajs/react';

import { CancelSubscriptionDialog } from '@/Components/billing/CancelSubscriptionDialog';
import { EnterpriseContactModal } from '@/Components/billing/EnterpriseContactModal';
import { ResumeSubscriptionDialog } from '@/Components/billing/ResumeSubscriptionDialog';
import { StatusBadge } from '@/Components/billing/StatusBadge';
import { SwapConfirmationDialog } from '@/Components/billing/SwapConfirmationDialog';
import PageHeader from '@/Components/layout/PageHeader';
import { Alert, AlertDescription, AlertTitle } from '@/Components/ui/alert';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { LoadingButton } from '@/Components/ui/loading-button';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEcommerceEvent, trackEvent } from '@/lib/analytics';
import { ANNUAL_UPSELL_CLICKED, CHECKOUT_LANDING, CHECKOUT_SUCCESS_CTA_CLICKED, TRIAL_BANNER_UPGRADE_CLICKED } from '@/lib/event-catalog';
import { formatCurrency, formatDateOnly } from '@/lib/format';
import type { PageProps } from '@/types';

interface SubscriptionInfo {
  name: string;
  status: string;
  priceId: string;
  trialEndsAt?: string | null;
  endsAt?: string | null;
  onGracePeriod: boolean;
  canceled: boolean;
  active: boolean;
}

interface PlatformTrial {
  endsAt: string;
  daysRemaining: number;
}

interface Invoice {
  id: string;
  date: string;
  amount: number;
  status: string;
  invoice_pdf: string | null;
}

interface IncompletePayment {
  paymentId: string;
  confirmUrl: string;
}

interface TierSummary {
  name: string;
  price: number | null;
  price_annual: number | null;
  features: string[];
  limits: Record<string, number | null>;
  contact_only?: boolean;
  cta_label?: string | null;
  price_id?: string | null;
}

interface AnnualUpsell {
  annual_price_id: string;
  monthly_price: number;
  annual_price: number;
  annual_savings: number;
  savings_percent: number;
  tier: string;
}

interface SetupState {
  has_sites: boolean;
  has_gsc: boolean;
  has_analysis: boolean;
  has_ai_key: boolean;
}

interface BillingPageProps {
  [key: string]: unknown;
  subscription?: SubscriptionInfo | null;
  platform_trial?: PlatformTrial | null;
  incomplete_payment?: IncompletePayment | null;
  invoices?: Invoice[];
  grace_days?: number;
  annual_upsell?: AnnualUpsell | null;
  tiers?: Record<string, TierSummary>;
  current_tier?: string;
  plan_price?: number;
  seat_count?: number | null;
  seat_price?: number | null;
  min_seats?: number | null;
  setup_state?: SetupState | null;
}

type CtaType = 'connect_site' | 'connect_gsc' | 'run_analysis' | 'setup_byok' | 'go_to_dashboard';

interface PrimaryCtaConfig {
  ctaType: CtaType;
  label: string;
  href: string;
  icon: React.ComponentType<{ className?: string }>;
}

function derivePrimaryCta(
  setupState: SetupState | null | undefined,
  platformTrial?: PlatformTrial | null,
  firstSiteId?: number | null,
): PrimaryCtaConfig {
  if (!setupState?.has_sites) {
    return {
      ctaType: 'connect_site',
      label: 'Connect Your First Site',
      href: route('sites.create'),
      icon: Globe,
    };
  }
  if (!setupState.has_gsc) {
    return {
      ctaType: 'connect_gsc',
      label: 'Connect Google Search Console',
      href: route('dashboard'),
      icon: BarChart3,
    };
  }
  if (!setupState.has_analysis) {
    return {
      ctaType: 'run_analysis',
      label: 'Run Your First Analysis',
      href: route('dashboard'),
      icon: BarChart3,
    };
  }
  if (!setupState.has_ai_key) {
    return {
      ctaType: 'setup_byok',
      label: 'Set Up Your AI Key',
      href: route('settings.ai'),
      icon: Key,
    };
  }
  if (platformTrial && platformTrial.daysRemaining > 0) {
    const days = platformTrial.daysRemaining;
    const daysLabel = `${days} day${days === 1 ? '' : 's'} left in trial`;
    return {
      ctaType: 'go_to_dashboard',
      label: `Start your first analysis — ${daysLabel}`,
      href: firstSiteId ? route('analyze.index', firstSiteId) : route('dashboard'),
      icon: BarChart3,
    };
  }
  return {
    ctaType: 'go_to_dashboard',
    label: 'See Your SEO Opportunities',
    href: route('dashboard'),
    icon: Sparkles,
  };
}

const SETUP_STEPS = ['connect_site', 'connect_gsc', 'run_analysis', 'setup_byok'] as const;
const TOTAL_SETUP_STEPS = SETUP_STEPS.length;

function deriveCurrentStep(ctaType: CtaType): number {
  const idx = SETUP_STEPS.indexOf(ctaType as (typeof SETUP_STEPS)[number]);
  return idx === -1 ? TOTAL_SETUP_STEPS : idx + 1;
}

function formatSubscriptionDate(dateString: string): { formatted: string; relative: string } {
  const date = new Date(dateString);
  const now = new Date();
  const diffTime = date.getTime() - now.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  let relative = '';
  if (diffDays < 0) {
    relative = 'Expired';
  } else if (diffDays === 0) {
    relative = 'Today';
  } else if (diffDays === 1) {
    relative = 'Tomorrow';
  } else if (diffDays <= 7) {
    relative = `${diffDays} days`;
  } else if (diffDays <= 30) {
    const weeks = Math.floor(diffDays / 7);
    relative = `${weeks} ${weeks === 1 ? 'week' : 'weeks'}`;
  } else {
    relative = `${Math.floor(diffDays / 30)} months`;
  }

  return {
    formatted: formatDateOnly(dateString),
    relative,
  };
}

export default function BillingIndex() {
  const {
    subscription,
    platform_trial: platformTrial,
    incomplete_payment: incompletePayment,
    invoices = [],
    grace_days: graceDays = 7,
    annual_upsell: annualUpsell,
    tiers,
    current_tier: currentTier,
    plan_price: planPrice,
    seat_count: initialSeatCount,
    seat_price: seatPrice,
    min_seats: minSeats,
    setup_state: setupState,
    sites,
  } = usePage<PageProps & BillingPageProps>().props;
  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [resumeDialogOpen, setResumeDialogOpen] = useState(false);
  const [annualSwapOpen, setAnnualSwapOpen] = useState(false);
  const [swapTarget, setSwapTarget] = useState<{ key: string; priceId: string; isDowngrade: boolean } | null>(null);

  // BILL-021-02: Trial value recap modal — localStorage-gated, shown once when trial expires
  const TRIAL_RECAP_KEY = 'trial_value_recap_v1_shown';
  const [trialRecapOpen, setTrialRecapOpen] = useState(() => {
    if (typeof window === 'undefined') return false;
    const daysLeft = platformTrial?.daysRemaining ?? Infinity;
    return daysLeft === 0 && localStorage.getItem(TRIAL_RECAP_KEY) !== '1';
  });
  const handleTrialRecapClose = () => {
    localStorage.setItem(TRIAL_RECAP_KEY, '1');
    setTrialRecapOpen(false);
  };
  const [checkoutSuccess, setCheckoutSuccess] = useState(false);
  const [portalLoading, setPortalLoading] = useState(false);
  const [enterpriseModalOpen, setEnterpriseModalOpen] = useState(false);
  const [expandedTierFeatures, setExpandedTierFeatures] = useState<Record<string, boolean>>({});
  const purchaseTracked = useRef(false);

  // BILL-011: Seat management state
  const [seatCount, setSeatCount] = useState(initialSeatCount ?? 0);
  const [seatUpdating, setSeatUpdating] = useState(false);
  const [seatConfirming, setSeatConfirming] = useState(false);
  const [pendingSeatDelta, setPendingSeatDelta] = useState(0);
  const isTeamPlan = currentTier === 'team';

  useEffect(() => {
    if (typeof window === 'undefined' || purchaseTracked.current) {
      return;
    }

    const params = new URLSearchParams(window.location.search);
    if (params.get('checkout') === 'success') {
      purchaseTracked.current = true;
      setCheckoutSuccess(true);

      // BILL-001: Fire checkout_landing with revenue properties so PostHog can
      // compute LTV and revenue cohorts.
      trackEvent(CHECKOUT_LANDING, {
        plan: subscription?.name ?? 'unknown',
        ...(planPrice !== undefined && planPrice !== null ? { revenue: planPrice } : {}),
      });

      // INST-002: Fire GA4 Enhanced Ecommerce purchase event so revenue appears in
      // GA4 ecommerce reports and PostHog receives a flat purchase event for cohort
      // attribution. Server-side also fires via StripeWebhookController for dedup.
      trackEcommerceEvent(
        'purchase',
        {
          item_id: currentTier ?? 'unknown',
          item_name: subscription?.name ?? 'unknown',
          price: planPrice ?? 0,
        },
        planPrice ?? 0,
        'USD',
      );

      params.delete('checkout');
      const nextQuery = params.toString();
      const nextUrl = nextQuery
        ? `${window.location.pathname}?${nextQuery}`
        : window.location.pathname;
      window.history.replaceState({}, '', nextUrl);
    }
  }, [subscription?.name, planPrice, currentTier]);

  const handlePortal = () => {
    setPortalLoading(true);
    router.visit(route('billing.portal'), {
      onFinish: () => setPortalLoading(false),
    });
  };

  const handleCancelSuccess = () => {
    router.reload();
  };

  const handleResumeSuccess = () => {
    router.reload();
  };

  // BILL-011: Seat management
  const handleSeatUpdate = async (newCount: number) => {
    if (newCount < (minSeats ?? 2) || newCount > 50) return;
    setSeatUpdating(true);
    try {
      await axios.post(route('billing.quantity'), { quantity: newCount });
      setSeatCount(newCount);
      setSeatConfirming(false);
      setPendingSeatDelta(0);
      toast.success('Seat count updated successfully.');
      router.reload({ only: ['seat_count'] });
    } catch {
      toast.error('Failed to update seat count. Please try again.');
    } finally {
      setSeatUpdating(false);
    }
  };

  return (
    <DashboardLayout>
      <Head title="Billing" />
      <PageHeader title="Billing" subtitle="Manage your subscription and payment details" />
      <div className="container py-8">
        <div className="max-w-2xl mx-auto space-y-6">
          {checkoutSuccess && (
            <Card className="border-success/20 bg-success/5">
              <CardContent className="pt-6 pb-6">
                <div className="text-center space-y-4">
                  <div className="mx-auto w-16 h-16 rounded-full bg-success/10 flex items-center justify-center">
                    <CheckCircle2 className="h-8 w-8 text-success" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-foreground">
                      Welcome to {subscription?.name ?? 'Pro'}!
                    </h2>
                    <p className="text-muted-foreground mt-1">
                      Your subscription is active. Here&apos;s how to get the most out of it:
                    </p>
                  </div>
                  {(() => {
                    const cta = derivePrimaryCta(setupState, platformTrial, sites?.[0]?.id);
                    const CtaIcon = cta.icon;
                    const currentStep = deriveCurrentStep(cta.ctaType);
                    const isAllDone = cta.ctaType === 'go_to_dashboard';
                    return (
                      <div className="pt-2 space-y-3">
                        {!isAllDone && (
                          <p className="text-sm text-muted-foreground">
                            Step {currentStep} of {TOTAL_SETUP_STEPS} &mdash; takes about 5 minutes to complete setup
                          </p>
                        )}
                        <Button
                          asChild
                          size="lg"
                          className="gap-2"
                          onClick={() => {
                            trackEvent(CHECKOUT_SUCCESS_CTA_CLICKED, { cta_type: cta.ctaType });
                          }}
                        >
                          <Link href={cta.href}>
                            <CtaIcon className="h-5 w-5" />
                            {cta.label}
                          </Link>
                        </Button>
                        {!isAllDone && (
                          <p className="text-xs text-muted-foreground">
                            Complete {TOTAL_SETUP_STEPS - currentStep + 1} quick step{TOTAL_SETUP_STEPS - currentStep + 1 !== 1 ? 's' : ''} to see your first insights
                          </p>
                        )}
                      </div>
                    );
                  })()}
                </div>
              </CardContent>
            </Card>
          )}

          {platformTrial &&
            (() => {
              const days = platformTrial.daysRemaining;
              const isUrgent = days < 3;
              const isWarning = days >= 3 && days <= 7;

              const alertClass = isUrgent
                ? 'border-destructive/20 bg-destructive/5'
                : isWarning
                  ? 'border-amber-500/20 bg-amber-500/5 dark:border-amber-400/20 dark:bg-amber-400/5'
                  : 'border-primary/20 bg-primary/5';

              const iconColor = isUrgent
                ? 'text-destructive'
                : isWarning
                  ? 'text-amber-600 dark:text-amber-400'
                  : 'text-primary';

              const titleColor = isUrgent
                ? 'text-destructive'
                : isWarning
                  ? 'text-amber-700 dark:text-amber-300'
                  : '';

              const title = isUrgent
                ? `Trial Expires in ${days} Day${days !== 1 ? 's' : ''}!`
                : isWarning
                  ? `Trial Ending Soon — ${days} Days Left`
                  : 'Pro Trial Active';

              const description = isUrgent
                ? 'Subscribe now to keep your data and Pro features.'
                : isWarning
                  ? "Don't lose access to Pro features."
                  : `You have ${days} days remaining to explore all Pro features.`;

              const TrialIcon = isUrgent ? AlertCircle : Info;

              return (
                <Alert className={alertClass}>
                  <TrialIcon className={`h-4 w-4 ${iconColor}`} />
                  <AlertTitle className={titleColor}>{title}</AlertTitle>
                  <AlertDescription>
                    {description} Trial expires on{' '}
                    <strong>{formatDateOnly(platformTrial.endsAt)}</strong>.{' '}
                    <Link
                      href={route('billing.plans')}
                      className="underline font-medium rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                    >
                      Upgrade now
                    </Link>
                  </AlertDescription>
                </Alert>
              );
            })()}

          {incompletePayment && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Payment Confirmation Required</AlertTitle>
              <AlertDescription>
                Your subscription requires payment confirmation.{' '}
                <a
                  href={incompletePayment.confirmUrl}
                  className="underline font-medium rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                >
                  Complete payment now
                </a>
              </AlertDescription>
            </Alert>
          )}

          {subscription?.status === 'incomplete' && !incompletePayment && (
            <Alert variant="destructive">
              <Info className="h-4 w-4" />
              <AlertTitle>Payment Processing</AlertTitle>
              <AlertDescription>
                Your subscription is being set up. This usually takes a few moments. If this
                persists, please contact support or visit the{' '}
                <LoadingButton
                  variant="link"
                  onClick={handlePortal}
                  loading={portalLoading}
                  loadingText="Opening..."
                  className="underline font-medium rounded-sm p-0 h-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                >
                  billing portal
                </LoadingButton>
                .
              </AlertDescription>
            </Alert>
          )}

          {subscription?.status === 'past_due' && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Payment Failed — Action Required</AlertTitle>
              <AlertDescription>
                <p>
                  Your last payment failed. Stripe will automatically retry over the next{' '}
                  <strong>{graceDays} days</strong>. If payment remains unresolved after that,{' '}
                  <strong>
                    access to AI drafts, analysis, and all paid features will be suspended
                  </strong>{' '}
                  until payment is confirmed.
                </p>
                {/* UX-018: Explicit recovery button */}
                <button
                  type="button"
                  onClick={handlePortal}
                  className="mt-3 inline-flex items-center gap-1.5 rounded-md border border-destructive/30 bg-background px-3 py-1.5 text-sm font-medium text-destructive hover:bg-destructive/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                  aria-label="Open Stripe billing portal to update payment method"
                >
                  Update payment method now
                </button>
              </AlertDescription>
            </Alert>
          )}

          {subscription?.status === 'incomplete_expired' && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Subscription Expired</AlertTitle>
              <AlertDescription>
                Your subscription could not be completed and has expired. Please start a new
                subscription to access paid features.{' '}
                <Link
                  href={route('billing.plans')}
                  className="underline font-medium rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                >
                  View plans
                </Link>
              </AlertDescription>
            </Alert>
          )}

          {subscription?.onGracePeriod && subscription.endsAt && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Subscription Ending</AlertTitle>
              <AlertDescription>
                Your subscription has been canceled and will end on{' '}
                <strong>{formatDateOnly(subscription.endsAt)}</strong>. You can resume your
                subscription at any time to continue enjoying all features.
              </AlertDescription>
            </Alert>
          )}

          {subscription?.canceled && !subscription.onGracePeriod && (
            <Alert>
              <Info className="h-4 w-4" />
              <AlertTitle>Subscription Ended</AlertTitle>
              <AlertDescription>
                Your subscription has ended. Upgrade to regain access to premium features.
              </AlertDescription>
            </Alert>
          )}

          <Card>
            <CardHeader>
              <CardTitle>Subscription Status</CardTitle>
              <CardDescription>
                {subscription
                  ? 'Your current plan details.'
                  : platformTrial
                    ? "You're on a Pro trial. Subscribe to keep access after your trial ends."
                    : 'You are not subscribed to a paid plan yet.'}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {subscription ? (
                <div className="space-y-4">
                  <div className="flex items-center justify-between pb-4 border-b border-border">
                    <div>
                      <p className="text-xs uppercase tracking-wide text-muted-foreground mb-1">
                        Current Plan
                      </p>
                      <p className="text-2xl font-semibold text-foreground">{subscription.name}</p>
                    </div>
                    <div className="scale-125">
                      <StatusBadge status={subscription.status} />
                    </div>
                  </div>

                  <div className="space-y-3">
                    {subscription.trialEndsAt && (
                      <div className="flex items-center justify-between py-2 border-b border-border/50">
                        <span className="text-sm font-medium text-muted-foreground">
                          Trial ends
                        </span>
                        <span className="text-sm font-semibold text-foreground tabular-nums">
                          {formatDateOnly(subscription.trialEndsAt)}
                        </span>
                      </div>
                    )}
                    {subscription.endsAt && subscription.onGracePeriod && (
                      <div className="flex items-center justify-between py-2 border-b border-border/50">
                        <span className="text-sm font-medium text-muted-foreground">
                          Access until
                        </span>
                        <div className="text-right">
                          <p className="text-sm font-semibold text-destructive tabular-nums">
                            {formatSubscriptionDate(subscription.endsAt).formatted}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {formatSubscriptionDate(subscription.endsAt).relative}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              ) : platformTrial ? (
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-muted-foreground">Plan</span>
                    <span className="text-sm text-foreground">Pro Trial</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-muted-foreground">Status</span>
                    <StatusBadge status="trialing" />
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-muted-foreground">Trial expires</span>
                    <span className="text-sm text-foreground">
                      {formatDateOnly(platformTrial.endsAt)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-muted-foreground">
                      Days remaining
                    </span>
                    <span className="text-sm text-foreground">{platformTrial.daysRemaining}</span>
                  </div>
                </div>
              ) : (
                <div className="py-8 text-center space-y-4">
                  <div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
                    <svg
                      className="w-8 h-8 text-primary"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M13 10V3L4 14h7v7l9-11h-7z"
                      />
                    </svg>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-foreground mb-1">
                      Ready to unlock premium features?
                    </p>
                    <p className="text-sm text-muted-foreground">
                      Get unlimited access with a paid subscription
                    </p>
                  </div>
                </div>
              )}

              <div className="flex flex-col gap-3 pt-4 border-t border-border">
                {subscription ? (
                  <>
                    {subscription.onGracePeriod ? (
                      <Button
                        onClick={() => setResumeDialogOpen(true)}
                        className="w-full sm:w-auto"
                      >
                        Resume Subscription
                      </Button>
                    ) : (
                      <div className="flex flex-col sm:flex-row gap-3">
                        <LoadingButton
                          onClick={handlePortal}
                          loading={portalLoading}
                          loadingText="Opening portal..."
                          className="flex-1 sm:flex-none"
                        >
                          Manage Billing
                        </LoadingButton>
                        {subscription.active && (
                          <Button
                            variant="outline"
                            onClick={() => setCancelDialogOpen(true)}
                            className="flex-1 sm:flex-none"
                          >
                            Cancel Subscription
                          </Button>
                        )}
                      </div>
                    )}
                  </>
                ) : (
                  <Button asChild className="w-full sm:w-auto">
                    <Link href={route('billing.plans')}>
                      {platformTrial ? 'Upgrade Now' : 'View Plans'}
                    </Link>
                  </Button>
                )}
                <Button asChild variant="outline" className="w-full sm:w-auto group">
                  <Link href="/contact" className="gap-2">
                    <HelpCircle className="h-4 w-4 transition-transform group-hover:scale-110" />
                    Need help?
                  </Link>
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* BILL-011: Inline seat management for Team plan */}
          {isTeamPlan && subscription?.active && !subscription.onGracePeriod && seatCount > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Users className="h-5 w-5 text-primary" />
                  Manage Seats
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Current seats</span>
                  <div className="flex items-center gap-3">
                    <button
                      type="button"
                      onClick={() => {
                        const newDelta = pendingSeatDelta - 1;
                        if (seatCount + newDelta >= (minSeats ?? 2)) {
                          setPendingSeatDelta(newDelta);
                          setSeatConfirming(true);
                        }
                      }}
                      disabled={seatUpdating || seatCount + pendingSeatDelta <= (minSeats ?? 2)}
                      className="rounded-md border p-1.5 hover:bg-accent disabled:opacity-50"
                      aria-label="Remove seat"
                    >
                      <Minus className="h-4 w-4" />
                    </button>
                    <span className="text-lg font-semibold tabular-nums w-8 text-center">
                      {seatCount + pendingSeatDelta}
                    </span>
                    <button
                      type="button"
                      onClick={() => {
                        const newDelta = pendingSeatDelta + 1;
                        if (seatCount + newDelta <= 50) {
                          setPendingSeatDelta(newDelta);
                          setSeatConfirming(true);
                        }
                      }}
                      disabled={seatUpdating || seatCount + pendingSeatDelta >= 50}
                      className="rounded-md border p-1.5 hover:bg-accent disabled:opacity-50"
                      aria-label="Add seat"
                    >
                      <Plus className="h-4 w-4" />
                    </button>
                  </div>
                </div>

                {seatConfirming && pendingSeatDelta !== 0 && (
                  <div className="rounded-lg border bg-muted/30 p-3 space-y-3">
                    <p className="text-sm text-muted-foreground">
                      {pendingSeatDelta > 0
                        ? `Adding ${pendingSeatDelta} seat${pendingSeatDelta > 1 ? 's' : ''}`
                        : `Removing ${Math.abs(pendingSeatDelta)} seat${Math.abs(pendingSeatDelta) > 1 ? 's' : ''}`}
                      {seatPrice
                        ? ` — ${pendingSeatDelta > 0 ? 'adds' : 'removes'} ${formatCurrency(Math.abs(pendingSeatDelta * seatPrice))}/mo to your next invoice.`
                        : '.'}
                    </p>
                    <div className="flex gap-2">
                      <LoadingButton
                        size="sm"
                        onClick={() => handleSeatUpdate(seatCount + pendingSeatDelta)}
                        loading={seatUpdating}
                        loadingText="Updating..."
                      >
                        Confirm
                      </LoadingButton>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          setPendingSeatDelta(0);
                          setSeatConfirming(false);
                        }}
                        disabled={seatUpdating}
                      >
                        Cancel
                      </Button>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {annualUpsell && subscription?.active && !subscription.onGracePeriod && (
            <Card className="border-primary/20 bg-primary/5">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Sparkles className="h-5 w-5 text-primary" />
                  Save {annualUpsell.savings_percent}% with Annual Billing
                </CardTitle>
                <CardDescription>
                  Switch to annual billing and save {formatCurrency(annualUpsell.annual_savings)}
                  /year — that's {formatCurrency(annualUpsell.annual_price / 12)}/mo instead of{' '}
                  {formatCurrency(annualUpsell.monthly_price)}/mo.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <Button
                  onClick={() => {
                    trackEvent(ANNUAL_UPSELL_CLICKED, { tier: annualUpsell.tier });
                    setAnnualSwapOpen(true);
                  }}
                >
                  Switch to Annual Billing
                </Button>
              </CardContent>
            </Card>
          )}

          {subscription && (
            <Card>
              <CardHeader>
                <CardTitle>Billing History</CardTitle>
                <CardDescription>Your past invoices and payments</CardDescription>
              </CardHeader>
              <CardContent>
                {invoices.length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground">
                    <p className="font-medium">No invoices yet</p>
                    <p className="text-sm mt-1">
                      Your invoices will appear here after your first billing cycle.
                    </p>
                  </div>
                ) : (
                  <div className="space-y-2">
                    {invoices.slice(0, 5).map((invoice) => (
                      <div
                        key={invoice.id}
                        className="flex items-center justify-between py-3 border-b border-border/50 last:border-0"
                      >
                        <div>
                          <p className="text-sm font-medium text-foreground">
                            {formatDateOnly(invoice.date)}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {invoice.status === 'paid' ? 'Paid' : 'Pending'}
                          </p>
                        </div>
                        <div className="flex items-center gap-3">
                          <span className="text-sm font-semibold tabular-nums">
                            {formatCurrency(invoice.amount)}
                          </span>
                          {invoice.invoice_pdf && (
                            <Button variant="ghost" size="sm" asChild>
                              <a
                                href={invoice.invoice_pdf}
                                target="_blank"
                                rel="noopener noreferrer"
                                aria-label={`Download invoice from ${formatDateOnly(invoice.date)}`}
                              >
                                <Download className="h-4 w-4" />
                              </a>
                            </Button>
                          )}
                        </div>
                      </div>
                    ))}
                    {invoices.length > 5 && (
                      <LoadingButton
                        variant="ghost"
                        className="w-full mt-2"
                        onClick={handlePortal}
                        loading={portalLoading}
                        loadingText="Opening portal..."
                      >
                        View all {invoices.length} invoices
                      </LoadingButton>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      {tiers && Object.keys(tiers).length > 0 && (
        <div className="container pb-8">
          <div className="max-w-2xl mx-auto">
            <Card>
              <CardHeader>
                <CardTitle>Plan Comparison</CardTitle>
                <CardDescription>See what each plan offers</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                  {Object.entries(tiers).map(([key, tier]) => {
                    const isExpanded = expandedTierFeatures[key] ?? false;
                    const visibleFeatures = isExpanded ? tier.features : tier.features.slice(0, 4);
                    return (
                      <div
                        key={key}
                        className={`rounded-lg border p-4 flex flex-col ${key === currentTier ? 'ring-2 ring-primary' : ''}`}
                      >
                        <p className="text-sm font-semibold text-foreground">{tier.name}</p>
                        <p className="text-lg font-bold text-foreground mt-1">
                          {tier.price === null
                            ? 'Custom'
                            : tier.price === 0
                              ? 'Free'
                              : `$${tier.price}/mo`}
                        </p>
                        {key === currentTier && (
                          <span className="inline-block mt-1 text-xs text-primary font-medium">
                            Current plan
                          </span>
                        )}
                        <ul className="mt-3 space-y-1 flex-1">
                          {visibleFeatures.map((feature) => (
                            <li
                              key={feature}
                              className="flex items-start gap-1.5 text-xs text-muted-foreground"
                            >
                              <CheckCircle2
                                className="h-3 w-3 text-success shrink-0 mt-0.5"
                                aria-hidden="true"
                              />
                              {feature}
                            </li>
                          ))}
                        </ul>
                        {tier.features.length > 4 && (
                          <button
                            type="button"
                            className="mt-2 text-xs text-primary hover:underline text-left"
                            onClick={() =>
                              setExpandedTierFeatures((prev) => ({
                                ...prev,
                                [key]: !isExpanded,
                              }))
                            }
                          >
                            {isExpanded
                              ? 'Show less'
                              : `+${tier.features.length - 4} more features`}
                          </button>
                        )}
                        {tier.contact_only && key !== currentTier && (
                          <Button
                            size="sm"
                            variant="outline"
                            className="mt-3 w-full text-xs"
                            onClick={() => setEnterpriseModalOpen(true)}
                          >
                            {tier.cta_label ?? 'Contact Sales'}
                          </Button>
                        )}
                        {!tier.contact_only && key !== currentTier && tier.price_id && subscription && (
                          (() => {
                            const currentPrice = tiers?.[currentTier ?? '']?.price ?? Infinity;
                            const targetPrice = tier.price ?? Infinity;
                            const isDowngrade = targetPrice < currentPrice;
                            return (
                              <Button
                                size="sm"
                                variant={isDowngrade ? 'outline' : 'default'}
                                className="mt-3 w-full text-xs"
                                onClick={() => setSwapTarget({ key, priceId: tier.price_id!, isDowngrade })}
                              >
                                {isDowngrade ? `Downgrade to ${tier.name}` : `Upgrade to ${tier.name}`}
                              </Button>
                            );
                          })()
                        )}
                      </div>
                    );
                  })}
                </div>
                <div className="mt-4 text-center">
                  <Button asChild variant="outline" size="sm">
                    <Link href={route('billing.plans')}>Compare All Plans</Link>
                  </Button>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      )}

      {/* BILL-004: Enterprise contact sales modal */}
      <EnterpriseContactModal open={enterpriseModalOpen} onOpenChange={setEnterpriseModalOpen} />

      <CancelSubscriptionDialog
        open={cancelDialogOpen}
        onOpenChange={setCancelDialogOpen}
        onSuccess={handleCancelSuccess}
      />

      <ResumeSubscriptionDialog
        open={resumeDialogOpen}
        onOpenChange={setResumeDialogOpen}
        onSuccess={handleResumeSuccess}
      />

      {/* BILL-021-01: Plan swap dialog — handles both upgrades and downgrades from the comparison grid */}
      {swapTarget && (
        <SwapConfirmationDialog
          open={!!swapTarget}
          onOpenChange={(open) => { if (!open) setSwapTarget(null); }}
          currentPlan={currentTier ?? ''}
          newPlan={swapTarget.key}
          newPriceId={swapTarget.priceId}
          tiers={tiers ?? {}}
          isDowngrade={swapTarget.isDowngrade}
        />
      )}

      {annualUpsell && (
        <SwapConfirmationDialog
          open={annualSwapOpen}
          onOpenChange={setAnnualSwapOpen}
          currentPlan={annualUpsell.tier}
          newPlan={annualUpsell.tier}
          newPriceId={annualUpsell.annual_price_id}
          tiers={tiers ?? {}}
        />
      )}

      {/* BILL-021-02: Trial value recap modal — shown once when daysRemaining reaches 0 */}
      <Dialog open={trialRecapOpen} onOpenChange={(open) => { if (!open) handleTrialRecapClose(); }}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Sparkles className="h-5 w-5 text-primary" />
              Your trial is ending today
            </DialogTitle>
            <DialogDescription>
              Here's what you've accomplished during your trial.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3 py-2">
            <div className="rounded-lg border bg-muted/30 p-3 space-y-2">
              {[
                setupState?.has_gsc && 'Connected Google Search Console',
                setupState?.has_analysis && 'Ran your first traffic analysis',
                setupState?.has_ai_key && 'Set up AI content generation',
              ].filter(Boolean).map((item) => (
                <div key={String(item)} className="flex items-center gap-2 text-sm">
                  <CheckCircle2 className="h-4 w-4 text-success shrink-0" />
                  <span>{item}</span>
                </div>
              ))}
              {(!setupState?.has_gsc && !setupState?.has_analysis && !setupState?.has_ai_key) && (
                <p className="text-sm text-muted-foreground">Subscribe to unlock the full RankWiz toolkit.</p>
              )}
            </div>
            <p className="text-sm text-muted-foreground">
              Subscribe now to keep your data and continue improving your SEO.
            </p>
          </div>
          <DialogFooter className="gap-2 sm:gap-0">
            <Button variant="ghost" size="sm" onClick={handleTrialRecapClose}>
              Maybe later
            </Button>
            <Button
              onClick={() => {
                trackEvent(TRIAL_BANNER_UPGRADE_CLICKED, { context: 'value_recap_modal' });
                handleTrialRecapClose();
                router.visit(route('billing.plans'));
              }}
            >
              Subscribe now
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </DashboardLayout>
  );
}
