"use client";

import { useState, useMemo } from "react";
import Image from "next/image";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import { useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { withCDN } from "@/src/lib/utils";
import { Tag, Check, AlertCircle, Sparkles, CreditCard, ChevronDown, ChevronLeft, ChevronRight, CalendarDays, ArrowLeft, User, CheckCircle2, Loader2 } from "lucide-react";
import { initiatePaymentAction, setupPaymentAction } from "@/src/lib/actions/paymentAction";
import { verifyCouponAction } from "@/src/lib/actions/couponAction";
import { fetchPaymentPlansAction } from "@/src/lib/actions/paymentPlansAction";
import type { PaymentPlan } from "@/src/lib/services/classwiseClassesService";
import type { PaymentPayload, SetupPaymentPayload } from "@/src/lib/services/paymentService";
import { RegisterDetailsResponse } from "@/src/lib/services/registerDetailsService";
import Footer from "../../../components/layout/Footer";
import Breadcrumbs from "../../../components/layout/Breadcrumbs";
import BackButton from "../../../components/layout/BackButton";
import { mergeContentWithTranslation } from "@/src/lib/utils/languageHelper";
import { getLocalizedUrl } from "@/src/lib/utils/urlHelper";
import { useLocalizedNavigation } from "@/src/lib/hooks/useLocalizedNavigation";

interface SubmissionPageClientProps {
  registerDetails: RegisterDetailsResponse | null;
  footerData: any;
  registrationId: string;
  pageData?: any;
}

export default function SubmissionPageClient({
  registerDetails,
  footerData,
  registrationId,
  pageData,
}: SubmissionPageClientProps) {
  const [isProcessing, setIsProcessing] = useState(false);

  // Coupon states
  const [couponCode, setCouponCode] = useState("");
  const [isCouponApplied, setIsCouponApplied] = useState(false);
  const [isVerifyingCoupon, setIsVerifyingCoupon] = useState(false);
  const [couponData, setCouponData] = useState<{
    discount: number;
    discount_type: "percentage" | "fixed";
    coupon_code: string;
  } | null>(null);
  const [couponError, setCouponError] = useState("");
  const [showCouponInput, setShowCouponInput] = useState(false);
  const [paymentError, setPaymentError] = useState<string | null>(null);

  // Payment plans states
  const [showPaymentPlans, setShowPaymentPlans] = useState(false);
  const [paymentPlans, setPaymentPlans] = useState<PaymentPlan[]>([]);
  const [isLoadingPlans, setIsLoadingPlans] = useState(false);
  const [plansError, setPlansError] = useState("");
  const [plansPage, setPlansPage] = useState(1);
  const PLANS_PER_PAGE = 5;

  const { currentLanguage } = useLanguage();
  // These redirects already carried the language but not the tenant, so a
  // preview or explicitly-scoped session lost its franchisee on the way to
  // checkout.
  const franchiseeId = useSearchParams().get("franchiseeId");

  // Translations
  const t = useMemo(() => {
    const def = pageData?.default || {};
    const trans = pageData?.translated;
    
    let activeData = def;
    if (currentLanguage !== "default" && trans && !Array.isArray(trans)) {
      activeData = mergeContentWithTranslation(def, trans);
    }
    
    const data = activeData?.submission;

    return data || {
      ageText: "Age",
      posText: "POS",
      nameText: "NAME",
      classText: "Class",
      emailText: "EMAIL",
      phoneText: "PHONE",
      setupText: "You're enrolled in a demo class. Add a payment method now or skip this step.",
      programText: "Program",
      payLaterText: "Pay Later",
      amountDueText: "Total Amount Due",
      childNameText: "CHILDS NAME",
      backToHomeText: "Go back to Home",
      schoolTypeText: "SCHOOL TYPE",
      yourDetailText: "Your Details",
      childDetailText: "child details",
      classDetailText: "class details",
      parentDetailText: "Parent detail",
      redeemCouponText: "Redeem Coupon",
      setupPaymentText: "Add Payment Method",
      registerSubHeading: "Review and complete your enrollment",
      registerMainHeading: "Registration Summary",
      viewPaymentPlanText: "View Payment Plans",
      proceedToPaymentText: "Proceed Payment",
      yourDetailSubHeading: "Review the information provided during registration"
    };
  }, [currentLanguage, pageData]);

  // Parse register details
  const details = registerDetails?.data?.[0];
  const submissionData = details?.submission_data || {};
  const formDataArray = Array.isArray(submissionData)
    ? submissionData
    : Object.values(submissionData);

  // Find class details
  const classDetailsObj = formDataArray.find((item: any) => item?.class_details);
  const classDetails = classDetailsObj?.class_details || {};

  // Adapt classDetails to mimic selectedClass structure
  const selectedClass = {
    ...classDetails,
    id: classDetails.group_id,
    label: classDetails.group_name,
    value: classDetails.price,
    fee_basis: classDetails.price_name,
    is_demo: classDetails.price === "0" || classDetails.price === 0 || !classDetails.price,
    tax_value: classDetails.invoice_tax_value ? parseFloat(classDetails.invoice_tax_value) : 0,
    tax_label: classDetails.invoice_tax_label || "Tax",
  };

  // Find email
  const step1 = formDataArray.find((item: any) => item?.step_1 || item?.name) || {};
  const email = step1?.email || step1?.Email || "";

  /**
   * The amount captured when the registration was created. The backend treats
   * this as authoritative and rejects anything else — see
   * PaymentAmountResolver::assertClientAmountMatches, whose comment reads
   * "Checkout form stores the exact amount the customer pays — do not
   * recalculate tax on top."
   *
   * This page used to derive its own total from `class_details.price` and add
   * tax on top of it. For any franchise with a non-zero invoice tax (or any
   * class paid by instalments, where the stored figure is the first
   * instalment) the two disagreed permanently, so payment failed with "The
   * payment total has changed" and refreshing never helped — both sides
   * recomputed the same mismatched pair every time.
   */
  const storedAmountDueNow = (() => {
    const paymentStep =
      formDataArray.find(
        (item: any) =>
          item?.step_3 === "payment_details" || item?.final_price != null,
      ) || {};

    const raw =
      paymentStep.amount_due_now ??
      paymentStep.final_price ??
      classDetails.amount_due_now;

    const value = typeof raw === "string" ? parseFloat(raw) : raw;
    return typeof value === "number" && !isNaN(value) && value > 0 ? value : null;
  })();

  // Get original price (Subtotal)
  const getOriginalPrice = () => {
    // Work backwards from the stored total so the pre-tax base, the tax line and
    // the final figure all reconcile to the amount the server will accept. This
    // mirrors how the resolver splits an explicit total server-side.
    if (storedAmountDueNow !== null) {
      const taxPercent = selectedClass.tax_value;
      return taxPercent > 0
        ? storedAmountDueNow / (1 + taxPercent / 100)
        : storedAmountDueNow;
    }

    // Legacy submissions saved before the amount was captured.
    if (selectedClass?.value) {
      return parseFloat(selectedClass.value as string);
    }
    return 0;
  };

  // Calculate discount amount
  const getDiscountAmount = () => {
    if (!isCouponApplied || !couponData) return 0;
    const originalPrice = getOriginalPrice();
    if (couponData.discount_type === "percentage") {
      return (originalPrice * couponData.discount) / 100;
    } else {
      return couponData.discount;
    }
  };

  // Calculate Tax Amount based on (Price - Discount)
  const getTaxAmount = () => {
    const taxableAmount = getOriginalPrice() - getDiscountAmount();
    if (selectedClass.tax_value > 0) {
      return (taxableAmount * selectedClass.tax_value) / 100;
    }
    return 0;
  };

  // Get final price (Total including Tax)
  //
  // Rounded to cents: with no coupon this reconstructs the stored total exactly,
  // and the server compares to within 0.02, so float drift from the divide above
  // can't push it over the threshold.
  const getFinalPrice = () => {
    const subtotal = getOriginalPrice();
    const discount = getDiscountAmount();
    const tax = getTaxAmount();
    return Math.round(Math.max(0, subtotal - discount + tax) * 100) / 100;
  };

  // Format price
  const formatPrice = (amount: number) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
    }).format(amount);
  };

  // Handle coupon verification
  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) {
      setCouponError("Please enter a coupon code");
      return;
    }

    if (!selectedClass?.id) {
      setCouponError("Class information not available");
      return;
    }

    setIsVerifyingCoupon(true);
    setCouponError("");

    try {
      const response = await verifyCouponAction(couponCode.trim(), selectedClass.id);
      if (response.success && response.data) {
        setCouponData(response.data);
        setIsCouponApplied(true);
        setCouponError("");
      } else {
        setCouponError(response.message || "Invalid coupon code");
        setIsCouponApplied(false);
        setCouponData(null);
      }
    } catch (error) {
      setCouponError("Failed to verify coupon. Please try again.");
      setIsCouponApplied(false);
      setCouponData(null);
    } finally {
      setIsVerifyingCoupon(false);
    }
  };

  const handleRemoveCoupon = () => {
    setCouponCode("");
    setIsCouponApplied(false);
    setCouponData(null);
    setCouponError("");
  };

  const handleTogglePaymentPlans = async () => {
    if (showPaymentPlans) {
      setShowPaymentPlans(false);
      return;
    }

    const groupId = selectedClass?.id;
    const accountId = footerData?.tenant?.zoho_franchise_id;

    if (!groupId || !accountId) {
      setPlansError("Class or account information not available.");
      setShowPaymentPlans(true);
      return;
    }

    setIsLoadingPlans(true);
    setPlansError("");
    setShowPaymentPlans(true);

    try {
      const response = await fetchPaymentPlansAction(String(groupId), String(accountId));
      if (response.success && response.data.length > 0) {
        setPaymentPlans(response.data);
      } else {
        setPlansError(response.message || "Failed to load payment plans.");
        setPaymentPlans([]);
      }
    } catch (err) {
      setPlansError("Unable to load payment plans. Please try again.");
      setPaymentPlans([]);
    } finally {
      setIsLoadingPlans(false);
    }
  };

  const handlePayNow = async () => {
    setIsProcessing(true);
    setPaymentError(null);
    try {
      let response;
      if (selectedClass?.is_demo) {
        const setupPaymentPayload: SetupPaymentPayload = {
          user_id: 1,
          gateway: "stripe",
          email: email,
          registration_id: registrationId,
        };
        response = await setupPaymentAction(setupPaymentPayload);
      } else {
        const amount = getFinalPrice();
        const paymentPayload: PaymentPayload = {
          user_id: 1,
          gateway: "stripe",
          amount: amount,
          currency: "usd",
          email: email,
          registration_id: registrationId,
          class_id: selectedClass?.id,
          class_name: selectedClass?.label,
          fee_basis: selectedClass?.fee_basis,
          number_of_lessons: selectedClass?.number_of_lessons,
          frequency: selectedClass?.frequency,
          submitted_data: formDataArray as any,
        };
        response = await initiatePaymentAction(paymentPayload);
      }

      if (response.status && response.data) {
        const responseRegistrationId = response.data.registration_id || registrationId;
        const clientSecret = response.data.response?.client_secret;
        const finalAmount = selectedClass?.is_demo ? 0 : getFinalPrice();

        if (responseRegistrationId && clientSecret) {
          sessionStorage.setItem(`payment_${responseRegistrationId}`, clientSecret);
          sessionStorage.setItem(`amount_${responseRegistrationId}`, finalAmount.toString());
          sessionStorage.setItem(`submission_${responseRegistrationId}`, responseRegistrationId);
          sessionStorage.setItem(`registration_id`, responseRegistrationId.toString());

          setTimeout(() => {
            window.location.href = getLocalizedUrl(`/pay/${responseRegistrationId}`, currentLanguage, franchiseeId);
          }, 100);
        } else {
          alert("Payment configuration error. Please try again.");
          setIsProcessing(false);
        }
      } else {
        if (response.message?.toLowerCase().includes("no active stripe payment method")) {
          setPaymentError("The franchisee has not configured their payment setup yet. Please contact the franchisee for assistance or try again later.");
        } else {
          alert(response.message || "Payment failed. Please try again.");
        }
        setIsProcessing(false);
      }
    } catch (error) {
      alert("An error occurred while processing payment. Please try again.");
      setIsProcessing(false);
    }
  };

  const formatDueDate = (dateStr: string) => {
    const d = new Date(dateStr);
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  };

  // --- NEW: Pre-process the steps for the split grid layout ---
  const processedSteps = formDataArray.slice(0, 3).map((stepData: any, index: number) => {
    const visibleFields = Object.entries(stepData).filter(([key]) =>
      !key.startsWith("step_") &&
      !key.startsWith("agree_step_") &&
      key !== "class_details"
    );
    return { originalIndex: index, visibleFields };
  }).filter((step: any) => step.visibleFields.length > 0);

  const firstStep = processedSteps[0];
  const remainingSteps = processedSteps.slice(1);

  // Helper to get step title
  const getStepTitle = (index: number) => {
    const titles: Record<number, string> = {
      0: t.parentDetailText || "Parent detail",
      1: t.childDetailText || "child details",
      2: t.classDetailText || "class details",
    };
    return titles[index] || `Application Step ${index + 1}`;
  };

  // Helper to get field label
  const getFieldLabel = (key: string) => {
    const label = key.replace(/_/g, " ");
    const mapping: Record<string, string> = {
      "select location": t.posText || "POS",
      "select programs": t.programText || "program",
      "choose classes": t.classText || "Class",
      "name": t.nameText || "NAME",
      "email": t.emailText || "EMAIL",
      "phone": t.phoneText || "PHONE",
      "age": t.ageText || "AGE",
      "school type": t.schoolTypeText || "SCHOOL TYPE",
      "childs name": t.childNameText || "CHILDS NAME",
    };
    return mapping[label.toLowerCase()] || label;
  };

  return (
    <main className="font-[Signika] text-[#58585A]">
      {/* 1. FIXED HERO BANNER */}
      <section
        className="relative w-full overflow-hidden py-10 md:py-16 lg:py-25 flex align-center justify-center
                min-h-[400px] min-[106rem]:h-[460px]
                px-4 md:px-8 sm:p b-0 max-[767px]:h-[531px]"
      >
        {/* Background */}
        <div className="absolute inset-0 -z-10">
          <div
            className="block md:hidden w-full h-full bg-cover bg-[position:50%_-36%]"
            style={{ backgroundImage: `url('${withCDN("/About/bg_hero%20screen%20(2).png")}')` }}
          />
          <div
            className="hidden md:block w-full h-full bg-cover bg-bottom"
            style={{ backgroundImage: `url('${withCDN("/About/bg_hero%20screen%20(2).png")}')` }}
          />
        </div>

        {/* Overlay */}
        <div className="pointer-events-none absolute inset-0" />
        <div className="relative z-10 flex flex-col gap-8 px-5 w-full px-4 lg:px-10 xl:px-26 lg:px-10 max-[991]:mt-[30px] max-[991]:px-0 max-[767px]:mt-[48px]">
          <BackButton />
          <Breadcrumbs hideLast />

          {/* Welcome text */}
          <div className="flex flex-col gap-3 leading-none ">
            <h1
              className="
                        heading-hero text-[30px] md:text-[50px] lg:text-[50px] max-[767px]:text-[50px]
                        text-white uppercase font-bold leading-tight tracking-wide md:whitespace-nowrap
                      "
            >
              {t.registerMainHeading || "Registration Summary"}
            </h1>
            <p className="text-[20px] md:text-[18px] lg:text-[25px] text-[#fff] uppercase max-[767px]:text-[25px] max-[767px]:leading-8">
              {t.registerSubHeading || "Review and complete your enrollment"}
            </p>
          </div>
        </div>
      </section>

      {/* 2. MAIN CONTENT AREA */}
      <section className="relative w-full overflow-hidden 
        pb-10 pt-50 md:pb-10 min-h-[600px]
        px-4 md:px-8 lg:px-18 xl:px-34 mt-[-210px] z-[10] min-[106rem]:mt-[-210px] max-[767px]:mt-[-203px] max-[767px]:pt-30">

        {/* Background */}
        <div className="absolute inset-0 -z-10">
          <div
            className="block md:hidden w-full h-full bg-cover bg-[position:30%_50%]"
            style={{ backgroundImage: `url('${withCDN("/form-footer.png")}')` }}
          />
          <div
            className="hidden md:block w-full h-full bg-cover bg-top"
            style={{ backgroundImage: `url('${withCDN("/form-footer.png")}')` }}
          />
        </div>

        <div className="xl:w-[90%] max-w-[1300px] mx-auto">

          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-10">

            {/* =========================================
                ROW 1: FIRST CARD & DYNAMIC IMAGE 
                ========================================= */}
            <div className="lg:col-span-7 flex flex-col">
              {/* Header Container */}
              <div className="flex items-center gap-4 mb-5 pl-1 h-[60px] shrink-0">
                <div className="w-12 h-12 rounded-2xl bg-[#E5F4FB] flex items-center justify-center shadow-inner shrink-0">
                  <User className="text-[#0097DC]" size={24} />
                </div>
                <div>
                  <h3 className="text-[28px] font-bold text-[#0097DC] leading-tight">{t.yourDetailText || "Your Details"}</h3>
                  <p className="text-[13px] text-[#828282] font-semibold mt-0.5">{t.yourDetailSubHeading || "Review the information provided during registration"}</p>
                </div>
              </div>

              {/* First Card */}
              {firstStep && (
                <motion.div
                  initial={{ opacity: 0, y: 15 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="flex-grow w-full bg-white rounded-2xl p-5 md:p-6 shadow-[0_2px_12px_rgb(0,0,0,0.03)] border border-gray-100 relative overflow-hidden group hover:shadow-[0_4px_20px_rgba(0,151,220,0.06)] transition-all duration-300"
                >
                  <div className="absolute left-0 top-0 bottom-0 w-1 bg-[#0097DC] opacity-50 group-hover:opacity-100 transition-opacity" />

                  <div className="flex items-center gap-2 mb-4 pb-3 border-b border-gray-100">
                    <CheckCircle2 size={16} className="text-[#0097DC]" />
                    <h4 className="text-[13px] font-bold text-[#0097DC] uppercase tracking-widest">
                      {getStepTitle(firstStep.originalIndex)}
                    </h4>
                  </div>

                  <div className="space-y-2">
                    {firstStep.visibleFields.map(([key, value]) => (
                      <div key={key} className="flex flex-col sm:flex-row sm:justify-between sm:items-center bg-gray-50/50 p-2.5 px-4 rounded-xl hover:bg-gray-50 transition-colors">
                        <span className="text-[12px] text-[#828282] font-bold uppercase tracking-wider mb-0.5 sm:mb-0">
                          {getFieldLabel(key)}
                        </span>
                        <span className="text-[14px] font-black text-[#58585A] sm:text-right">
                          {String(value)}
                        </span>
                      </div>
                    ))}
                  </div>
                </motion.div>
              )}
            </div>

            <div className="lg:col-span-5 flex flex-col h-full max-lg:mt-2">
              {/* Invisible Spacer exactly matching the Left Header to push the image down smoothly */}
              <div className="hidden lg:block h-[60px] mb-5 shrink-0"></div>

              {/* Responsive Image Container automatically mirroring left card height */}
              <motion.div
                initial={{ scale: 0.95, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ delay: 0.2, type: "spring", damping: 20 }}
                className="relative w-full flex-grow min-h-[250px] drop-shadow-xl"
              >
                <Image
                  src={withCDN("/congratulations.png")}
                  alt="Congratulations"
                  fill
                  className="rounded-2xl object-cover shadow-lg border border-gray-100"
                />
              </motion.div>
            </div>

            {/* =========================================
                ROW 2: REMAINING CARDS & PAYMENT BLOCK 
                ========================================= */}
            <div className="lg:col-span-7 space-y-5 max-lg:mt-5">
              {remainingSteps.map((step: any) => (
                <motion.div
                  key={step.originalIndex}
                  initial={{ opacity: 0, y: 15 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: step.originalIndex * 0.1 }}
                  className="bg-white rounded-2xl p-5 md:p-6 shadow-[0_2px_12px_rgb(0,0,0,0.03)] border border-gray-100 relative overflow-hidden group hover:shadow-[0_4px_20px_rgba(0,151,220,0.06)] transition-all duration-300"
                >
                  <div className="absolute left-0 top-0 bottom-0 w-1 bg-[#0097DC] opacity-50 group-hover:opacity-100 transition-opacity" />

                  <div className="flex items-center gap-2 mb-4 pb-3 border-b border-gray-100">
                    <CheckCircle2 size={16} className="text-[#0097DC]" />
                    <h4 className="text-[13px] font-bold text-[#0097DC] uppercase tracking-widest">
                      {getStepTitle(step.originalIndex)}
                    </h4>
                  </div>

                  <div className="space-y-2">
                    {step.visibleFields.map(([key, value]: any) => (
                      <div key={key} className="flex flex-col sm:flex-row sm:justify-between sm:items-center bg-gray-50/50 p-2.5 px-4 rounded-xl hover:bg-gray-50 transition-colors">
                        <span className="text-[12px] text-[#828282] font-bold uppercase tracking-wider mb-0.5 sm:mb-0">
                          {getFieldLabel(key)}
                        </span>
                        <span className="text-[14px] font-black text-[#58585A] sm:text-right">
                          {String(value)}
                        </span>
                      </div>
                    ))}
                  </div>
                </motion.div>
              ))}
            </div>

            <div className="lg:col-span-5 h-full max-lg:mt-5">
              <div className="lg:sticky lg:top-[120px] pb-10">

                {/* Payment Card */}
                <div className="bg-white rounded-[24px] p-6 md:p-8 shadow-[0_4px_24px_rgb(0,0,0,0.06)] border border-gray-100">
                  {/* Price Breakdown */}
                  <div className="space-y-3 mb-6">
                    {/* Subtotal - Only show if there is tax or coupon */}
                    {(selectedClass.tax_value > 0 || isCouponApplied) && (
                      <div className="flex justify-between items-center text-[13px] text-[#828282] font-semibold uppercase tracking-wider">
                        <span>Subtotal</span>
                        <span>{formatPrice(getOriginalPrice())}</span>
                      </div>
                    )}

                    {/* Discount */}
                    {isCouponApplied && (
                      <div className="flex justify-between items-center text-[13px] text-green-600 font-bold uppercase tracking-wider">
                        <span>Discount</span>
                        <span>- {formatPrice(getDiscountAmount())}</span>
                      </div>
                    )}

                    {/* Tax */}
                    {selectedClass.tax_value > 0 && (
                      <div className="flex justify-between items-center text-[13px] text-[#828282] font-semibold uppercase tracking-wider">
                        <span>{selectedClass.tax_label} ({selectedClass.tax_value}%)</span>
                        <span>{formatPrice(getTaxAmount())}</span>
                      </div>
                    )}
                  </div>

                  {/* Total Price Display */}
                  <div className="flex justify-between items-end mb-8 pt-4 border-t border-gray-100">
                    <div>
                      <p className="text-[11px] text-[#828282] font-black uppercase tracking-[0.2em] mb-2">{t.amountDueText || "Total Amount Due"}</p>
                      <div className="flex items-baseline gap-3">
                        <p className="text-4xl lg:text-[42px] font-black text-[#0097DC] font-[Signika]">
                          {formatPrice(getFinalPrice())}
                        </p>
                      </div>
                    </div>
                    <div className="w-11 h-11 bg-[#E5F4FB] rounded-xl flex items-center justify-center text-[#0097DC]">
                      <CreditCard size={22} />
                    </div>
                  </div>

                  {/* Demo Class Badge */}
                  {selectedClass?.is_demo && (
                    <div className="mb-6 flex items-start gap-3 bg-amber-50 border border-amber-200 rounded-xl p-4">
                      <Sparkles size={16} className="text-amber-500 mt-0.5" />
                      <div>
                        <p className="text-[13px] font-bold text-amber-800">Demo Class</p>
                        <p className="text-[12px] text-amber-700 mt-0.5 leading-tight">{t.setupText || "You're enrolled in a demo class. Add a payment method now or skip this step."}</p>
                      </div>
                    </div>
                  )}

                  {/* Coupons Section */}
                  {/* {!isCouponApplied && !selectedClass.is_demo && (
                    <div className="pt-4 border-t border-gray-100 mb-4">
                      {!showCouponInput ? (
                        <button
                          onClick={() => setShowCouponInput(true)}
                          className="flex items-center gap-2 text-[#0097DC] hover:text-[#0077B6] font-bold text-[13px] uppercase tracking-wider transition-colors cursor-pointer"
                        >
                          <Tag size={15} /> {t.redeemCouponText || "Redeem Coupon"}
                        </button>
                      ) : (
                        <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }} className="space-y-3">
                          <div className="flex flex-col sm:flex-row gap-2">
                            <input
                              type="text"
                              value={couponCode}
                              onChange={(e) => setCouponCode(e.target.value.toUpperCase())}
                              placeholder="ENTER CODE"
                              className="flex-1 px-4 py-2.5 bg-gray-50 border border-gray-200 focus:border-[#0097DC] rounded-xl focus:outline-none text-[13px] font-bold uppercase transition-colors"
                            />
                            <button
                              onClick={handleApplyCoupon}
                              disabled={isVerifyingCoupon || !couponCode.trim()}
                              className="px-6 py-2.5 bg-[#0097DC] text-white rounded-xl font-bold text-[13px] hover:bg-[#0077B6] transition-all disabled:opacity-50"
                            >
                              {isVerifyingCoupon ? "..." : "Apply"}
                            </button>
                          </div>
                          {couponError && <p className="text-[11px] text-red-500 font-bold flex items-center gap-1"><AlertCircle size={12} />{couponError}</p>}
                          <button onClick={() => setShowCouponInput(false)} className="text-[11px] text-gray-400 font-bold hover:text-gray-600">Cancel</button>
                        </motion.div>
                      )}
                    </div>
                  )} */}

                  {/* Applied Coupon Badge */}
                  {/* {isCouponApplied && couponData && (
                    <motion.div initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="mb-6 bg-green-50 border border-green-100 rounded-xl p-3.5 flex items-center justify-between shadow-sm">
                      <div className="flex items-center gap-3">
                        <div className="w-7 h-7 bg-green-500 rounded-full flex items-center justify-center shadow-md shadow-green-200"><Check size={14} className="text-white" /></div>
                        <div>
                          <p className="text-[12px] font-bold text-green-700 uppercase">{couponData.coupon_code} Applied!</p>
                          <p className="text-[11px] text-green-600 font-semibold">Saved {formatPrice(getDiscountAmount())}</p>
                        </div>
                      </div>
                      <button onClick={handleRemoveCoupon} className="text-green-600 hover:text-green-800 p-1.5"><ArrowLeft size={14} className="rotate-180" /></button>
                    </motion.div>
                  )} */}

                  {/* Payment Plans Accordion */}
                  {!selectedClass.is_demo && (
                    <div className="pt-4 border-t border-gray-100 mb-6">
                      <button
                        onClick={handleTogglePaymentPlans}
                        className="w-full flex items-center justify-between text-[#58585A] hover:text-[#0097DC] transition-colors cursor-pointer"
                      >
                        <div className="flex items-center gap-2 font-bold text-[13px] uppercase tracking-wider">
                          <CreditCard size={16} /> {t.viewPaymentPlanText || "View Payment Plans"}
                        </div>
                        <ChevronDown size={16} className={`transition-transform duration-300 ${showPaymentPlans ? "rotate-180" : ""}`} />
                      </button>

                      <AnimatePresence>
                        {showPaymentPlans && (
                          <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} className="overflow-hidden">
                            <div className="mt-4 space-y-2.5">
                              {isLoadingPlans ? (
                                <div className="flex flex-col items-center justify-center py-8 gap-2">
                                  <Loader2 className="w-6 h-6 text-[#0097DC] animate-spin" />
                                  <p className="text-[11px] font-bold text-[#0097DC] uppercase tracking-widest">Fetching Plans</p>
                                </div>
                              ) : paymentPlans.length > 0 ? (
                                <>
                                  {paymentPlans.slice((plansPage - 1) * PLANS_PER_PAGE, plansPage * PLANS_PER_PAGE).map((plan, idx) => (
                                    <div key={plan.id} className="flex justify-between items-center bg-gray-50 hover:bg-gray-100 transition-colors border border-gray-200 rounded-xl p-3">
                                      <div className="flex items-center gap-3">
                                        <div className="w-6 h-6 bg-white rounded-full flex items-center justify-center text-[11px] font-black text-[#0097DC] shadow-sm">{(plansPage - 1) * PLANS_PER_PAGE + idx + 1}</div>
                                        <div>
                                          <p className="text-[12px] font-semibold text-[#58585A] flex items-center gap-1.5"><CalendarDays size={11} /> {formatDueDate(plan.due_date)}</p>
                                          <p className="text-[10px] font-bold text-amber-600 uppercase mt-0.5 tracking-wider">
                                            {plan.status.replace(/_/g, " ")}
                                          </p>
                                        </div>
                                      </div>
                                      <p className="text-[13px] font-black text-[#0097DC]">{formatPrice(parseFloat(plan.amount))}</p>
                                    </div>
                                  ))}

                                  {paymentPlans.length > PLANS_PER_PAGE && (
                                    <div className="flex items-center justify-between bg-[#E5F4FB] rounded-xl p-2 mt-3">
                                      <button
                                        onClick={() => setPlansPage(prev => Math.max(1, prev - 1))}
                                        disabled={plansPage === 1}
                                        className="p-1.5 hover:bg-[#D0EBF8] rounded-lg transition-colors disabled:opacity-30 disabled:cursor-not-allowed text-[#0097DC] cursor-pointer"
                                      >
                                        <ChevronLeft size={18} />
                                      </button>

                                      <div className="text-[11px] font-black text-[#0097DC] uppercase tracking-widest">
                                        Page {plansPage} / {Math.ceil(paymentPlans.length / PLANS_PER_PAGE)}
                                      </div>

                                      <button
                                        onClick={() => setPlansPage(prev => Math.min(Math.ceil(paymentPlans.length / PLANS_PER_PAGE), prev + 1))}
                                        disabled={plansPage >= Math.ceil(paymentPlans.length / PLANS_PER_PAGE)}
                                        className="p-1.5 hover:bg-[#D0EBF8] rounded-lg transition-colors disabled:opacity-30 disabled:cursor-not-allowed text-[#0097DC] cursor-pointer"
                                      >
                                        <ChevronRight size={18} />
                                      </button>
                                    </div>
                                  )}
                                </>
                              ) : (
                                <p className="text-[11px] text-center text-gray-500 bg-gray-50 p-3 rounded-xl border border-dashed border-gray-200">{plansError || "No future payment plans."}</p>
                              )}
                            </div>
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </div>
                  )}

                  {/* Payment Gateway Errors */}
                  <AnimatePresence>
                    {paymentError && (
                      <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }} exit={{ opacity: 0, height: 0 }} className="mb-6">
                        <div className="bg-red-50 border border-red-200 rounded-xl p-3.5 flex items-start gap-2.5">
                          <AlertCircle size={15} className="text-red-500 mt-0.5 flex-shrink-0" />
                          <p className="text-[12px] text-red-700 font-medium leading-tight">{paymentError}</p>
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>

                  {/* Final Checkout Buttons */}
                  <div className="space-y-4 pt-5 border-t border-gray-100">
                    <div className="flex flex-col sm:flex-row gap-3">
                      {String(selectedClass?.payer_id) !== "2" && (
                        <button
                          onClick={handlePayNow}
                          disabled={isProcessing}
                          className="flex-1 py-[10px] bg-[#0097DC] hover:bg-[#0077B6] 
                            text-white rounded-lg font-semibold text-sm uppercase tracking-wide 
                            transition-all shadow-sm hover:shadow-md 
                            disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                        >
                          {isProcessing
                            ? "Processing..."
                            : selectedClass.is_demo
                              ? (t.setupPaymentText || "Add Payment Method")
                              : (t.proceedToPaymentText || "Proceed Payment")}
                        </button>
                      )}

                      {(!selectedClass.is_demo || String(selectedClass?.payer_id) === "2") && (
                        <button
                          onClick={() => {
                            window.location.href = getLocalizedUrl(`/thank-you/${registrationId}?paylater=true`, currentLanguage, franchiseeId);
                          }}
                          className="flex-1 py-[10px] bg-[#95C11F] hover:bg-[#7ba119] 
                            text-white rounded-lg font-semibold text-sm uppercase tracking-wide 
                            transition-all shadow-sm hover:shadow-md cursor-pointer"
                        >
                          {t.payLaterText || "Pay Later"}
                        </button>
                      )}
                    </div>

                    <button
                      onClick={() => {
                        window.location.href = getLocalizedUrl("/", currentLanguage, franchiseeId);
                      }}
                      className="w-full py-3 bg-white text-gray-500 border border-gray-200 
                        rounded-lg font-medium text-xs uppercase tracking-wide 
                        hover:bg-gray-50 hover:text-gray-700 hover:border-gray-300 
                        transition-all flex items-center justify-center gap-2 cursor-pointer"
                    >
                      <ArrowLeft size={14} /> {t.backToHomeText || "Go back to Home"}
                    </button>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </section>

      {/* Footer Section */}
      <Footer footerData={footerData} />
    </main>
  );
}