/**
 * Brand voice: "The WordPress SEO tool that closes the loop between analysis and proof."
 * Voice pillars: (1) Real data not estimates, (2) Included not add-on, (3) Measured not claimed
 * Tone: authoritative but accessible — not academic, not salesy
 */
import {
  AlertCircle,
  Check,
  CheckCircle2,
  ChevronDown,
  ArrowRight,
  Minus,
  Star,
  TrendingUp,
} from 'lucide-react';

import { useEffect, useMemo, useState } from 'react';

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

import { EnterpriseContactModal } from '@/Components/billing/EnterpriseContactModal';
import { PlanCard } from '@/Components/billing/PlanCard';
import { ExitIntentCapture } from '@/Components/marketing/ExitIntentCapture';
import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import { TestimonialsSection } from '@/Components/marketing/TestimonialsSection';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/Components/ui/collapsible';
import { Slider } from '@/Components/ui/slider';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { ToggleGroup, ToggleGroupItem } from '@/Components/ui/toggle-group';
import { COMPETITOR_PRICES } from '@/config/competitor-pricing';
import { CTA_LABELS } from '@/config/cta-labels';
import { BYOK_COST_CALCULATOR } from '@/config/plan-limits';
import { getPricingFaqItems } from '@/config/pricing-copy';
import { trackEvent } from '@/lib/analytics';
import {
  ANNUAL_BILLING_SELECTED,
  CTA_CLICKED,
  PRICING_CTA_CLICKED,
  PRICING_VIEWED,
} from '@/lib/event-catalog';
import { formatNumber } from '@/lib/format';
import { softwareApplicationBase } from '@/lib/schema';
import { type PageProps } from '@/types';

interface TierConfig {
  name: string;
  description: string;
  price: number | null;
  price_annual?: number | null;
  stripe_price_id?: string | null;
  stripe_price_id_annual?: string | null;
  per_seat?: boolean;
  min_seats?: number | null;
  coming_soon?: boolean;
  limits?: Record<string, number | null>;
  features?: string[];
  best_for?: string;
  cta_label?: string;
  cta_subtext?: string;
}

interface TestimonialData {
  id: number;
  name: string;
  role: string;
  company: string;
  quote: string;
  avatar_url: string | null;
  rating: number;
  source: string;
  source_url: string | null;
  featured: boolean;
}

interface FeatureMatrixRow {
  label: string;
  values: Record<string, string | boolean>;
}

interface FeatureMatrixSection {
  section: string;
  rows: FeatureMatrixRow[];
}

interface PricingProps {
  tiers: Record<string, TierConfig>;
  features_matrix?: FeatureMatrixSection[];
  can_login: boolean;
  can_register: boolean;
  current_plan?: string | null;
  recommended_plan?: string | null;
  is_subscribed?: boolean;
  trial?: {
    active: boolean;
    daysRemaining: number | null;
    endsAt: string | null;
  } | null;
  trial_enabled?: boolean;
  trial_days?: number;
  sales_email?: string;
  pro_price?: number;
  pro_bundled_drafts?: number;
  free_bundled_drafts?: number;
  meta_description?: string;
  og_description?: string;
  testimonials?: TestimonialData[];
  metrics?: {
    active_users_count?: number;
  };
  lifecycle_stage?: 'trialing' | 'activated' | 'at_risk' | 'winback' | 'churned' | null;
  has_had_subscription?: boolean;
}

interface CostComparison {
  name: string;
  monthlyCost: number;
  isRankWiz?: boolean;
}

