"use client";

import { useState, useEffect, useRef, Suspense } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { useTranslations, useLocale } from "next-intl";
import toast from "react-hot-toast";
import {
  useSubscriptionControllerCreateCheckoutV1,
  useSubscriptionControllerStartTrialV1,
  useSubscriptionControllerGetBillingHistoryV1,
  useSubscriptionControllerGetPlansV1,
  useSubscriptionControllerGetBillingPortalV1,
  useSubscriptionControllerGetSubscriptionStatusV1,
} from "@/api/user/practitioner-subscription/practitioner-subscription";
import { getUserDataCookie, setUserDataCookie, type UserData } from "@/lib/cookies";

// Fallback ES translations for plan feature strings not yet translated by the backend.
// Only used when the API does not return `monthly_es` / `yearly_es` for a plan.
const FEATURE_ES: Record<string, string> = {
  "Up to 10 practitioners": "Hasta 10 terapeutas",
  "Up to 5 practitioners": "Hasta 5 terapeutas",
  "Up to 20 practitioners": "Hasta 20 terapeutas",
  "Up to 50 practitioners": "Hasta 50 terapeutas",
  "Unlimited practitioners": "Terapeutas ilimitados",
  "Unlimited client screenings": "Evaluaciones de clientes ilimitadas",
  "Unlimited screenings": "Evaluaciones ilimitadas",
  "Dedicated account manager": "Gerente de cuenta dedicado",
  "Custom data retention policies": "Políticas de retención de datos personalizadas",
  "Advanced security features": "Funciones de seguridad avanzadas",
  "On-premise deployment option": "Opción de implementación en sus instalaciones",
  "24/7 phone support": "Soporte telefónico 24/7",
  "Custom training & onboarding": "Capacitación e incorporación personalizada",
  "Priority support": "Soporte prioritario",
  "Advanced analytics": "Análisis avanzado",
  "Team collaboration": "Colaboración en equipo",
  "All monthly features included": "Todas las funciones mensuales incluidas",
  "2 months free": "2 meses gratis",
};
const applyFeatureTranslations = (features: string[], locale: string): string[] =>
  locale === "es" ? features.map((f) => FEATURE_ES[f] ?? f) : features;

