"use client";

import React, { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  FaMapMarkerAlt,
  FaCheckCircle,
  FaLock,
  FaArrowLeft,
  FaExclamationTriangle,
  FaArrowRight,
  FaShoppingBag,
  FaHome,
  FaCreditCard,
  FaUniversity,
  FaPlus,
  FaBuilding,
  FaWallet
} from "react-icons/fa";
import { resolveImage, PLACEHOLDER_IMAGE } from "@/utils/imageHelper";
import { formatPrice } from "@/utils/currencyHelper";
import { API_BASE_URL } from "@/utils/apiHelper";

/* ─── Types ──────────────────────────────────────────────── */
type CartItem = {
  inward_id: string;
  name: string;
  sku_no: string;
  dealer_price: number;
  quantity: number;
  subtotal: number;
  image: string;
  currency?: string;
  is_individual?: boolean;
  is_carton?: boolean;
  carton_box_size?: number;
};

type CartData = {
  items: CartItem[];
  total_items: number;
  total_price: number;
};

type Address = {
  address_id: string;
  name?: string | null;
  business_name: string;
  address_line: string;
  city: string;
  state: string;
  pincode: string;
  gstin?: string | null;
  alternate_mobile?: string | null;
  web?: string | null;
  business_email?: string | null;
  business_mobile?: string | null;
  address_type?: string | null;
  is_business_address?: boolean | null;
};

type CheckoutSummary = {
  company_address: Address;
  items: CartItem[];
  total_items: number;
  subtotal: number;
  discount_applied: number;
  coin_discount: number;
  total_price: number;
  coupon_code: string | null;
  coin_balance: number;
  potential_coins_earned: number;
};

type Coupon = {
  coupon_code: string;
  description: string;
  discount_type: string;
  discount_value: number;
  max_discount_value: number;
  minimum_order_value: number;
};

type CoinWallet = {
  coin_balance: number;
  total_earned: number;
  total_redeemed: number;
};

type CoinConfig = {
  earn_rate_percent: number;
  coin_to_inr: number;
  is_active: boolean;
};

type DealerCreditStatus = {
  user_id: string;
  business_name?: string | null;
  order_credit_limit?: number | null;
  overall_credit_limit?: number | null;
  outstanding_amount: number;
  remaining_credit?: number | null;
};

