// "use client";

// import React, { useEffect } from 'react';
// import { useRouter, useSearchParams } from 'next/navigation';
// import useSWR from 'swr';
// import { useAuth } from '@/context/AuthContext';
// import { useReducedMotion } from 'framer-motion';
// import {
//   BuildingLibraryIcon,
//   ArrowPathRoundedSquareIcon,
//   ShieldCheckIcon,
//   SparklesIcon,
//   MapPinIcon,
//   ArrowLeftIcon,
//   ClipboardDocumentCheckIcon,
//   ChatBubbleBottomCenterTextIcon,
//   CheckBadgeIcon,
//   ArrowTopRightOnSquareIcon,
// } from '@heroicons/react/24/outline';
// import { motion } from "framer-motion";
// import ModernCheckoutHeader from '@/components/jsxFiles/ModernCheckoutHeader';
// import BottomNavigation from '@/components/jsxFiles/BottomNavigation';

// // --- Helpers ---
// const fetcher = (...args) => fetch(...args).then((res) => res.json());

// const LoadingSpinner = () => (
//   <div className="flex justify-center items-center h-screen bg-slate-50" role="status" aria-label="در حال بارگذاری">
//     <div className="relative">
//       <div className="absolute inset-0 bg-blue-500/20 blur-2xl rounded-full" aria-hidden="true" />
//       <ArrowPathRoundedSquareIcon className="relative w-12 h-12 animate-spin text-blue-600" aria-hidden="true" />
//     </div>
//   </div>
// );

// // --- کارت روش پرداخت (قابل کلیک) ---
// const PaymentMethodInfo = ({ title, description, icon: Icon, badge, accent = "blue", onClick }) => {
//   const accents = {
//     blue: {
//       iconBg: "bg-gradient-to-br from-blue-500 to-sky-600",
//       iconShadow: "shadow-blue-500/20",
//       glow: "bg-blue-400/30",
//       badge: "bg-blue-50 text-blue-700 ring-1 ring-blue-100",
//       dot: "bg-blue-500",
//     },
//     sky: {
//       iconBg: "bg-gradient-to-br from-sky-500 to-blue-600",
//       iconShadow: "shadow-sky-500/25",
//       glow: "bg-sky-400/30",
//       badge: "bg-sky-50 text-sky-700 ring-1 ring-sky-100",
//       dot: "bg-sky-500",
//     },
//   };
//   const c = accents[accent] || accents.blue;

//   return (
//     <button
//       type="button"
//       onClick={onClick}
//       className="
//         relative w-full text-right overflow-hidden p-5 rounded-[28px]
//         bg-white/80 backdrop-blur-xl border border-white
//         shadow-[0_10px_40px_-15px_rgba(2,6,23,0.15)]
//         ring-1 ring-slate-100
//         cursor-pointer active:scale-[0.99] transition-transform duration-150
//         focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2
//       "
//     >
//       <div className="flex items-center gap-4 relative z-10">
//         <div className={`
//           relative w-14 h-14 rounded-2xl flex items-center justify-center
//           text-white shadow-lg ${c.iconShadow} shrink-0 ${c.iconBg}
//         `}>
//           <Icon className="w-7 h-7" aria-hidden="true" />
//         </div>

//         <div className="flex-1 min-w-0">
//           <div className="flex items-center gap-2 flex-wrap">
//             <h3 className="text-[15px] font-extrabold text-slate-900">{title}</h3>
//             {badge && (
//               <span className={`text-[11px] font-bold px-2.5 py-0.5 rounded-full ${c.badge}`}>
//                 {badge}
//               </span>
//             )}
//           </div>
//           <p className="text-[13px] text-slate-500 mt-1 font-medium leading-6 line-clamp-2">
//             {description}
//           </p>
//         </div>

//         <div className="flex items-center justify-center shrink-0" aria-hidden="true">
//           <span className={`w-3 h-3 rounded-full ring-4 ring-slate-100 ${c.dot}`} />
//         </div>
//       </div>
//       <div className={`absolute -top-10 -left-10 w-40 h-40 ${c.glow} rounded-full blur-3xl opacity-60`} aria-hidden="true" />
//     </button>
//   );
// };