function SubscriptionPageContent() {
  const t = useTranslations();
  const locale = useLocale();
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const [currentPage, setCurrentPage] = useState(1);
  const [pmBillingCycle, setPmBillingCycle] = useState<'monthly' | 'annual'>('annual');
  const [pendingCard, setPendingCard] = useState<string | null>(null);
  const [trialUsed, setTrialUsed] = useState(false);
  const pricingRef = useRef<HTMLDivElement>(null);

  // Handle Stripe cancel redirect — show toast once then strip the query param
  useEffect(() => {
    if (searchParams.get("canceled") === "true") {
      toast.error(t("practitioner.subscription.paymentCanceled"), { duration: 4000 });
      router.replace(pathname, { scroll: false });
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps


  // Fetch plans from backend API (Stripe)
  const { data: plansData, isLoading: isLoadingPlans, error: plansError, refetch: refetchPlans } = useSubscriptionControllerGetPlansV1();

  // Separate individual plans (rendered as separate cards) and group plan (single card with toggle)
  const allPlans = plansData?.data || [];
  const groupRawPlan = allPlans.find((p) => ((p as any).subscription_type || 'individual') === 'group');
  const individualRawPlans = allPlans.filter((p) => ((p as any).subscription_type || 'individual') !== 'group');

  const individualPlans: Array<{ name: string; price: string; period: string; description: string; features: string[]; buttonText: string; buttonStyle: string; planType: "monthly" | "annual"; savings?: number }> = [];
  individualRawPlans.forEach((plan) => {
    const featuresObj = plan.features as Record<string, string[]> | undefined;
    const planName = locale === 'es' ? ((plan as any).name_es || plan.name) : plan.name;
    const planDescription = locale === 'es' ? ((plan as any).description_es || plan.description) : plan.description;
    const yearlySavings = plan.price_monthly && plan.price_yearly
      ? plan.price_monthly * 12 - plan.price_yearly
      : 0;
    if (plan.price_monthly) {
      const monthlyFeatures = applyFeatureTranslations(locale === 'es'
        ? (featuresObj?.monthly_es || featuresObj?.monthly || featuresObj?.month || Object.values(featuresObj || {})[0] as string[] || [])
        : (featuresObj?.monthly || featuresObj?.month || Object.values(featuresObj || {})[0] as string[] || []), locale);
      individualPlans.push({
        name: planName,
        price: `$${plan.price_monthly}`,
        period: t("practitioner.subscription.perMonth"),
        description: planDescription,
        features: monthlyFeatures,
        buttonText: t("practitioner.subscription.subscribeNow"),
        buttonStyle: "filled",
        planType: "monthly",
      });
    }
    if (plan.price_yearly) {
      const yearlyFeatures = applyFeatureTranslations(locale === 'es'
        ? (featuresObj?.yearly_es || featuresObj?.yearly || featuresObj?.year || Object.values(featuresObj || {})[1] as string[] || Object.values(featuresObj || {})[0] as string[] || [])
        : (featuresObj?.yearly || featuresObj?.year || Object.values(featuresObj || {})[1] as string[] || Object.values(featuresObj || {})[0] as string[] || []), locale);
      individualPlans.push({
        name: planName,
        price: `$${plan.price_yearly}`,
        period: t("practitioner.subscription.perYear"),
        description: planDescription,
        features: yearlyFeatures,
        buttonText: t("practitioner.subscription.upgradeNow"),
        buttonStyle: "outline",
        planType: "annual",
        savings: yearlySavings > 0 ? yearlySavings : undefined,
      });
    }
  });

  // Group/PM plan — single card with monthly/yearly toggle
  const groupPlanData = groupRawPlan ? (() => {
    const featuresObj = groupRawPlan.features as Record<string, string[]> | undefined;
    const groupSavings = groupRawPlan.price_monthly && groupRawPlan.price_yearly
      ? groupRawPlan.price_monthly * 12 - groupRawPlan.price_yearly
      : 0;
    return {
      name: locale === 'es' ? ((groupRawPlan as any).name_es || groupRawPlan.name) : groupRawPlan.name,
      description: locale === 'es' ? ((groupRawPlan as any).description_es || groupRawPlan.description) : groupRawPlan.description,
      priceMonthly: groupRawPlan.price_monthly ? `$${groupRawPlan.price_monthly}` : null,
      priceYearly: groupRawPlan.price_yearly ? `$${groupRawPlan.price_yearly}` : null,
      yearlySavings: groupSavings > 0 ? groupSavings : 0,
      featuresMonthly: applyFeatureTranslations(locale === 'es'
        ? (featuresObj?.monthly_es || featuresObj?.monthly || featuresObj?.month || Object.values(featuresObj || {})[0] as string[] || [])
        : (featuresObj?.monthly || featuresObj?.month || Object.values(featuresObj || {})[0] as string[] || []), locale),
      featuresYearly: applyFeatureTranslations(locale === 'es'
        ? (featuresObj?.yearly_es || featuresObj?.yearly || featuresObj?.year || Object.values(featuresObj || {})[1] as string[] || Object.values(featuresObj || {})[0] as string[] || [])
        : (featuresObj?.yearly || featuresObj?.year || Object.values(featuresObj || {})[1] as string[] || Object.values(featuresObj || {})[0] as string[] || []), locale),
    };
  })() : null;

  // Fetch billing history from API (backend check for active subscription)
  const { data: billingData, isLoading: isLoadingBilling, error: billingError } = useSubscriptionControllerGetBillingHistoryV1();
  const billingRecords = billingData?.data || [];
  const billingMeta = billingData?.meta;
  const totalPages = billingMeta?.totalPages || 1;

  // Show toast when billing history API fails
  useEffect(() => {
    if (billingError) {
      toast.error(t("practitioner.subscription.billingLoadError"), { id: "billing-error", duration: 5000 });
    }
  }, [billingError]);

  // Read cookie on client only (avoids hydration mismatch)
  const [userData, setUserData] = useState<UserData | null>(null);
  useEffect(() => {
    setUserData(getUserDataCookie());
  }, []);

  // Fetch subscription status from API via Orval hook
  const { data: statusData, isLoading: isLoadingStatus, refetch: refetchStatus } = useSubscriptionControllerGetSubscriptionStatusV1();
  const subscriptionStatus = statusData?.data?.status || null;
  const periodEnd = statusData?.data?.current_period_end || null;
  const activePlanType = statusData?.data?.plan_type || null;
  const trialEnd = statusData?.data?.trial_end || null;
  const isTrialing = statusData?.data?.is_trial ?? false;
  const screeningsUsed = statusData?.data?.trial_screenings_used ?? 0;

  // amount / renewal_date / billing_cycle no longer exposed on the practitioner status endpoint —
  // fall back to current_period_end and the plan-derived price below.
  const subscriptionAmountRaw: number | null = null;
  const renewalDate = statusData?.data?.current_period_end || null;
  const billingCycleNormalized: 'monthly' | 'annual' | null = null;

  // Complimentary banner fields — backend ships these on the response payload
  // but they are not yet declared in the generated FrontendSubscriptionStatusData
  // type (no Swagger regen per backend). Read via local extension.
  type ComplimentaryFields = {
    is_complimentary?: boolean;
    complimentary_ends_at?: string | null;
    canceled_at?: string | null;
  };
  const compFields = (statusData?.data ?? {}) as ComplimentaryFields;
  const isComplimentary = compFields.is_complimentary ?? false;
  const complimentaryEndsAt = compFields.complimentary_ends_at ?? null;
  const complimentaryCanceledAt = compFields.canceled_at ?? null;

  /**
   * Three states from the backend doc:
   *  - active       : is_complimentary=true + status=active        → "ends {complimentary_ends_at}"
   *  - auto_expired : is_complimentary=true + status=cancelled     → "ended on {complimentary_ends_at}"
   *  - revoked      : is_complimentary=false + status=cancelled +
   *                   canceled_at + complimentary_ends_at set      → "revoked on {canceled_at}"
   *
   * complimentary_ends_at being non-null is what distinguishes a revoked
   * complimentary sub from a regular paid cancellation.
   */
  const complimentaryBanner: (
    | { kind: 'active'; endsAt: string | null }
    | { kind: 'auto_expired'; endedAt: string }
    | { kind: 'revoked'; revokedAt: string }
  ) | null = (() => {
    if (isComplimentary && subscriptionStatus === 'active') {
      return { kind: 'active', endsAt: complimentaryEndsAt };
    }
    if (isComplimentary && subscriptionStatus === 'cancelled' && complimentaryEndsAt) {
      return { kind: 'auto_expired', endedAt: complimentaryEndsAt };
    }
    if (
      !isComplimentary &&
      subscriptionStatus === 'cancelled' &&
      complimentaryCanceledAt &&
      complimentaryEndsAt
    ) {
      return { kind: 'revoked', revokedAt: complimentaryCanceledAt };
    }
    return null;
  })();

  const formatBannerDate = (iso: string) =>
    new Date(iso).toLocaleDateString(locale === 'es' ? 'es-ES' : 'en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });

  // During trial, amount from API is $0 — show plan price instead
  const displayAmount = (() => {
    const isYearly = billingCycleNormalized === 'annual';
    const suffix = isYearly ? '/year' : '/month';
    if (isTrialing || subscriptionAmountRaw === 0) {
      const isGroup = userData?.subscription_type === 'group';
      if (isGroup) {
        const gp = groupRawPlan as any;
        const price = isYearly ? gp?.price_yearly : gp?.price_monthly;
        return price ? `$${price}${suffix}` : '';
      }
      const match = allPlans.find((p: any) => (p.subscription_type || 'individual') === 'individual');
      if (match) {
        const price = isYearly ? match.price_yearly : match.price_monthly;
        return price ? `$${price}${suffix}` : '';
      }
      return '';
    }
    return subscriptionAmountRaw != null ? `$${subscriptionAmountRaw}${suffix}` : '';
  })();

  // Status helpers
  const noSub = subscriptionStatus === 'none';
  const isCancelled = subscriptionStatus === 'cancelled';

  // Trial days remaining
  const trialDaysRemaining = trialEnd
    ? Math.max(0, Math.ceil((new Date(trialEnd).getTime() - Date.now()) / (1000 * 60 * 60 * 24)))
    : 0;



  // Auto-sync toggle to match billing_cycle from detail (falls back to activePlanType from status)
  useEffect(() => {
    const cycle = billingCycleNormalized || activePlanType;
    if (cycle === 'monthly' || cycle === 'annual') {
      setPmBillingCycle(cycle);
    }
  }, [billingCycleNormalized, activePlanType]);

  const hasBillingHistory = !isLoadingBilling && billingRecords.length > 0;

  // Unified loading state - wait for all critical APIs to complete
  const isLoadingSubscriptionData = isLoadingPlans || isLoadingBilling || isLoadingStatus;

  // Status-aware subscription check — only true for real subscription statuses (not "none" for fresh users)
  const hasActiveSubscription = subscriptionStatus === "active" || subscriptionStatus === "past_due" || subscriptionStatus === "incomplete" || subscriptionStatus === "paused";

  // Show the current plan card for active subscriptions AND cancelled (so user can see their cancelled plan)
  const showSubscriptionCard = hasActiveSubscription || isCancelled;

  // Disable subscribe buttons only for fully-paid active subs (not trialing users — they should be able to pick a plan to upgrade)
  // NOTE: "incomplete" is intentionally excluded — users must be able to re-initiate checkout to complete payment
  const shouldDisableSubscribe = hasActiveSubscription && !isTrialing && (subscriptionStatus === "active" || subscriptionStatus === "past_due" || subscriptionStatus === "paused");

  const getStatusConfig = (status: string | null) => {
    switch (status) {
      case "active":
        return { label: t("practitioner.subscription.statusActive"), bg: "bg-green-100", text: "text-green-600", dot: "bg-green-500" };
      case "past_due":
        return { label: t("practitioner.subscription.statusPastDue"), bg: "bg-red-100", text: "text-red-600", dot: "bg-red-500" };
      case "incomplete":
        return { label: t("practitioner.subscription.statusIncomplete"), bg: "bg-yellow-100", text: "text-yellow-600", dot: "bg-yellow-500" };
      case "paused":
        return { label: t("practitioner.subscription.statusPaused"), bg: "bg-gray-100", text: "text-gray-600", dot: "bg-gray-500" };
      case "cancelled":
        return { label: t("practitioner.subscription.statusCancelled"), bg: "bg-red-100", text: "text-red-600", dot: "bg-red-500" };
      default:
        return { label: t("practitioner.subscription.activePlan"), bg: "bg-green-100", text: "text-green-600", dot: "bg-green-500" };
    }
  };

  // Stripe billing portal for managing subscription
  const portalMutation = useSubscriptionControllerGetBillingPortalV1({
    mutation: {
      onSuccess: (data: any) => {
        const portalUrl = data?.data?.portal_url || data?.portal_url;
        // is_trial: true  → portal is for payment method / cancel only (plan switch uses /trial/switch-plan)
        // is_trial: false → portal handles everything including plan switch
        if (portalUrl) {
          window.location.href = portalUrl;
        }
      },
      onError: () => {
        toast.error(t("practitioner.subscription.portalError"));
      },
      onSettled: () => setPendingCard(null),
    },
  });

  const handlePortal = (cardId: string) => {
    setPendingCard(cardId);
    portalMutation.mutate();
  };



  // Stripe checkout mutation
  const checkoutMutation = useSubscriptionControllerCreateCheckoutV1({
    mutation: {
      onSuccess: (data: any) => {
        const checkoutUrl = data?.data?.checkout_url || data?.checkout_url;
        if (checkoutUrl) {
          window.location.href = checkoutUrl;
        } else if (data?.data?.subscription) {
          // SKIP_PAYMENT dev mode — subscription created directly
          const current = getUserDataCookie();
          const devSubType = data?.data?.subscription?.subscription_type || current?.subscription_type || 'individual';
          if (current) {
            setUserDataCookie({ ...current, has_active_subscription: true, subscription_type: devSubType });
          }
          toast.success(data?.data?.message || t("practitioner.subscription.subscriptionActivated"));
          const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "";
          if (devSubType === 'group') {
            window.location.href = `${basePath}/practice-manager/dashboard`;
          } else {
            window.location.href = `${basePath}/practitioner`;
          }
        } else {
          toast.error(t("practitioner.subscription.checkoutError"));
        }
      },
      onError: (error: any) => {
        setPendingCard(null);
        const message: string = error?.response?.data?.message || "";
        if (message === "subscriptions.already_active") {
          const currentUserData = getUserDataCookie();
          if (currentUserData) {
            setUserDataCookie({ ...currentUserData, has_active_subscription: true });
          }
          refetchStatus();
          toast.error(t("practitioner.subscription.alreadySubscribed"), { duration: 4000 });
        } else {
          toast.error(message || t("practitioner.subscription.checkoutFailedRetry"), { duration: 4000 });
        }
      },
    },
  });

  // Trial start mutation — POST /trial for first-time users (never use checkout for new users)
  const trialMutation = useSubscriptionControllerStartTrialV1({
    mutation: {
      onSuccess: (data: any) => {
        const checkoutUrl = data?.data?.checkout_url || data?.checkout_url;
        if (checkoutUrl) {
          window.location.href = checkoutUrl;
        } else if (data?.data?.subscription) {
          // SKIP_PAYMENT dev mode
          const current = getUserDataCookie();
          const devSubType = data?.data?.subscription?.subscription_type || current?.subscription_type || 'individual';
          if (current) {
            setUserDataCookie({ ...current, has_active_subscription: true, subscription_type: devSubType });
          }
          toast.success(data?.data?.message || t("practitioner.subscription.subscriptionActivated"));
          const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "";
          window.location.href = devSubType === 'group' ? `${basePath}/practice-manager/dashboard` : `${basePath}/practitioner`;
        } else {
          toast.error(t("practitioner.subscription.checkoutError"));
        }
      },
      onError: (error: any) => {
        setPendingCard(null);
        const message: string = error?.response?.data?.message || "";
        if (message === "subscriptions.trial_already_used") {
          // Trial already used — show message, hide "Start Free Trial", refetch status
          setTrialUsed(true);
          toast.error(t("practitioner.subscription.trialAlreadyUsed"), { duration: 5000 });
          refetchStatus();
        } else {
          toast.error(message || t("practitioner.subscription.checkoutFailedRetry"), { duration: 4000 });
        }
      },
    },
  });

  const handleSubscribe = (planType: 'monthly' | 'annual', subscriptionType: 'individual' | 'group' = 'individual', cardId?: string) => {
    if (cardId) setPendingCard(cardId);
    // Brand new users (noSub + never had a trial) → POST /trial for 14-day free trial
    // Users whose trial expired and backend returns 'none' status → POST /checkout (no second trial)
    // Returning users (cancelled) → POST /checkout directly
    const hadPriorTrial = !!trialEnd || trialUsed;
    if (noSub && !hadPriorTrial && subscriptionType === 'individual') {
      trialMutation.mutate({ data: { plan_type: planType, subscription_type: subscriptionType } });
    } else {
      checkoutMutation.mutate({ data: { plan_type: planType, subscription_type: subscriptionType } }, {
        onSettled: () => setPendingCard(null),
      });
    }
  };

  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    const total = totalPages || 1;
    if (total <= 7) {
      for (let i = 1; i <= total; i++) pages.push(i);
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, "...", total - 1, total);
      } else if (currentPage >= total - 2) {
        pages.push(1, 2, "...", total - 2, total - 1, total);
      } else {
        pages.push(1, "...", currentPage - 1, currentPage, currentPage + 1, "...", total);
      }
    }
    return pages;
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", { day: "2-digit", month: "short", year: "numeric" });
  };

  const InvoiceIcon = () => (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
    </svg>
  );

  const CheckIcon = () => (
    <svg className="w-5 h-5 text-[#3B9EC9]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
    </svg>
  );

  return (
    <>
      {/* Main Content */}
      <main className="pt-20 pb-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Page Title — onboarding copy for first-time users, manage copy for returning users */}
        <div className="mb-8">
          <h1 className="text-2xl font-semibold text-gray-900">
            {!isLoadingStatus && noSub && !trialEnd && !trialUsed
              ? t("practitioner.subscription.choosePlanTitle")
              : t("practitioner.subscription.title")}
          </h1>
          <p className="mt-1 text-gray-500">
            {!isLoadingStatus && noSub && !trialEnd && !trialUsed
              ? t("practitioner.subscription.choosePlanSubtitle")
              : t("practitioner.subscription.subtitle")}
          </p>
        </div>

        {/* Unified Loading State */}
        {isLoadingSubscriptionData && (
          <div className="flex items-center justify-center py-16">
            <div className="flex flex-col items-center gap-3">
              <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-[#3B9EC9]"></div>
              <p className="text-sm text-gray-500">{t("practitioner.subscription.loadingInfo")}</p>
            </div>
          </div>
        )}

        {/* Content - only show when all data is loaded */}
        {!isLoadingSubscriptionData && (
        <>

        {/* ── FIRST-TIME USER: Welcome banner ── */}
        {noSub && !trialEnd && !trialUsed && (
          <div className="bg-gradient-to-r from-[#3B9EC9]/10 to-[#3B9EC9]/5 border border-[#3B9EC9]/20 rounded-2xl p-6 mb-8 flex items-start gap-4">
            <div className="flex-shrink-0 w-10 h-10 rounded-full bg-[#3B9EC9]/15 flex items-center justify-center">
              <svg className="w-5 h-5 text-[#3B9EC9]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z" />
              </svg>
            </div>
            <div>
              <h2 className="text-lg font-semibold text-gray-900">{t("practitioner.subscription.welcomeBannerTitle")}</h2>
              <p className="text-sm text-gray-600 mt-0.5">{t("practitioner.subscription.welcomeBannerMessage")}</p>
            </div>
          </div>
        )}

        {/* ── TRIALING: Trial countdown + Upgrade Now ── */}
        {isTrialing && (
          <div className="bg-[#3B9EC9]/5 border border-[#3B9EC9]/20 rounded-2xl p-6 mb-8">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
              <div>
                <h2 className="text-lg font-semibold text-gray-900">{t("practitioner.subscription.trialBannerTitle")}</h2>
                <p className="text-sm text-[#3B9EC9] mt-1">
                  {t("practitioner.subscription.trialEndsOn")}: {new Date(trialEnd!).toLocaleDateString("en-US", { day: "2-digit", month: "short", year: "numeric" })}
                  {" — "}
                  {t("practitioner.subscription.trialDaysRemaining", { days: trialDaysRemaining })}
                </p>
                <p className="text-xs text-gray-500 mt-1">
                  {t("practitioner.subscription.screeningsUsed")}: <strong>{screeningsUsed} / 5</strong>
                  {" — "}
                  <strong>{Math.max(0, 5 - screeningsUsed)}</strong> {t("practitioner.subscription.screeningsRemaining")}
                </p>
                <p className="text-xs text-gray-500">{t("practitioner.subscription.upgradeFromTrialDesc")}</p>
              </div>
              <button
                onClick={() => pricingRef.current?.scrollIntoView({ behavior: "smooth", block: "start" })}
                className="shrink-0 inline-flex items-center gap-2 px-5 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
              >
                {t("practitioner.subscription.upgradeFromTrial")}
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                </svg>
              </button>
            </div>
          </div>
        )}

        {/* ── COMPLIMENTARY: 3-state banner ── */}
        {complimentaryBanner?.kind === 'active' && (
          <div className="bg-emerald-50 border border-emerald-200 rounded-2xl p-6 mb-8 flex items-start gap-3">
            <svg className="w-5 h-5 text-emerald-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <div>
              <p className="text-sm font-medium text-emerald-700">Complimentary access</p>
              <p className="text-sm text-emerald-700 mt-1">
                {complimentaryBanner.endsAt
                  ? `Your free access ends on ${formatBannerDate(complimentaryBanner.endsAt)}.`
                  : 'Your free access is granted for life. No expiry date.'}
              </p>
            </div>
          </div>
        )}

        {complimentaryBanner?.kind === 'auto_expired' && (
          <div className="bg-amber-50 border border-amber-200 rounded-2xl p-6 mb-8 flex items-start gap-3">
            <svg className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
            </svg>
            <div>
              <p className="text-sm font-medium text-amber-800">Complimentary access ended</p>
              <p className="text-sm text-amber-700 mt-1">
                Your free access ended on {formatBannerDate(complimentaryBanner.endedAt)}.
                Subscribe below to continue using MBHS.
              </p>
            </div>
          </div>
        )}

        {complimentaryBanner?.kind === 'revoked' && (
          <div className="bg-red-50 border border-red-200 rounded-2xl p-6 mb-8 flex items-start gap-3">
            <svg className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728L5.636 5.636m12.728 12.728L5.636 5.636" />
            </svg>
            <div>
              <p className="text-sm font-medium text-red-700">Complimentary access revoked</p>
              <p className="text-sm text-red-600 mt-1">
                Your free access was revoked on {formatBannerDate(complimentaryBanner.revokedAt)}.
                Please contact support if you believe this was a mistake, or subscribe below to continue.
              </p>
            </div>
          </div>
        )}

        {/* ── CANCELLED: Resubscribe prompt (regular paid cancel — hidden when comp banner is shown) ── */}
        {isCancelled && !complimentaryBanner && (
          <div className="bg-red-50 border border-red-200 rounded-2xl p-6 mb-8 flex items-start gap-3">
            <svg className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
            </svg>
            <div>
              <p className="text-sm font-medium text-red-700">{t("practitioner.subscription.cancelledMessage")}</p>
              {periodEnd && new Date() <= new Date(periodEnd) && (
                <p className="text-sm text-red-600 mt-1">
                  {t("practitioner.subscription.cancelledAccessUntil", {
                    date: new Date(periodEnd).toLocaleDateString(locale === 'es' ? 'es-ES' : 'en-US', { year: 'numeric', month: 'long', day: 'numeric' }),
                  })}
                </p>
              )}
            </div>
          </div>
        )}

        {/* Current Plan Card - shown for active subscriptions */}
        {showSubscriptionCard && (() => {
          const statusConfig = getStatusConfig(subscriptionStatus);
          return (
            <div className="bg-white rounded-2xl border border-gray-100 p-6 mb-8">
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-lg font-semibold text-gray-900">
                    {t("practitioner.subscription.currentPlan")}
                  </h2>
                  {activePlanType && (
                    <p className="text-sm text-gray-500">
                      {activePlanType === "monthly" ? t("practitioner.subscription.monthlyPlan") : activePlanType === "annual" ? t("practitioner.subscription.annualPlan") : activePlanType}
                    </p>
                  )}
                  <p className="text-gray-500">{displayAmount}</p>
                </div>
                <div className="flex flex-col items-end gap-2">
                  <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium ${statusConfig.bg} ${statusConfig.text}`}>
                    <span className={`w-1.5 h-1.5 rounded-full ${statusConfig.dot}`}></span>
                    {statusConfig.label}
                  </span>
                  <p className="text-sm text-[#3B9EC9]">
                    {t("practitioner.subscription.nextBilling")}: {(renewalDate || periodEnd) ? new Date((renewalDate || periodEnd)!).toLocaleDateString("en-US", { day: "2-digit", month: "short", year: "numeric" }) : "-"}
                  </p>
                  <button
                      onClick={() => portalMutation.mutate()}
                      disabled={portalMutation.isPending}
                      className="mt-1 flex items-center gap-2 px-4 py-2 text-sm font-medium text-[#3B9EC9] bg-white border border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {portalMutation.isPending ? (
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-[#3B9EC9]"></div>
                      ) : (
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M10.343 3.94c.09-.542.56-.94 1.11-.94h1.093c.55 0 1.02.398 1.11.94l.149.894c.07.424.384.764.78.93.398.164.855.142 1.205-.108l.737-.527a1.125 1.125 0 011.45.12l.773.774c.39.389.44 1.002.12 1.45l-.527.737c-.25.35-.272.806-.107 1.204.165.397.505.71.93.78l.893.15c.543.09.94.56.94 1.109v1.094c0 .55-.397 1.02-.94 1.11l-.893.149c-.425.07-.765.383-.93.78-.165.398-.143.854.107 1.204l.527.738c.32.447.269 1.06-.12 1.45l-.774.773a1.125 1.125 0 01-1.449.12l-.738-.527c-.35-.25-.806-.272-1.204-.107-.397.165-.71.505-.78.929l-.15.894c-.09.542-.56.94-1.11.94h-1.094c-.55 0-1.019-.398-1.11-.94l-.148-.894c-.071-.424-.384-.764-.781-.93-.398-.164-.854-.142-1.204.108l-.738.527c-.447.32-1.06.269-1.45-.12l-.773-.774a1.125 1.125 0 01-.12-1.45l.527-.737c.25-.35.273-.806.108-1.204-.165-.397-.506-.71-.93-.78l-.894-.15c-.542-.09-.94-.56-.94-1.109v-1.094c0-.55.398-1.02.94-1.11l.894-.149c.424-.07.765-.383.93-.78.165-.398.143-.854-.107-1.204l-.527-.738a1.125 1.125 0 01.12-1.45l.773-.773a1.125 1.125 0 011.45-.12l.737.527c.35.25.807.272 1.204.107.397-.165.71-.505.78-.929l.15-.894z" />
                          <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        </svg>
                      )}
                      {t("practitioner.subscription.manageSubscription")}
                    </button>
                </div>
              </div>

              {/* Status-specific alert banners */}
              {subscriptionStatus === "past_due" && (
                <div className="mt-4 p-4 rounded-xl bg-red-50 border border-red-200 flex items-start gap-3">
                  <svg className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                  </svg>
                  <div>
                    <p className="text-sm font-medium text-red-700">{t("practitioner.subscription.pastDueMessage")}</p>
                    <button
                      onClick={() => portalMutation.mutate()}
                      className="mt-2 text-sm font-medium text-red-600 underline hover:text-red-800 cursor-pointer"
                    >
                      {t("practitioner.subscription.updatePayment")}
                    </button>
                  </div>
                </div>
              )}

              {subscriptionStatus === "incomplete" && (
                <div className="mt-4 p-4 rounded-xl bg-yellow-50 border border-yellow-200 flex items-start gap-3">
                  <svg className="w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                  </svg>
                  <div>
                    <p className="text-sm font-medium text-yellow-700">{t("practitioner.subscription.incompleteMessage")}</p>
                    <button
                      onClick={() => handleSubscribe((activePlanType as 'monthly' | 'annual') || 'annual', (userData?.subscription_type === 'group' ? 'group' : 'individual') as 'individual' | 'group', 'complete-payment')}
                      disabled={!!pendingCard}
                      className="mt-2 inline-flex items-center gap-1.5 text-sm font-medium text-yellow-700 underline hover:text-yellow-900 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {pendingCard === 'complete-payment' ? (
                        <>
                          <div className="animate-spin rounded-full h-3.5 w-3.5 border-b-2 border-yellow-700"></div>
                          {t("practitioner.subscription.processing")}
                        </>
                      ) : (
                        <>
                          {t("practitioner.subscription.completePayment")}
                          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
                          </svg>
                        </>
                      )}
                    </button>
                  </div>
                </div>
              )}

              {subscriptionStatus === "paused" && (
                <div className="mt-4 p-4 rounded-xl bg-gray-50 border border-gray-200 flex items-start gap-3">
                  <svg className="w-5 h-5 text-gray-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 5.25v13.5m-7.5-13.5v13.5" />
                  </svg>
                  <p className="text-sm font-medium text-gray-700">{t("practitioner.subscription.pausedMessage")}</p>
                </div>
              )}

            </div>
          );
        })()}

        {/* Billing History - shown when API confirms subscription or billing records exist */}
        {(hasActiveSubscription || hasBillingHistory) && (
          <div className="bg-white rounded-2xl border border-gray-100 p-6 mb-12">
            <h2 className="text-lg font-semibold text-gray-900 mb-6">{t("practitioner.subscription.billingHistory")}</h2>

            {/* Table */}
            <div className="overflow-x-auto border border-gray-200 rounded-lg">
              <table className="w-full border-collapse">
                <thead>
                  <tr className="border-b border-gray-200 bg-gray-50">
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 w-16 border-r border-gray-200">{t("practitioner.subscription.no")}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("practitioner.subscription.date")}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("practitioner.subscription.plan")}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("practitioner.subscription.amount")}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("practitioner.subscription.status")}</th>
                    <th className="text-center py-3 px-4 text-sm font-medium text-gray-500">{t("practitioner.subscription.action")}</th>
                  </tr>
                </thead>
                <tbody>
                  {billingRecords.length === 0 ? (
                    <tr>
                      <td colSpan={6} className="py-8 text-center text-gray-500">
                        {t("practitioner.subscription.noRecords")}
                      </td>
                    </tr>
                  ) : (
                    billingRecords.map((record, index) => (
                      <tr key={record.id} className={`${index !== billingRecords.length - 1 ? 'border-b border-gray-200' : ''} hover:bg-gray-50/50 transition`}>
                        <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">{index + 1}</td>
                        <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">{formatDate(record.date)}</td>
                        <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">{record.plan_name || "-"}</td>
                        <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">{`$${record.amount}`}</td>
                        <td className="py-4 px-4 border-r border-gray-200">
                          <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium ${
                            record.status?.toLowerCase() === "paid" || record.status?.toLowerCase() === "succeeded" ? "bg-green-100 text-green-600" :
                            record.status?.toLowerCase() === "pending" || record.status?.toLowerCase() === "open" ? "bg-yellow-100 text-yellow-600" :
                            "bg-red-100 text-red-600"
                          }`}>
                            <span className="w-1.5 h-1.5 rounded-full bg-current"></span>
                            {record.status}
                          </span>
                        </td>
                        <td className="py-4 px-4">
                          <div className="flex justify-center">
                            <button
                              onClick={() => {
                                if (record.invoice_url) window.open(record.invoice_url, '_blank');
                                else if (record.invoice_pdf) window.open(record.invoice_pdf, '_blank');
                              }}
                              disabled={!record.invoice_url && !record.invoice_pdf}
                              className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                            >
                              <InvoiceIcon />
                              {t("practitioner.subscription.invoice")}
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>

            {/* Pagination - only show when there are multiple pages */}
            {billingRecords.length > 0 && totalPages > 1 && (
              <div className="flex items-center justify-between mt-6 pt-4 border-t border-gray-100">
                <button
                  onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                  disabled={currentPage === 1}
                  className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition cursor-pointer"
                >
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                  </svg>
                  {t("practitioner.common.previous")}
                </button>

                <div className="flex items-center gap-1">
                  {getPageNumbers().map((page, index) =>
                    page === "..." ? (
                      <span key={`ellipsis-${index}`} className="px-2 text-gray-400">...</span>
                    ) : (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page as number)}
                        className={`w-10 h-10 text-sm font-medium rounded-lg transition cursor-pointer ${
                          currentPage === page
                            ? "bg-gray-100 text-gray-900"
                            : "text-gray-600 hover:bg-gray-50"
                        }`}
                      >
                        {page}
                      </button>
                    )
                  )}
                </div>

                <button
                  onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                  disabled={currentPage === totalPages}
                  className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition cursor-pointer"
                >
                  {t("practitioner.common.next")}
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              </div>
            )}
          </div>
        )}

        {/* Pricing Section */}
        <div ref={pricingRef} className="text-center mb-12">
          <h2 className="text-3xl font-bold text-gray-900 mb-4">{t("practitioner.subscription.simplePricing")}</h2>
          <p className="text-gray-500 max-w-2xl mx-auto">
            {t("practitioner.subscription.pricingSubtitle")}
          </p>
        </div>

        {/* Plans Error State */}
        {!!plansError && (
          <div className="bg-red-50 border border-red-200 rounded-2xl p-6 text-center mb-8">
            <p className="text-red-600 font-medium mb-2">{t("practitioner.subscription.plansLoadError")}</p>
            <p className="text-red-500 text-sm mb-4">{t("practitioner.subscription.plansLoadErrorRetry")}</p>
            <button
              onClick={() => refetchPlans()}
              className="inline-flex items-center gap-2 px-5 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182" />
              </svg>
              {t("practitioner.common.retry")}
            </button>
          </div>
        )}

        {/* Global Monthly/Yearly Toggle */}
        <div className="flex items-center justify-center gap-3 mb-8">
          <span className={`text-sm font-medium transition ${pmBillingCycle === 'monthly' ? 'text-gray-900' : 'text-gray-400'}`}>
            {t("practitioner.subscription.monthly")}
          </span>
          <button
            type="button"
            onClick={() => setPmBillingCycle(pmBillingCycle === 'monthly' ? 'annual' : 'monthly')}
            className={`relative inline-flex h-6 w-11 items-center rounded-full transition cursor-pointer ${
              pmBillingCycle === 'annual' ? 'bg-[#3B9EC9]' : 'bg-gray-300'
            }`}
            aria-label="Toggle billing cycle"
          >
            <span className={`inline-block h-4 w-4 rounded-full bg-white transition-transform ${
              pmBillingCycle === 'annual' ? 'translate-x-6' : 'translate-x-1'
            }`} />
          </button>
          <span className={`text-sm font-medium transition ${pmBillingCycle === 'annual' ? 'text-gray-900' : 'text-gray-400'}`}>
            {t("practitioner.subscription.yearly")}
          </span>
        </div>

        {/* Pricing Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-4xl mx-auto">
          {/* Individual Plan Cards — render only the card matching the global toggle */}
          {individualPlans.filter((plan) => plan.planType === pmBillingCycle).map((plan, index) => {
            const isActivePlan = hasActiveSubscription && userData?.subscription_type !== 'group' && !!activePlanType && plan.planType === activePlanType;
            return (
            <div
              key={index}
              className={`bg-white rounded-2xl p-6 relative cursor-pointer hover:shadow-md transition-shadow ${
                isActivePlan
                  ? "border-2 border-[#3B9EC9] shadow-lg"
                  : "border border-gray-100"
              }`}
            >
              {isActivePlan && (
                <span className="absolute top-4 right-4 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-green-50 text-green-600">
                  <span className="w-1.5 h-1.5 rounded-full bg-green-500" />
                  {t("practitioner.subscription.activePlan")}
                </span>
              )}

              <div className="mb-6">
                {plan.planType === "annual" && plan.savings ? (
                  <span className="inline-flex items-center gap-1.5 px-2.5 py-1 mb-3 rounded-full text-xs font-medium bg-amber-50 text-amber-700">
                    <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M10 2L12.39 7.05L18 7.84L14 11.74L14.94 17.32L10 14.69L5.06 17.32L6 11.74L2 7.84L7.61 7.05L10 2Z" />
                    </svg>
                    {t("practitioner.subscription.saveBadge", { amount: `$${plan.savings}` })}
                  </span>
                ) : null}
                <div className="flex items-baseline gap-1 mb-1">
                  <span className="text-4xl font-bold text-gray-900">{plan.price}</span>
                  <span className="text-gray-500 text-sm">/{plan.period}</span>
                </div>
                <p className="text-xs text-gray-500 mb-2">
                  {plan.planType === "annual"
                    ? t("practitioner.subscription.billedAnnually")
                    : t("practitioner.subscription.billedMonthly")}
                </p>
                <h3 className="text-lg font-semibold text-gray-900">{plan.name}</h3>
              </div>

              <p className="text-gray-500 text-sm mb-6">{plan.description}</p>

              <div className="mb-6">
                <p className="text-sm font-medium text-gray-900 mb-4">{t("practitioner.subscription.whatsIncluded")}</p>
                <ul className="space-y-3">
                  {plan.features.map((feature: string, featureIndex: number) => (
                    <li key={featureIndex} className="flex items-start gap-3">
                      <CheckIcon />
                      <span className="text-sm text-gray-600">{feature}</span>
                    </li>
                  ))}
                </ul>
              </div>

              <button
                onClick={() => {
                  const cardId = `individual-${plan.planType}`;
                  if (isActivePlan) {
                    handlePortal(cardId);
                  } else if (shouldDisableSubscribe) {
                    // Paid active user clicking different card → open portal to switch plan
                    handlePortal(cardId);
                  } else if (isTrialing) {
                    // Trialing user clicking any plan → open Stripe portal
                    handlePortal(cardId);
                  } else {
                    const currentData = getUserDataCookie();
                    if (currentData) {
                      setUserDataCookie({ ...currentData, subscription_type: 'individual' });
                    }
                    handleSubscribe(plan.planType, 'individual', cardId);
                  }
                }}
                disabled={!!pendingCard || (isActivePlan && !shouldDisableSubscribe)}
                className={`w-full py-3 px-4 rounded-full text-sm font-medium transition flex items-center justify-center gap-2 disabled:cursor-default disabled:pointer-events-none ${
                  pendingCard === `individual-${plan.planType}`
                    ? "bg-[#3B9EC9]/60 text-white/80"
                    : isActivePlan
                    ? "bg-[#3B9EC9] text-white"
                    : !!pendingCard
                    ? "opacity-40 bg-[#3B9EC9] text-white"
                    : plan.buttonStyle === "filled"
                      ? "bg-[#3B9EC9] text-white hover:bg-[#2D8AB5] cursor-pointer"
                      : "bg-white text-[#3B9EC9] border border-[#3B9EC9] hover:bg-[#3B9EC9]/5 cursor-pointer"
                }`}
              >
                {pendingCard === `individual-${plan.planType}` ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
                    {t("practitioner.subscription.processing")}
                  </>
                ) : isActivePlan ? (
                  <>
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                    </svg>
                    {t("practitioner.subscription.currentPlan")}
                  </>
                ) : (
                  <>
                    {(noSub && !trialUsed)
                      ? t("practitioner.subscription.startFreeTrialBtn")
                      : (isTrialing || shouldDisableSubscribe)
                        ? t("practitioner.subscription.upgradeNow")
                        : t("practitioner.subscription.subscribeNow")}
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
                    </svg>
                  </>
                )}
              </button>
            </div>
            );
          })}

          {/* Practice Manager Card with Monthly/Yearly Toggle */}
          {groupPlanData && (() => {
            const gp = groupPlanData;
            const pmPrice = pmBillingCycle === 'monthly' ? gp.priceMonthly : gp.priceYearly;
            const pmPeriod = pmBillingCycle === 'monthly' ? t("practitioner.subscription.perMonth") : t("practitioner.subscription.perYear");
            const pmFeatures = pmBillingCycle === 'monthly' ? gp.featuresMonthly : gp.featuresYearly;
            const pmButtonText = (isTrialing || shouldDisableSubscribe)
              ? t("practitioner.subscription.upgradeNow")
              : t("practitioner.subscription.subscribeNow");
            const isActivePM = hasActiveSubscription && userData?.subscription_type === 'group' && !!activePlanType && pmBillingCycle === activePlanType;
            return (
              <div className={`bg-white rounded-2xl p-6 relative cursor-pointer hover:shadow-md transition-shadow ${
                isActivePM ? "border-2 border-[#3B9EC9] shadow-lg" : "border border-gray-100"
              }`}>
                {isActivePM && (
                  <span className="absolute top-4 right-4 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-green-50 text-green-600">
                    <span className="w-1.5 h-1.5 rounded-full bg-green-500" />
                    {t("practitioner.subscription.activePlan")}
                  </span>
                )}

                <div className="mb-6">
                  {pmBillingCycle === 'annual' && gp.yearlySavings > 0 ? (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 mb-3 rounded-full text-xs font-medium bg-amber-50 text-amber-700">
                      <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M10 2L12.39 7.05L18 7.84L14 11.74L14.94 17.32L10 14.69L5.06 17.32L6 11.74L2 7.84L7.61 7.05L10 2Z" />
                      </svg>
                      {t("practitioner.subscription.saveBadge", { amount: `$${gp.yearlySavings}` })}
                    </span>
                  ) : null}
                  <div className="flex items-baseline gap-1 mb-1">
                    <span className="text-4xl font-bold text-gray-900">{pmPrice || 'N/A'}</span>
                    <span className="text-gray-500 text-sm">/{pmPeriod}</span>
                  </div>
                  <p className="text-xs text-gray-500 mb-2">
                    {pmBillingCycle === 'annual'
                      ? t("practitioner.subscription.billedAnnually")
                      : t("practitioner.subscription.billedMonthly")}
                  </p>
                  <h3 className="text-lg font-semibold text-gray-900">{gp.name}</h3>
                </div>

                <p className="text-gray-500 text-sm mb-6">{gp.description}</p>

                <div className="mb-6">
                  <p className="text-sm font-medium text-gray-900 mb-4">{t("practitioner.subscription.whatsIncluded")}</p>
                  <ul className="space-y-3">
                    {pmFeatures.map((feature: string, featureIndex: number) => (
                      <li key={featureIndex} className="flex items-start gap-3">
                        <CheckIcon />
                        <span className="text-sm text-gray-600">{feature}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                <button
                  onClick={() => {
                    if (isActivePM) {
                      handlePortal('group');
                    } else if (shouldDisableSubscribe) {
                      handlePortal('group');
                    } else if (isTrialing) {
                      handlePortal('group');
                    } else {
                      const currentData = getUserDataCookie();
                      if (currentData) {
                        setUserDataCookie({ ...currentData, subscription_type: 'group' });
                      }
                      handleSubscribe(pmBillingCycle, 'group', 'group');
                    }
                  }}
                  disabled={!!pendingCard || (isActivePM && !shouldDisableSubscribe)}
                  className={`w-full py-3 px-4 rounded-full text-sm font-medium transition flex items-center justify-center gap-2 disabled:cursor-default disabled:pointer-events-none ${
                    pendingCard === 'group'
                      ? "bg-[#3B9EC9]/60 text-white/80"
                      : isActivePM
                      ? "bg-[#3B9EC9] text-white"
                      : !!pendingCard
                      ? "opacity-40 bg-[#3B9EC9] text-white"
                      : "bg-[#3B9EC9] text-white hover:bg-[#2D8AB5] cursor-pointer"
                  }`}
                >
                  {pendingCard === 'group' ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
                      {t("practitioner.subscription.processing")}
                    </>
                  ) : isActivePM ? (
                    <>
                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                      </svg>
                      {t("practitioner.subscription.currentPlan")}
                    </>
                  ) : (
                    <>
                      {pmButtonText}
                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
                      </svg>
                    </>
                  )}
                </button>
              </div>
            );
          })()}
        </div>

        {/* Trust line below pricing cards */}
        <p className="mt-6 text-center text-sm text-gray-500">
          {t("practitioner.subscription.noCreditCardRequired")}
        </p>
        </>
        )}
        </div>
      </main>
    </>
  );
}

export default function SubscriptionPage() {
  return (
    <Suspense fallback={<div className="pt-20 pb-8 flex items-center justify-center"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div></div>}>
      <SubscriptionPageContent />
    </Suspense>
  );
}