function CostCalculator({
  bundledDrafts,
  proPriceMonthly,
}: {
  bundledDrafts: number;
  proPriceMonthly: number;
}) {
  const [draftVolume, setDraftVolume] = useState<number>(bundledDrafts);

  const rankwizPlatform = proPriceMonthly;
  const bundledIncluded = bundledDrafts;
  const openAiCostPerDraft = BYOK_COST_CALCULATOR;
  const extraDrafts = Math.max(0, draftVolume - bundledIncluded);
  const rankwizTotal = rankwizPlatform + extraDrafts * openAiCostPerDraft;

  const competitors: CostComparison[] = [
    { name: 'RankWiz Pro', monthlyCost: rankwizTotal, isRankWiz: true },
    ...COMPETITOR_PRICES.map((c) => ({
      name: `${c.name} ${c.planName}`,
      monthlyCost: c.monthlyCost,
    })),
  ];

  const maxCost = Math.max(...competitors.map((c) => c.monthlyCost));

  return (
    <div className="rounded-lg border bg-card p-8">
      <h3 className="mb-2 text-lg font-semibold">AI Cost Calculator</h3>
      <p className="mb-6 text-sm text-muted-foreground">
        Pro includes {bundledDrafts} AI drafts/month. Need more? Add your own OpenAI key for
        unlimited at cost — no markup. Drag to compare at your draft volume.
      </p>

      <div className="mb-6 space-y-3">
        <div className="flex items-center justify-between">
          <label className="text-sm font-medium" htmlFor="draft-volume-slider">
            Monthly AI drafts
          </label>
          <span className="text-sm font-semibold text-primary">{draftVolume} drafts/mo</span>
        </div>
        <Slider
          id="draft-volume-slider"
          min={10}
          max={200}
          step={5}
          value={[draftVolume]}
          onValueChange={(val: number[]) => setDraftVolume(val[0] ?? draftVolume)}
          className="w-full"
        />
        <div className="flex justify-between text-xs text-muted-foreground">
          <span>10</span>
          <span>200</span>
        </div>
      </div>

      <div className="space-y-3">
        {competitors.map((competitor) => {
          const barWidth = maxCost > 0 ? (competitor.monthlyCost / maxCost) * 100 : 0;
          const savings = competitor.isRankWiz ? null : competitor.monthlyCost - rankwizTotal;
          return (
            <div key={competitor.name} className="space-y-1">
              <div className="flex items-center justify-between text-sm">
                <span
                  className={
                    competitor.isRankWiz ? 'font-semibold text-primary' : 'text-muted-foreground'
                  }
                >
                  {competitor.name}
                  {competitor.isRankWiz && (
                    <span className="ml-2 text-xs font-normal text-muted-foreground">
                      (${rankwizPlatform} +{' '}
                      {extraDrafts > 0
                        ? `$${(extraDrafts * openAiCostPerDraft).toFixed(2)} BYOK`
                        : `${bundledIncluded} drafts included`}
                      )
                    </span>
                  )}
                </span>
                <span
                  className={
                    competitor.isRankWiz ? 'font-semibold text-primary' : 'text-muted-foreground'
                  }
                >
                  ${competitor.monthlyCost.toFixed(2)}/mo
                  {savings !== null && savings > 0 && (
                    <span className="ml-2 text-xs text-green-600 dark:text-green-400">
                      Save ${savings.toFixed(2)}/mo
                    </span>
                  )}
                </span>
              </div>
              <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
                <div
                  className={`h-full rounded-full transition-all duration-300 ${
                    competitor.isRankWiz ? 'bg-primary' : 'bg-muted-foreground/30'
                  }`}
                  style={{ width: `${barWidth}%` }}
                />
              </div>
            </div>
          );
        })}
      </div>

      <p className="mt-4 text-xs text-muted-foreground">
        * BYOK cost estimated at ~$0.01–$0.05/draft depending on model — only applies when over the{' '}
        {bundledIncluded} included drafts. Competitor prices as of 2026; verify at their respective
        pricing pages.
      </p>
    </div>
  );
}

type PricingComponent = ((props: PricingProps) => JSX.Element) & {
  disableGlobalUi?: boolean;
};

