"use client";

import React, { useEffect, useMemo, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import useSWR from "swr";
import { useAuth } from "@/context/AuthContext";
import { motion } from "framer-motion";

import {
  CheckCircleIcon,
  ClipboardDocumentIcon,
  PhoneIcon,
  ArrowRightIcon,
  ArrowPathRoundedSquareIcon,
  ExclamationTriangleIcon,
  ShieldCheckIcon,
  ClockIcon,
  ReceiptRefundIcon,
  ChatBubbleLeftRightIcon,
  BanknotesIcon,
  DocumentCheckIcon,
  XMarkIcon,
  ArrowTopRightOnSquareIcon,
} from "@heroicons/react/24/outline";

import { TbBrandWhatsapp } from "react-icons/tb";
import { CardToCardSMS } from "@/lib/ServerActions/CardToCardSMS";

const CARD_NUMBER = "6037991932458999";
const ACCOUNT_NUMBER = "0113145236003";
const SHEBA_NUMBER = "IR330170000000113145236003";
const CARD_OWNER = "آریا عبدی پور";
const BANK_NAME = "بانک ملی ایران";
const SUPPORT_PHONE = "09186704541";
const WHATSAPP_PHONE = "989186704541";

const apiFetch = async (url, options = {}) => {
  return fetch(url, {
    headers: {
      "Content-Type": "application/json",
    },
    credentials: "include",
    ...options,
  });
};

const fetcher = async (...args) => {
  const res = await fetch(...args);

  if (!res.ok) {
    throw new Error("خطا در دریافت اطلاعات محصول");
  }

  return res.json();
};

function commafy(num) {
  if (!num) return "0";
  return new Intl.NumberFormat("en-US").format(num);
}

const LoadingSpinner = () => (
  <div
    className="h-screen flex flex-col items-center justify-center gap-4 bg-slate-50"
    dir="rtl"
    role="status"
    aria-label="در حال ثبت سفارش"
  >
    <ArrowPathRoundedSquareIcon
      className="w-11 h-11 animate-spin text-teal-600"
      aria-hidden="true"
    />

    <span className="text-slate-500 text-sm">
      در حال دریافت اطلاعات و ثبت سفارش...
    </span>
  </div>
);

export default function CardToCardPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { user, loading: authLoading } = useAuth();

  const [orderCode, setOrderCode] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [isLicenseOpen, setIsLicenseOpen] = useState(false);

  const submitCalled = useRef(false);

  const productId = searchParams.get("id");
  const selectedColor = searchParams.get("color") || "freeColor";
  const selectedSize = searchParams.get("size") || "freeSize";
  const shippingMethod = searchParams.get("shipping");
  const costumerIsWarranty = searchParams.get("warranty");
  const costumerWarrantyAmount = searchParams.get("warranty_amount");

  const {
    data: productData,
    error: productError,
    isLoading: productLoading,
  } = useSWR(productId ? `/api/productorder/${productId}` : null, fetcher, {
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
    shouldRetryOnError: false,
  });

  const product = productData?.[0];

  const shippingCost = shippingMethod === "post" ? 50000 : 0;
  const finalPrice = Number(product?.price || 0) + shippingCost;

  const whatsappHref = useMemo(() => {
    const message = [
      "سلام، پرداخت کارت‌به‌کارت سفارش را انجام دادم.",
      orderCode ? `کد سفارش: ${orderCode}` : "",
      product?.title ? `محصول: ${product.title}` : "",
      finalPrice ? `مبلغ سفارش: ${commafy(finalPrice)} تومان` : "",
      "لطفاً پرداخت را بررسی و تایید کنید.",
    ]
      .filter(Boolean)
      .join("\n");

    return `https://api.whatsapp.com/send/?phone=${WHATSAPP_PHONE}&text=${encodeURIComponent(
      message
    )}`;
  }, [orderCode, product?.title, finalPrice]);

  useEffect(() => {
    document.title = "پرداخت کارت به کارت";
  }, []);
  
  useEffect(() => {
    if (!isLicenseOpen) return;

    const handleKeyDown = (event) => {
      if (event.key === "Escape") {
        setIsLicenseOpen(false);
      }
    };

    const previousOverflow = document.body.style.overflow;

    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", handleKeyDown);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [isLicenseOpen]);

  useEffect(() => {
    if (authLoading || productLoading) return;

    if (!user) {
      const currentPath = `/checkout/payment/card-to-card?${searchParams.toString()}`;
      router.push(`/login?redirect=${encodeURIComponent(currentPath)}`);
      return;
    }

    if ((!productId || productError || !product) && !orderCode) {
      router.push("/");
      return;
    }

    if (!shippingMethod && !orderCode) {
      router.back();
    }
  }, [
    user,
    authLoading,
    productId,
    product,
    productError,
    productLoading,
    shippingMethod,
    orderCode,
    router,
    searchParams,
  ]);

  useEffect(() => {
    if (
      authLoading ||
      productLoading ||
      !user ||
      !product ||
      !shippingMethod ||
      orderCode ||
      isSubmitting ||
      submitCalled.current
    ) {
      return;
    }

    const storageKey = [
      "card_to_card_saved",
      product._id,
      selectedColor,
      selectedSize,
      shippingMethod,
      costumerIsWarranty || "false",
      costumerWarrantyAmount || "0",
    ].join("_");

    let savedOrderCode = null;

    try {
      savedOrderCode = sessionStorage.getItem(storageKey);
    } catch (storageError) {
      console.warn("دسترسی به حافظه مرورگر ممکن نیست؛ ثبت سفارش ادامه پیدا می‌کند.");
    }

    if (savedOrderCode) {
      setOrderCode(savedOrderCode);
      submitCalled.current = true;
      return;
    }

    const submitOrder = async () => {
      submitCalled.current = true;
      setIsSubmitting(true);
      setSubmitError("");

      try {
        const res = await apiFetch("/api/orders", {
          method: "POST",
          body: JSON.stringify({
            productId: product._id,
            selectedColor: decodeURIComponent(selectedColor),
            selectedSize: decodeURIComponent(selectedSize),
            shippingMethod,
            paymentMethod: "کارت به کارت",
            customerExactAddress: user.address,
            costumerPostCode: user.userPostalCode,
            exportCostumerIsWarranty: costumerIsWarranty,
            exportCostumerWarrantyAmount: costumerWarrantyAmount,
          }),
        });

        const data = await res.json();

        if (!res.ok) {
          throw new Error(
            data?.error ||
              data?.message ||
              "ثبت سفارش انجام نشد. لطفاً دوباره تلاش کنید."
          );
        }

        if (!data?.orderCode) {
          throw new Error("کد سفارش از سرور دریافت نشد.");
        }

        setOrderCode(data.orderCode);

        try {
          sessionStorage.setItem(storageKey, data.orderCode);
        } catch (storageError) {}

        try {
          await CardToCardSMS({
            customerName:
              user.name ||
              `${user.firstName || ""} ${user.lastName || ""}`.trim() ||
              "مشتری",
            customerPhone: user.phoneNumber || user.phone || user.mobile,
            orderCode: data.orderCode,
            orderId: data.orderId,
            productTitle: product.title,
            totalPrice: Number(product.price || 0) + (shippingMethod === "post" ? 50000 : 0),
            shippingCost: shippingMethod === "post" ? 50000 : 0,
            address: user.address,
            paymentMethod: "کارت به کارت",
          });
        } catch (smsError) {
          console.error("سفارش ثبت شد، اما ارسال پیامک با خطا مواجه شد:", smsError);
        }
      } catch (error) {
        console.error("خطا در ثبت سفارش کارت به کارت:", error);

        setSubmitError(
          error?.message || "در ثبت سفارش مشکلی پیش آمد. لطفاً دوباره تلاش کنید."
        );

        submitCalled.current = false;
      } finally {
        setIsSubmitting(false);
      }
    };

    submitOrder();
  }, [
    authLoading,
    productLoading,
    user,
    product,
    shippingMethod,
    orderCode,
    isSubmitting,
    selectedColor,
    selectedSize,
    costumerIsWarranty,
    costumerWarrantyAmount,
  ]);

  const retrySubmit = () => {
    submitCalled.current = false;
    setSubmitError("");
    setIsSubmitting(false);
  };

  const copyToClipboard = async (text, successMessage = "کپی شد.") => {
    try {
      await navigator.clipboard.writeText(text);
      alert(successMessage);
    } catch (error) {
      console.error("خطا در کپی:", error);
      alert("کپی خودکار انجام نشد. لطفاً مقدار را دستی کپی کنید.");
    }
  };

  if (authLoading || productLoading || isSubmitting || (!orderCode && !submitError)) {
    return <LoadingSpinner />;
  }

  if (submitError) {
    return (
      <div
        className="min-h-screen bg-slate-50 p-4 flex items-center justify-center"
        dir="rtl"
      >
        <div className="w-full max-w-md bg-white border border-rose-100 shadow-lg rounded-3xl p-6 text-center">
          <div className="w-14 h-14 mx-auto flex items-center justify-center rounded-full bg-rose-50 text-rose-600">
            <ExclamationTriangleIcon className="w-7 h-7" aria-hidden="true" />
          </div>

          <h1 className="mt-4 text-base font-bold text-slate-900">
            ثبت سفارش انجام نشد
          </h1>

          <p className="mt-2 text-sm leading-6 text-slate-500">{submitError}</p>

          <div className="mt-6 grid grid-cols-2 gap-3">
            <button
              type="button"
              onClick={() => router.back()}
              className="h-12 rounded-xl border border-slate-200 text-sm font-bold text-slate-700 hover:bg-slate-50 transition-colors"
            >
              بازگشت
            </button>

            <button
              type="button"
              onClick={retrySubmit}
              className="h-12 rounded-xl bg-teal-600 text-sm font-bold text-white hover:bg-teal-700 transition-colors"
            >
              تلاش مجدد
            </button>
          </div>
        </div>
      </div>
    );
  }
  const openLicense = () => setIsLicenseOpen(true);
  const closeLicense = () => setIsLicenseOpen(false);

  return (
    <main
      className="min-h-screen md:bg-[radial-gradient(circle_at_top,#f0fdfa_0,#f8fafc_45%,#f1f5f9_100%)] md:p-4 flex items-center justify-center font-normal"
      dir="rtl"
    >
      <motion.section
        initial={{ y: 18, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.28 }}
        className="w-full max-w-lg overflow-hidden rounded-3xl bg-white shadow-xl shadow-slate-200/70 border border-white"
      >
        <div className="px-5 py-4 border-b border-slate-100 flex items-center justify-between bg-white/95 backdrop-blur">
          <button
            type="button"
            onClick={() => router.back()}
            className="flex items-center gap-1.5 text-sm font-bold text-slate-500 hover:text-slate-900 bg-slate-50 hover:bg-slate-100 px-3 py-2 rounded-xl transition-all"
          >
            <ArrowRightIcon className="w-4 h-4" aria-hidden="true" />
            بازگشت
          </button>

          <div className="text-left">
            <h1 className="text-base font-black text-slate-900">تکمیل پرداخت</h1>
            <p className="text-[11px] text-slate-400 mt-0.5">
              سفارش ثبت و قابل پیگیری است
            </p>
          </div>
        </div>

        <div className="p-5 space-y-5">
          <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
            <div className="flex items-start gap-3">
              <div className="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center shrink-0">
                <CheckCircleIcon className="w-6 h-6 text-emerald-700" aria-hidden="true" />
              </div>

              <div className="min-w-0">
                <p className="text-sm font-black text-emerald-900">
                  سفارش شما با موفقیت ثبت شد
                </p>

                <div className="mt-2 flex items-center gap-2">
                  <span className="text-xs text-emerald-800">کد سفارش:</span>
                  <button
                    type="button"
                    onClick={() => copyToClipboard(orderCode, "کد سفارش کپی شد.")}
                    className="inline-flex items-center gap-1 rounded-lg bg-white/80 px-2.5 py-1 text-xs font-black text-emerald-900 border border-emerald-100"
                  >
                    <ClipboardDocumentIcon className="w-4 h-4" aria-hidden="true" />
                    {orderCode}
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div className="rounded-2xl border border-teal-100 bg-teal-50 p-4">
            <div className="flex gap-3">
              <ClockIcon className="w-6 h-6 text-teal-700 shrink-0" aria-hidden="true" />

              <div>
                <p className="text-sm font-black text-teal-900">
                  پرداخت آنلاین موقتاً در حال فعال‌سازی مجدد است
                </p>
                <p className="mt-1.5 text-xs leading-6 text-teal-800">
                  تا زمان بازگشت درگاه، سفارش‌ها بدون وقفه ثبت می‌شوند و پرداخت از طریق کارت‌به‌کارت بررسی و تأیید می‌شود.
                </p>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-3 gap-2">
            <div className="rounded-2xl bg-slate-50 border border-slate-100 p-3 text-center">
              <ShieldCheckIcon className="w-6 h-6 mx-auto text-teal-700" aria-hidden="true" />
              <p className="mt-2 text-[11px] font-bold text-slate-700 leading-5">
                پرداخت قابل پیگیری
              </p>
            </div>

            <div className="rounded-2xl bg-slate-50 border border-slate-100 p-3 text-center">
              <ReceiptRefundIcon className="w-6 h-6 mx-auto text-teal-700" aria-hidden="true" />
              <p className="mt-2 text-[11px] font-bold text-slate-700 leading-5">
                عودت وجه در مغایرت
              </p>
            </div>

            <div className="rounded-2xl bg-slate-50 border border-slate-100 p-3 text-center">
              <DocumentCheckIcon className="w-6 h-6 mx-auto text-teal-700" aria-hidden="true" />
              <p className="mt-2 text-[11px] font-bold text-slate-700 leading-5">
                ثبت با کد سفارش
              </p>
            </div>
          </div>

          <div className="rounded-3xl bg-slate-900 text-white overflow-hidden">
            <div className="h-1.5 bg-gradient-to-l from-teal-400 via-emerald-400 to-cyan-400" />

            <div className="p-5 space-y-4">
              <div className="flex items-center justify-between gap-3">
                <div>
                  <p className="text-xs text-slate-400">مبلغ قابل پرداخت</p>
                  <p className="mt-1 text-xl font-black">
                    {commafy(finalPrice)}
                    <span className="mr-1 text-xs font-bold text-slate-300">تومان</span>
                  </p>
                </div>

                <button
                  type="button"
                  onClick={() => copyToClipboard(String(finalPrice), "مبلغ سفارش کپی شد.")}
                  className="rounded-xl bg-white/10 hover:bg-white/15 p-2.5 transition"
                  aria-label="کپی مبلغ"
                  title="کپی مبلغ"
                >
                  <ClipboardDocumentIcon className="w-5 h-5" aria-hidden="true" />
                </button>
              </div>

              <div className="border-t border-white/10 pt-4 space-y-3">
                <p className="text-xs text-slate-400">مشخصات پرداخت</p>

                <div className="rounded-2xl bg-white px-3 py-3 text-slate-900">
                  <div className="flex items-center justify-between gap-3">
                    <button
                      type="button"
                      onClick={() => copyToClipboard(CARD_NUMBER, "شماره کارت کپی شد.")}
                      className="rounded-xl bg-slate-100 hover:bg-slate-200 p-2 transition shrink-0"
                      aria-label="کپی شماره کارت"
                      title="کپی شماره کارت"
                    >
                      <ClipboardDocumentIcon className="w-5 h-5 text-slate-700" aria-hidden="true" />
                    </button>

                    <div className="text-left min-w-0">
                      <p className="text-[11px] font-bold text-slate-500">شماره کارت</p>
                      <span
                        dir="ltr"
                        className="block mt-1 font-mono text-[1rem] font-black tracking-wider select-all whitespace-nowrap"
                      >
                        {CARD_NUMBER}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="rounded-2xl bg-white/8 border border-white/10 px-3 py-3">
                  <div className="flex items-center justify-between gap-3">
                    <button
                      type="button"
                      onClick={() => copyToClipboard(ACCOUNT_NUMBER, "شماره حساب کپی شد.")}
                      className="rounded-xl bg-white/10 hover:bg-white/15 p-2 transition shrink-0"
                      aria-label="کپی شماره حساب"
                      title="کپی شماره حساب"
                    >
                      <ClipboardDocumentIcon className="w-5 h-5" aria-hidden="true" />
                    </button>

                    <div className="text-left min-w-0">
                      <p className="text-[11px] text-slate-400">شماره حساب</p>
                      <span
                        dir="ltr"
                        className="block mt-1 font-mono text-sm font-black text-white select-all whitespace-nowrap"
                      >
                        {ACCOUNT_NUMBER}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="rounded-2xl bg-white/8 border border-white/10 px-3 py-3">
                  <div className="flex items-center justify-between gap-3">
                    <button
                      type="button"
                      onClick={() => copyToClipboard(SHEBA_NUMBER, "شماره شبا کپی شد.")}
                      className="rounded-xl bg-white/10 hover:bg-white/15 p-2 transition shrink-0"
                      aria-label="کپی شماره شبا"
                      title="کپی شماره شبا"
                    >
                      <ClipboardDocumentIcon className="w-5 h-5" aria-hidden="true" />
                    </button>

                    <div className="text-left min-w-0">
                      <p className="text-[11px] text-slate-400">شماره شبا</p>
                      <span
                        dir="ltr"
                        className="block mt-1 font-mono text-[12px] sm:text-sm font-black text-white select-all break-all"
                      >
                        {SHEBA_NUMBER}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3 text-xs">
                <div className="rounded-2xl bg-white/8 border border-white/10 p-3">
                  <p className="text-slate-400">به نام</p>
                  <p className="mt-1 font-black text-white">{CARD_OWNER}</p>
                </div>

                <div className="rounded-2xl bg-white/8 border border-white/10 p-3">
                  <p className="text-slate-400">بانک</p>
                  <p className="mt-1 font-black text-white">{BANK_NAME}</p>
                </div>
              </div>

              <div className="rounded-2xl border border-amber-300/30 bg-amber-300/10 p-3">
                <p className="text-xs leading-6 text-amber-100">
                  تمام تراکنش‌های پرداخت کارت‌به‌کارت رصد و با کد سفارش، مبلغ و رسید ارسالی تطبیق داده می‌شوند.
                </p>
              </div>
            </div>
          </div>

          {costumerIsWarranty === "true" && (
            <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
              <p className="text-xs leading-6 text-emerald-800">
                هزینه گارانتی برابر با{" "}
                <strong>{commafy(costumerWarrantyAmount)} هزار تومان</strong>{" "}
                است و توسط شرکت گارانتی‌کننده به‌صورت جداگانه دریافت می‌شود.
              </p>
            </div>
          )}

          <div className="rounded-2xl bg-slate-50 border border-slate-100 p-4">
            <p className="text-sm font-black text-slate-900">
              بعد از واریز چه کاری انجام دهید؟
            </p>

            <div className="mt-3 space-y-2 text-xs leading-6 text-slate-600">
              <p>۱. مبلغ سفارش را دقیقاً مطابق عدد بالا واریز کنید.</p>
              <p>۲. رسید، شماره پیگیری یا تصویر فیش را در واتساپ ارسال کنید.</p>
              <p>۳. پس از بررسی، وضعیت سفارش در پنل شما به‌روزرسانی می‌شود.</p>
            </div>
          </div>

          <div className="rounded-2xl border border-teal-100 bg-teal-50 p-4">
            <div className="flex gap-3">
              <BanknotesIcon className="w-6 h-6 text-teal-700 shrink-0" aria-hidden="true" />
              <p className="text-xs leading-6 text-teal-800">
                پرداخت به نام صاحب حساب اعلام‌شده انجام می‌شود و با کد سفارش شما قابل بررسی است. در صورت عدم موجودی، مغایرت یا انصراف قبل از ارسال، مبلغ پرداختی طبق هماهنگی پشتیبانی عودت داده می‌شود.
              </p>
            </div>
          </div>

          <div className="rounded-2xl border border-slate-100 bg-white p-4">
            <div className="flex items-center gap-2">
              <ShieldCheckIcon className="w-5 h-5 text-teal-700" aria-hidden="true" />
              <p className="text-sm font-black text-slate-900">مجوزها و نمادهای اعتماد</p>
            </div>

            <p className="mt-1.5 text-[11px] leading-5 text-slate-500">
              فروشگاه دارای نماد نشان ضمانت ترب و مجوز رسمی است. برای اطمینان می‌توانید روی نمادها کلیک کنید.
            </p>

            <div className="mt-3 grid grid-cols-2 gap-3">
              <button
                type="button"
                onClick={() => setIsLicenseOpen(true)}
                className="flex min-h-32 w-full cursor-zoom-in items-center justify-center overflow-hidden rounded-xl border border-slate-100 bg-slate-50 p-2 transition-colors hover:border-teal-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-teal-500 focus-visible:ring-offset-2"
                aria-label="بزرگ‌نمایی تصویر مجوز کسب‌وکار"
                aria-haspopup="dialog"
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src="/mojavez.JPG"
                  alt="مجوز کسب‌وکار"
                  className="max-h-32 w-auto max-w-full object-contain"
                />
              </button>


              <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>
          </div>

          <div>
            <p className="text-sm text-slate-800 mb-3 text-center font-black">
              رسید پرداخت را از یکی از راه‌های زیر ارسال کنید
            </p>

            <div className="space-y-3">
              <a
                href={whatsappHref}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center justify-between p-3.5 bg-emerald-600 !text-white rounded-2xl hover:bg-emerald-700 active:scale-[0.99] transition-all shadow-lg shadow-emerald-100"
              >
                <div className="flex items-center gap-3">
                  <TbBrandWhatsapp className="text-2xl" aria-hidden="true" />
                  <span className="font-black text-sm">ارسال رسید در واتساپ</span>
                </div>

                <ArrowRightIcon className="w-4 h-4 rotate-180" aria-hidden="true" />
              </a>

              <a
                href={`tel:${SUPPORT_PHONE}`}
                className="flex items-center justify-between p-3.5 bg-white border border-slate-200 rounded-2xl hover:border-teal-400 hover:shadow-sm transition-all group"
              >
                <div className="flex items-center gap-3">
                  <PhoneIcon className="w-6 h-6 text-teal-600" aria-hidden="true" />
                  <span className="font-black text-sm text-slate-700">تماس با پشتیبانی</span>
                </div>

                <span dir="ltr" className="text-xs font-bold text-slate-400">
                  {SUPPORT_PHONE}
                </span>
              </a>

              <a
                href={whatsappHref}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center justify-between p-3.5 bg-white border border-slate-200 rounded-2xl hover:border-slate-400 hover:shadow-sm transition-all"
              >
                <div className="flex items-center gap-3">
                  <ChatBubbleLeftRightIcon className="w-6 h-6 text-slate-700" aria-hidden="true" />
                  <span className="font-black text-sm text-slate-700">سؤال درباره پرداخت</span>
                </div>

                <ArrowRightIcon className="w-4 h-4 text-slate-300 rotate-180" aria-hidden="true" />
              </a>
            </div>
          </div>

          <div className="pt-2">
            <button
              type="button"
              onClick={() => router.push("/dashboard/orders")}
              className="w-full h-12 bg-slate-900 text-white rounded-2xl font-black hover:bg-slate-800 active:scale-[0.98] transition-all shadow-lg shadow-slate-200"
            >
              مشاهده و پیگیری سفارش
            </button>
          </div>
        </div>
      </motion.section>
      {isLicenseOpen && (
        <div
          role="dialog"
          aria-modal="true"
          aria-labelledby="license-dialog-title"
          className="fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/85 p-3 backdrop-blur-sm sm:p-4"
          onMouseDown={(event) => {
            if (event.target === event.currentTarget) {
              closeLicense();
            }
          }}
        >
          <div className="relative flex max-h-[94dvh] w-full max-w-4xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
            <div className="flex shrink-0 items-center justify-between border-b border-slate-100 px-4 py-3">
              <h2
                id="license-dialog-title"
                className="text-sm font-black text-slate-900"
              >
                مجوز کسب‌وکار
              </h2>

              <button
                type="button"
                onClick={closeLicense}
                className="flex size-10 shrink-0 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-teal-500"
                aria-label="بستن تصویر مجوز"
                title="بستن"
                autoFocus
              >
                <XMarkIcon className="size-6" aria-hidden="true" />
              </button>
            </div>

            <div className="min-h-0 flex-1 overflow-auto bg-slate-100 p-3 sm:p-5">
              <div className="flex min-h-full min-w-full items-center justify-center">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src="/mojavez.JPG"
                  alt="نمای بزرگ مجوز کسب‌وکار"
                  className="h-auto w-full max-w-5xl rounded-lg bg-white object-contain shadow-sm"
                  style={{
                    touchAction: "auto",
                  }}
                />
              </div>
            </div>

            <div className="flex shrink-0 items-center justify-between gap-3 border-t border-slate-100 px-4 py-3">
              <p className="text-xs leading-5 text-slate-500">
                برای مشاهده جزئیات، تصویر را با دو انگشت بزرگ‌نمایی کنید.
              </p>
            </div>
          </div>
        </div>
      )}

    </main>
  );
}
