"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import { BaseModal } from "@/components/modal";
import DynamicButton from "@/components/button";
import { useAppToast, useNumberFormatter } from "@/app/[lang]/providers";
import {
  usePurchaseNormalPaddleForGroupAuction,
  usePurchaseNormalPaddleForAuctionGroup,
  usePurchasePremiumPaddleForGroupAuction,
  useWalletBalances,
  useGroupAuctionLocalizedAuctionTerms,
  UserPaddle,
} from "@/lib/clientQueries";
import { payWithGateway } from "@/actions/payment";
import {
  buildReturnPathForGatewayRequest,
  persistGatewayMetaFromGatewayResponse,
} from "@/lib/payment-return";
import { useApplePayVisible } from "@/lib/platform";
import { toMoneyNumber } from "@/lib/moneyParse";
import TopUpModal from "@/components/sections/wallet/TopUpModal";
import PaymentGatewayModal from "@/components/payment/PaymentGatewayModal";
import { Wallet, CreditCard, Crown, CheckCircle2 } from "lucide-react";
import PaddleElectronicPaymentInfo from "@/components/paddles/PaddleElectronicPaymentInfo";

const SAR_ICON = "/Riyal.svg";

interface YearlyPaddleModalProps {
  open: boolean;
  onClose: () => void;
  groupAuctionId?: string | null;
  yearlyAuctionId: string;
  yearlyAuctionType: "group" | "single";
  prices: {
    normalPrice: number | string;
    premiumPrice: number | string;
    premiumUseTimes: number | string;
  };
  availablePaddles: UserPaddle[];
  onJoined?: () => void;
  normalOnly?: boolean;
  /** Localized HTML from group-auction show (`auction_terms`). Omit to fetch when the modal opens. */
  prefetchedAuctionTerms?: string | null | undefined;
  /**
   * When true, non-empty group `auction_terms` are shown alone first; purchase UI is step 2 (no inline terms).
   * Other pages keep a single step with terms embedded in the purchase modal.
   */
  twoStepAuctionTerms?: boolean;
}
export default function YearlyPaddleModal({
  open,
  onClose,
  groupAuctionId,
  yearlyAuctionId,
  yearlyAuctionType,
  prices,
  availablePaddles,
  onJoined,
  normalOnly = false,
  prefetchedAuctionTerms,
  twoStepAuctionTerms = false,
}: YearlyPaddleModalProps) {
  const t = useTranslations("YEARLY_PADDLE_MODAL");
  const toast = useAppToast();
  const { toLatinDigits } = useNumberFormatter();
  const queryClient = useQueryClient();
  const { data: walletBalances } = useWalletBalances();

  const gatewayOpeningRef = useRef<{ normal: boolean; premium: boolean }>({
    normal: false,
    premium: false,
  });
  const purchaseNormalPaddleGroup = usePurchaseNormalPaddleForGroupAuction(
    !normalOnly ? (yearlyAuctionId ?? undefined) : undefined,
  );
  const purchaseNormalPaddleAuctionGroup = usePurchaseNormalPaddleForAuctionGroup(
    normalOnly ? (yearlyAuctionId ?? undefined) : undefined,
  );
  const purchaseNormalPaddle = normalOnly
    ? purchaseNormalPaddleAuctionGroup
    : purchaseNormalPaddleGroup;
  const purchasePremiumPaddle = usePurchasePremiumPaddleForGroupAuction(
    groupAuctionId ?? undefined,
  );
  const walletBalance = toMoneyNumber(walletBalances?.available_balance, 0);
  const normalPrice = toMoneyNumber(prices.normalPrice, 0);
  const premiumPrice = toMoneyNumber(prices.premiumPrice, 0);
  const premiumUseTimes = toMoneyNumber(prices.premiumUseTimes, 0);
  const canAffordNormal = normalPrice <= 0 || walletBalance >= normalPrice;
  const canAffordPremium = premiumPrice <= 0 || walletBalance >= premiumPrice;
  const applePayVisible = useApplePayVisible();
  const [action, setAction] = useState<string | null>(null);
  const [paymentMethod, setPaymentMethod] = useState<
    "wallet" | "gateway" | "apple_pay"
  >("gateway");
  const [showTopUpModal, setShowTopUpModal] = useState(false);
  const [topUpPaddleChoice, setTopUpPaddleChoice] = useState<
    "normal" | "premium"
  >("normal");
  const [gatewayUrl, setGatewayUrl] = useState<string | null>(null);
  const locale = useLocale();
  const isAr = (locale || "ar").startsWith("ar");
  const { data: fetchedAuctionTerms } = useGroupAuctionLocalizedAuctionTerms(
    groupAuctionId,
    { modalOpen: open, prefetchedTerms: prefetchedAuctionTerms },
  );
  const auctionTermsHtml = useMemo(() => {
    const raw =
      prefetchedAuctionTerms !== undefined
        ? prefetchedAuctionTerms
        : (fetchedAuctionTerms ?? null);
    if (raw == null) return null;
    const s = String(raw).trim();
    return s ? String(raw) : null;
  }, [prefetchedAuctionTerms, fetchedAuctionTerms]);
  const requiresTermsGate = Boolean(
    twoStepAuctionTerms && groupAuctionId && auctionTermsHtml,
  );
  const [termsGateStep, setTermsGateStep] = useState<1 | 2>(1);
  const [termsAcceptChecked, setTermsAcceptChecked] = useState(false);

  useEffect(() => {
    if (!open) {
      setTermsGateStep(1);
      setTermsAcceptChecked(false);
      return;
    }
    const nextStep = requiresTermsGate ? 1 : 2;
    setTermsGateStep(nextStep);
    if (nextStep === 1) setTermsAcceptChecked(false);
  }, [open, requiresTermsGate]);

  const onTermsGateContinue = () => setTermsGateStep(2);
  const normalShortfall = Math.max(0, normalPrice - walletBalance);
  const premiumShortfall = Math.max(0, premiumPrice - walletBalance);
  const canBuyPremiumPackage = yearlyAuctionType === "group" && !!groupAuctionId;
  /** auction_group (room) paddle: backend expects auction_type "group" + amount, like LiveRoomsTable results. */
  const useGroupRoomGatewayPayload =
    Boolean(normalOnly) && yearlyAuctionType !== "group";
  const availablePaddlesCount = (availablePaddles || []).filter(
    (paddle) => paddle.is_available !== false,
  ).length;
  const suggestedTopUpAmount = useMemo(() => {
    const premiumRelevant = !normalOnly && canBuyPremiumPackage;
    const usePremium =
      premiumRelevant && topUpPaddleChoice === "premium" && premiumShortfall > 0;
    if (usePremium) return premiumShortfall;
    if (normalShortfall > 0) return normalShortfall;
    return premiumShortfall;
  }, [
    normalOnly,
    canBuyPremiumPackage,
    topUpPaddleChoice,
    normalShortfall,
    premiumShortfall,
  ]);
  const hasWalletShortfall =
    paymentMethod === "wallet" && (normalShortfall > 0 || premiumShortfall > 0);
  const renderAmount = (value: number, iconClassName = "w-4 h-4") => (
    <span className="inline-flex items-center gap-1">
      <span>{toLatinDigits(value.toLocaleString())}</span>
      <img
        src={SAR_ICON}
        className={iconClassName}
        alt={isAr ? "ريال" : "SAR"}
      />
    </span>
  );
  const normalWalletStatusMessage = canAffordNormal
    ? isAr
      ? "متاح للشراء من المحفظة"
      : "Available via wallet"
    : isAr
      ? (
          <>
            يحتاج شحن {renderAmount(normalShortfall)}
          </>
        )
      : (
          <>
            Needs top-up of {renderAmount(normalShortfall)}
          </>
        );
  const premiumWalletStatusMessage = !canBuyPremiumPackage
    ? t("group_required")
    : canAffordPremium
      ? isAr
        ? "متاح للشراء من المحفظة"
        : "Available via wallet"
      : isAr
        ? (
            <>
              يحتاج شحن {renderAmount(premiumShortfall)}
            </>
          )
        : (
            <>
              Needs top-up of {renderAmount(premiumShortfall)}
            </>
          );
  const showPremiumStatusMessage =
    !canBuyPremiumPackage || paymentMethod === "wallet";
  const refreshQueries = () => {
    queryClient.invalidateQueries({ queryKey: ["wallet-balances"] });
    queryClient.invalidateQueries({ queryKey: ["user-paddles"] });
    queryClient.invalidateQueries({
      queryKey: ["available-paddles", yearlyAuctionId, "annual"],
    });
    onJoined?.();
  };

  const handleBuyNormal = async () => {
    if (!yearlyAuctionId) return;

    if (paymentMethod === "wallet") {
      if (!canAffordNormal) {
        toast.warning(t("insufficient_wallet"));
        return;
      }
      try {
        setAction("normal");
        const res = await purchaseNormalPaddle.mutateAsync();
        toast.success(t("purchase_success"));
        refreshQueries();
        onClose();
      } catch (error: any) {
        const msg =
          error?.response?.data?.message ||
          error?.message ||
          t("purchase_failed");
        toast.error(String(msg));
      } finally {
        setAction(null);
      }
    } else {
      try {
        if (gatewayOpeningRef.current.normal) return;
        gatewayOpeningRef.current.normal = true;
        setAction("normal");
        const returnPath = buildReturnPathForGatewayRequest() ?? "/";
        const res = await payWithGateway({
          payment_purpose: "pay_paddle_fee",
          auction_id: yearlyAuctionId,
          payment_method:
            paymentMethod === "apple_pay" ? "apple_pay" : "online_payment",
          return_path: returnPath,
          ...(useGroupRoomGatewayPayload
            ? {
                auction_type: "group",
                amount: normalPrice,
              }
            : {
                auction_type: "annual",
                paddle_type: "normal",
              }),
        });
        const receivedGatewayUrl =
          (res as any)?.data?.payment_url || (res as any)?.data?.redirect_url;
        if ((res as any)?.success && receivedGatewayUrl) {
          persistGatewayMetaFromGatewayResponse(
            (res as any)?.data as Record<string, unknown>,
            returnPath,
          );
          toast.success(t("redirecting_to_gateway"));
          setGatewayUrl(receivedGatewayUrl);
        } else {
          const msg = (res as any)?.message || t("purchase_failed");
          toast.error(msg);
        }
      } catch (error: any) {
        const msg = error?.message || t("purchase_failed");
        toast.error(String(msg));
      } finally {
        setAction(null);
        gatewayOpeningRef.current.normal = false;
      }
    }
  };

  const handleBuyPremium = async () => {
    if (!canBuyPremiumPackage || !groupAuctionId) {
      toast.error(t("group_required"));
      return;
    }

    if (paymentMethod === "wallet") {
      if (!canAffordPremium) {
        toast.warning(t("insufficient_wallet"));
        return;
      }
      try {
        setAction("premium");
        const res = await purchasePremiumPaddle.mutateAsync();
        toast.success(t("premium_purchase_success"));
        refreshQueries();
        onClose();
      } catch (error: any) {
        const msg =
          error?.response?.data?.message ||
          error?.message ||
          t("premium_purchase_failed");
        toast.error(String(msg));
      } finally {
        setAction(null);
      }
    } else {
      try {
        if (gatewayOpeningRef.current.premium) return;
        gatewayOpeningRef.current.premium = true;
        setAction("premium");
        const returnPathPremium = buildReturnPathForGatewayRequest() ?? "/";
        const res = await payWithGateway({
          payment_purpose: "pay_paddle_fee",
          auction_id: groupAuctionId,
          auction_type: "annual",
          paddle_type: "premium",
          payment_method:
            paymentMethod === "apple_pay" ? "apple_pay" : "online_payment",
          return_path: returnPathPremium,
        });
        const receivedPremiumGatewayUrl =
          (res as any)?.data?.payment_url || (res as any)?.data?.redirect_url;
        if ((res as any)?.success && receivedPremiumGatewayUrl) {
          persistGatewayMetaFromGatewayResponse(
            (res as any)?.data as Record<string, unknown>,
            returnPathPremium,
          );
          toast.success(t("redirecting_to_gateway"));
          setGatewayUrl(receivedPremiumGatewayUrl);
        } else {
          const msg = (res as any)?.message || t("premium_purchase_failed");
          toast.error(msg);
        }
      } catch (error: any) {
        const msg = error?.message || t("premium_purchase_failed");
        toast.error(String(msg));
      } finally {
        setAction(null);
        gatewayOpeningRef.current.premium = false;
      }
    }
  };

  const showTermsOnlyStep = requiresTermsGate && termsGateStep === 1;

  return (
    <BaseModal
      isOpen={open}
      onOpenChange={(nextOpen) => {
        if (!nextOpen) onClose();
      }}
      dis={
        showTermsOnlyStep
          ? t("terms_step_intro")
          : isAr
            ? "اختر طريقة الدفع ونوع المضرب المناسب، ثم أكمل الشراء."
            : "Choose payment method and paddle type, then complete your purchase."
      }
      title={showTermsOnlyStep ? t("auction_terms_title") : t("title")}
      contentClassName="w-full max-w-3xl rounded-xl p-0 overflow-hidden"
      bodyClassName="p-0"
    >
      {showTermsOnlyStep ? (
        <div className="p-6 space-y-6 text-sm text-slate-700">
          <div
            className="space-y-2 rounded-xl border-2 border-amber-200/80 bg-amber-50/50 p-4"
            dir={isAr ? "rtl" : "ltr"}
          >
            <div
              className="max-h-[min(24rem,55vh)] overflow-y-auto rounded-lg border border-slate-200 bg-white/90 p-3 text-sm text-slate-800 [word-break:break-word] [&_a]:text-blue-600 [&_a]:underline [&_img]:max-h-96 [&_img]:max-w-full [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:ps-6 [&_ul]:my-2 [&_ul]:list-disc [&_ul]:ps-6"
              dangerouslySetInnerHTML={{ __html: auctionTermsHtml! }}
            />
          </div>
          <label
            dir={isAr ? "rtl" : "ltr"}
            className="flex items-start gap-3 cursor-pointer rounded-lg border border-slate-200 bg-slate-50/80 px-4 py-3"
          >
            <input
              type="checkbox"
              checked={termsAcceptChecked}
              onChange={(e) => setTermsAcceptChecked(e.target.checked)}
              className="mt-1 h-4 w-4 shrink-0 rounded border-slate-300 text-[#0F5132] focus:ring-[#0F5132]"
            />
            <span className="text-sm font-semibold text-slate-800 leading-snug">
              {t("terms_accept_checkbox")}
            </span>
          </label>
          <DynamicButton
            onClick={onTermsGateContinue}
            isDisabled={!termsAcceptChecked}
            className="w-full px-4 py-3 rounded-xl bg-[#0F5132] text-white font-bold hover:bg-[#0F5132]/90 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {t("continue_to_purchase")}
          </DynamicButton>
        </div>
      ) : (
      <div className="p-6 space-y-6 text-sm text-slate-700">
        <div className="grid gap-3 md:grid-cols-3">
          <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
            <div className="text-xs text-slate-500">{t("wallet_title")}</div>
            <div className="font-bold text-slate-900 mt-1">
              {renderAmount(walletBalance)}
            </div>
          </div>
          <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
            <div className="text-xs text-slate-500">
              {isAr ? "المضارب المتاحة لديك" : "Available paddles"}
            </div>
            <div className="font-bold text-slate-900 mt-1">
              {toLatinDigits(String(availablePaddlesCount))}
            </div>
          </div>
          <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
            <div className="text-xs text-slate-500">
              {isAr ? "طريقة الدفع المحددة" : "Selected payment"}
            </div>
            <div className="font-bold text-slate-900 mt-1">
              {paymentMethod === "wallet"
                ? t("payment_method_wallet")
                : paymentMethod === "apple_pay"
                  ? "Apple Pay"
                  : t("payment_method_gateway")}
            </div>
          </div>
        </div>

        <div className="space-y-3">
          <div className="flex items-center justify-between gap-2">
            <div className="text-sm font-bold text-slate-800 min-w-0 flex-1">
              {t("payment_method_prompt")}
            </div>
            <PaddleElectronicPaymentInfo paymentMethod={paymentMethod} />
          </div>
          <div className="grid gap-3 sm:grid-cols-2">
            <label
              className={`rounded-xl border p-4 cursor-pointer transition ${
                paymentMethod === "gateway"
                  ? "border-blue-500 bg-blue-50"
                  : "border-slate-200 bg-white hover:border-blue-300"
              }`}
            >
              <input
                type="radio"
                name="paddle_payment_method"
                checked={paymentMethod === "gateway"}
                onChange={() => setPaymentMethod("gateway")}
                className="sr-only"
              />
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-blue-600/10 text-blue-700 flex items-center justify-center">
                  <CreditCard className="w-5 h-5" />
                </div>
                <div>
                  <div className="font-semibold text-slate-900">
                    {t("payment_method_gateway")}
                  </div>
                  <div className="text-xs text-slate-500">
                    Visa, Mastercard, mada
                  </div>
                </div>
                {paymentMethod === "gateway" && (
                  <CheckCircle2 className="w-4 h-4 text-blue-600 ms-auto" />
                )}
              </div>
            </label>

            {applePayVisible && (
              <label
                className={`rounded-xl border p-4 cursor-pointer transition ${
                  paymentMethod === "apple_pay"
                    ? "border-slate-900 bg-slate-50"
                    : "border-slate-200 bg-white hover:border-slate-400"
                }`}
              >
                <input
                  type="radio"
                  name="paddle_payment_method"
                  checked={paymentMethod === "apple_pay"}
                  onChange={() => setPaymentMethod("apple_pay")}
                  className="sr-only"
                />
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-slate-900 flex items-center justify-center">
                    <svg viewBox="0 0 24 24" className="w-5 h-5 fill-white" aria-hidden="true">
                      <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.7 9.05 7.4c1.28.07 2.16.72 2.98.73 1.16-.1 2.26-.79 3.47-.68 1.45.13 2.54.79 3.25 2.02-3.13 1.87-2.39 5.88.3 6.97-.5 1.32-1.29 2.59-2 3.84zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/>
                    </svg>
                  </div>
                  <div>
                    <div className="font-semibold text-slate-900">
                      Apple Pay
                    </div>
                    <div className="text-xs text-slate-500">
                      {isAr ? "الدفع عبر Apple Pay" : "Pay with Apple Pay"}
                    </div>
                  </div>
                  {paymentMethod === "apple_pay" && (
                    <CheckCircle2 className="w-4 h-4 text-slate-700 ms-auto" />
                  )}
                </div>
              </label>
            )}

            <label
              className={`rounded-xl border p-4 cursor-pointer transition ${
                paymentMethod === "wallet"
                  ? "border-emerald-500 bg-emerald-50"
                  : "border-slate-200 bg-white hover:border-emerald-300"
              }`}
            >
              <input
                type="radio"
                name="paddle_payment_method"
                checked={paymentMethod === "wallet"}
                onChange={() => setPaymentMethod("wallet")}
                className="sr-only"
              />
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-emerald-600/10 text-emerald-700 flex items-center justify-center">
                  <Wallet className="w-5 h-5" />
                </div>
                <div>
                  <div className="font-semibold text-slate-900">
                    {t("payment_method_wallet")}
                  </div>
                  <div className="text-xs text-slate-500">
                    {isAr
                      ? "الدفع من الرصيد المتاح"
                      : "Pay from available balance"}
                  </div>
                </div>
                {paymentMethod === "wallet" && (
                  <CheckCircle2 className="w-4 h-4 text-emerald-600 ms-auto" />
                )}
              </div>
            </label>
          </div>
        </div>

        {auctionTermsHtml && groupAuctionId && !twoStepAuctionTerms ? (
          <div
            className="space-y-2 rounded-xl border-2 border-amber-200/80 bg-amber-50/50 p-4"
            dir={isAr ? "rtl" : "ltr"}
          >
            <div className="text-sm font-extrabold text-slate-900">
              {t("auction_terms_title")}
            </div>
            <div
              className="max-h-52 overflow-y-auto rounded-lg border border-slate-200 bg-white/90 p-3 text-sm text-slate-800 [word-break:break-word] [&_a]:text-blue-600 [&_a]:underline [&_img]:max-h-96 [&_img]:max-w-full [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:ps-6 [&_ul]:my-2 [&_ul]:list-disc [&_ul]:ps-6"
              dangerouslySetInnerHTML={{ __html: auctionTermsHtml }}
            />
          </div>
        ) : null}

        <div className="space-y-3">
          <div className="text-sm font-bold text-slate-800">
            {isAr ? "اختر نوع المضرب" : "Choose Paddle Type"}
          </div>
          <div className={`grid gap-4 ${normalOnly ? "" : "md:grid-cols-2"}`}>
            <div
              role="button"
              tabIndex={0}
              onClick={() => setTopUpPaddleChoice("normal")}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ")
                  setTopUpPaddleChoice("normal");
              }}
              className={`rounded-2xl border border-slate-200 bg-white p-5 flex flex-col cursor-pointer outline-none transition-shadow ${
                !normalOnly && canBuyPremiumPackage && topUpPaddleChoice === "normal"
                  ? "ring-2 ring-[#0F5132]/25"
                  : ""
              }`}
            >
              <div className="flex items-start justify-between">
                <div>
                  <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">
                    {isAr ? "الخيار القياسي" : "Standard Option"}
                  </div>
                  <h4 className="text-base font-bold text-slate-900 mt-1">
                    {t("normal_title")}
                  </h4>
                </div>
                <div className="px-2.5 py-1 rounded-full bg-slate-100 text-slate-700 text-xs font-bold">
                  {isAr ? "عادي" : "Normal"}
                </div>
              </div>

              <div className="mt-4 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">
                <div className="text-xs text-slate-500">
                  {isAr ? "السعر" : "Price"}
                </div>
                <div className="text-2xl font-black text-[#0F5132]">
                  {renderAmount(normalPrice, "w-5 h-5")}
                </div>
              </div>

              <ul className="mt-4 space-y-2 text-xs text-slate-600">
                <li className="flex items-center gap-2">
                  <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                  <span>
                    {isAr
                      ? "استخدام واحد لمزاد واحد"
                      : "Single use for one auction"}
                  </span>
                </li>
                <li className="flex items-center gap-2">
                  <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                  <span>
                    {isAr
                      ? "مناسب للمشاركة القياسية"
                      : "Suitable for standard participation"}
                  </span>
                </li>
              </ul>

              <div
                className={`mt-3 min-h-[20px] text-xs font-medium transition-opacity ${
                  canAffordNormal ? "text-emerald-700" : "text-amber-700"
                } ${
                  paymentMethod === "wallet"
                    ? "opacity-100"
                    : "opacity-0 pointer-events-none select-none"
                }`}
              >
                {normalWalletStatusMessage}
              </div>

              <div className="mt-auto pt-4">
                <DynamicButton
                  onClick={handleBuyNormal}
                  isDisabled={
                    action !== null ||
                    (paymentMethod === "wallet" && !canAffordNormal) ||
                    purchaseNormalPaddle.isPending
                  }
                  className="w-full px-4 py-3 rounded-xl bg-[#0F5132] text-white font-bold hover:bg-[#0F5132]/90 disabled:opacity-60 disabled:cursor-not-allowed transition-all"
                >
                  {action === "normal" || purchaseNormalPaddle.isPending
                    ? t("processing")
                    : t("buy_normal")}
                </DynamicButton>
              </div>
            </div>

            {!normalOnly && (
              <div
                role="button"
                tabIndex={0}
                onClick={() => setTopUpPaddleChoice("premium")}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ")
                    setTopUpPaddleChoice("premium");
                }}
                className={`rounded-2xl border border-emerald-200 bg-gradient-to-b from-emerald-50 to-white p-5 flex flex-col cursor-pointer outline-none transition-shadow ${
                  canBuyPremiumPackage && topUpPaddleChoice === "premium"
                    ? "ring-2 ring-emerald-600/35"
                    : ""
                }`}
              >
              <div className="flex items-start justify-between">
                <div>
                  <div className="text-xs font-semibold uppercase tracking-wide text-emerald-700">
                    {isAr ? "الخيار المتقدم" : "Advanced Option"}
                  </div>
                  <h4 className="text-base font-bold text-slate-900 mt-1">
                    {t("premium_title")}
                  </h4>
                </div>
                <div className="w-9 h-9 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center">
                  <Crown className="w-5 h-5" />
                </div>
              </div>

              <div className="mt-4 rounded-xl border border-emerald-200 bg-white px-3 py-2">
                <div className="text-xs text-slate-500">
                  {isAr ? "السعر" : "Price"}
                </div>
                <div className="text-2xl font-black text-[#0F5132]">
                  {renderAmount(premiumPrice, "w-5 h-5")}
                </div>
              </div>

              <ul className="mt-4 space-y-2 text-xs text-slate-700">
                <li className="flex items-center gap-2">
                  <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                  <span>
                    {t("premium_uses", {
                      value: toLatinDigits(String(premiumUseTimes)),
                    })}
                  </span>
                </li>
                <li className="flex items-center gap-2">
                  <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                  <span>
                    {isAr
                      ? "صالح لمزادات متعددة"
                      : "Valid for multiple auctions"}
                  </span>
                </li>
                <li className="flex items-center gap-2">
                  <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                  <span>
                    {isAr
                      ? "أولوية في المشاركة حسب شروط المزاد"
                      : "Priority access based on auction policy"}
                  </span>
                </li>
              </ul>

              <div
                className={`mt-3 min-h-[20px] text-xs font-medium transition-opacity ${
                  !canBuyPremiumPackage || !canAffordPremium
                    ? "text-amber-700"
                    : "text-emerald-700"
                } ${
                  showPremiumStatusMessage
                    ? "opacity-100"
                    : "opacity-0 pointer-events-none select-none"
                }`}
              >
                {premiumWalletStatusMessage}
              </div>

              <div className="mt-auto pt-4">
                <DynamicButton
                  onClick={handleBuyPremium}
                  isDisabled={
                    action !== null ||
                    !canBuyPremiumPackage ||
                    (paymentMethod === "wallet" && !canAffordPremium) ||
                    purchasePremiumPaddle.isPending
                  }
                  className="w-full px-4 py-3 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 text-white font-bold hover:from-emerald-700 hover:to-teal-700 disabled:opacity-60 disabled:cursor-not-allowed transition-all"
                >
                  {action === "premium" || purchasePremiumPaddle.isPending
                    ? t("processing")
                    : t("buy_premium")}
                </DynamicButton>
              </div>
            </div>
            )}
          </div>
        </div>

        {hasWalletShortfall && (
          <div className="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 space-y-3">
            <div className="text-xs font-semibold text-amber-800">
              {t("insufficient_wallet")}
            </div>
            <div className="space-y-1 text-xs text-amber-800">
              {normalShortfall > 0 && (
                <div>
                  {isAr ? "المضرب العادي يحتاج: +" : "Normal paddle needs: +"}
                  {renderAmount(normalShortfall)}
                </div>
              )}
              {premiumShortfall > 0 && (
                <div>
                  {isAr
                    ? "الباقة البريميوم تحتاج: +"
                    : "Premium package needs: +"}
                  {renderAmount(premiumShortfall)}
                </div>
              )}
            </div>
            <button
              type="button"
              onClick={() => setShowTopUpModal(true)}
              className="w-full sm:w-auto px-4 py-2 rounded-lg bg-emerald-600 text-white text-xs font-bold hover:bg-emerald-700 transition-colors"
            >
              <span className="inline-flex items-center gap-1">
                <span>{isAr ? "شحن المحفظة" : "Top up wallet"}</span>
                <span>(</span>
                {renderAmount(suggestedTopUpAmount)}
                <span>)</span>
              </span>
            </button>
          </div>
        )}
      </div>
      )}
      <TopUpModal
        isOpen={showTopUpModal}
        onOpenChange={setShowTopUpModal}
        defaultAmount={suggestedTopUpAmount}
        onSuccess={() => {
          setShowTopUpModal(false);
          queryClient.invalidateQueries({ queryKey: ["wallet-balances"] });
        }}
      />
      <PaymentGatewayModal
        isOpen={!!gatewayUrl}
        onClose={() => setGatewayUrl(null)}
        gatewayUrl={gatewayUrl || ""}
        isAr={isAr}
      />
    </BaseModal>
  );
}