// // --- تایم‌لاین مسیر اعلام قیمت ---
// const PriceFlowTimeline = () => {
//   const reduceMotion = useReducedMotion();
//   const steps = [
//     {
//       icon: ClipboardDocumentCheckIcon,
//       title: "ثبت سفارش بدون پرداخت",
//       desc: "سفارش شما رزرو می‌شود؛ در این مرحله هیچ مبلغی پرداخت نمی‌کنید.",
//     },
//     {
//       icon: ChatBubbleBottomCenterTextIcon,
//       title: "اعلام قیمت قطعی",
//       desc: "کارشناسان ما قیمت نهایی و به‌روز کالا را برای شما ارسال می‌کنند.",
//     },
//     {
//       icon: CheckBadgeIcon,
//       title: "تأیید شما یا لغو رایگان",
//       desc: "اگر قیمت را تأیید کنید خرید نهایی می‌شود؛ در غیر این صورت سفارش بدون هیچ هزینه‌ای لغو می‌شود.",
//     },
//   ];

//   return (
//     <motion.div
//       initial={reduceMotion ? false : { opacity: 0, y: 16 }}
//       animate={{ opacity: 1, y: 0 }}
//       transition={{ delay: 0.15 }}
//       className="relative bg-white/80 backdrop-blur-xl p-5 rounded-[28px] ring-1 ring-slate-100 border border-white shadow-[0_10px_40px_-18px_rgba(2,6,23,0.18)]"
//     >
//       <div className="flex items-center gap-2 mb-4">
//         <SparklesIcon className="w-5 h-5 text-blue-600 shrink-0" aria-hidden="true" />
//         <h3 className="text-sm font-extrabold text-slate-900">مسیر خرید این کالا چگونه است؟</h3>
//       </div>

//       <ol className="relative space-y-5">
//         <span className="absolute right-[19px] top-2 bottom-2 w-px bg-gradient-to-b from-blue-200 via-sky-200 to-blue-100" aria-hidden="true" />

//         {steps.map((s, i) => (
//           <motion.li
//             key={i}
//             initial={reduceMotion ? false : { opacity: 0, x: 10 }}
//             animate={{ opacity: 1, x: 0 }}
//             transition={{ delay: 0.2 + i * 0.08 }}
//             className="relative flex items-start gap-4"
//           >
//             <div className="relative z-10 w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-sky-600 text-white flex items-center justify-center shadow-lg shadow-blue-500/25 shrink-0">
//               <s.icon className="w-5 h-5" aria-hidden="true" />
//             </div>
//             <div className="flex-1 min-w-0 pt-0.5">
//               <div className="flex items-center gap-2 flex-wrap">
//                 <span className="text-[11px] font-black text-blue-600">مرحله {i + 1}</span>
//                 <h4 className="text-[13.5px] font-extrabold text-slate-900">{s.title}</h4>
//               </div>
//               <p className="text-[12.5px] text-slate-500 leading-6 font-medium mt-1">{s.desc}</p>
//             </div>
//           </motion.li>
//         ))}
//       </ol>

//       <div className="mt-4 flex items-center gap-2 bg-blue-50/70 rounded-2xl px-4 py-2.5 ring-1 ring-blue-100/70">
//         <ShieldCheckIcon className="w-4 h-4 text-blue-600 shrink-0" aria-hidden="true" />
//         <p className="text-[12px] text-blue-800 font-bold leading-5">
//           اختیار نهایی با شماست؛ تا قیمت را تأیید نکنید هیچ مبلغی از شما دریافت نمی‌شود.
//         </p>
//       </div>
//     </motion.div>
//   );
// };

// export default function PaymentPage() {
//   const router = useRouter();
//   const searchParams = useSearchParams();
//   const { user, loading: authLoading } = useAuth();
//   const reduceMotion = useReducedMotion();

//   const productId = searchParams.get('id');

//   const { data: productData, isLoading: productLoading } = useSWR(
//     productId ? `/api/productorder/${productId}` : null,
//     fetcher
//   );
//   const product = productData?.[0];

//   const shouldFetchProfile = user && !user.address;
//   const { data: userProfile } = useSWR(
//     shouldFetchProfile ? '/api/auth/me' : null,
//     fetcher,
//     { shouldRetryOnError: false }
//   );

//   const targetUser = userProfile?.user || userProfile || user;

//   useEffect(() => {
//     document.title = "صفحه انتخاب روش پرداخت";
//   }, []);

