import {
  AlertCircle,
  CheckCircle2,
  ChevronDown,
  Lock,
  Minus,
  Plus,
  Shield,
  Sparkles,
} from 'lucide-react';

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

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

import { EnterpriseContactModal } from '@/Components/billing/EnterpriseContactModal';
import { LaunchPricingBadge } from '@/Components/billing/LaunchPricingBadge';
import { PlanCard } from '@/Components/billing/PlanCard';
import { SwapConfirmationDialog } from '@/Components/billing/SwapConfirmationDialog';
import PageHeader from '@/Components/layout/PageHeader';
import { CostCalculator } from '@/Components/marketing/CostCalculator';
import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import { TestimonialsSection } from '@/Components/marketing/TestimonialsSection';
import { Alert, AlertDescription } from '@/Components/ui/alert';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/Components/ui/collapsible';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { Input } from '@/Components/ui/input';
import { LoadingButton } from '@/Components/ui/loading-button';
import { ToggleGroup, ToggleGroupItem } from '@/Components/ui/toggle-group';
import {
  BYOK_BULLETS,
  COMPETITIVE_PRICING_FAQ_ITEMS,
  PRICING_FAQ_ITEMS,
} from '@/config/pricing-copy';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEcommerceEvent, trackProductEvent } from '@/lib/analytics';
import { PRICING_VIEWED } from '@/lib/event-catalog';
import { softwareApplicationBase } from '@/lib/schema';
import type { Auth, Limits, 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;
  contact_only?: boolean;
  limits?: Record<string, number | null>;
  features?: string[];
  best_for?: string;
  cta_label?: string;
  cta_subtext?: string;
}

interface PricingTrial {
  active: boolean;
  daysRemaining: number | null;
  endsAt: string;
}

interface PricingPageProps extends Omit<PageProps, 'trial'> {
  tiers: Record<string, TierConfig>;
  current_plan?: string | null;
  is_subscribed?: boolean;
  trial?: PricingTrial | null;
  trialEnabled?: boolean;
  trialDays?: number;
  salesEmail?: string;
  recommended_plan?: string;
  /** Allowlisted lifecycle stage ('activated' | 'at_risk' | 'winback' | 'churned' | null) */
  lifecycle_stage?: string | null;
  /** When true, renders the "Launch pricing — locked in for life" badge on the highlighted Pro tier card. */
  launch_pricing?: boolean;
  testimonials?: Array<{
    id: number;
    name: string;
    role: string;
    company: string;
    quote: string;
    avatar_url: string | null;
    rating: number;
    source: string;
    source_url: string | null;
    featured: boolean;
  }>;
}

