/**
 * Billing Panel Client Component
 *
 * Client-side component that handles UI state and interactions.
 * Receives pre-fetched user data from BillingPanelServer to eliminate
 * client-side API calls for user info.
 *
 * Pattern Reference: This follows the same server/client split as
 * app/[lang]/dashboard/page.tsx with NewDashboardClient.tsx
 */

"use client";

import { useState } from "react";
import Link from "next/link";
import type { Lang } from "@/lib/config";
import type { DashboardSubscriptionDetails } from "../types";
import type { Currency, TierId } from "@/lib/types/pricing";
import { PRICING_TIERS, TIER_MAPPING } from "@/lib/config/pricing-tiers";
import {
  convertPrice,
  calculateProratedUpgrade,
  calculateDowngradeCredit,
  getDaysUntilBilling,
} from "@/lib/utils/pricing-helpers";
import BillingHistory from "./BillingHistory";
import { PlanUpgradeModal } from "./PlanUpgradeModal";
import PricingSelectionModal from "./PricingSelectionModal";
import { fetchWithCSRF } from "@/lib/csrf-client";
import { showWorkflowToast as showToast } from "@/lib/types/dashboard.types";

/**
 * User data that can be pre-fetched server-side
 */
export interface InitialUserData {
  id: string;
  email: string;
  companyName?: string | null;
  goals?: string[] | null;
}

export interface BillingPanelClientProps {
  lang: Lang;
  subscriptionDetails: DashboardSubscriptionDetails | null;
  billingCurrency: Currency;
  onUpgradeSuccess: () => void;
  /**
   * Pre-fetched user data from server component.
   * When provided, eliminates need for client-side API calls.
   */
  initialUserData?: InitialUserData | null;
}