//   useEffect(() => {
//     if (authLoading || productLoading) return;
//     if (!user) {
//       const currentPath = `/checkout/payment?${searchParams.toString()}`;
//       router.push(`/login?redirect=${encodeURIComponent(currentPath)}`);
//     } else if (!product) {
//       router.push('/');
//     }
//   }, [user, authLoading, product, productLoading, router, searchParams]);

//   if (authLoading || productLoading || !user || !product) return <LoadingSpinner />;

//   const canPayOnline = product.isOnlinePayment === true;
//   const paramsString = searchParams.toString();

//   // --- تعیین برچسب و مقصد دکمه اصلی بر اساس نوع پرداخت ---
//   const ctaLabel = canPayOnline ? "ادامه و پرداخت اینترنتی" : "ادامه و ثبت سفارش";
//   const handleContinue = () => {
//     if (canPayOnline) {
//       router.push(`/checkout/payment/online?${paramsString}`);
//     } else {
//       router.push(`/checkout/payment/inquiry?${paramsString}`);
//     }
//   };

//   return (
//     <div className="min-h-screen bg-gradient-to-b from-slate-50 via-blue-50/30 to-slate-50 overflow-x-hidden" dir="rtl">
//       <ModernCheckoutHeader
//         currentStep={3}
//         cartUrl={`/getOrder/${productId}/${searchParams.get('color')}/${searchParams.get('size')}`}
//       />

//       {/* فاصله انتهایی (pb) اضافه شده تا نوار چسبیده به پایین محتوا را نپوشاند */}
//       <div className="max-w-lg mx-auto px-4 sm:px-5 pb-10 pt-2">
//         <main className="space-y-6">

//           {/* --- سرتیتر صفحه --- */}
//           <motion.div
//             initial={reduceMotion ? false : { opacity: 0, y: 12 }}
//             animate={{ opacity: 1, y: 0 }}
//             className="pt-2"
//           >
//             <h1 className="text-xl font-black text-slate-900">تکمیل پرداخت</h1>
//             <p className="text-sm text-slate-500 mt-1 font-medium">
//               یک گام تا ثبت نهایی سفارش باقی مانده است.
//             </p>
//           </motion.div>

//           {/* --- بخش آدرس --- */}
//           <motion.div
//             initial={reduceMotion ? false : { opacity: 0, y: 16 }}
//             animate={{ opacity: 1, y: 0 }}
//             transition={{ delay: 0.05 }}
//             className="relative bg-white/80 backdrop-blur-xl p-5 rounded-[28px] ring-1 ring-slate-100 border border-white shadow-[0_10px_40px_-18px_rgba(2,6,23,0.18)]"
//           >
//             <div className="flex items-start gap-4">
//               <div className="p-3 bg-gradient-to-br from-blue-50 to-sky-50 rounded-2xl text-blue-600 ring-1 ring-blue-100/60 shrink-0">
//                 <MapPinIcon className="w-6 h-6" aria-hidden="true" />
//               </div>
//               <div className="flex-1 min-w-0">
//                 <h3 className="font-extrabold text-slate-900 text-sm mb-1">آدرس تحویل سفارش</h3>
//                 <p className="text-sm text-slate-600 leading-7 font-medium line-clamp-2 break-words">
//                   {targetUser?.address || "آدرس ثبت نشده است"}
//                 </p>
//               </div>
//             </div>
//           </motion.div>

//           {/* --- روش پرداخت (کارت قابل کلیک) --- */}
//           <motion.section
//             initial={reduceMotion ? false : { opacity: 0, y: 16 }}
//             animate={{ opacity: 1, y: 0 }}
//             transition={{ delay: 0.1 }}
//             className="space-y-4"
//             aria-labelledby="payment-methods-heading"
//           >
//             <h2 id="payment-methods-heading" className="text-sm font-extrabold text-slate-700 px-1">
//               روش پرداخت شما
//             </h2>

//             {canPayOnline && (
//               <PaymentMethodInfo
//                 title="پرداخت اینترنتی"
//                 description="با کلیه کارت‌های بانکی عضو شتاب، آنی و امن"
//                 icon={BuildingLibraryIcon}
//                 badge="پیشنهادی"
//                 accent="sky"
//                 onClick={handleContinue}
//               />
//             )}