export default function Pricing() {
  const {
    tiers,
    current_plan: currentPlan,
    is_subscribed: isSubscribedProp,
    trial,
    app_url,
    recommended_plan,
    testimonials = [],
    limits: limitsRaw,
    auth,
    lifecycle_stage: lifecycleStage,
    launch_pricing: launchPricing = false,
  } = usePage<PricingPageProps>().props;
  const limits = limitsRaw as Limits | null;
  const isAuthenticated = Boolean((auth as Auth | undefined)?.user);
  const tierEntries = useMemo(() => Object.entries(tiers), [tiers]);

  // BILL-004: Pre-select annual billing from URL param (carried through registration)
  const [billingPeriod, setBillingPeriod] = useState<'monthly' | 'annual'>(() => {
    if (typeof window !== 'undefined') {
      const params = new URLSearchParams(window.location.search);
      if (params.get('billing_period') === 'annual') return 'annual';
    }
    return 'monthly';
  });

  // BILL-004: Auto-scroll to highlighted plan card (carried through post-registration redirect)
  const highlightPlan = useMemo(
    () =>
      typeof window !== 'undefined'
        ? new URLSearchParams(window.location.search).get('highlight')
        : null,
    [],
  );
  const [highlightActive, setHighlightActive] = useState(!!highlightPlan);
  const highlightTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (!highlightPlan) return;
    const el = document.getElementById(`plan-${highlightPlan}`);
    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
    highlightTimerRef.current = setTimeout(() => setHighlightActive(false), 3000);
    return () => {
      if (highlightTimerRef.current) clearTimeout(highlightTimerRef.current);
    };
  }, [highlightPlan]);

  // ANA-007: Track pricing page view on mount to close the conversion funnel gap
  useEffect(() => {
    trackProductEvent(PRICING_VIEWED, { source: 'billing_page', plan_count: tierEntries.length });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const [checkoutLoading, setCheckoutLoading] = useState<string | null>(null);
  const [enterpriseModalOpen, setEnterpriseModalOpen] = useState(false);
  const testimonialsToShow = testimonials;
  const [swapDialog, setSwapDialog] = useState<{
    open: boolean;
    newPlan: string;
    newPriceId: string;
  }>({ open: false, newPlan: '', newPriceId: '' });

  // CRO-013: Pre-checkout confirmation step for new subscribers
  const [checkoutConfirm, setCheckoutConfirm] = useState<{
    open: boolean;
    planKey: string;
    priceId: string;
  }>({ open: false, planKey: '', priceId: '' });

  // BILL-005: Seat count state for Team plan
  const teamTier = tiers.team;
  const teamMinSeats = teamTier?.min_seats ?? 2;
  const [seatCount, setSeatCount] = useState<number>(teamMinSeats);

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

  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.contact_only || tier.price === null)
      return { label: 'Custom', sublabel: null, crossedOut: 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,
    };
  };

  const isSubscribed = Boolean(isSubscribedProp);

  const handleCheckout = (planKey: string) => {
    const tier = tiers[planKey];
    const priceId =
      billingPeriod === 'annual' && tier.stripe_price_id_annual
        ? tier.stripe_price_id_annual
        : tier.stripe_price_id;

    setCheckoutLoading(planKey);

    // INST-002: Use trackEcommerceEvent (GA4 Enhanced Ecommerce items-array schema) so
    // begin_checkout appears in GA4 ecommerce funnel reports, not just as a flat event.
    trackEcommerceEvent(
      'begin_checkout',
      {
        item_id: planKey,
        item_name: tier.name,
        price:
          billingPeriod === 'annual' && tier.price_annual ? tier.price_annual : (tier.price ?? 0),
      },
      billingPeriod === 'annual' && tier.price_annual ? tier.price_annual : (tier.price ?? 0),
      'USD',
    );

    if (isSubscribed) {
      setCheckoutLoading(null);
      setSwapDialog({ open: true, newPlan: planKey, newPriceId: priceId ?? '' });
      return;
    }

    // CRO-013: Show pre-checkout confirmation for new subscribers before redirecting to Stripe
    setCheckoutLoading(null);
    setCheckoutConfirm({ open: true, planKey, priceId: priceId ?? '' });
  };

  const handleConfirmCheckout = () => {
    const { planKey, priceId } = checkoutConfirm;
    const tier = tiers[planKey];
    if (!tier) return;
    const quantity = tier.per_seat ? seatCount : 1;
    setCheckoutConfirm((prev) => ({ ...prev, open: false }));
    setCheckoutLoading(planKey);
    router.post(
      route('billing.subscribe'),
      {
        price_id: priceId,
        quantity,
        seat_count: tier.per_seat ? seatCount : undefined,
      },
      { onFinish: () => setCheckoutLoading(null) },
    );
  };

  const pricingContent = (
    <>
      <Head title="Pricing">
        {isAuthenticated ? (
          <link rel="canonical" href={`${app_url}/billing/plans`} />
        ) : (
          <link rel="canonical" href={`${app_url}/pricing`} />
        )}
        {isAuthenticated && <meta name="robots" content="noindex" />}
        <meta
          name="description"
          content="Simple, transparent pricing for WordPress SEO. Free to start, Pro with unlimited AI drafts. You control your OpenAI costs — no markup."
        />
        <meta
          property="og:title"
          content={`Pricing — ${import.meta.env.VITE_APP_NAME || 'RankWiz'}`}
        />
        <meta
          property="og:description"
          content="Free traffic analysis and recommendations. Pro: unlimited AI drafts with your OpenAI key. No surprise bills, no markup."
        />
        <meta property="og:type" content="website" />
        <meta property="og:image" content={`${app_url}/og-image.png`} />
        <meta name="twitter:card" content="summary" />
        <meta name="twitter:site" content="@rankwiz_ai" />
        <meta
          name="twitter:title"
          content={`Pricing — ${import.meta.env.VITE_APP_NAME || 'RankWiz'}`}
        />
        <meta
          name="twitter:description"
          content="Free traffic analysis and recommendations. Pro: unlimited AI drafts with your OpenAI key. No surprise bills, no markup."
        />
        <meta name="twitter:image" content={`${app_url}/og-image.png`} />
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            ...softwareApplicationBase(import.meta.env.VITE_APP_NAME || 'RankWiz'),
            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: [...PRICING_FAQ_ITEMS, ...COMPETITIVE_PRICING_FAQ_ITEMS].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: isAuthenticated ? `${app_url}/billing/plans` : `${app_url}/pricing`,
              },
            ],
          })}
        </script>
      </Head>
      <PageHeader
        title="Pricing"
        subtitle={
          isAuthenticated
            ? 'Your own OpenAI key — pay ~$0.01 per draft, no markup. Cancel any time.'
            : 'Simple, transparent pricing that grows with you'
        }
      />
      <div className="container py-12">
        <div className="max-w-5xl mx-auto space-y-10">
          {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={(value) =>
                    value && setBillingPeriod(value as 'monthly' | 'annual')
                  }
                >
                  <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 gives your whole agency unlimited
            sites with shared drafts and white-label reporting.
          </p>

          {/* Competitive positioning strip */}
          <div className="rounded-lg border bg-primary/5 p-4 text-center text-sm text-muted-foreground">
            Pro includes {tiers.pro?.limits?.bundled_ai_drafts ?? 30} AI drafts/month — no OpenAI
            key needed. Compare: Surfer Scale AI $219, Clearscope $399. RankWiz Pro $
            {tiers.pro?.price ?? 49}.
          </div>

          {trial?.active &&
            (() => {
              const days = trial.daysRemaining ?? 0;
              const isUrgent = days < 3;
              const isWarning = days >= 3 && days <= 7;

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

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

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

              const drafts = limits?.drafts_used_this_month ?? 0;
              const sites = limits?.sites_used_count ?? 0;
              const specificParts: string[] = [];
              if (drafts > 0) specificParts.push(`${drafts} AI draft${drafts !== 1 ? 's' : ''}`);
              if (sites > 0) specificParts.push(`${sites} connected site${sites !== 1 ? 's' : ''}`);
              const specificLoss = specificParts.length > 0 ? specificParts.join(' and ') : null;

              const message = isUrgent
                ? specificLoss
                  ? `Your trial expires in ${days} day${days !== 1 ? 's' : ''} — your ${specificLoss} will lose Pro access`
                  : `Your trial expires in ${days} day${days !== 1 ? 's' : ''} — subscribe now to keep your data`
                : isWarning
                  ? specificLoss
                    ? `Don't lose access to your ${specificLoss} — ${days} day${days !== 1 ? 's' : ''} remaining`
                    : `Don't lose access to Pro features — ${days} day${days !== 1 ? 's' : ''} remaining`
                  : `Pro Trial Active — You have ${days} day${days !== 1 ? 's' : ''} remaining. Upgrade now to keep your Pro features!`;

              const Icon = isUrgent ? AlertCircle : Sparkles;

              return (
                <Alert className={alertClass}>
                  <Icon className={`h-4 w-4 ${iconColor}`} />
                  <AlertDescription className="text-center">
                    <strong className={textColor}>{message}</strong>
                  </AlertDescription>
                </Alert>
              );
            })()}

          {/* Lifecycle-aware messaging — only shown when trial banner is not active */}
          {isAuthenticated && !isSubscribed && !trial?.active && lifecycleStage === 'at_risk' && (
            <Alert className="border-amber-500/30 bg-amber-500/10 dark:border-amber-400/30 dark:bg-amber-400/10">
              <AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-400" />
              <AlertDescription>
                <strong className="text-amber-700 dark:text-amber-300">
                  We noticed you haven&apos;t logged in for a while.
                </strong>{' '}
                Your analysis history, keyword opportunities, and ROI snapshots are still here — and
                your sites have kept tracking while you were away. Check what&apos;s changed.
              </AlertDescription>
            </Alert>
          )}

          {isAuthenticated && !isSubscribed && !trial?.active && lifecycleStage === 'activated' && (
            <Alert className="border-primary/30 bg-primary/10">
              <Sparkles className="h-4 w-4 text-primary" />
              <AlertDescription>
                <strong className="text-primary">
                  You&apos;ve already used RankWiz — now go further.
                </strong>{' '}
                Upgrade to Pro for unlimited AI drafts, 5-site analysis, full ROI tracking, and team
                collaboration.
              </AlertDescription>
            </Alert>
          )}

          {isAuthenticated &&
            !isSubscribed &&
            !trial?.active &&
            (lifecycleStage === 'winback' || lifecycleStage === 'churned') && (
              <Alert className="border-primary/30 bg-primary/10">
                <Sparkles className="h-4 w-4 text-primary" />
                <AlertDescription>
                  <strong className="text-primary">Welcome back.</strong> Since you last subscribed
                  we&apos;ve added content briefs, SEO calendars, traffic anomaly detection, and
                  deeper ROI tracking. All your historical data is still here.
                </AlertDescription>
              </Alert>
            )}

          {/* Lifecycle-aware messaging — trialing fallback when trial object is unavailable */}
          {isAuthenticated && !isSubscribed && !trial?.active && lifecycleStage === 'trialing' && (
            <Alert className="border-amber-500/30 bg-amber-500/10 dark:border-amber-400/30 dark:bg-amber-400/10">
              <AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-400" />
              <AlertDescription>
                <strong className="text-amber-700 dark:text-amber-300">
                  Your Pro trial is active.
                </strong>{' '}
                Subscribe before it ends to keep your analysis history, AI drafts, and ROI
                snapshots. Everything you&apos;ve built stays with your account.
              </AlertDescription>
            </Alert>
          )}

          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
            {tierEntries.map(([key, tier]) => {
              const isCurrent = currentPlan === key;
              const isEnterprise = tier.contact_only === true;
              const isPro = key === 'pro';
              const pricing = getPrice(tier);
              const isHighlighted = highlightActive && highlightPlan === key;

              return (
                <div
                  key={key}
                  id={`plan-${key}`}
                  className={
                    isHighlighted
                      ? 'rounded-xl ring-2 ring-primary ring-offset-2 transition-all'
                      : ''
                  }
                >
                  <PlanCard
                    tierKey={key}
                    tier={tier}
                    pricing={pricing}
                    billingPeriod={billingPeriod}
                    isPro={isPro}
                    isCurrent={isCurrent}
                    isRecommended={key === recommended_plan}
                    headerExtra={launchPricing && isPro ? <LaunchPricingBadge /> : undefined}
                  >
                    {/* BILL-005: Seat count picker for Team plan */}
                    {tier.per_seat && tier.min_seats && !isCurrent && (
                      <div className="rounded-lg border bg-muted/30 p-3 space-y-2">
                        <label htmlFor={`seat-count-${key}`} className="text-sm font-medium">
                          Team size
                        </label>
                        <div className="flex items-center gap-2">
                          <button
                            type="button"
                            aria-label="Remove a seat"
                            onClick={() =>
                              setSeatCount((c) => Math.max(tier.min_seats ?? 2, c - 1))
                            }
                            className="flex h-11 w-11 items-center justify-center rounded-md border border-input bg-background text-muted-foreground hover:bg-muted hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                          >
                            <Minus className="h-4 w-4" />
                          </button>
                          <Input
                            id={`seat-count-${key}`}
                            type="number"
                            min={tier.min_seats}
                            max={50}
                            value={seatCount}
                            onChange={(e) => {
                              const val = parseInt(e.target.value, 10);
                              if (!isNaN(val))
                                setSeatCount(Math.max(tier.min_seats ?? 2, Math.min(50, val)));
                            }}
                            className="w-16 min-h-[44px] text-center tabular-nums [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
                            aria-label="Number of seats"
                          />
                          <button
                            type="button"
                            aria-label="Add a seat"
                            onClick={() => setSeatCount((c) => Math.min(50, c + 1))}
                            className="flex h-11 w-11 items-center justify-center rounded-md border border-input bg-background text-muted-foreground hover:bg-muted hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                          >
                            <Plus className="h-4 w-4" />
                          </button>
                          <span className="text-sm text-muted-foreground">seats</span>
                        </div>
                        <p className="text-xs font-medium text-primary">
                          Total: $
                          {(
                            (billingPeriod === 'annual' && tier.price_annual
                              ? tier.price_annual / 12
                              : (tier.price ?? 0)) * seatCount
                          ).toFixed(2)}
                          /mo
                        </p>
                      </div>
                    )}

                    {/* Authenticated users: direct checkout flow. Guests: register-link CTAs. */}
                    {!isEnterprise && !isCurrent && key !== 'free' && (
                      <>
                        {tier.coming_soon ? (
                          <Button className="w-full" variant="secondary" disabled>
                            Coming Soon
                          </Button>
                        ) : isAuthenticated ? (
                          <>
                            <LoadingButton
                              className="w-full"
                              onClick={() => handleCheckout(key)}
                              loading={checkoutLoading === key}
                              loadingText="Processing..."
                            >
                              {isSubscribed
                                ? `Switch to ${tier.name}${billingPeriod === 'annual' ? ' (Annual)' : ''}`
                                : (tier.cta_label ??
                                  `Upgrade to ${tier.name}${billingPeriod === 'annual' ? ' (Annual)' : ''}`)}
                            </LoadingButton>
                            <div className="mt-2 flex items-center justify-center gap-3 text-xs text-muted-foreground">
                              <span className="flex items-center gap-1">
                                <Shield className="h-3 w-3" aria-hidden="true" />
                                Stripe Secured
                              </span>
                              <span className="flex items-center gap-1 font-medium text-foreground/70">
                                <Shield className="h-3 w-3 text-success" aria-hidden="true" />
                                30-day money-back guarantee
                              </span>
                            </div>
                          </>
                        ) : (
                          <>
                            <Button className="w-full" asChild>
                              <Link
                                href={`${route('register')}?plan=${key}${billingPeriod === 'annual' ? '&billing_period=annual' : ''}`}
                              >
                                {tier.cta_label ?? `Get started with ${tier.name}`}
                              </Link>
                            </Button>
                            <div className="mt-2 flex items-center justify-center gap-3 text-xs text-muted-foreground">
                              <span className="flex items-center gap-1">
                                <Shield className="h-3 w-3 text-success" aria-hidden="true" />
                                30-day money-back guarantee
                              </span>
                            </div>
                          </>
                        )}
                      </>
                    )}

                    {!isEnterprise && !isCurrent && key === 'free' && (
                      <Button asChild className="w-full" variant="outline">
                        {isAuthenticated ? (
                          <Link href="/dashboard">Go to Dashboard</Link>
                        ) : (
                          <Link href={route('register')}>Start free</Link>
                        )}
                      </Button>
                    )}

                    {isEnterprise && !isCurrent && (
                      <>
                        <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>
                        )}
                      </>
                    )}

                    {isCurrent && (
                      <Button asChild className="w-full" variant="outline">
                        <Link href={route('billing.index')}>Manage Billing</Link>
                      </Button>
                    )}
                  </PlanCard>
                </div>
              );
            })}
          </div>

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

          {/* BYOK Section */}
          <div className="mt-16 rounded-lg border bg-card p-8">
            <div className="flex items-start gap-4">
              <div className="rounded-lg bg-primary/10 p-3">
                <Lock className="h-6 w-6 text-primary" />
              </div>
              <div className="flex-1">
                <div className="flex flex-wrap items-center gap-3 mb-2">
                  <h3 className="text-lg font-semibold">
                    No Surprise AI Bills — Bring Your Own OpenAI Key
                  </h3>
                  <span className="rounded-full bg-primary/10 px-2.5 py-0.5 text-xs font-medium text-primary">
                    No AI markup
                  </span>
                </div>
                <p className="text-muted-foreground mb-4">
                  Bring your own OpenAI account. Pay ~$0.01 per draft direct to OpenAI — we never
                  mark it up. No surprise bills. Full transparency.
                </p>
                <div className="grid gap-4 sm:grid-cols-2">
                  <ul className="space-y-2 text-sm text-muted-foreground">
                    {BYOK_BULLETS.map((bullet) => (
                      <li key={bullet} className="flex items-center gap-2">
                        <CheckCircle2
                          aria-hidden="true"
                          className="h-4 w-4 text-success shrink-0"
                        />
                        {bullet}
                      </li>
                    ))}
                  </ul>
                  <ul className="space-y-2 text-sm text-muted-foreground">
                    <li className="flex items-center gap-2">
                      <CheckCircle2 aria-hidden="true" className="h-4 w-4 text-success shrink-0" />
                      Free plan: {tiers.free?.limits?.max_sites_per_user ?? 1} site,{' '}
                      {tiers.free?.limits?.bundled_ai_drafts ?? 5} AI drafts/month
                    </li>
                    <li className="flex items-center gap-2">
                      <CheckCircle2 aria-hidden="true" className="h-4 w-4 text-success shrink-0" />
                      Full traffic analysis on free plan
                    </li>
                    <li className="flex items-center gap-2">
                      <CheckCircle2 aria-hidden="true" className="h-4 w-4 text-success shrink-0" />
                      No credit card required to start
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>

          {/* Testimonials Section — only real testimonials */}
          {testimonialsToShow.length > 0 && (
            <TestimonialsSection testimonials={testimonialsToShow} />
          )}

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

      <EnterpriseContactModal
        open={enterpriseModalOpen}
        onOpenChange={setEnterpriseModalOpen}
        pricePerSeat={tiers.enterprise?.price ?? 199}
        annualPricePerSeat={tiers.enterprise?.price_annual ?? undefined}
      />

      <SwapConfirmationDialog
        open={swapDialog.open}
        onOpenChange={(open) => setSwapDialog((prev) => ({ ...prev, open }))}
        currentPlan={currentPlan ?? 'free'}
        newPlan={swapDialog.newPlan}
        newPriceId={swapDialog.newPriceId}
        tiers={
          tiers as Record<string, Parameters<typeof SwapConfirmationDialog>[0]['tiers'][string]>
        }
      />

      {/* CRO-013: Pre-checkout confirmation step — reinforces value before Stripe redirect */}
      {checkoutConfirm.planKey && tiers[checkoutConfirm.planKey] && (
        <Dialog
          open={checkoutConfirm.open}
          onOpenChange={(open) => setCheckoutConfirm((prev) => ({ ...prev, open }))}
        >
          <DialogContent className="max-w-md">
            <DialogHeader>
              <DialogTitle>Confirm your {tiers[checkoutConfirm.planKey].name} plan</DialogTitle>
              <DialogDescription>
                Review what&apos;s included before you proceed to secure checkout.
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4 py-2">
              {/* Plan summary */}
              <div className="rounded-lg border bg-muted/30 p-4">
                <div className="flex items-center justify-between mb-2">
                  <span className="font-semibold text-foreground">
                    {tiers[checkoutConfirm.planKey].name}
                  </span>
                  <span className="text-sm font-medium text-foreground">
                    {getPrice(tiers[checkoutConfirm.planKey]).label}
                  </span>
                </div>
                {tiers[checkoutConfirm.planKey].description && (
                  <p className="text-sm text-muted-foreground">
                    {tiers[checkoutConfirm.planKey].description}
                  </p>
                )}
              </div>

              {/* Key features */}
              {(tiers[checkoutConfirm.planKey].features ?? []).slice(0, 4).length > 0 && (
                <ul className="space-y-1.5">
                  {(tiers[checkoutConfirm.planKey].features ?? []).slice(0, 4).map((f) => (
                    <li key={f} className="flex items-center gap-2 text-sm text-muted-foreground">
                      <CheckCircle2 className="h-4 w-4 text-success shrink-0" aria-hidden="true" />
                      {f}
                    </li>
                  ))}
                </ul>
              )}

              {/* Trial period */}
              {trial?.active && (
                <div className="flex items-center gap-2 rounded-md border border-primary/30 bg-primary/5 px-3 py-2 text-sm text-primary">
                  <Sparkles className="h-4 w-4 shrink-0" aria-hidden="true" />
                  <span>Your trial access continues — no charge until the trial ends.</span>
                </div>
              )}

              {/* Guarantee — prominently surfaced */}
              <div className="flex items-center gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2 text-sm text-foreground">
                <Shield className="h-4 w-4 shrink-0 text-success" aria-hidden="true" />
                <span>
                  <strong>30-day money-back guarantee</strong> — full refund within 30 days, no
                  questions asked.
                </span>
              </div>
            </div>

            <DialogFooter className="flex-col gap-3">
              <div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
                <Button
                  variant="outline"
                  onClick={() => setCheckoutConfirm((prev) => ({ ...prev, open: false }))}
                  className="w-full sm:w-auto"
                >
                  Go back
                </Button>
                <LoadingButton
                  className="w-full sm:w-auto"
                  onClick={handleConfirmCheckout}
                  loading={checkoutLoading === checkoutConfirm.planKey}
                  loadingText="Redirecting to checkout…"
                >
                  Confirm and proceed to checkout
                </LoadingButton>
              </div>
              {/* CRO-001: Trust strip — Stripe badge + guarantee + social proof at highest-friction moment */}
              <div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-1 border-t pt-3 text-xs text-muted-foreground">
                <span className="flex items-center gap-1">
                  <Shield className="h-3 w-3" aria-hidden="true" />
                  Stripe Secured
                </span>
                <span className="flex items-center gap-1">
                  <Shield className="h-3 w-3 text-success" aria-hidden="true" />
                  30-day money-back guarantee
                </span>
              </div>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </>
  );

  if (!isAuthenticated) {
    // Guest view: marketing layout with register/login CTAs
    let canLogin = false;
    let canRegister = false;
    try {
      canLogin = !!route('login');
    } catch {
      /* route not registered */
    }
    try {
      canRegister = !!route('register');
    } catch {
      /* route not registered */
    }

    return (
      <div className="min-h-screen bg-linear-to-b from-background to-muted/30">
        <MarketingNav canLogin={canLogin} canRegister={canRegister} />
        <main id="main-content">{pricingContent}</main>
        <MarketingFooter />
      </div>
    );
  }

  return <DashboardLayout>{pricingContent}</DashboardLayout>;
}