const Pricing: PricingComponent = ({
  tiers,
  features_matrix: featuresMatrix,
  can_login: canLogin,
  can_register: canRegister,
  current_plan: currentPlan,
  recommended_plan: recommendedPlan,
  is_subscribed: isSubscribedProp,
  trial_enabled: trialEnabled,
  trial_days: trialDays,
  pro_price: proPrice,
  pro_bundled_drafts: proBundledDrafts,
  free_bundled_drafts: freeBundledDrafts,
  meta_description: metaDescription,
  og_description: ogDescription,
  testimonials,
  metrics,
  trial,
  lifecycle_stage: lifecycleStage,
  has_had_subscription: hasHadSubscription,
}) => {
  const appName = import.meta.env.VITE_APP_NAME || 'RankWiz';
  const { app_url, auth } = usePage<PageProps>().props;
  const is_authenticated = Boolean(auth?.user);
  const is_subscribed = isSubscribedProp ?? Boolean(currentPlan && currentPlan !== 'free');
  const is_free_user = is_authenticated && !is_subscribed;
  const tierEntries = useMemo(() => Object.entries(tiers), [tiers]);
  const [billingPeriod, setBillingPeriod] = useState<'monthly' | 'annual'>(() => {
    try {
      const stored = sessionStorage.getItem('pricing_billing_period');
      return stored === 'annual' ? 'annual' : 'monthly';
    } catch {
      return 'monthly';
    }
  });
  const [enterpriseModalOpen, setEnterpriseModalOpen] = useState(false);

  const handleBillingPeriodChange = (value: string) => {
    if (!value) return;
    const period = value as 'monthly' | 'annual';
    setBillingPeriod(period);
    try {
      sessionStorage.setItem('pricing_billing_period', period);
    } catch {
      // sessionStorage unavailable (e.g., private browsing restrictions)
    }
    if (period === 'annual') {
      trackEvent(ANNUAL_BILLING_SELECTED, { source: 'pricing_page' });
    }
  };

  useEffect(() => {
    trackEvent(PRICING_VIEWED, {
      source: 'marketing_page',
      plan_count: tierEntries.length,
    });
  }, [tierEntries.length]);

  const hasAnnualPricing = useMemo(() => {
    return tierEntries.some(([, tier]) => tier.price_annual && tier.price_annual > 0);
  }, [tierEntries]);

  const faqItems = useMemo(
    () =>
      getPricingFaqItems({
        freeDrafts: freeBundledDrafts ?? 5,
        proDrafts: proBundledDrafts ?? 30,
        proPrice: proPrice ?? 49,
      }),
    [freeBundledDrafts, proBundledDrafts, proPrice],
  );

  const annualSavingsPercent = useMemo(() => {
    const proTier = tiers.pro;
    if (proTier?.price == null || proTier?.price_annual == null || proTier.price <= 0) return 0;
    const monthlyTotal = proTier.price * 12;
    const savings = monthlyTotal - proTier.price_annual;
    return Math.round((savings / monthlyTotal) * 100);
  }, [tiers.pro]);

  const getPrice = (tier: TierConfig) => {
    if (tier.price === null) return { label: 'Custom', sublabel: null, savings: null };

    if (billingPeriod === 'annual' && tier.price_annual) {
      const monthlyEquivalent = (tier.price_annual / 12).toFixed(2);
      const yearlySavings = tier.price * 12 - tier.price_annual;
      return {
        label: `$${monthlyEquivalent}/mo`,
        sublabel: `Billed $${tier.price_annual}/year`,
        crossedOut: `$${tier.price}/mo`,
        savings: yearlySavings > 0 ? yearlySavings : null,
      };
    }

    return {
      label: tier.price === 0 ? 'Free' : `$${tier.price}/mo`,
      sublabel: null,
      crossedOut: null,
      savings: null,
    };
  };

  return (
    <>
      <Head title="Pricing">
        <link rel="canonical" href={`${app_url}/pricing`} />
        <meta
          name="description"
          content={
            metaDescription ??
            'WordPress SEO with AI drafts included — no API key needed. 14-day free trial. Free: 5 AI drafts/month. Pro: $49/mo with 30 drafts included. Need more? Add your own OpenAI key for unlimited at cost.'
          }
        />
        <meta property="og:title" content={`Pricing — ${appName}`} />
        <meta
          property="og:description"
          content={
            ogDescription ??
            'Free plan includes 5 AI drafts/month — no OpenAI key needed. 14-day free trial on Pro. Pro at $49/mo with 30 drafts. Surfer is $219. Clearscope is $399. Start free, upgrade when ready.'
          }
        />
        <meta property="og:type" content="website" />
        <meta property="og:url" content={`${app_url}/pricing`} />
        <meta property="og:image" content={`${app_url}/og-image.png`} />
        <meta
          property="og:image:alt"
          content={`${appName} — SEO Diagnostic and Content Optimization Tool`}
        />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content={`Pricing — ${appName}`} />
        <meta
          name="twitter:description"
          content={
            ogDescription ??
            'Free plan includes 5 AI drafts/month — no OpenAI key needed. 14-day free trial on Pro. Pro at $49/mo with 30 drafts. Surfer is $219. Clearscope is $399. Start free, upgrade when ready.'
          }
        />
        <meta name="twitter:image" content={`${app_url}/og-image.png`} />
        <meta name="twitter:image:width" content="1200" />
        <meta name="twitter:image:height" content="630" />
        <meta property="og:image:width" content="1200" />
        <meta property="og:image:height" content="630" />
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            ...softwareApplicationBase(appName),
            offers: {
              '@type': 'AggregateOffer',
              lowPrice: '0',
              highPrice: String(
                Math.max(
                  0,
                  ...tierEntries
                    .filter(([, t]) => t.price !== null && t.price !== undefined)
                    .map(([, t]) => t.price ?? 0),
                ),
              ),
              priceCurrency: 'USD',
              offerCount: String(tierEntries.filter(([, tier]) => tier.price !== null).length),
              offers: tierEntries
                .filter(([, tier]) => tier.price !== null)
                .map(([, tier]) => ({
                  '@type': 'Offer',
                  name: tier.name,
                  price: String(tier.price ?? 0),
                  priceCurrency: 'USD',
                  description: tier.description,
                })),
            },
          })}
        </script>
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'FAQPage',
            mainEntity: faqItems.map((faq) => ({
              '@type': 'Question',
              name: faq.question,
              acceptedAnswer: {
                '@type': 'Answer',
                text: faq.answer,
              },
            })),
          })}
        </script>
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'BreadcrumbList',
            itemListElement: [
              {
                '@type': 'ListItem',
                position: 1,
                name: 'Home',
                item: `${app_url}/`,
              },
              {
                '@type': 'ListItem',
                position: 2,
                name: 'Pricing',
                item: `${app_url}/pricing`,
              },
            ],
          })}
        </script>
      </Head>

      <div className="min-h-screen bg-linear-to-b from-background to-muted/30">
        <MarketingNav canLogin={canLogin} canRegister={canRegister} />

        <main id="main-content">
          {/* Hero Section */}
          <section className="container py-12 text-center">
            <div className="mx-auto max-w-3xl space-y-4">
              <h1 className="text-4xl font-bold tracking-tight sm:text-5xl">
                Simple, transparent pricing
              </h1>
              <p className="text-lg text-muted-foreground">
                {trialEnabled && trialDays
                  ? `Start your ${trialDays}-day free trial. No credit card required. Cancel anytime.`
                  : "Start free. Upgrade when you're ready. No long-term contracts."}
              </p>
              {metrics?.active_users_count != null && metrics.active_users_count > 0 && (
                <p className="text-sm text-muted-foreground">
                  <span className="font-semibold text-foreground">
                    {formatNumber(metrics.active_users_count)}
                  </span>{' '}
                  SEOs already using {appName}
                </p>
              )}
            </div>
          </section>

          <div className="container pb-12">
            <div className="max-w-5xl mx-auto space-y-10">
              {/* Competitive Positioning — AI drafts included */}
              <div className="rounded-lg border bg-card p-8">
                <div className="flex items-start gap-4">
                  <div className="rounded-lg bg-primary/10 p-3 shrink-0">
                    <ArrowRight className="h-6 w-6 text-primary" aria-hidden="true" />
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold mb-2">
                      AI Drafts Included — No API Key Required to Start
                    </h2>
                    <p className="text-muted-foreground mb-4">
                      Every plan includes bundled AI drafts powered by GPT-4o-mini. Connect your
                      site, run analysis, and generate your first AI fix in minutes — no OpenAI
                      account or API key needed. RankWiz Pro is{' '}
                      <strong>${tiers.pro?.price ?? proPrice ?? 49}/mo</strong> with{' '}
                      {tiers.pro?.limits?.bundled_ai_drafts ?? proBundledDrafts ?? 30} AI drafts
                      included.
                    </p>
                    <ul className="space-y-2 text-sm text-muted-foreground">
                      <li className="flex items-center gap-2">
                        <CheckCircle2 className="h-4 w-4 text-success shrink-0" />
                        {freeBundledDrafts ?? 5} free AI drafts/month on Free
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle2 className="h-4 w-4 text-success shrink-0" />
                        No OpenAI account required — just connect your WordPress site
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle2 className="h-4 w-4 text-success shrink-0" />
                        Need more? Bring your own key on Pro+ — unlimited at cost, no markup
                      </li>
                      <li className="flex items-center gap-2">
                        <CheckCircle2 className="h-4 w-4 text-success shrink-0" />
                        Traffic analysis and recommendations always free — no AI quota needed
                      </li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* Cost Calculator */}
              <CostCalculator
                bundledDrafts={tiers.pro?.limits?.bundled_ai_drafts ?? proBundledDrafts ?? 30}
                proPriceMonthly={tiers.pro?.price ?? proPrice ?? 49}
              />

              {/* Trial Urgency Countdown — shown to authenticated users with an active trial */}
              {trial?.active &&
                (() => {
                  const days = trial.daysRemaining ?? 0;
                  const isUrgent = days < 3;
                  const isWarning = days >= 3 && days <= 7;
                  const borderColor = isUrgent
                    ? 'border-destructive/30 bg-destructive/5'
                    : isWarning
                      ? 'border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/30'
                      : 'border-primary/20 bg-primary/5';
                  const iconColor = isUrgent
                    ? 'text-destructive'
                    : isWarning
                      ? 'text-amber-600 dark:text-amber-400'
                      : 'text-primary';
                  const Icon = isUrgent ? AlertCircle : Star;
                  const message = isUrgent
                    ? `Your trial expires in ${days} day${days !== 1 ? 's' : ''} — subscribe now to keep your Pro features`
                    : isWarning
                      ? `${days} day${days !== 1 ? 's' : ''} left in your trial — don't lose your analysis history and AI drafts`
                      : `Pro Trial Active — ${days} day${days !== 1 ? 's' : ''} remaining. Upgrade now to keep your Pro features`;
                  return (
                    <div
                      className={`flex items-center gap-3 rounded-lg border px-6 py-4 ${borderColor}`}
                    >
                      <Icon className={`h-5 w-5 shrink-0 ${iconColor}`} aria-hidden="true" />
                      <div>
                        <p className="text-sm font-semibold text-foreground">{message}</p>
                        <p className="text-xs text-muted-foreground mt-1">
                          Your analysis history and AI drafts stay with your account when you
                          upgrade.
                        </p>
                      </div>
                    </div>
                  );
                })()}

              {/* Trial Banner — shown to unauthenticated / non-trialing users when trials are enabled */}
              {trialEnabled && !trial?.active && (
                <div className="flex items-center gap-3 rounded-lg border border-primary/20 bg-primary/10 px-6 py-4">
                  <Star className="h-5 w-5 shrink-0 text-primary" aria-hidden="true" />
                  <div>
                    <p className="text-sm font-semibold text-foreground">
                      Try Pro free for {trialDays} days — no credit card required
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      Your analysis history and AI drafts stay with your account when you upgrade.
                    </p>
                  </div>
                </div>
              )}

              {/* Personalised banner for authenticated free-plan users */}
              {is_free_user && recommendedPlan && (
                <div className="flex items-center gap-3 rounded-lg border border-primary/20 bg-primary/5 px-6 py-4">
                  <TrendingUp className="h-5 w-5 shrink-0 text-primary" aria-hidden="true" />
                  <div>
                    <p className="text-sm font-semibold text-foreground">
                      Recommended for you: {tiers[recommendedPlan]?.name ?? recommendedPlan}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      Based on your current usage — upgrade when you&apos;re ready. No credit card
                      required to explore.
                    </p>
                  </div>
                </div>
              )}

              {/* Lifecycle: activated — user has seen value but not yet subscribed */}
              {is_authenticated && !is_subscribed && lifecycleStage === 'activated' && (
                <div className="flex items-center gap-3 rounded-lg border border-primary/20 bg-primary/5 px-6 py-4">
                  <TrendingUp className="h-5 w-5 shrink-0 text-primary" aria-hidden="true" />
                  <div>
                    <p className="text-sm font-semibold text-foreground">
                      You&apos;ve already seen what {appName} can do — now go further.
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      Upgrade to Pro and unlock unlimited analysis, more AI drafts, and priority
                      support.
                    </p>
                  </div>
                </div>
              )}

              {/* Lifecycle: at_risk — inactive free user, re-engage with value reminder */}
              {is_authenticated && !is_subscribed && lifecycleStage === 'at_risk' && (
                <div className="flex items-center gap-3 rounded-lg border border-amber-200 bg-amber-50 px-6 py-4 dark:border-amber-800 dark:bg-amber-950/30">
                  <Star
                    className="h-5 w-5 shrink-0 text-amber-600 dark:text-amber-400"
                    aria-hidden="true"
                  />
                  <div>
                    <p className="text-sm font-semibold text-foreground">
                      We noticed you haven&apos;t logged in for a while.
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      Your site&apos;s GSC data is still syncing. Connect WordPress and let{' '}
                      {appName} show you what&apos;s changed since you were last here.
                    </p>
                  </div>
                </div>
              )}

              {/* Lifecycle: winback/churned — former subscriber, has_had_subscription guards
                  against showing this copy to users who never subscribed */}
              {!is_subscribed &&
                hasHadSubscription &&
                (lifecycleStage === 'winback' || lifecycleStage === 'churned') && (
                  <div className="flex items-center gap-3 rounded-lg border border-primary/20 bg-primary/5 px-6 py-4">
                    <ArrowRight className="h-5 w-5 shrink-0 text-primary" aria-hidden="true" />
                    <div>
                      <p className="text-sm font-semibold text-foreground">
                        Reactivate your Pro plan and pick up right where you left off.
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">
                        Your analysis history is still here. Reactivate to resume tracking and
                        generating AI content fixes.
                      </p>
                    </div>
                  </div>
                )}

              {/* Lifecycle: trialing — fallback urgency banner when trial object is unavailable */}
              {is_authenticated &&
                !is_subscribed &&
                !trial?.active &&
                lifecycleStage === 'trialing' && (
                  <div className="flex items-center gap-3 rounded-lg border border-amber-200 bg-amber-50 px-6 py-4 dark:border-amber-800 dark:bg-amber-950/30">
                    <AlertCircle
                      className="h-5 w-5 shrink-0 text-amber-600 dark:text-amber-400"
                      aria-hidden="true"
                    />
                    <div>
                      <p className="text-sm font-semibold text-foreground">
                        Your Pro trial is active — subscribe before it ends to keep your Pro
                        features.
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">
                        Your analysis history, AI drafts, and ROI data stay with your account when
                        you upgrade.
                      </p>
                    </div>
                  </div>
                )}

              {hasAnnualPricing ? (
                <div className="flex justify-center">
                  <div className="inline-flex items-center gap-4 p-1 bg-muted rounded-lg">
                    <ToggleGroup
                      type="single"
                      value={billingPeriod}
                      onValueChange={handleBillingPeriodChange}
                    >
                      <ToggleGroupItem value="monthly" className="px-4">
                        Monthly
                      </ToggleGroupItem>
                      <ToggleGroupItem value="annual" className="px-4">
                        Annual
                        {annualSavingsPercent > 0 && (
                          <Badge variant="success" className="ml-2">
                            Save {annualSavingsPercent}%
                          </Badge>
                        )}
                      </ToggleGroupItem>
                    </ToggleGroup>
                  </div>
                </div>
              ) : (
                <p className="text-center text-sm text-muted-foreground">
                  Annual billing (save up to 20%) — coming soon. Contact us to request annual
                  pricing.
                </p>
              )}

              <p className="text-center text-sm text-muted-foreground max-w-2xl mx-auto">
                Plans scale with the number of WordPress sites you manage and how deeply you analyze
                them. Free handles 1 site. Pro handles up to 5. Team plan gives your whole agency
                unlimited sites with shared drafts and white-label reporting.
              </p>

              <h2 className="sr-only">Plans</h2>
              <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
                {tierEntries.map(([key, tier]) => {
                  const isEnterprise = tier.price === null;
                  const isPro = key === 'pro';
                  const pricing = getPrice(tier);

                  return (
                    <PlanCard
                      key={key}
                      tierKey={key}
                      tier={tier}
                      pricing={pricing}
                      billingPeriod={billingPeriod}
                      isPro={isPro}
                      isCurrent={currentPlan != null && key === currentPlan}
                      isRecommended={recommendedPlan != null && key === recommendedPlan}
                      headerExtra={
                        isPro ? (
                          <div className="mt-2">
                            <Badge variant="success" className="text-xs">
                              vs. Surfer Scale AI $219/mo
                            </Badge>
                          </div>
                        ) : undefined
                      }
                    >
                      {is_authenticated && is_subscribed && !isEnterprise && (
                        <>
                          <Button asChild className="w-full" variant="outline">
                            <Link href={route('billing.index')}>Manage Billing</Link>
                          </Button>
                          <p className="mt-2 text-center text-xs text-muted-foreground">
                            Cancel anytime &middot; Secured by Stripe
                          </p>
                        </>
                      )}

                      {is_authenticated && !is_subscribed && !isEnterprise && (
                        <>
                          {tier.coming_soon ? (
                            <Button className="w-full" variant="secondary" disabled>
                              Coming Soon
                            </Button>
                          ) : key === 'free' ? (
                            <Button asChild className="w-full" variant="outline">
                              <Link href={route('dashboard')}>Go to Dashboard</Link>
                            </Button>
                          ) : (
                            <Button
                              asChild
                              className="w-full"
                              variant={isPro ? 'default' : 'outline'}
                              onClick={() =>
                                isPro
                                  ? trackEvent(CTA_CLICKED, {
                                      cta_type: 'upgrade',
                                      cta_location: 'pricing',
                                      page: 'pricing',
                                      billing_period: billingPeriod,
                                    })
                                  : undefined
                              }
                            >
                              <Link
                                href={`${route('billing.plans')}?billing_period=${billingPeriod}&plan=${key}`}
                              >
                                Upgrade to {tier.name}
                              </Link>
                            </Button>
                          )}
                          <p className="mt-2 text-center text-xs text-muted-foreground">
                            {key === 'free'
                              ? 'Free forever \u00b7 No credit card required'
                              : trialEnabled && trialDays
                                ? `${trialDays}-day free trial \u00b7 Cancel anytime`
                                : 'Cancel anytime \u00b7 Switch plans anytime'}
                          </p>
                        </>
                      )}

                      {!is_authenticated && canRegister && !isEnterprise && (
                        <>
                          {tier.coming_soon ? (
                            <Button className="w-full" variant="secondary" disabled>
                              Coming Soon
                            </Button>
                          ) : (
                            <Button
                              asChild
                              className="w-full"
                              variant={isPro ? 'default' : 'outline'}
                              onClick={() =>
                                trackEvent(PRICING_CTA_CLICKED, {
                                  plan: key,
                                  billing_period: billingPeriod,
                                  cta_location: 'pricing',
                                })
                              }
                            >
                              {/* CRO-005/BILL-004: Carry billing_period and plan through to registration.
                                  Register.tsx reads ?billing_period= (not ?billing=) to set
                                  localStorage.intended_billing_period for post-auth redirect. */}
                              <Link
                                href={`${route('register')}?billing_period=${billingPeriod}&plan=${key}`}
                              >
                                {isPro && trialEnabled && trialDays
                                  ? `Start ${trialDays}-Day Free Trial`
                                  : isPro
                                    ? CTA_LABELS.FREE_ENTRY
                                    : CTA_LABELS.FREE_PLAN}
                              </Link>
                            </Button>
                          )}
                          <p className="mt-2 text-center text-xs text-muted-foreground">
                            {key === 'free'
                              ? 'Free forever \u00b7 No credit card required'
                              : trialEnabled && trialDays
                                ? `${trialDays}-day free trial \u00b7 Cancel anytime`
                                : 'Cancel anytime \u00b7 Switch plans anytime'}
                          </p>
                        </>
                      )}

                      {isEnterprise && (
                        <>
                          <Button
                            className="w-full"
                            variant="outline"
                            onClick={() => setEnterpriseModalOpen(true)}
                          >
                            {tier.cta_label ?? 'Contact Sales'}
                          </Button>
                          {tier.cta_subtext && (
                            <p className="mt-2 text-center text-xs text-muted-foreground">
                              {tier.cta_subtext}
                            </p>
                          )}
                        </>
                      )}
                    </PlanCard>
                  );
                })}
              </div>

              <p className="text-xs text-muted-foreground text-center">
                * Based on Clearscope Business plan pricing ($399/mo). Competitor pricing verified
                March 2026. See our{' '}
                <Link href="/vs/clearscope" className="underline hover:text-foreground">
                  comparison pages
                </Link>{' '}
                for details.
              </p>

              {/* Feature Comparison Table — driven from config/plans.php features_matrix */}
              {featuresMatrix && featuresMatrix.length > 0 && (
                <div className="mt-12">
                  <h2 className="mb-6 text-2xl font-bold text-center">Compare Plans</h2>
                  <div className="overflow-x-auto rounded-lg border bg-card">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-2/5 text-sm font-medium">Feature</TableHead>
                          {tierEntries.map(([key, tier]) => (
                            <TableHead
                              key={key}
                              className={`text-center text-sm font-semibold ${key === 'pro' ? 'bg-primary/5 text-primary' : ''}`}
                            >
                              {tier.name}
                            </TableHead>
                          ))}
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {featuresMatrix.map((section) => (
                          <>
                            <TableRow key={section.section} className="bg-muted/50">
                              <TableCell
                                colSpan={tierEntries.length + 1}
                                className="text-xs font-semibold uppercase tracking-wider text-muted-foreground py-2"
                              >
                                {section.section}
                              </TableCell>
                            </TableRow>
                            {section.rows.map((row) => (
                              <TableRow key={row.label}>
                                <TableCell className="text-sm font-medium">{row.label}</TableCell>
                                {tierEntries.map(([tierKey]) => {
                                  const value = row.values[tierKey];
                                  return (
                                    <TableCell
                                      key={tierKey}
                                      className={`text-center ${tierKey === 'pro' ? 'bg-primary/5' : ''}`}
                                    >
                                      {typeof value === 'boolean' ? (
                                        value ? (
                                          <Check
                                            className="mx-auto h-4 w-4 text-primary"
                                            aria-label="Included"
                                          />
                                        ) : (
                                          <Minus
                                            className="mx-auto h-4 w-4 text-muted-foreground/40"
                                            aria-label="Not included"
                                          />
                                        )
                                      ) : (
                                        <span className="text-sm">{value ?? '—'}</span>
                                      )}
                                    </TableCell>
                                  );
                                })}
                              </TableRow>
                            ))}
                          </>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              )}

              {/* Testimonials Section */}
              <TestimonialsSection testimonials={testimonials ?? []} />

              {/* FAQ Section */}
              <div className="mt-16">
                <h2 className="mb-8 text-2xl font-bold text-center">Frequently Asked Questions</h2>
                <div className="space-y-4">
                  {faqItems.map((faq, index) => (
                    <Collapsible key={index} className="border rounded-lg">
                      <CollapsibleTrigger className="group flex w-full items-center justify-between p-4 hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded-t-lg">
                        <h3 className="font-semibold text-left">{faq.question}</h3>
                        <ChevronDown
                          className="h-4 w-4 shrink-0 transition-transform group-data-[state=open]:rotate-180"
                          aria-hidden="true"
                        />
                      </CollapsibleTrigger>
                      <CollapsibleContent className="px-4 pb-4 text-sm text-muted-foreground border-t">
                        {faq.answer}
                      </CollapsibleContent>
                    </Collapsible>
                  ))}
                </div>
              </div>

              {/* CTA Section */}
              {canRegister && (
                <section className="py-12" data-testid="bottom-cta-section">
                  <div className="rounded-2xl bg-linear-to-r from-primary/10 via-primary/5 to-background p-12 text-center">
                    <h2 className="mb-4 text-3xl font-bold tracking-tight">
                      Start Free — 5 AI Drafts Included, No Credit Card
                    </h2>
                    <p className="mb-8 text-lg text-muted-foreground">
                      Join free. Get your first AI content fix in under 10 minutes. Upgrade when
                      you&apos;re ready — cancel anytime.
                    </p>
                    <Button size="lg" asChild>
                      <Link href={route('register')}>
                        {CTA_LABELS.FREE_PLAN}
                        <ArrowRight className="ml-2 h-4 w-4" />
                      </Link>
                    </Button>
                  </div>
                </section>
              )}
            </div>
          </div>
        </main>

        <EnterpriseContactModal open={enterpriseModalOpen} onOpenChange={setEnterpriseModalOpen} />
        <MarketingFooter />
        {!is_authenticated && canRegister && <ExitIntentCapture />}
      </div>
    </>
  );
};

Pricing.disableGlobalUi = true;

export default Pricing;