//             {!canPayOnline && (
//               <>
//                 <PaymentMethodInfo
//                   title="ثبت سفارش"
//                   description="ادامه فرآیند ثبت سفارش و پرداخت"
//                   icon={SparklesIcon}
//                   badge="پیشنهادی"
//                   accent="sky"
//                   onClick={handleContinue}
//                 />
//                 {/* <PriceFlowTimeline /> */}
//               </>
//             )}
//           </motion.section>
//         </main>
//       </div>

//       {/* --- نشان‌های اعتماد --- */}
//       <div className="flex flex-row flex-wrap mx-auto justify-center items-center gap-3 px-4 pb-6">
//         <div className="">
//             <a target="_blank" href="https://torob.com/shop/143402" rel="nofollow" className="" aria-label="نشان ضمانت ترب">
//               <img alt="" src="https://api.torob.com/third-party/guarantee/v1/hologram/?instance_id=143402"/>
//             </a>
//         </div>
//       </div>

//       {/* --- نوار اقدام اصلی چسبیده به پایین صفحه (CTA) --- */}
//       <motion.div
//         initial={reduceMotion ? false : { opacity: 0, y: 24 }}
//         animate={{ opacity: 1, y: 0 }}
//         transition={{ delay: 0.18, type: "spring", stiffness: 260, damping: 26 }}
//         className="fixed bottom-0 inset-x-0 z-40"
//       >
//         <div className="max-w-lg mx-auto px-4 sm:px-5">
//           <div className="
//             bg-white/85 backdrop-blur-xl border-t border-white
//             ring-1 ring-slate-100
//             shadow-[0_-10px_40px_-12px_rgba(2,6,23,0.20)]
//             rounded-t-[28px]
//             px-4 pt-3.5
//             pb-[max(1rem,env(safe-area-inset-bottom))]
//           ">
//             {/* خط اعتماد بالای دکمه */}
//             <div className="flex items-center justify-center gap-1.5 text-slate-500 text-[11.5px] font-semibold mb-3">
//               <ShieldCheckIcon className="w-3.5 h-3.5 text-blue-500 shrink-0" aria-hidden="true" />
//               پرداخت امن و رمزنگاری‌شده
//             </div>

//             {/* دکمه اصلی رفتن به مرحله بعد */}
//             <motion.button
//               type="button"
//               whileTap={{ scale: 0.98 }}
//               onClick={handleContinue}
//               className="
//                 relative w-full h-14 rounded-2xl overflow-hidden group
//                 bg-gradient-to-l from-blue-600 to-sky-500
//                 text-white font-extrabold text-[15px]
//                 flex items-center justify-center gap-2
//                 shadow-lg shadow-blue-500/30
//                 transition-shadow duration-300 active:shadow-md
//                 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-blue-500
//               "
//             >
//               <span className="relative z-10">{ctaLabel}</span>
//               <ArrowLeftIcon className="relative z-10 w-5 h-5 transition-transform duration-300 group-hover:-translate-x-1" aria-hidden="true" />
//               <span className="absolute inset-0 bg-white/10 opacity-0 group-hover:opacity-100 transition-opacity duration-300" aria-hidden="true" />
//             </motion.button>
//           </div>
//         </div>
//       </motion.div>

//       {/* <BottomNavigation /> */}
//     </div>
//   );
// }
"use client";