export default function CheckoutPage() {
  const [cart, setCart] = useState<CartData | null>(null);
  const [addresses, setAddresses] = useState<Address[]>([]);
  const [profile, setProfile] = useState<{
    order_credit_limit?: number | null;
    overall_credit_limit?: number | null;
  } | null>(null);
  const [credit, setCredit] = useState<DealerCreditStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [shippingAddressId, setShippingAddressId] = useState<string>("");
  const [billingAddressId, setBillingAddressId] = useState<string>("");
  const [billingSameAsShipping, setBillingSameAsShipping] = useState<boolean>(true);
  const [placingOrder, setPlacingOrder] = useState(false);
  const [checkoutSummary, setCheckoutSummary] = useState<CheckoutSummary | null>(null);
  const [summaryLoading, setSummaryLoading] = useState(false);

  // Stepper state: 1 = Address, 2 = Order Summary, 3 = Payment
  const [step, setStep] = useState<number>(1);

  // Add Address drawer/form states
  const [showAddForm, setShowAddForm] = useState(false);
  const [addressForm, setAddressForm] = useState({
    first_name: "",
    last_name: "",
    business_name: "",
    address_line: "",
    city: "",
    state: "",
    pincode: "",
    gstin: "",
    alternate_mobile: "",
    web: "",
    business_email: "",
    business_mobile: "",
    address_type: "shipping",
    is_business_address: false,
  });
  const [addressFormLoading, setAddressFormLoading] = useState(false);

  // Custom checkout error modal states
  const [checkoutErrorMsg, setCheckoutErrorMsg] = useState<string>("");
  const [checkoutErrorCode, setCheckoutErrorCode] = useState<string | number>("");
  const [showErrorModal, setShowErrorModal] = useState<boolean>(false);

  // Coupons
  const [coupons, setCoupons] = useState<Coupon[]>([]);
  const [couponCode, setCouponCode] = useState<string>("");
  const [appliedCoupon, setAppliedCoupon] = useState<string>("");
  const [couponError, setCouponError] = useState<string>("");
  const [showCouponsDropdown, setShowCouponsDropdown] = useState<boolean>(false);
  const [couponSuccessToast, setCouponSuccessToast] = useState<string>("");
  const [coinSuccessToast, setCoinSuccessToast] = useState<string>("");

  // Coins (Flipkart SuperCoins style)
  const [wallet, setWallet] = useState<CoinWallet | null>(null);
  const [coinConfig, setCoinConfig] = useState<CoinConfig | null>(null);
  const [coinsToRedeem, setCoinsToRedeem] = useState<number>(0);
  const [useCoinsToggle, setUseCoinsToggle] = useState<boolean>(false);

  // Payment UI screenshot states
  const [paymentType, setPaymentType] = useState<string>("credit");
  const [paymentSubMethod, setPaymentSubMethod] = useState<"card" | "bank">("card");
  const [cardDetails, setCardDetails] = useState({
    number: "",
    expiry: "",
    cvc: "",
    cardholder: "",
    saveInfo: true
  });

  const router = useRouter();

  /* ── Initial data load ── */
  const fetchAllData = async () => {
    const token = localStorage.getItem("access_token");
    if (!token) { router.push("/login"); return; }

    try {
      const [cartRes, addrRes, couponsRes, walletRes, configRes, profileRes, creditRes] = await Promise.all([
        fetch(`${API_BASE_URL}/api/v1/b2b-cart/`, {
          headers: { Authorization: `Bearer ${token}` },
        }),
        fetch(`${API_BASE_URL}/api/v1/b2b-dealer/company/addresses`, {
          headers: { Authorization: `Bearer ${token}` },
        }),
        fetch(`${API_BASE_URL}/api/v1/b2b-dealer/coupons`, {
          headers: { Authorization: `Bearer ${token}` },
        }).catch(() => null),
        fetch(`${API_BASE_URL}/api/v1/coins/my-wallet`, {
          headers: { Authorization: `Bearer ${token}` },
        }).catch(() => null),
        fetch(`${API_BASE_URL}/api/v1/coins/config`, {
          headers: { Authorization: `Bearer ${token}` },
        }).catch(() => null),
        fetch(`${API_BASE_URL}/users/me`, {
          headers: { Authorization: `Bearer ${token}` },
        }).catch(() => null),
        fetch(`${API_BASE_URL}/api/v1/b2b-dealer/my-credit`, {
          headers: { Authorization: `Bearer ${token}` },
        }).catch(() => null),
      ]);

      if (cartRes.status === 401) {
        localStorage.removeItem("access_token");
        router.push("/login");
        return;
      }

      if (cartRes.ok) {
        const data = await cartRes.json();
        if (!data.items || data.items.length === 0) { router.push("/cart"); return; }
        setCart(data);
      }

      if (addrRes.ok) {
        const addrs = await addrRes.json();
        setAddresses(addrs);
        if (addrs.length > 0) {
          if (!shippingAddressId) setShippingAddressId(addrs[0].address_id);
          if (!billingAddressId) setBillingAddressId(addrs[0].address_id);
        }
      }

      if (couponsRes && couponsRes.ok) setCoupons(await couponsRes.json());
      if (walletRes && walletRes.ok) setWallet(await walletRes.json());
      if (configRes && configRes.ok) setCoinConfig(await configRes.json());
      if (profileRes && profileRes.ok) setProfile(await profileRes.json());
      if (creditRes && creditRes.ok) setCredit(await creditRes.json());
    } catch (err) {
      console.error("Checkout init error:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAllData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [router]);

  /* ── Fetch summary whenever key params change ── */
  const fetchSummary = useCallback(async (
    shippingAddrId: string,
    billingAddrId: string,
    coupon: string,
    coins: number,
    payment: string
  ) => {
    if (!shippingAddrId) return;
    const token = localStorage.getItem("access_token");
    if (!token) return;

    setSummaryLoading(true);
    setCouponError("");
    try {
      const body: Record<string, unknown> = {
        address_id: shippingAddrId, // Keep for backward compatibility
        shipping_address_id: shippingAddrId,
        billing_address_id: billingAddrId,
        payment_type: payment,
        coins_to_redeem: coins,
      };
      if (coupon) body.coupon_code = coupon;

      const res = await fetch(
        `${API_BASE_URL}/api/v1/b2b-orders/checkout/summary`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
          body: JSON.stringify(body),
        }
      );

      if (res.ok) {
        const summary = await res.json();
        setCheckoutSummary(summary);
        // If the API returns no discount for the coupon, treat it as a failure
        if (coupon && (!summary.coupon_code || summary.discount_applied === 0)) {
          const errMsg = `Coupon '${coupon}' is not valid for this order.`;
          setCouponError(errMsg);
          setAppliedCoupon("");
          setCouponCode("");
          setTimeout(() => setCouponError(""), 4000);
        } else if (coupon && summary.discount_applied > 0) {
          const checkoutCurrency = summary.items?.[0]?.currency || "INR";
          setCouponSuccessToast(`Coupon '${coupon}' applied! Saved ${formatPrice(summary.discount_applied, checkoutCurrency)}`);
          setTimeout(() => setCouponSuccessToast(""), 4000);
        }

        if (coins > 0 && summary.coin_discount > 0) {
          const checkoutCurrency = summary.items?.[0]?.currency || "INR";
          setCoinSuccessToast(`Redeemed ${coins.toLocaleString("en-IN")} SuperCoins! Saved ${formatPrice(summary.coin_discount, checkoutCurrency)}`);
          setTimeout(() => setCoinSuccessToast(""), 4000);
        }
      } else {
        const err = await res.json().catch(() => ({}));
        setCheckoutErrorCode(res.status);

        // ALWAYS clear coupon states on any error if a coupon was being applied
        if (coupon) {
          setAppliedCoupon("");
          setCouponCode("");
          const errMsg = err.detail || `Coupon '${coupon}' could not be applied.`;
          setCouponError(errMsg);
          setTimeout(() => setCouponError(""), 4000);
        }

        // If it is a minimum order value constraint, trigger the beautiful error popup modal
        if (err.detail && err.detail.toLowerCase().includes("minimum order value")) {
          setCheckoutErrorMsg(err.detail);
          setShowErrorModal(true);
          // If a coupon was active, fetch a clean summary without the failed coupon
          if (coupon) {
            await fetchSummary(shippingAddrId, billingAddrId, "", coins, payment);
          }
        } else if (coupon) {
          setCheckoutErrorMsg(err.detail || `Coupon '${coupon}' could not be applied.`);
          setShowErrorModal(true);
          // Retry without coupon to still get a valid summary
          await fetchSummary(shippingAddrId, billingAddrId, "", coins, payment);
        } else {
          setCheckoutErrorMsg(err.detail || "Unable to load checkout details.");
          setShowErrorModal(true);
        }
      }
    } catch {
      /* silent */
    } finally {
      setSummaryLoading(false);
    }
  }, []);

  useEffect(() => {
    if (shippingAddressId) {
      const currentBillingId = billingSameAsShipping ? shippingAddressId : billingAddressId;
      fetchSummary(shippingAddressId, currentBillingId, appliedCoupon, coinsToRedeem, paymentType);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shippingAddressId, billingAddressId, billingSameAsShipping, appliedCoupon, coinsToRedeem, paymentType]);

  /* ── Address Creator handler ── */
  const handleAddAddress = async (e: React.FormEvent) => {
    e.preventDefault();
    const token = localStorage.getItem("access_token");
    if (!token) return;

    setAddressFormLoading(true);
    try {
      const payload = {
        ...addressForm,
        name: `${addressForm.first_name} ${addressForm.last_name}`.trim(),
        is_business_address: addressForm.address_type === "business"
      };
      const res = await fetch(`${API_BASE_URL}/api/v1/b2b-dealer/company/addresses`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      if (res.ok) {
        const newAddr = await res.json();
        setAddresses(prev => [...prev, newAddr]);
        setShippingAddressId(newAddr.address_id);
        if (billingSameAsShipping) {
          setBillingAddressId(newAddr.address_id);
        }
        setShowAddForm(false);
        setAddressForm({
          first_name: "",
          last_name: "",
          business_name: "",
          address_line: "",
          city: "",
          state: "",
          pincode: "",
          gstin: "",
          alternate_mobile: "",
          web: "",
          business_email: "",
          business_mobile: "",
          address_type: "shipping",
          is_business_address: false,
        });
      } else {
        const errorData = await res.json().catch(() => ({}));
        alert(`Failed to add address: ${errorData.detail || "Unknown error"}`);
      }
    } catch (err) {
      console.error(err);
      alert("Something went wrong while adding the address.");
    } finally {
      setAddressFormLoading(false);
    }
  };

  /* ── Coupon handlers ── */
  const applyCoupon = () => {
    if (!couponCode.trim()) return;
    setCouponError("");
    setAppliedCoupon(couponCode.trim().toUpperCase());
  };

  const removeCoupon = () => {
    setCouponCode("");
    setAppliedCoupon("");
    setCouponError("");
  };

  /* ── Coin handlers ── */
  const maxRedeemable = wallet ? Math.floor(Math.min(
    wallet.coin_balance,
    checkoutSummary
      ? checkoutSummary.subtotal * (coinConfig?.coin_to_inr ?? 1)
      : wallet.coin_balance
  )) : 0;

  const toggleSuperCoins = (apply: boolean) => {
    setUseCoinsToggle(apply);
    if (apply) {
      setCoinsToRedeem(maxRedeemable);
    } else {
      setCoinsToRedeem(0);
    }
  };

  /* ── Place order ── */
  const placeOrder = async () => {
    if (!shippingAddressId) return;
    const token = localStorage.getItem("access_token");
    if (!token) return;

    setPlacingOrder(true);
    try {
      const currentBillingId = billingSameAsShipping ? shippingAddressId : billingAddressId;
      const body: Record<string, unknown> = {
        address_id: shippingAddressId, // Keep for backward compatibility
        shipping_address_id: shippingAddressId,
        billing_address_id: currentBillingId,
        payment_type: paymentType,
        coins_to_redeem: coinsToRedeem,
      };
      if (appliedCoupon) body.coupon_code = appliedCoupon;

      const res = await fetch(
        `${API_BASE_URL}/api/v1/b2b-orders/checkout`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
          body: JSON.stringify(body),
        }
      );

      if (res.ok) {
        window.dispatchEvent(new Event("cart-updated"));
        router.push("/checkout/success");
      } else {
        const err = await res.json().catch(() => ({}));
        setCheckoutErrorCode(res.status);
        setCheckoutErrorMsg(err.detail || "Unknown error occurred during checkout.");
        setShowErrorModal(true);
      }
    } catch (err) {
      console.error(err);
      setCheckoutErrorCode("CLIENT_ERROR");
      setCheckoutErrorMsg("Something went wrong during checkout. Please try again.");
      setShowErrorModal(true);
    } finally {
      setPlacingOrder(false);
    }
  };

  if (loading || !cart) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary" />
      </div>
    );
  }

  const summary = checkoutSummary;
  const displayItems = summary?.items || cart.items;
  const totalItems = summary?.total_items ?? cart.total_items;
  const subtotal = summary?.subtotal ?? cart.total_price;
  const discount = summary?.discount_applied ?? 0;
  const coinDiscount = summary?.coin_discount ?? 0;
  const totalPrice = summary?.total_price ?? cart.total_price;
  const potentialCoins = summary?.potential_coins_earned ?? 0;
  const couponAppliedOk = !!appliedCoupon && !!summary?.coupon_code && discount > 0;

  return (
    <div className="max-w-[56rem] mx-auto px-4 sm:px-6 lg:px-8 py-10 min-h-[85vh] select-none">

      {/* Scoped CSS header overrides */}
      <style>{`
        header nav div.hidden.lg\\:flex {
          display: none !important;
        }
        header nav div.flex.items-center.gap-3 {
          display: none !important;
        }
      `}</style>

      {/* ── 3-STEP TRACKER HEADER ── */}
      <div className="flex justify-center items-center gap-6 md:gap-10 mb-10 select-none">

        {/* Step 1: Address */}
        <div className="flex items-center gap-2 cursor-pointer" onClick={() => step > 1 && setStep(1)}>
          <div className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-black transition-all ${step >= 1 ? "bg-primary text-white ring-4 ring-primary/10" : "bg-gray-100 text-gray-400"
            }`}>
            {step > 1 ? "✓" : "1"}
          </div>
          <span className={`text-xs uppercase tracking-widest font-black ${step >= 1 ? "text-gray-900" : "text-gray-400"}`}>
            Address
          </span>
        </div>

        <div className={`h-0.5 w-12 md:w-20 rounded transition-all ${step > 1 ? "bg-primary" : "bg-gray-200"}`} />

        {/* Step 2: Order Summary */}
        <div className="flex items-center gap-2 cursor-pointer" onClick={() => step > 2 && setStep(2)}>
          <div className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-black transition-all ${step >= 2 ? "bg-primary text-white ring-4 ring-primary/10" : "bg-gray-100 text-gray-400"
            }`}>
            {step > 2 ? "✓" : "2"}
          </div>
          <span className={`text-xs uppercase tracking-widest font-black ${step >= 2 ? "text-gray-900" : "text-gray-400"}`}>
            Order Summary
          </span>
        </div>

        <div className={`h-0.5 w-12 md:w-20 rounded transition-all ${step > 2 ? "bg-primary" : "bg-gray-200"}`} />

        {/* Step 3: Payment */}
        <div className="flex items-center gap-2">
          <div className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-black transition-all ${step >= 3 ? "bg-primary text-white ring-4 ring-primary/10" : "bg-gray-100 text-gray-400"
            }`}>
            3
          </div>
          <span className={`text-xs uppercase tracking-widest font-black ${step >= 3 ? "text-gray-900" : "text-gray-400"}`}>
            Payment
          </span>
        </div>
      </div>

      {/* ── STEP 1: ADDRESS SELECTION ── */}
      {step === 1 && (
        <div className="max-w-xl mx-auto bg-white rounded-[2.5rem] border border-gray-200/60 shadow-[0_8px_30px_rgba(0,0,0,0.02)] p-6 sm:p-8 flex flex-col gap-6 animate-fade-in text-slate-800">
          <div className="flex justify-between items-center select-none">
            <div>
              <div className="text-[10px] font-black text-primary uppercase tracking-widest mb-1">Step 1 of 3</div>
              <h2 className="text-xl font-black text-gray-900 uppercase tracking-tight">Delivery Address</h2>
            </div>

            <button
              onClick={() => setShowAddForm(!showAddForm)}
              className="px-4 py-2 border border-gray-200 hover:border-slate-800 text-slate-800 font-extrabold text-[10px] tracking-wider uppercase rounded-xl transition-all shadow-sm flex items-center gap-1.5"
            >
              <FaPlus size={8} /> {showAddForm ? "Close Form" : "Add Address"}
            </button>
          </div>

          {/* Collapsible New Address Form */}
          {showAddForm && (
            <form onSubmit={handleAddAddress} className="grid grid-cols-1 sm:grid-cols-2 gap-4 border border-dashed border-gray-200 rounded-2.5xl p-5 bg-slate-50/50 animate-fade-in-up">
              <h3 className="col-span-1 sm:col-span-2 text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 border-b border-gray-200/50 pb-2">Register New Address</h3>

              <div>
                <label className="block text-[9px] font-bold text-gray-450 uppercase mb-1">First Name *</label>
                <input required type="text" value={addressForm.first_name} onChange={e => setAddressForm(p => ({ ...p, first_name: e.target.value }))} placeholder="John" className="w-full px-4 py-2.5 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none" />
              </div>

              <div>
                <label className="block text-[9px] font-bold text-gray-450 uppercase mb-1">Last Name *</label>
                <input required type="text" value={addressForm.last_name} onChange={e => setAddressForm(p => ({ ...p, last_name: e.target.value }))} placeholder="Doe" className="w-full px-4 py-2.5 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none" />
              </div>

              <div className="col-span-1 sm:col-span-2">
                <label className="block text-[9px] font-bold text-gray-450 uppercase mb-1">Address Line *</label>
                <input required type="text" value={addressForm.address_line} onChange={e => setAddressForm(p => ({ ...p, address_line: e.target.value }))} placeholder="Street, Building, Floor" className="w-full px-4 py-2.5 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none" />
              </div>

              <div>
                <label className="block text-[9px] font-bold text-gray-450 uppercase mb-1">City *</label>
                <input required type="text" value={addressForm.city} onChange={e => setAddressForm(p => ({ ...p, city: e.target.value }))} placeholder="e.g. Mumbai" className="w-full px-4 py-2.5 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none" />
              </div>

              <div>
                <label className="block text-[9px] font-bold text-gray-450 uppercase mb-1">State *</label>
                <input required type="text" value={addressForm.state} onChange={e => setAddressForm(p => ({ ...p, state: e.target.value }))} placeholder="e.g. Maharashtra" className="w-full px-4 py-2.5 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none" />
              </div>

              <div>
                <label className="block text-[9px] font-bold text-gray-450 uppercase mb-1">Pincode *</label>
                <input required type="text" value={addressForm.pincode} onChange={e => setAddressForm(p => ({ ...p, pincode: e.target.value }))} placeholder="400001" className="w-full px-4 py-2.5 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none" />
              </div>

              <div>
                <label className="block text-[9px] font-bold text-gray-450 uppercase mb-1">Address Type *</label>
                <select value={addressForm.address_type} onChange={e => setAddressForm(p => ({ ...p, address_type: e.target.value }))} className="w-full px-4 py-2.5 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none">
                  <option value="shipping">Shipping Address</option>
                  <option value="billing">Billing Address</option>
                  <option value="business">Business Address</option>
                </select>
              </div>

              <div className="col-span-1 sm:col-span-2">
                <label className="block text-[9px] font-bold text-gray-450 uppercase mb-1">Alternate Contact</label>
                <input type="text" value={addressForm.alternate_mobile} onChange={e => setAddressForm(p => ({ ...p, alternate_mobile: e.target.value }))} placeholder="+91 98765 43210" className="w-full px-4 py-2.5 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none" />
              </div>

              {/* ── Business fields — only when address_type is business ── */}
              {addressForm.address_type === "business" && (
                <div className="col-span-1 sm:col-span-2 rounded-2xl bg-amber-50 border border-amber-200 p-4">
                  <div className="flex items-center gap-1.5 text-[9px] font-black text-amber-700 uppercase tracking-widest mb-3">
                    <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-2 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                    </svg>
                    Business Details
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div className="col-span-1 sm:col-span-2">
                      <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">Business Name *</label>
                      <input required={addressForm.address_type === "business"} type="text" value={addressForm.business_name} onChange={e => setAddressForm(p => ({ ...p, business_name: e.target.value }))} placeholder="e.g. Acme Motors Pvt Ltd" className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:border-amber-400" />
                    </div>
                    <div>
                      <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">Business Email</label>
                      <input type="email" value={addressForm.business_email} onChange={e => setAddressForm(p => ({ ...p, business_email: e.target.value }))} placeholder="billing@acme.com" className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:border-amber-400" />
                    </div>
                    <div>
                      <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">Business Mobile</label>
                      <input type="text" value={addressForm.business_mobile} onChange={e => setAddressForm(p => ({ ...p, business_mobile: e.target.value }))} placeholder="+91 80 44332211" className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:border-amber-400" />
                    </div>
                    <div>
                      <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">Website</label>
                      <input type="text" value={addressForm.web} onChange={e => setAddressForm(p => ({ ...p, web: e.target.value }))} placeholder="https://acme.com" className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:border-amber-400" />
                    </div>
                    <div>
                      <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">GSTIN</label>
                      <input type="text" value={addressForm.gstin} onChange={e => setAddressForm(p => ({ ...p, gstin: e.target.value }))} placeholder="29AAAAA0000A1Z5" className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 uppercase focus:outline-none focus:border-amber-400" />
                    </div>
                  </div>
                </div>
              )}

              <button disabled={addressFormLoading} type="submit" className="col-span-1 sm:col-span-2 w-full mt-2 bg-slate-900 hover:bg-slate-800 text-white font-extrabold text-[10px] tracking-wider uppercase py-3 rounded-xl shadow-sm transition-all disabled:opacity-75">
                {addressFormLoading ? "Saving Address..." : "Save and Select Address"}
              </button>
            </form>
          )}

          {addresses.length === 0 ? (
            <div className="text-center py-12 bg-gray-50 rounded-2.5xl border border-dashed border-gray-200">
              <FaMapMarkerAlt className="text-4xl text-gray-300 mx-auto mb-4" />
              <h3 className="text-base font-bold text-gray-900 mb-1">No Addresses Saved</h3>
              <p className="text-xs font-semibold text-gray-555 mb-6 max-w-xs mx-auto">Please add a delivery location using the form above to check out.</p>
            </div>
          ) : (
            <div className="flex flex-col gap-6">
              {/* Shipping Address Selection */}
              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3">SELECT SHIPPING ADDRESS</h3>
                <div className="flex flex-col gap-4">
                  {addresses.map(addr => (
                    <div
                      key={`ship-${addr.address_id}`}
                      onClick={() => setShippingAddressId(addr.address_id)}
                      className={`p-5 rounded-2.5xl border-2 cursor-pointer transition-all flex items-start gap-4 ${shippingAddressId === addr.address_id
                        ? "border-primary bg-primary/5 shadow-sm"
                        : "border-gray-200/70 bg-white hover:border-gray-300"
                        }`}
                    >
                      <div className="pt-1">
                        <div className={`w-5 h-5 rounded-full border flex items-center justify-center transition-colors ${shippingAddressId === addr.address_id ? "border-primary bg-primary" : "border-gray-300 bg-white"
                          }`}>
                          {shippingAddressId === addr.address_id && <div className="w-2 h-2 rounded-full bg-white" />}
                        </div>
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="text-[9px] font-black tracking-widest uppercase bg-slate-105 text-slate-700 px-2 py-0.5 rounded">
                            {addr.is_business_address ? "BUSINESS" : (addr.address_type ? addr.address_type.toUpperCase() : "SHIPPING")}
                          </span>
                          <h3 className="font-extrabold text-gray-800 text-[14px]">{addr.business_name}</h3>
                        </div>
                        <p className="text-xs font-semibold text-gray-550 mb-1 leading-relaxed">{addr.address_line}</p>
                        <p className="text-xs font-semibold text-gray-550 leading-relaxed">{addr.city}, {addr.state} — {addr.pincode}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Billing Same As Shipping Toggle */}
              <div className="bg-slate-50 border border-gray-200/60 rounded-2.5xl p-4 flex items-center justify-between select-none">
                <div className="flex flex-col gap-0.5">
                  <span className="text-xs font-black text-slate-800 uppercase tracking-wide">Billing Details</span>
                  <span className="text-[10px] text-gray-400 font-bold">Use the same address for billing</span>
                </div>
                <input
                  type="checkbox"
                  checked={billingSameAsShipping}
                  onChange={(e) => setBillingSameAsShipping(e.target.checked)}
                  className="w-5 h-5 accent-primary cursor-pointer"
                />
              </div>

              {/* Billing Address Selection (Conditional) */}
              {!billingSameAsShipping && (
                <div className="animate-fade-in-up">
                  <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3">SELECT BILLING ADDRESS</h3>
                  <div className="flex flex-col gap-4">
                    {addresses.map(addr => (
                      <div
                        key={`bill-${addr.address_id}`}
                        onClick={() => setBillingAddressId(addr.address_id)}
                        className={`p-5 rounded-2.5xl border-2 cursor-pointer transition-all flex items-start gap-4 ${billingAddressId === addr.address_id
                          ? "border-primary bg-primary/5 shadow-sm"
                          : "border-gray-200/70 bg-white hover:border-gray-300"
                          }`}
                      >
                        <div className="pt-1">
                          <div className={`w-5 h-5 rounded-full border flex items-center justify-center transition-colors ${billingAddressId === addr.address_id ? "border-primary bg-primary" : "border-gray-300 bg-white"
                            }`}>
                            {billingAddressId === addr.address_id && <div className="w-2 h-2 rounded-full bg-white" />}
                          </div>
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <span className="text-[9px] font-black tracking-widest uppercase bg-slate-105 text-slate-700 px-2 py-0.5 rounded">
                              {addr.is_business_address ? "BUSINESS" : (addr.address_type ? addr.address_type.toUpperCase() : "BILLING")}
                            </span>
                            <h3 className="font-extrabold text-gray-800 text-[14px]">{addr.business_name}</h3>
                          </div>
                          <p className="text-xs font-semibold text-gray-555 mb-1 leading-relaxed">{addr.address_line}</p>
                          <p className="text-xs font-semibold text-gray-555 leading-relaxed">{addr.city}, {addr.state} — {addr.pincode}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          <button
            onClick={() => setStep(2)}
            disabled={!shippingAddressId || (!billingSameAsShipping && !billingAddressId)}
            className="w-full bg-slate-900 hover:bg-slate-800 text-white h-14 rounded-2xl font-black text-xs tracking-widest uppercase transition-all flex items-center justify-center gap-2 disabled:opacity-50 active:scale-98 shadow-md mt-4"
          >
            Continue to Order Summary <FaArrowRight className="text-[10px]" />
          </button>
        </div>
      )}

      {/* ── STEP 2: ORDER SUMMARY ── */}
      {step === 2 && (
        <div className="max-w-2xl mx-auto bg-white rounded-[2.5rem] border border-gray-200/60 shadow-[0_8px_30px_rgba(0,0,0,0.02)] overflow-hidden animate-fade-in">
          {/* Header */}
          <div className="px-6 pt-6 pb-4 border-b border-gray-100">
            <div className="text-[10px] font-black text-primary uppercase tracking-widest mb-1">Step 2 of 3</div>
            <h2 className="text-xl font-black text-gray-900 uppercase tracking-tight">Order Summary</h2>
          </div>

          {/* Simple Invoice Items List */}
          <div className="px-6 py-4">
            <div className="max-h-[28rem] overflow-y-auto custom-scrollbar flex flex-col gap-1 pr-1">
              {displayItems.map((item, idx) => (
                <div key={idx} className="flex justify-between items-center py-3 border-b border-gray-100 last:border-0 text-xs text-gray-800">
                  <div className="flex items-center gap-3 flex-1 pr-4">
                    {/* Image */}
                    <div className="w-12 h-12 shrink-0 bg-gray-50/80 rounded-lg flex items-center justify-center overflow-hidden border border-gray-100 p-0.5">
                      <img 
                        src={`${API_BASE_URL || ''}${item.image}`} 
                        alt={item.name} 
                        className="w-full h-full object-contain mix-blend-multiply"
                        onError={(e) => {
                          (e.target as HTMLImageElement).src = "https://static.wixstatic.com/media/703249_3a76a53b765e46d4b3a5e4c3ec6ddd7e~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/Full%20Face%20Helmet.png";
                        }}
                      />
                    </div>
                    <div>
                      <span className="font-extrabold block text-gray-900 leading-snug">{item.name}</span>
                      <span className="text-[10px] text-gray-400 font-bold block mt-0.5">SKU: {item.sku_no} • PRICE: {formatPrice(item.dealer_price, item.currency)}</span>
                    </div>
                  </div>
                  <div className="w-16 text-center shrink-0">
                    <span className="text-gray-400 font-bold block text-[9px] uppercase tracking-wider mb-0.5">Qty</span>
                    <span className="font-black text-gray-900 text-sm">{item.quantity}</span>
                  </div>
                  <div className="w-24 text-right shrink-0">
                    <span className="text-gray-400 font-bold block text-[9px] uppercase tracking-wider mb-0.5">Subtotal</span>
                    <span className="font-black text-gray-900 text-sm tabular-nums">{formatPrice(item.subtotal, item.currency)}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Summary Footer */}
          <div className="border-t border-gray-200 bg-gray-50/60">
            {/* Total quantity */}
            <div className="flex justify-between items-center px-6 py-3 border-b border-gray-100">
              <span className="text-[11px] font-bold text-gray-600 uppercase tracking-wider">Total quantity</span>
              <span className="text-[12px] font-black text-gray-900 tabular-nums">{totalItems}</span>
            </div>
            {/* Subtotal */}
            <div className="flex justify-between items-center px-6 py-3.5">
              <span className="text-[11px] font-black text-gray-800 uppercase tracking-wider">Subtotal</span>
              <span className="text-lg font-black text-gray-900 tabular-nums">
                {formatPrice(subtotal, displayItems?.[0]?.currency)}
              </span>
            </div>
          </div>

          {/* Action Row */}
          <div className="flex gap-3 px-6 pb-6 pt-4">
            <button
              onClick={() => setStep(1)}
              className="flex-grow bg-gray-50 hover:bg-gray-105 text-gray-505 h-12 rounded-2xl font-bold text-xs uppercase tracking-wider border border-gray-200/60 transition-all flex items-center justify-center gap-1.5"
            >
              <FaArrowLeft className="text-[9px]" /> Back to Address
            </button>
            <button
              onClick={() => setStep(3)}
              className="flex-grow bg-slate-900 hover:bg-slate-800 text-white h-12 rounded-2xl font-black text-xs tracking-widest uppercase transition-all flex items-center justify-center gap-2 shadow-md"
            >
              Proceed to Payment <FaArrowRight className="text-[10px]" />
            </button>
          </div>
        </div>
      )}


      {/* ── STEP 3: PAYMENT & REWARDS ── */}
      {step === 3 && (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start max-w-5xl mx-auto animate-fade-in text-slate-800">

          {/* Left Column: Compact Payment Details & Coupon Form */}
          <div className="lg:col-span-7 bg-white rounded-[2.5rem] border border-gray-200/60 shadow-[0_8px_30px_rgba(0,0,0,0.02)] p-6 flex flex-col gap-5">
            <div>
              <div className="text-[10px] font-black text-primary uppercase tracking-widest mb-0.5">Step 3 of 3</div>
              <h2 className="text-lg font-black text-gray-900 uppercase tracking-tight">Payment Details</h2>
            </div>

            {/* Select Payment Method */}
            <div className="flex flex-col gap-3">
              <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Select Payment Method</span>
              <div className="grid grid-cols-2 gap-3">
                {/* Option 1: Card Method (Locked) */}
                <div
                  className="p-3.5 rounded-xl border border-gray-105 bg-gray-50/50 cursor-not-allowed flex flex-col items-center justify-center text-center gap-1.5 opacity-60 select-none relative"
                  title="Card payments are locked. Please use B2B Credit Limit."
                >
                  <div className="absolute top-1 right-1 text-[8px]">🔒</div>
                  <FaCreditCard className="text-base text-gray-400" />
                  <span className="text-[10px] font-black text-gray-400">Debit / Card</span>
                </div>

                {/* Option 2: Active B2B Credit Limit */}
                <div
                  onClick={() => { setPaymentType("credit"); setPaymentSubMethod("bank"); }}
                  className={`p-3.5 rounded-xl border-2 cursor-pointer transition-all flex flex-col items-center justify-center text-center gap-1.5 ${paymentType === "credit"
                    ? "border-primary bg-primary/5 shadow-sm"
                    : "border-gray-200/70 bg-white hover:border-gray-300"
                    }`}
                >
                  <FaUniversity className={`text-base ${paymentType === "credit" ? "text-primary" : "text-gray-400"}`} />
                  <span className="text-[10px] font-black text-gray-800">B2B Credit Limit</span>
                </div>
              </div>

              {paymentType === "credit" && (
                <div className="mt-3.5 space-y-2">
                  {credit && (
                    <div className="bg-white rounded-2xl p-4 text-slate-800 flex flex-col gap-3 shadow-md border border-gray-200/85 animate-fade-in-up select-none">
                      <div className="flex justify-between items-center border-b border-gray-100 pb-2">
                        <span className="text-[8.5px] font-black text-slate-700 uppercase tracking-widest">Available Credit Facility</span>
                        <span className="text-[8px] font-black text-slate-805 bg-[#FFC633] px-2 py-0.5 rounded-full uppercase tracking-wider">⚡ Approved B2B</span>
                      </div>
                      <div className="grid grid-cols-2 gap-2">
                        <div className="bg-gray-50/50 border border-gray-200/60 rounded-xl p-2.5 flex flex-col">
                          <span className="text-[7.5px] text-gray-400 font-extrabold uppercase tracking-widest">Overall Ceiling</span>
                          <span className="text-xs font-black text-slate-800 mt-0.5">
                            {credit.overall_credit_limit !== null && credit.overall_credit_limit !== undefined ? (
                              `$${Math.round(credit.overall_credit_limit).toLocaleString("en-IN")}`
                            ) : (
                              "Unlimited"
                            )}
                          </span>
                        </div>
                        <div className="bg-gray-50/50 border border-gray-200/60 rounded-xl p-2.5 flex flex-col">
                          <span className="text-[7.5px] text-gray-400 font-extrabold uppercase tracking-widest">Single Order Cap</span>
                          <span className="text-xs font-black text-slate-800 mt-0.5">
                            {credit.order_credit_limit !== null && credit.order_credit_limit !== undefined ? (
                              `$${Math.round(credit.order_credit_limit).toLocaleString("en-IN")}`
                            ) : (
                              "No Limit"
                            )}
                          </span>
                        </div>
                        <div className="bg-rose-50 border border-rose-100 rounded-xl p-2.5 flex flex-col">
                          <span className="text-[7.5px] text-rose-500 font-extrabold uppercase tracking-widest">Outstanding</span>
                          <span className="text-xs font-black text-rose-600 mt-0.5">
                            ${Math.round(credit.outstanding_amount).toLocaleString("en-IN")}
                          </span>
                        </div>
                        <div className="bg-[#FFC633]/10 border border-[#FFC633]/30 rounded-xl p-2.5 flex flex-col">
                          <span className="text-[7.5px] text-slate-855 font-extrabold uppercase tracking-widest">Remaining</span>
                          <span className="text-xs font-black text-slate-900 mt-0.5">
                            {credit.remaining_credit !== null && credit.remaining_credit !== undefined ? (
                              `$${Math.round(credit.remaining_credit).toLocaleString("en-IN")}`
                            ) : (
                              "Unlimited"
                            )}
                          </span>
                        </div>
                      </div>
                    </div>
                  )}
                  <p className="text-[10px] text-gray-550 font-bold leading-relaxed pl-0.5">
                    * Debited directly from your active B2B wholesale credit ceiling. Payments are due within your agreed billing lifecycle.
                  </p>
                </div>
              )}
            </div>
            <div className="border-t border-gray-100 my-0.5" />
            <div className="bg-blue-50/5 border border-gray-200/50 rounded-2xl p-3.5 flex flex-col gap-3">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-1.5">
                  <span className="text-[10px] font-black text-gray-550 uppercase tracking-wide">Promo Code</span>
                  {coupons.length > 0 && !appliedCoupon && (
                    <button
                      onClick={() => setShowCouponsDropdown(true)}
                      className="text-[9.5px] font-black text-primary hover:text-primary-dark transition-colors uppercase tracking-wider select-none px-1.5 py-0.5 bg-primary/5 rounded border border-primary/10"
                    >
                      Get Code
                    </button>
                  )}
                </div>
                {appliedCoupon && (
                  <span className="text-[9.5px] font-black text-emerald-600 uppercase">✓ Coupon &apos;{appliedCoupon}&apos; Applied</span>
                )}
              </div>
              <div className="flex gap-2">
                <input
                  type="text"
                  placeholder="ENTER COUPON CODE"
                  value={couponCode}
                  onChange={e => { setCouponCode(e.target.value.toUpperCase()); setCouponError(""); }}
                  disabled={!!appliedCoupon}
                  className="flex-grow bg-white border border-dashed border-gray-300 rounded-xl px-3 py-2.5 text-xs font-bold text-gray-800 placeholder-gray-400 focus:outline-none focus:border-primary transition-colors uppercase tracking-wider"
                />
                {appliedCoupon ? (
                  <button onClick={removeCoupon} className="px-4 py-2.5 bg-red-50 hover:bg-red-100 text-red-600 font-extrabold text-xs rounded-xl transition-all uppercase">
                    Remove
                  </button>
                ) : (
                  <button onClick={applyCoupon} disabled={!couponCode} className="px-4 py-2.5 bg-gray-150 hover:bg-gray-200 text-gray-700 font-extrabold text-xs rounded-xl transition-all disabled:opacity-50 uppercase">
                    Apply
                  </button>
                )}
              </div>

              {couponError && (
                <div className="text-[10.5px] font-bold text-red-600 bg-red-50 border border-red-100 px-3 py-1.5 rounded-lg text-left">
                  ✕ {couponError}
                </div>
              )}
            </div>
          </div>

          {/* Right Column: Billing Breakdown & SuperCoins */}
          <div className="lg:col-span-5 bg-white border border-gray-200/60 rounded-[2.5rem] p-6 shadow-[0_8px_30px_rgba(0,0,0,0.02)] flex flex-col gap-4">
            <h3 className="text-xs font-black text-gray-400 uppercase tracking-widest border-b border-gray-100 pb-3">
              Billing Breakdown
            </h3>

            {/* Horizontal SuperCoins Row inside Billing Breakdown (Moved here!) */}
            {wallet && coinConfig?.is_active && (
              <div className="bg-amber-50/15 border border-amber-100/70 rounded-2xl p-3.5 flex items-center justify-between gap-3">
                <div className="flex items-center gap-2.5">
                  <div className="w-8 h-8 rounded-full bg-[#FFC633] text-[#121212] flex items-center justify-center text-sm font-black shadow-sm">
                    ⚡
                  </div>
                  <div className="text-left">
                    <span className="block text-xs font-black text-gray-800">
                      ⚡ {Math.floor(wallet.coin_balance).toLocaleString("en-IN")} SuperCoins
                    </span>
                    <span className="block text-[9.5px] text-slate-600 font-bold mt-0.5">
                      Redeem for instant savings
                    </span>
                  </div>
                </div>

                <div>
                  {useCoinsToggle ? (
                    <div className="flex items-center gap-2">
                      <span className="text-[10px] font-black text-emerald-600 bg-emerald-50 px-2 py-1 rounded-lg">
                        −{formatPrice(maxRedeemable * (coinConfig?.coin_to_inr ?? 1), displayItems?.[0]?.currency)}
                      </span>
                      <button
                        onClick={() => toggleSuperCoins(false)}
                        className="text-[10px] font-black text-red-500 hover:text-red-700 px-2 py-1 transition-colors"
                      >
                        Remove
                      </button>
                    </div>
                  ) : (
                    <button
                      onClick={() => toggleSuperCoins(true)}
                      disabled={maxRedeemable <= 0}
                      className="px-3.5 py-1.5 bg-primary hover:bg-primary-dark disabled:opacity-50 text-white font-black text-[10px] rounded-lg shadow-sm transition-all uppercase tracking-wide"
                    >
                      Apply
                    </button>
                  )}
                </div>
              </div>
            )}

            {/* Pricing details */}
            <div className="flex flex-col gap-3 pt-2">
              <div className="flex justify-between items-center text-xs font-semibold text-gray-500">
                <span>Subtotal ({totalItems} items)</span>
                <span>{formatPrice(subtotal, displayItems?.[0]?.currency)}</span>
              </div>

              {discount > 0 && (
                <div className="flex justify-between items-center text-xs font-bold text-emerald-605">
                  <span>Coupon discount</span>
                  <span>−{formatPrice(discount, displayItems?.[0]?.currency)}</span>
                </div>
              )}

              {coinDiscount > 0 && (
                <div className="flex justify-between items-center text-xs font-bold text-primary">
                  <span>⚡ SuperCoins Applied</span>
                  <span>−{formatPrice(coinDiscount, displayItems?.[0]?.currency)}</span>
                </div>
              )}

              <div className="border-t border-dashed border-gray-200 my-1" />

              <div className="flex justify-between items-baseline">
                <span className="text-xs font-extrabold text-gray-700 uppercase tracking-wider">Total Payable</span>
                <span className="text-xl font-black text-gray-900">
                  {formatPrice(totalPrice, displayItems?.[0]?.currency)}
                </span>
              </div>
            </div>

            {potentialCoins > 0 && (
              <div className="bg-amber-50/50 border border-amber-100 rounded-xl p-3 flex items-center justify-between gap-3 select-none">
                <div className="flex items-center gap-2">
                  <span className="text-xs">⚡</span>
                  <span className="text-[10px] font-black text-amber-800 uppercase tracking-wider">SuperCoins to earn: </span>
                </div>
                <span className="text-xs font-black text-amber-600">+{potentialCoins.toLocaleString("en-IN")}</span>
              </div>
            )}

            {/* Action buttons stacked for vertical sidebar flow */}
            <div className="flex flex-col gap-2 pt-2 border-t border-gray-100">
              <button
                onClick={placeOrder}
                disabled={placingOrder || addresses.length === 0 || !shippingAddressId || summaryLoading}
                className="w-full bg-slate-900 hover:bg-slate-800 text-white h-13 rounded-xl font-black text-xs tracking-widest uppercase transition-all flex items-center justify-center gap-2 disabled:opacity-50 active:scale-98 shadow-md"
              >
                {placingOrder ? "Placing Order…" : "Order Now"}
              </button>

              <button
                onClick={() => setStep(2)}
                className="w-full bg-gray-50 hover:bg-gray-105 text-gray-505 h-11 rounded-xl font-bold text-xs uppercase tracking-wider border border-gray-250/60 transition-all flex items-center justify-center gap-1.5"
              >
                <FaArrowLeft className="text-[9px]" /> Back to Order Summary
              </button>
            </div>
          </div>

        </div>
      )}
      <>
        {showCouponsDropdown && (
          <div
            onClick={() => setShowCouponsDropdown(false)}
            className="fixed inset-0 bg-black/45 z-[200] transition-opacity duration-300 backdrop-blur-sm"
          />
        )}
        <div
          className={`fixed top-0 right-0 h-full w-96 max-w-[85vw] bg-white z-[210] flex flex-col shadow-[0_0_50px_rgba(0,0,0,0.1)] transition-transform duration-300 ease-out ${showCouponsDropdown ? "translate-x-0" : "translate-x-full"
            }`}
        >
          <div className="flex items-center justify-between px-6 py-5 border-b border-gray-100 select-none">
            <div>
              <h3 className="text-sm font-black text-gray-900 uppercase tracking-wider text-left">Available Coupons</h3>
              <p className="text-[9px] text-gray-400 font-bold uppercase tracking-widest mt-0.5 text-left">{coupons.length} Active Offers</p>
            </div>
            <button
              onClick={() => setShowCouponsDropdown(false)}
              className="w-8 h-8 rounded-full bg-gray-50 hover:bg-gray-100 flex items-center justify-center text-gray-400 hover:text-gray-700 transition-colors text-sm font-light"
            >
              ✕
            </button>
          </div>

          {/* Body */}
          <div className="flex-1 overflow-y-auto p-6 flex flex-col gap-4 custom-scrollbar">
            {coupons.map((coupon, idx) => (
              <div
                key={idx}
                onClick={() => {
                  setCouponCode(coupon.coupon_code);
                  setAppliedCoupon(coupon.coupon_code);
                  setShowCouponsDropdown(false);
                  setCouponError("");
                }}
                className="group border border-gray-200/80 hover:border-primary rounded-2xl p-4 flex flex-col gap-3 cursor-pointer transition-all bg-white hover:bg-primary/5 active:scale-[0.98] select-none text-left"
              >
                <div className="flex justify-between items-center">
                  <span className="text-xs font-black text-primary uppercase bg-primary/5 border border-primary/10 px-2.5 py-1 rounded-lg tracking-wider">
                    {coupon.coupon_code}
                  </span>
                  <span className="text-[10px] font-black text-primary uppercase tracking-wider group-hover:underline">
                    Apply
                  </span>
                </div>
                {coupon.description && (
                  <p className="text-xs text-gray-505 font-semibold leading-relaxed">
                    {coupon.description}
                  </p>
                )}
                <div className="border-t border-dashed border-gray-100 pt-2 flex items-center justify-between text-[9px] text-gray-405 font-bold uppercase tracking-wider">
                  <span>Wholesale Exclusive</span>
                  <span>Active Offer</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </>

      {/* ── Checkout Error Modal ── */}
      <>
        <div
          onClick={() => setShowErrorModal(false)}
          className={`fixed inset-0 bg-black/45 z-[200] transition-opacity duration-350 backdrop-blur-sm ${showErrorModal ? "opacity-100 visible" : "opacity-0 invisible pointer-events-none"}`}
        />
        <div className={`fixed inset-0 flex items-center justify-center z-[210] p-4 transition-all duration-350 ${showErrorModal ? "opacity-100 scale-100 visible" : "opacity-0 scale-95 invisible pointer-events-none"}`}>
          <div className="bg-white rounded-3xl w-full max-w-[340px] p-8 shadow-[0_15px_40px_rgba(0,0,0,0.15)] flex flex-col items-center text-center gap-6 relative overflow-hidden">

            {/* Top accent red line from mockup */}
            <div className="absolute top-0 left-0 right-0 h-1.5 bg-[#FF4D4D]" />

            {/* Error Cross Circle */}
            <div className="w-20 h-20 rounded-full border-4 border-[#FF4D4D] flex items-center justify-center mt-2 select-none">
              <span className="text-[#FF4D4D] text-4xl font-light leading-none">✕</span>
            </div>

            {/* Title & Desc */}
            <div className="flex flex-col gap-2">
              <h3 className="text-[#FF4D4D] text-2xl font-extrabold tracking-tight">Error</h3>
              {checkoutErrorCode && (
                <div className="text-[10px] font-black tracking-widest uppercase bg-red-50 text-[#FF4D4D] border border-red-100/50 px-2.5 py-1 rounded w-fit mx-auto mt-1">
                  Code: {checkoutErrorCode}
                </div>
              )}
              <p className="text-gray-550 font-bold text-xs leading-relaxed max-w-[240px] mt-2">
                {checkoutErrorMsg || "Something Went Wrong, Please Try Again"}
              </p>
            </div>

            {/* Action pill button */}
            <button
              onClick={() => {
                setShowErrorModal(false);
              }}
              className="w-full bg-[#FF4D4D] hover:bg-[#E63939] text-white font-black text-xs tracking-wider uppercase py-4 rounded-full shadow-md shadow-red-100 transition-all active:scale-95 mt-2"
            >
              Okay
            </button>

          </div>
        </div>
      </>

      {/* ── Premium Floating Toast Alerts ── */}
      <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[300] flex flex-col gap-3 w-full max-w-sm px-4 pointer-events-none">
        {couponSuccessToast && (
          <div className="bg-emerald-600/95 backdrop-blur-md text-white px-4 py-3 rounded-2xl shadow-[0_10px_30px_rgba(16,185,129,0.3)] flex items-center gap-3 animate-slide-in pointer-events-auto border border-emerald-500/30">
            <div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center text-xs font-black">
              ✓
            </div>
            <div className="flex-1 text-left">
              <p className="text-xs font-black uppercase tracking-wider">Success</p>
              <p className="text-[11px] font-bold opacity-90 mt-0.5">{couponSuccessToast}</p>
            </div>
            <button
              onClick={() => setCouponSuccessToast("")}
              className="text-white/60 hover:text-white text-xs font-bold px-1"
            >
              ✕
            </button>
          </div>
        )}

        {coinSuccessToast && (
          <div className="bg-amber-500/95 backdrop-blur-md text-white px-4 py-3 rounded-2xl shadow-[0_10px_30px_rgba(245,158,11,0.3)] flex items-center gap-3 animate-slide-in pointer-events-auto border border-amber-400/30">
            <div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center text-xs font-black">
              ⚡
            </div>
            <div className="flex-1 text-left">
              <p className="text-xs font-black uppercase tracking-wider">SuperCoins Applied</p>
              <p className="text-[11px] font-bold opacity-90 mt-0.5">{coinSuccessToast}</p>
            </div>
            <button
              onClick={() => setCoinSuccessToast("")}
              className="text-white/60 hover:text-white text-xs font-bold px-1"
            >
              ✕
            </button>
          </div>
        )}

        {couponError && (
          <div className="bg-rose-605/95 backdrop-blur-md text-white px-4 py-3 rounded-2xl shadow-[0_10px_30px_rgba(244,63,94,0.3)] flex items-center gap-3 animate-slide-in pointer-events-auto border border-rose-500/30">
            <div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center text-xs font-black">
              ✕
            </div>
            <div className="flex-1 text-left">
              <p className="text-xs font-black uppercase tracking-wider">Failed</p>
              <p className="text-[11px] font-bold opacity-90 mt-0.5">{couponError}</p>
            </div>
            <button
              onClick={() => setCouponError("")}
              className="text-white/60 hover:text-white text-xs font-bold px-1"
            >
              ✕
            </button>
          </div>
        )}
      </div>
    </div >
  );
}