export default function BillingPanelClient({
  lang,
  subscriptionDetails,
  billingCurrency,
  onUpgradeSuccess,
  initialUserData: _initialUserData,
}: BillingPanelClientProps) {
  const isAr = lang === "ar";
  const [selectedTier, setSelectedTier] = useState<TierId | null>(null);
  const [showUpgradeModal, setShowUpgradeModal] = useState(false);
  const [showPricingModal, setShowPricingModal] = useState(false);
  const [isCreatingCheckout, setIsCreatingCheckout] = useState(false);
  // Suppress unused warning - state is set but UI doesn't currently use it
  void isCreatingCheckout;

  const mapTierToPlanType = (
    tierId: TierId,
  ): "starter" | "professional" | "enterprise" => {
    // Collapse 5 public tiers into billing plan families we support for change-plan
    const mapped = (TIER_MAPPING as Record<string, string>)[tierId];
    if (mapped === "starter") return "starter";
    if (mapped === "professional" || mapped === "business")
      return "professional";
    return "enterprise";
  };

  const handleSelectPlan = async (
    tierId: TierId,
    billingPeriod: "monthly" | "yearly",
  ) => {
    setIsCreatingCheckout(true);

    try {
      const hasStripeSubscription = Boolean(
        subscriptionDetails?.subscription?.stripeSubscriptionId,
      );
      const isPendingPayment =
        needsPayment ||
        subscriptionDetails?.subscription?.status === "pending_payment";
      const isChangePlanFlow = hasStripeSubscription && !isPendingPayment;

      // If user already has a paid subscription, change plan with proration difference only (no setup fee, reuse trial logic)
      if (isChangePlanFlow) {
        const newPlanType = mapTierToPlanType(tierId);
        const changeRes = await fetchWithCSRF("/api/billing/change-plan", {
          method: "POST",
          body: JSON.stringify({
            newPlanType,
            prorationBehavior: "create_prorations",
          }),
        });

        const changeData = await changeRes.json().catch(() => ({}));
        if (!changeRes.ok) {
          throw new Error(
            changeData.error ||
              (isAr ? "فشل تحديث الخطة" : "Failed to change plan"),
          );
        }

        showToast(
          "success",
          isAr ? "تم التحديث" : "Plan Updated",
          isAr
            ? "تم تحديث خطتك. سيتم تطبيق الفارق فقط (لا توجد رسوم إعداد إضافية)."
            : "Plan updated. Only the difference is applied (no extra setup fee).",
        );
        onUpgradeSuccess();
        return;
      }

      // No active subscription or payment pending: create checkout for recurring only (no setup fee/trial if already used)
      const response = await fetchWithCSRF(
        "/api/subscriptions/create-checkout",
        {
          method: "POST",
          body: JSON.stringify({
            tierId,
            billingPeriod,
            currency: billingCurrency,
            language: lang,
          }),
        },
      );

      if (!response.ok) {
        const data = await response.json().catch(() => ({}));
        throw new Error(
          data.error ||
            (isAr
              ? "فشل إنشاء جلسة الدفع"
              : "Failed to create checkout session"),
        );
      }

      const { url, sessionUrl } = await response.json();
      const redirectUrl = sessionUrl || url;
      if (redirectUrl) {
        // Redirect to Stripe checkout
        window.location.href = redirectUrl;
      } else {
        throw new Error(
          isAr ? "رابط الدفع غير متوفر" : "Checkout link missing",
        );
      }
    } catch (error) {
      console.error("Failed to start checkout:", error);
      const message =
        error instanceof Error
          ? error.message
          : isAr
            ? "فشل بدء عملية الدفع"
            : "Failed to start checkout";
      showToast("error", isAr ? "فشل الدفع" : "Checkout Failed", message);
    } finally {
      setIsCreatingCheckout(false);
    }
  };

  const handleUpgradePlan = (tier: TierId) => {
    if (!subscriptionDetails) return;
    setSelectedTier(tier);
    setShowUpgradeModal(true);
  };

  const handleDowngradePlan = (tier: TierId) => {
    if (!subscriptionDetails) return;
    setSelectedTier(tier);
    setShowUpgradeModal(true); // Use same modal, it handles both
  };

  // Handler for when a tier is selected from PricingSelectionModal
  const handleTierSelectedFromModal = async (
    tierId: TierId,
    _priceId: string,
    billingPeriod: "monthly" | "yearly",
  ) => {
    setShowPricingModal(false);
    // Use the existing handleSelectPlan which handles CSRF and checkout
    await handleSelectPlan(tierId, billingPeriod);
  };

  // Check if user has selected package but needs payment
  const needsPayment = !!(
    subscriptionDetails as unknown as Record<string, unknown>
  )?.needsPayment;

  // If user has SELECTED package but hasn't paid, show special "Complete Payment" UI
  if (subscriptionDetails && needsPayment) {
    const currentTier = subscriptionDetails.subscription.tierId;
    const tierInfo = PRICING_TIERS.find((t) => t.id === currentTier);
    const currentTierName = isAr ? tierInfo?.nameAr : tierInfo?.nameEn;
    const packageName = (
      subscriptionDetails as unknown as Record<string, unknown>
    ).packageName as Record<string, string> | undefined;
    const packageDisplayName = isAr ? packageName?.ar : packageName?.en;
    const setupFeeAlreadyPaid = Boolean(
      subscriptionDetails.subscription.setupFeePaid,
    );
    const trialEndsAt = subscriptionDetails.subscription.trialEndsAt
      ? new Date(subscriptionDetails.subscription.trialEndsAt)
      : null;
    const trialStillActive = trialEndsAt
      ? trialEndsAt.getTime() > Date.now()
      : false;

    return (
      <div className="space-y-6">
        {/* Selected Package - Pending Payment Card */}
        <div className="rounded-xl bg-white p-6 shadow-sm border-2 border-amber-400">
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <div className="inline-flex items-center gap-2 rounded-full bg-amber-100 px-3 py-1 text-xs font-semibold text-amber-700 mb-3">
                <span role="img" aria-label="warning">
                  &#9888;&#65039;
                </span>{" "}
                {isAr ? "الدفع معلق" : "Payment Pending"}
              </div>
              <h2 className="text-xl font-bold text-slate-900 mb-2">
                {isAr ? "لقد اخترت خطة:" : "You selected:"}{" "}
                <span className="text-brand-green">
                  {packageDisplayName || currentTierName}
                </span>
              </h2>
              <p className="text-sm text-slate-600 mb-4">
                {isAr
                  ? "لتفعيل اشتراكك والوصول إلى جميع المميزات، يرجى إكمال عملية الدفع."
                  : "To activate your subscription and access all features, please complete the payment process."}
              </p>

              {/* Selected Package Benefits */}
              {tierInfo && (
                <div className="rounded-lg bg-emerald-50 p-4 mb-4">
                  <p className="text-xs font-semibold text-slate-700 mb-2">
                    {isAr ? "مميزات هذه الخطة:" : "This plan includes:"}
                  </p>
                  <ul className="space-y-1.5">
                    {(isAr ? tierInfo.featuresAr : tierInfo.featuresEn)
                      .slice(0, 6)
                      .map((feature, idx) => (
                        <li
                          key={idx}
                          className="flex items-start gap-2 text-xs text-slate-700"
                        >
                          <span className="text-emerald-600 flex-shrink-0">
                            &#10003;
                          </span>
                          <span>{feature}</span>
                        </li>
                      ))}
                  </ul>
                </div>
              )}

              {/* Pricing Summary */}
              <div className="rounded-lg bg-slate-50 p-4">
                <div className="flex justify-between items-center text-sm">
                  <span className="text-slate-600">
                    {isAr ? "الاشتراك الشهري:" : "Monthly subscription:"}
                  </span>
                  <span className="font-bold text-slate-900">
                    {billingCurrency}{" "}
                    {convertPrice(
                      tierInfo?.priceGBP || 0,
                      billingCurrency,
                    ).toLocaleString()}
                  </span>
                </div>
                <div className="flex justify-between items-center text-sm mt-2 pt-2 border-t border-slate-200">
                  <span className="text-slate-600">
                    {isAr ? "رسوم الإعداد:" : "Setup fee:"}
                  </span>
                  {setupFeeAlreadyPaid ? (
                    <span className="font-bold text-emerald-700">
                      {isAr ? "مدفوعة بالفعل" : "Already paid"}
                    </span>
                  ) : (
                    <span className="font-bold text-slate-900">
                      {billingCurrency}{" "}
                      {convertPrice(
                        tierInfo?.setupGBP || 0,
                        billingCurrency,
                      ).toLocaleString()}
                    </span>
                  )}
                </div>
                {trialStillActive ? (
                  <p className="text-xs text-amber-600 mt-2">
                    <span role="img" aria-label="lightbulb">
                      &#128161;
                    </span>{" "}
                    {isAr ? "تجربة مجانية نشطة" : "Free trial is active"}
                  </p>
                ) : setupFeeAlreadyPaid ? (
                  <p className="text-xs text-slate-500 mt-2">
                    {isAr
                      ? "تم استخدام الفترة التجريبية، سيتم بدء الفوترة الشهرية بدون رسوم إعداد إضافية."
                      : "Trial already used—monthly billing starts now with no extra setup fee."}
                  </p>
                ) : null}
              </div>
            </div>
          </div>

          {/* Complete Payment CTA */}
          <div className="mt-6 flex gap-3">
            <button
              onClick={() => handleSelectPlan(currentTier as TierId, "monthly")}
              className="flex-1 rounded-lg bg-brand-green px-6 py-4 text-sm font-bold text-white hover:bg-brand-greenHover shadow-md hover:shadow-lg transition-all"
            >
              <span role="img" aria-label="sparkles">
                &#10024;
              </span>{" "}
              {isAr ? "إكمال الدفع الآن" : "Complete Payment Now"}
            </button>
            <button
              onClick={() => setShowPricingModal(true)}
              className="rounded-lg border-2 border-slate-200 px-6 py-4 text-sm font-medium text-slate-700 hover:border-brand-green hover:bg-slate-50 transition-all"
            >
              {isAr ? "تغيير الخطة" : "Change Plan"}
            </button>
          </div>

          {/* Help Text */}
          <p className="mt-4 text-xs text-center text-slate-500">
            <span role="img" aria-label="lock">
              &#128274;
            </span>{" "}
            {isAr
              ? "دفع آمن عبر Stripe - لن يتم تحصيل رسوم خلال الفترة التجريبية"
              : "Secure payment via Stripe - No charges during trial period"}
          </p>
        </div>

        {/* Why This Plan Section */}
        <div className="rounded-xl bg-white p-6 shadow-sm">
          <h3 className="text-base font-semibold text-slate-900 mb-4">
            {isAr ? "لماذا اخترت هذه الخطة؟" : "Why you selected this plan:"}
          </h3>
          <ul className="space-y-3">
            <li className="flex items-start gap-3 text-sm text-slate-700">
              <span className="flex-shrink-0 text-brand-green">
                <span role="img" aria-label="sparkles">
                  &#10024;
                </span>
              </span>
              <span>
                {isAr
                  ? "توازن مثالي بين الميزات والتكلفة"
                  : "Perfect balance of features and cost"}
              </span>
            </li>
            <li className="flex items-start gap-3 text-sm text-slate-700">
              <span className="flex-shrink-0 text-brand-green">
                <span role="img" aria-label="briefcase">
                  &#128188;
                </span>
              </span>
              <span>
                {isAr
                  ? "مناسبة لحجم ونوع عملك"
                  : "Suitable for your business size and type"}
              </span>
            </li>
            <li className="flex items-start gap-3 text-sm text-slate-700">
              <span className="flex-shrink-0 text-brand-green">
                <span role="img" aria-label="chart">
                  &#128200;
                </span>
              </span>
              <span>
                {isAr
                  ? "إمكانية الترقية في أي وقت"
                  : "Upgrade anytime as you grow"}
              </span>
            </li>
          </ul>
        </div>

        {/* Support */}
        <div className="rounded-xl bg-blue-50 p-6 text-center">
          <p className="text-sm text-slate-600 mb-3">
            {isAr ? "لديك أسئلة حول الدفع؟" : "Have questions about payment?"}
          </p>
          <Link
            href={`/${lang}/contact`}
            className="inline-flex items-center gap-2 rounded-lg border border-blue-200 bg-white px-6 py-2 text-sm font-medium text-blue-700 hover:bg-blue-50"
          >
            {isAr ? "تحدث إلينا" : "Contact us"} &rarr;
          </Link>
        </div>

        {/* Pricing Selection Modal for Change Plan */}
        <PricingSelectionModal
          lang={lang}
          isOpen={showPricingModal}
          onClose={() => setShowPricingModal(false)}
          onTierSelected={handleTierSelectedFromModal}
          defaultCurrency={billingCurrency}
        />
      </div>
    );
  }

  // If user has ACTIVE subscription, show current plan + upgrade option
  if (subscriptionDetails) {
    const currentTier = subscriptionDetails.subscription.tierId;
    const tierInfo = PRICING_TIERS.find((t) => t.id === currentTier);
    const currentTierName = isAr ? tierInfo?.nameAr : tierInfo?.nameEn;
    const daysRemaining = getDaysUntilBilling(
      new Date(subscriptionDetails.subscription.currentPeriodEnd),
    );

    // Check if subscription is in trial period
    const isTrialing = subscriptionDetails.subscription.status === "trialing";

    // Get available upgrade tiers (higher than current)
    // Trial users cannot upgrade until trial ends and subscription is active
    const currentTierIndex = PRICING_TIERS.findIndex(
      (t) => t.id === currentTier,
    );
    const upgradeTiers = isTrialing
      ? []
      : PRICING_TIERS.slice(currentTierIndex + 1);

    // Get available downgrade tiers (lower than current)
    // Trial users cannot downgrade until trial ends
    const downgradeTiers = isTrialing
      ? []
      : PRICING_TIERS.slice(0, currentTierIndex);

    return (
      <div className="space-y-6">
        {/* Current Plan Card */}
        <div className="rounded-xl bg-white p-6 shadow-sm border-2 border-emerald-200">
          <div className="flex items-start justify-between">
            <div>
              <div className="inline-flex items-center gap-2 rounded-full bg-sky-100 px-3 py-1 text-xs font-semibold text-sky-700 mb-2">
                {isAr ? "حساب مدفوع" : "Paid Account"}
              </div>
              <h2 className="text-lg font-semibold text-slate-900">
                {isAr ? "أنت حالياً في خطة" : "You are currently on"}{" "}
                <span className="text-brand-green">{currentTierName}</span>
              </h2>
              <div className="mt-2 flex items-center gap-3">
                <span className="inline-flex items-center gap-2 rounded-full bg-emerald-100 px-4 py-2 text-base font-bold text-emerald-700">
                  <span>&#10003;</span>
                  <span>{currentTierName}</span>
                </span>
                <span className="text-sm text-slate-600">
                  {subscriptionDetails.subscription.billingPeriod === "monthly"
                    ? isAr
                      ? "شهري"
                      : "Monthly"
                    : isAr
                      ? "سنوي"
                      : "Yearly"}
                </span>
              </div>
              <p className="mt-3 text-sm text-slate-600">
                {isAr ? "الحالة:" : "Status:"}{" "}
                <span className="font-semibold text-emerald-700">
                  {subscriptionDetails.subscription.status === "active"
                    ? isAr
                      ? "نشط"
                      : "Active"
                    : subscriptionDetails.subscription.status}
                </span>
              </p>
              <p className="mt-1 text-sm text-slate-600">
                {isAr ? "التجديد:" : "Renews:"}{" "}
                <span className="font-medium">
                  {new Date(
                    subscriptionDetails.subscription.currentPeriodEnd,
                  ).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                  })}
                </span>
                <span className="ml-2 text-xs text-slate-500">
                  ({daysRemaining} {isAr ? "يوم متبقي" : "days remaining"})
                </span>
              </p>
              {subscriptionDetails.subscription.setupFeePaid && (
                <p className="mt-1 text-xs text-emerald-600">
                  &#10003;{" "}
                  {isAr ? "رسوم الإعداد مدفوعة" : "Setup fee already paid"}
                </p>
              )}
            </div>
            {!isTrialing && (
              <button
                onClick={() => setShowUpgradeModal(true)}
                className="rounded-lg bg-brand-green px-6 py-3 text-sm font-semibold text-white hover:bg-brand-greenHover"
              >
                {isAr ? "ترقية الخطة" : "Upgrade Plan"}
              </button>
            )}
          </div>

          {/* Plan Pricing Summary */}
          <div className="mt-6 grid gap-4 sm:grid-cols-3">
            <div className="rounded-lg bg-emerald-50 p-4">
              <p className="text-xs font-medium text-slate-600">
                {isAr ? "السعر الشهري" : "Monthly Price"}
              </p>
              <p className="mt-1 text-2xl font-bold text-emerald-700">
                {billingCurrency}{" "}
                {convertPrice(
                  tierInfo?.priceGBP || 0,
                  billingCurrency,
                ).toLocaleString()}
              </p>
            </div>
            <div className="rounded-lg bg-sky-50 p-4">
              <p className="text-xs font-medium text-slate-600">
                {isAr ? "رسوم الإعداد" : "Setup Fee"}
              </p>
              <p className="mt-1 text-2xl font-bold text-sky-700">
                {subscriptionDetails.subscription.setupFeePaid
                  ? isAr
                    ? "✓ مدفوع"
                    : "✓ Paid"
                  : `${billingCurrency} ${convertPrice(tierInfo?.setupGBP || 0, billingCurrency)}`}
              </p>
            </div>
            <div className="rounded-lg bg-violet-50 p-4">
              <p className="text-xs font-medium text-slate-600">
                {isAr ? "أيام متبقية" : "Days Remaining"}
              </p>
              <p className="mt-1 text-2xl font-bold text-violet-700">
                {daysRemaining}
              </p>
              <p className="text-xs text-slate-500">
                {isAr ? "حتى التجديد" : "until renewal"}
              </p>
            </div>
          </div>

          {/* Current Plan Features */}
          {tierInfo && (
            <div className="mt-4 rounded-lg bg-slate-50 p-4">
              <p className="text-xs font-semibold text-slate-700 mb-2">
                {isAr ? "مميزات الخطة:" : "Plan Features:"}
              </p>
              <ul className="grid gap-2 sm:grid-cols-2">
                {(isAr ? tierInfo.featuresAr : tierInfo.featuresEn)
                  .slice(0, 6)
                  .map((feature, idx) => (
                    <li
                      key={idx}
                      className="flex items-start gap-2 text-xs text-slate-700"
                    >
                      <span className="text-emerald-600">&#10003;</span>
                      <span>{feature}</span>
                    </li>
                  ))}
              </ul>
            </div>
          )}
        </div>

        {/* Trial Notice - Show when user is in trial period */}
        {isTrialing && (
          <div className="rounded-xl bg-gradient-to-r from-amber-50 to-orange-50 p-6 shadow-sm border-2 border-amber-200">
            <div className="flex items-start gap-4">
              <div className="flex-shrink-0 text-3xl">
                <span role="img" aria-label="hourglass">
                  &#9203;
                </span>
              </div>
              <div>
                <h3 className="text-base font-semibold text-amber-900 mb-2">
                  {isAr ? "فترة تجريبية نشطة" : "Trial Period Active"}
                </h3>
                <p className="text-sm text-amber-800 mb-3">
                  {isAr
                    ? "أنت حالياً في الفترة التجريبية المجانية. بمجرد انتهاء التجربة وتفعيل اشتراكك، ستتمكن من ترقية أو تخفيض خطتك."
                    : "You are currently in your free trial period. Once your trial ends and your subscription becomes active, you'll be able to upgrade or downgrade your plan."}
                </p>
                <div className="flex items-center gap-2 text-sm font-medium text-amber-700">
                  <span>
                    <span role="img" aria-label="calendar">
                      &#128197;
                    </span>
                  </span>
                  <span>
                    {isAr ? "تنتهي التجربة:" : "Trial ends:"}{" "}
                    {subscriptionDetails.subscription.trialEndsAt
                      ? new Date(
                          subscriptionDetails.subscription.trialEndsAt,
                        ).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                          year: "numeric",
                          month: "long",
                          day: "numeric",
                        })
                      : new Date(
                          subscriptionDetails.subscription.currentPeriodEnd,
                        ).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                          year: "numeric",
                          month: "long",
                          day: "numeric",
                        })}
                  </span>
                  <span className="text-amber-600">
                    ({daysRemaining} {isAr ? "يوم متبقي" : "days remaining"})
                  </span>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Usage Metrics */}
        <div className="rounded-xl bg-gradient-to-r from-slate-50 to-slate-100 p-6 shadow-sm">
          <h3 className="text-base font-semibold text-slate-900 mb-4">
            {isAr ? "استخدام الخطة" : "Plan Usage"}
          </h3>
          <div className="space-y-4">
            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-slate-700">
                  {isAr ? "المحادثات هذا الشهر" : "Conversations this month"}
                </span>
                <span className="text-sm font-semibold text-slate-900">
                  0 / {"\u221E"}
                </span>
              </div>
              <div className="h-2 w-full rounded-full bg-white overflow-hidden">
                <div
                  className="h-full bg-emerald-500"
                  style={{ width: "0%" }}
                ></div>
              </div>
            </div>
          </div>
          <p className="mt-4 text-xs text-slate-500">
            {isAr ? "تتجدد الحدود في" : "Limits reset on"}{" "}
            {new Date(
              subscriptionDetails.subscription.currentPeriodEnd,
            ).toLocaleDateString(isAr ? "ar-SA" : "en-US")}
          </p>
        </div>

        {/* Available Upgrades */}
        {upgradeTiers.length > 0 && (
          <div className="rounded-xl bg-gradient-to-r from-emerald-50 to-sky-50 p-6 shadow-sm">
            <h3 className="text-base font-semibold text-slate-900 mb-4">
              {isAr ? "ترقيات متاحة" : "Available Upgrades"}
            </h3>
            <div className="grid gap-4 sm:grid-cols-2">
              {upgradeTiers.map((upgradeTier) => {
                const upgradeTierName = isAr
                  ? upgradeTier.nameAr
                  : upgradeTier.nameEn;
                const upgradeMonthlyPrice = convertPrice(
                  upgradeTier.priceGBP,
                  billingCurrency,
                );
                const currentMonthlyPrice = convertPrice(
                  tierInfo?.priceGBP || 0,
                  billingCurrency,
                );

                // Calculate prorated charge
                const proratedCharge = calculateProratedUpgrade(
                  currentMonthlyPrice,
                  upgradeMonthlyPrice,
                  daysRemaining,
                  subscriptionDetails.subscription.billingPeriod,
                );

                return (
                  <div
                    key={upgradeTier.id}
                    className="rounded-lg bg-white p-4 border-2 border-brand-green/20 hover:border-brand-green transition-all"
                  >
                    <h4 className="text-sm font-bold text-slate-900">
                      {upgradeTierName}
                    </h4>
                    <div className="mt-2">
                      <p className="text-2xl font-bold text-brand-green">
                        {billingCurrency} {upgradeMonthlyPrice.toLocaleString()}
                        <span className="text-sm font-normal text-slate-600">
                          /{isAr ? "شهر" : "mo"}
                        </span>
                      </p>
                      <p className="mt-1 text-xs text-amber-600">
                        {isAr
                          ? "رسوم الترقية المقسمة:"
                          : "Prorated upgrade fee:"}{" "}
                        {billingCurrency} {proratedCharge.toLocaleString()}
                      </p>
                      <p className="text-xs text-slate-500">
                        ({daysRemaining} {isAr ? "يوم متبقي" : "days remaining"}
                        )
                      </p>
                    </div>
                    <button
                      onClick={() =>
                        handleUpgradePlan(upgradeTier.id as TierId)
                      }
                      className="mt-3 w-full rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover"
                    >
                      {isAr ? "ترقية إلى" : "Upgrade to"} {upgradeTierName}
                    </button>
                  </div>
                );
              })}
            </div>
            <p className="mt-4 text-xs text-slate-600">
              <span role="img" aria-label="lightbulb">
                &#128161;
              </span>{" "}
              {isAr
                ? "الترقية تحسب تلقائياً رسوم مقسمة بناءً على الأيام المتبقية في دورتك الحالية. لا توجد رسوم إعداد إضافية."
                : "Upgrades are automatically prorated based on days remaining in your current cycle. No additional setup fees."}
            </p>
          </div>
        )}

        {/* Available Downgrades */}
        {downgradeTiers.length > 0 && (
          <div className="rounded-xl bg-gradient-to-r from-slate-50 to-slate-100 p-6 shadow-sm">
            <h3 className="text-base font-semibold text-slate-900 mb-4">
              {isAr ? "خيارات التخفيض" : "Downgrade Options"}
            </h3>
            <p className="text-sm text-slate-600 mb-4">
              {isAr
                ? "سيتم تطبيق الرصيد المتبقي على فاتورتك القادمة. لن تفقد المميزات الحالية حتى نهاية دورة الفوترة."
                : "Remaining credit will be applied to your next invoice. You'll keep current features until the end of your billing cycle."}
            </p>
            <div className="grid gap-4 sm:grid-cols-2">
              {downgradeTiers.map((downgradeTier) => {
                const downgradeTierName = isAr
                  ? downgradeTier.nameAr
                  : downgradeTier.nameEn;
                const downgradeMonthlyPrice = convertPrice(
                  downgradeTier.priceGBP,
                  billingCurrency,
                );
                const currentMonthlyPrice = convertPrice(
                  tierInfo?.priceGBP || 0,
                  billingCurrency,
                );

                // Calculate credit
                const creditInfo = calculateDowngradeCredit(
                  currentMonthlyPrice,
                  downgradeMonthlyPrice,
                  daysRemaining,
                  subscriptionDetails.subscription.billingPeriod,
                );

                return (
                  <div
                    key={downgradeTier.id}
                    className="rounded-lg bg-white p-4 border-2 border-slate-200 hover:border-slate-300 transition-all"
                  >
                    <h4 className="text-sm font-bold text-slate-900">
                      {downgradeTierName}
                    </h4>
                    <div className="mt-2">
                      <p className="text-2xl font-bold text-slate-700">
                        {billingCurrency}{" "}
                        {downgradeMonthlyPrice.toLocaleString()}
                        <span className="text-sm font-normal text-slate-600">
                          /{isAr ? "شهر" : "mo"}
                        </span>
                      </p>
                      <div className="mt-2 space-y-1">
                        <p className="text-xs text-emerald-600">
                          <span role="img" aria-label="money">
                            &#128176;
                          </span>{" "}
                          {isAr ? "رصيد متبقي:" : "Credit:"} {billingCurrency}{" "}
                          {creditInfo.creditAmount.toLocaleString()}
                        </p>
                        <p className="text-xs text-slate-600">
                          {isAr ? "الفاتورة القادمة:" : "Next bill:"}{" "}
                          {billingCurrency}{" "}
                          {creditInfo.nextBillingCharge.toLocaleString()}
                        </p>
                        <p className="text-xs text-slate-500">
                          ({daysRemaining}{" "}
                          {isAr ? "يوم متبقي" : "days remaining"})
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={() =>
                        handleDowngradePlan(downgradeTier.id as TierId)
                      }
                      className="mt-3 w-full rounded-lg border-2 border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                    >
                      {isAr ? "التخفيض إلى" : "Downgrade to"}{" "}
                      {downgradeTierName}
                    </button>
                  </div>
                );
              })}
            </div>
            <p className="mt-4 text-xs text-slate-600">
              <span role="img" aria-label="lightbulb">
                &#128161;
              </span>{" "}
              {isAr
                ? "التخفيض يطبق فوراً ويتم حساب الرصيد المتبقي تلقائياً. ستحتفظ بجميع المميزات حتى نهاية الدورة الحالية."
                : "Downgrades apply immediately and credit is calculated automatically. You'll retain all features until the end of current cycle."}
            </p>
          </div>
        )}

        {/* Billing History */}
        <div className="rounded-xl bg-white p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-base font-semibold text-slate-900">
              {isAr ? "سجل الفوترة" : "Billing History"}
            </h3>
            <Link
              href={`/${lang}/dashboard/billing`}
              className="text-sm text-brand-green hover:underline"
            >
              {isAr ? "عرض الكل" : "View all"} &rarr;
            </Link>
          </div>
          <BillingHistory lang={lang} limit={5} />
        </div>

        {/* Upgrade Modal */}
        <PlanUpgradeModal
          lang={lang}
          isOpen={showUpgradeModal}
          onClose={() => setShowUpgradeModal(false)}
          subscriptionData={subscriptionDetails}
          currency={billingCurrency}
          initialTier={selectedTier || undefined}
          billingPeriod={subscriptionDetails.subscription.billingPeriod}
          onSuccess={() => {
            setShowUpgradeModal(false);
            onUpgradeSuccess();
          }}
        />
      </div>
    );
  }

  // No subscription - show plan selector
  return (
    <div className="space-y-6">
      {/* No Subscription Hero */}
      <div className="rounded-xl bg-gradient-to-r from-brand-green/10 to-emerald-50 p-8 shadow-sm text-center">
        <div className="text-6xl mb-4">
          <span role="img" aria-label="rocket">
            &#128640;
          </span>
        </div>
        <h2 className="text-2xl font-bold text-slate-900 mb-2">
          {isAr ? "اختر خطتك المثالية" : "Choose Your Perfect Plan"}
        </h2>
        <p className="text-sm text-slate-600 max-w-2xl mx-auto">
          {isAr
            ? "ابدأ مع ماويدي اليوم - اختر الخطة التي تناسب احتياجات عملك"
            : "Get started with Mawidi today - Select the plan that fits your business needs"}
        </p>
      </div>

      {/* Inline Plan Selection */}
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        {PRICING_TIERS.slice(0, 5).map((tier) => {
          // Convert GBP prices to user's currency
          const baseMonthlyGBP = tier.priceGBP || 0;
          const baseSetupGBP = tier.setupGBP || 0;

          const monthlyPrice = convertPrice(baseMonthlyGBP, billingCurrency);
          const yearlyPrice = Math.round(monthlyPrice * 12 * 0.93); // 7% yearly discount
          const setupFee = convertPrice(baseSetupGBP, billingCurrency);

          const isPopular =
            tier.popular || tier.id === "tier2" || tier.id === "tier3";
          const tierName = isAr ? tier.nameAr : tier.nameEn;
          const tierFeatures = isAr ? tier.featuresAr : tier.featuresEn;

          return (
            <div
              key={tier.id}
              className={`relative rounded-xl bg-white p-6 shadow-sm border-2 transition-all hover:shadow-lg ${
                isPopular ? "border-brand-green" : "border-slate-200"
              }`}
            >
              {isPopular && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                  <span className="inline-flex rounded-full bg-brand-green px-3 py-1 text-xs font-bold text-white">
                    {isAr ? "الأكثر شعبية" : "Most Popular"}
                  </span>
                </div>
              )}

              {/* Plan Name */}
              <h3 className="text-lg font-bold text-slate-900">{tierName}</h3>
              {setupFee > 0 && (
                <p className="mt-1 text-xs text-slate-600">
                  {isAr ? "رسوم الإعداد:" : "Setup fee:"} {billingCurrency}{" "}
                  {setupFee}
                </p>
              )}

              {/* Pricing */}
              <div className="mt-4">
                <div className="flex items-baseline gap-1">
                  <span className="text-3xl font-bold text-slate-900">
                    {billingCurrency} {monthlyPrice.toLocaleString()}
                  </span>
                  <span className="text-sm text-slate-600">
                    /{isAr ? "شهر" : "mo"}
                  </span>
                </div>
                {yearlyPrice > 0 && (
                  <p className="mt-1 text-xs text-emerald-600">
                    {isAr ? "أو" : "or"} {billingCurrency}{" "}
                    {yearlyPrice.toLocaleString()}/{isAr ? "سنة" : "yr"}{" "}
                    <span className="font-semibold">
                      ({isAr ? "وفر" : "Save"} 7%)
                    </span>
                  </p>
                )}
                {setupFee > 0 && (
                  <p className="mt-1 text-xs text-slate-500">
                    + {billingCurrency} {setupFee}{" "}
                    {isAr ? "رسوم إعداد" : "setup fee"}
                  </p>
                )}
              </div>

              {/* Key Features */}
              <ul className="mt-4 space-y-2">
                {tierFeatures.slice(0, 4).map((feature, idx) => (
                  <li
                    key={idx}
                    className="flex items-start gap-2 text-xs text-slate-700"
                  >
                    <span className="text-emerald-600">&#10003;</span>
                    <span>{feature}</span>
                  </li>
                ))}
              </ul>

              {/* CTA Buttons */}
              <div className="mt-6 space-y-2">
                <button
                  onClick={() => handleSelectPlan(tier.id as TierId, "monthly")}
                  className={`w-full rounded-lg px-4 py-3 text-sm font-semibold transition-all ${
                    isPopular
                      ? "bg-brand-green text-white hover:bg-brand-greenHover"
                      : "bg-slate-100 text-slate-900 hover:bg-slate-200"
                  }`}
                >
                  {isAr ? "ابدأ شهرياً" : "Start Monthly"}
                </button>
                {yearlyPrice > 0 && (
                  <button
                    onClick={() =>
                      handleSelectPlan(tier.id as TierId, "yearly")
                    }
                    className="w-full rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:border-brand-green hover:bg-slate-50"
                  >
                    {isAr ? "ادفع سنوياً" : "Pay Yearly"}
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Need Help */}
      <div className="rounded-xl bg-white p-6 shadow-sm text-center">
        <p className="text-sm text-slate-600 mb-4">
          {isAr
            ? "تحتاج مساعدة في اختيار الخطة المناسبة؟"
            : "Need help choosing the right plan?"}
        </p>
        <Link
          href={`/${lang}/contact`}
          className="inline-flex items-center gap-2 rounded-lg border border-brand-green px-6 py-2 text-sm font-medium text-brand-green hover:bg-brand-green hover:text-white"
        >
          {isAr ? "تحدث إلى فريق المبيعات" : "Talk to Sales"} &rarr;
        </Link>
      </div>
    </div>
  );
}