import React, { useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import { useAuth } from '@/context/AuthContext';
import { useReducedMotion } from 'framer-motion';
import {
  CreditCardIcon,
  ArrowPathRoundedSquareIcon,
  ShieldCheckIcon,
  SparklesIcon,
  MapPinIcon,
  ArrowLeftIcon,
  ClipboardDocumentCheckIcon,
  ChatBubbleBottomCenterTextIcon,
  CheckBadgeIcon,
} from '@heroicons/react/24/outline';
import { motion } from "framer-motion";
import ModernCheckoutHeader from '@/components/jsxFiles/ModernCheckoutHeader';

// --- Helpers ---
const fetcher = (...args) => fetch(...args).then((res) => res.json());

const LoadingSpinner = () => (
  <div className="flex justify-center items-center h-screen bg-slate-50" role="status" aria-label="در حال بارگذاری">
    <div className="relative">
      <div className="absolute inset-0 bg-blue-500/20 blur-2xl rounded-full" aria-hidden="true" />
      <ArrowPathRoundedSquareIcon className="relative w-12 h-12 animate-spin text-blue-600" aria-hidden="true" />
    </div>
  </div>
);

// --- کارت روش پرداخت قابل کلیک ---
const PaymentMethodInfo = ({ title, description, icon: Icon, badge, accent = "blue", onClick }) => {
  const accents = {
    blue: {
      iconBg: "bg-gradient-to-br from-blue-500 to-sky-600",
      iconShadow: "shadow-blue-500/20",
      glow: "bg-blue-400/30",
      badge: "bg-blue-50 text-blue-700 ring-1 ring-blue-100",
      dot: "bg-blue-500",
    },
    sky: {
      iconBg: "bg-gradient-to-br from-sky-500 to-blue-600",
      iconShadow: "shadow-sky-500/25",
      glow: "bg-sky-400/30",
      badge: "bg-sky-50 text-sky-700 ring-1 ring-sky-100",
      dot: "bg-sky-500",
    },
  };

  const c = accents[accent] || accents.blue;

  return (
    <button
      type="button"
      onClick={onClick}
      className="
        relative w-full text-right overflow-hidden p-5 rounded-[28px]
        bg-white/80 backdrop-blur-xl border border-white
        shadow-[0_10px_40px_-15px_rgba(2,6,23,0.15)]
        ring-1 ring-slate-100
        cursor-pointer active:scale-[0.99] transition-transform duration-150
        focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2
      "
    >
      <div className="flex items-center gap-4 relative z-10">
        <div className={`
          relative w-14 h-14 rounded-2xl flex items-center justify-center
          text-white shadow-lg ${c.iconShadow} shrink-0 ${c.iconBg}
        `}>
          <Icon className="w-7 h-7" aria-hidden="true" />
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <h3 className="text-[15px] font-extrabold text-slate-900">{title}</h3>

            {badge && (
              <span className={`text-[11px] font-bold px-2.5 py-0.5 rounded-full ${c.badge}`}>
                {badge}
              </span>
            )}
          </div>

          <p className="text-[13px] text-slate-500 mt-1 font-medium leading-6 line-clamp-2">
            {description}
          </p>
        </div>

        <div className="flex items-center justify-center shrink-0" aria-hidden="true">
          <span className={`w-3 h-3 rounded-full ring-4 ring-slate-100 ${c.dot}`} />
        </div>
      </div>

      <div className={`absolute -top-10 -left-10 w-40 h-40 ${c.glow} rounded-full blur-3xl opacity-60`} aria-hidden="true" />
    </button>
  );
};

// --- تایم‌لاین مسیر اعلام قیمت ---
const PriceFlowTimeline = () => {
  const reduceMotion = useReducedMotion();

  const steps = [
    {
      icon: ClipboardDocumentCheckIcon,
      title: "ثبت سفارش بدون پرداخت",
      desc: "سفارش شما رزرو می‌شود؛ در این مرحله هیچ مبلغی پرداخت نمی‌کنید.",
    },
    {
      icon: ChatBubbleBottomCenterTextIcon,
      title: "اعلام قیمت قطعی",
      desc: "کارشناسان ما قیمت نهایی و به‌روز کالا را برای شما ارسال می‌کنند.",
    },
    {
      icon: CheckBadgeIcon,
      title: "تأیید شما یا لغو رایگان",
      desc: "اگر قیمت را تأیید کنید خرید نهایی می‌شود؛ در غیر این صورت سفارش بدون هیچ هزینه‌ای لغو می‌شود.",
    },
  ];

  return (
    <motion.div
      initial={reduceMotion ? false : { opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: 0.15 }}
      className="relative bg-white/80 backdrop-blur-xl p-5 rounded-[28px] ring-1 ring-slate-100 border border-white shadow-[0_10px_40px_-18px_rgba(2,6,23,0.18)]"
    >
      <div className="flex items-center gap-2 mb-4">
        <SparklesIcon className="w-5 h-5 text-blue-600 shrink-0" aria-hidden="true" />
        <h3 className="text-sm font-extrabold text-slate-900">مسیر خرید این کالا چگونه است؟</h3>
      </div>

      <ol className="relative space-y-5">
        <span className="absolute right-[19px] top-2 bottom-2 w-px bg-gradient-to-b from-blue-200 via-sky-200 to-blue-100" aria-hidden="true" />

        {steps.map((s, i) => (
          <motion.li
            key={i}
            initial={reduceMotion ? false : { opacity: 0, x: 10 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.2 + i * 0.08 }}
            className="relative flex items-start gap-4"
          >
            <div className="relative z-10 w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-sky-600 text-white flex items-center justify-center shadow-lg shadow-blue-500/25 shrink-0">
              <s.icon className="w-5 h-5" aria-hidden="true" />
            </div>

            <div className="flex-1 min-w-0 pt-0.5">
              <div className="flex items-center gap-2 flex-wrap">
                <span className="text-[11px] font-black text-blue-600">مرحله {i + 1}</span>
                <h4 className="text-[13.5px] font-extrabold text-slate-900">{s.title}</h4>
              </div>

              <p className="text-[12.5px] text-slate-500 leading-6 font-medium mt-1">
                {s.desc}
              </p>
            </div>
          </motion.li>
        ))}
      </ol>

      <div className="mt-4 flex items-center gap-2 bg-blue-50/70 rounded-2xl px-4 py-2.5 ring-1 ring-blue-100/70">
        <ShieldCheckIcon className="w-4 h-4 text-blue-600 shrink-0" aria-hidden="true" />

        <p className="text-[12px] text-blue-800 font-bold leading-5">
          اختیار نهایی با شماست؛ تا قیمت را تأیید نکنید هیچ مبلغی از شما دریافت نمی‌شود.
        </p>
      </div>
    </motion.div>
  );
};

export default function PaymentPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { user, loading: authLoading } = useAuth();
  const reduceMotion = useReducedMotion();

  const productId = searchParams.get('id');

  const { data: productData, isLoading: productLoading } = useSWR(
    productId ? `/api/productorder/${productId}` : null,
    fetcher
  );

  const product = productData?.[0];

  const shouldFetchProfile = user && !user.address;

  const { data: userProfile } = useSWR(
    shouldFetchProfile ? '/api/auth/me' : null,
    fetcher,
    { shouldRetryOnError: false }
  );

  const targetUser = userProfile?.user || userProfile || user;

  useEffect(() => {
    document.title = "صفحه انتخاب روش پرداخت";
  }, []);

  useEffect(() => {
    if (authLoading || productLoading) return;

    if (!user) {
      const currentPath = `/checkout/payment?${searchParams.toString()}`;
      router.push(`/login?redirect=${encodeURIComponent(currentPath)}`);
    } else if (!product) {
      router.push('/');
    }
  }, [user, authLoading, product, productLoading, router, searchParams]);

  if (authLoading || productLoading || !user || !product) return <LoadingSpinner />;

  const canPayOnline = product.isOnlinePayment === true;
  const paramsString = searchParams.toString();

  // اگر قبلاً پرداخت اینترنتی فعال بوده، فعلاً موقتاً به کارت‌به‌کارت می‌رود.
  // اگر پرداخت اینترنتی false باشد، مثل قبل به inquiry می‌رود.
  const ctaLabel = canPayOnline ? "ادامه و پرداخت کارت‌به‌کارت" : "ادامه و ثبت سفارش";

  const handleContinue = () => {
    if (canPayOnline) {
      router.push(`/checkout/payment/card-to-card?${paramsString}`);
    } else {
      router.push(`/checkout/payment/inquiry?${paramsString}`);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-50 via-blue-50/30 to-slate-50 overflow-x-hidden" dir="rtl">
      <ModernCheckoutHeader
        currentStep={3}
        cartUrl={`/getOrder/${productId}/${searchParams.get('color')}/${searchParams.get('size')}`}
      />

      <div className="max-w-lg mx-auto px-4 sm:px-5 pb-10 pt-2">
        <main className="space-y-6">

          {/* --- سرتیتر صفحه --- */}
          <motion.div
            initial={reduceMotion ? false : { opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            className="pt-2"
          >
            <h1 className="text-xl font-black text-slate-900">تکمیل پرداخت</h1>

            <p className="text-sm text-slate-500 mt-1 font-medium">
              یک گام تا ثبت نهایی سفارش باقی مانده است.
            </p>
          </motion.div>

          {/* --- بخش آدرس --- */}
          <motion.div
            initial={reduceMotion ? false : { opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.05 }}
            className="relative bg-white/80 backdrop-blur-xl p-5 rounded-[28px] ring-1 ring-slate-100 border border-white shadow-[0_10px_40px_-18px_rgba(2,6,23,0.18)]"
          >
            <div className="flex items-start gap-4">
              <div className="p-3 bg-gradient-to-br from-blue-50 to-sky-50 rounded-2xl text-blue-600 ring-1 ring-blue-100/60 shrink-0">
                <MapPinIcon className="w-6 h-6" aria-hidden="true" />
              </div>

              <div className="flex-1 min-w-0">
                <h3 className="font-extrabold text-slate-900 text-sm mb-1">
                  آدرس تحویل سفارش
                </h3>

                <p className="text-sm text-slate-600 leading-7 font-medium line-clamp-2 break-words">
                  {targetUser?.address || "آدرس ثبت نشده است"}
                </p>
              </div>
            </div>
          </motion.div>

          {/* --- روش پرداخت --- */}
          <motion.section
            initial={reduceMotion ? false : { opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="space-y-4"
            aria-labelledby="payment-methods-heading"
          >
            <h2 id="payment-methods-heading" className="text-sm font-extrabold text-slate-700 px-1">
              روش پرداخت شما
            </h2>

            {canPayOnline && (
              <PaymentMethodInfo
                title="پرداخت کارت‌به‌کارت"
                description="ثبت سفارش و دریافت شماره کارت برای واریز مبلغ سفارش"
                icon={CreditCardIcon}
                badge="روش فعال"
                accent="sky"
                onClick={handleContinue}
              />
            )}

            {!canPayOnline && (
              <>
                <PaymentMethodInfo
                  title="ثبت سفارش"
                  description="ادامه فرآیند ثبت سفارش و اعلام قیمت نهایی"
                  icon={SparklesIcon}
                  badge="پیشنهادی"
                  accent="sky"
                  onClick={handleContinue}
                />

                {/* اگر خواستی تایم‌لاین دوباره نمایش داده شود، این خط را از کامنت خارج کن */}
                {/* <PriceFlowTimeline /> */}
              </>
            )}
          </motion.section>
        </main>
      </div>

      {/* --- نشان ضمانت ترب --- */}
      <div className="flex flex-row flex-wrap mx-auto justify-center items-center gap-3 px-4 pb-6">
        <div>
          <a
            target="_blank"
            href="https://torob.com/shop/143402"
            rel="nofollow"
            aria-label="نشان ضمانت ترب"
          >
            <img
              alt=""
              src="https://api.torob.com/third-party/guarantee/v1/hologram/?instance_id=143402"
            />
          </a>
        </div>
      </div>

      {/* --- نوار اقدام اصلی پایین صفحه --- */}
      <motion.div
        initial={reduceMotion ? false : { opacity: 0, y: 24 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.18, type: "spring", stiffness: 260, damping: 26 }}
        className="fixed bottom-0 inset-x-0 z-40"
      >
        <div className="max-w-lg mx-auto px-4 sm:px-5">
          <div className="
            bg-white/85 backdrop-blur-xl border-t border-white
            ring-1 ring-slate-100
            shadow-[0_-10px_40px_-12px_rgba(2,6,23,0.20)]
            rounded-t-[28px]
            px-4 pt-3.5
            pb-[max(1rem,env(safe-area-inset-bottom))]
          ">
            <div className="flex items-center justify-center gap-1.5 text-slate-500 text-[11.5px] font-semibold mb-3">
              <ShieldCheckIcon className="w-3.5 h-3.5 text-blue-500 shrink-0" aria-hidden="true" />

              {canPayOnline ? "ثبت امن سفارش و پرداخت کارت‌به‌کارت" : "ثبت سفارش بدون پرداخت آنلاین"}
            </div>

            <motion.button
              type="button"
              whileTap={{ scale: 0.98 }}
              onClick={handleContinue}
              className="
                relative w-full h-14 rounded-2xl overflow-hidden group
                bg-gradient-to-l from-blue-600 to-sky-500
                text-white font-extrabold text-[15px]
                flex items-center justify-center gap-2
                shadow-lg shadow-blue-500/30
                transition-shadow duration-300 active:shadow-md
                focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-blue-500
              "
            >
              <span className="relative z-10">{ctaLabel}</span>

              <ArrowLeftIcon
                className="relative z-10 w-5 h-5 transition-transform duration-300 group-hover:-translate-x-1"
                aria-hidden="true"
              />

              <span
                className="absolute inset-0 bg-white/10 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
                aria-hidden="true"
              />
            </motion.button>
          </div>
        </div>
      </motion.div>
    </div>
  );
}
