"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { ChevronRight, ShoppingBag, Shield, Check, MapPin, CreditCard, Truck, Tag } from "lucide-react";
import { CartItem, getCart, cartTotal, cartCount, clearCart } from "@/lib/cart";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import StripeCheckout from "@/components/StripeCheckout";
import { useCurrency } from "@/providers/CurrencyProvider";
import Swal from "sweetalert2";

const STEPS = ["Shipping", "Payment", "Confirm"];

export default function CheckoutPage() {
  const router = useRouter();
  const { formatPrice, selectedCurrency, convertPrice } = useCurrency();
  const [items, setItems] = useState<CartItem[]>([]);
  const [mounted, setMounted] = useState(false);
  const [promoCode, setPromoCode] = useState("");
  const [discountPercentage, setDiscountPercentage] = useState(0);
  const [step, setStep] = useState(0);
  const [placing, setPlacing] = useState(false);
  const [placed, setPlaced] = useState(false);

  // Loyalty reward points state hooks
  const [availablePoints, setAvailablePoints] = useState(0);
  const [redeemInput, setRedeemInput] = useState("");
  const [pointsRedeemedApplied, setPointsRedeemedApplied] = useState(false);
  const [pointsRedeemed, setPointsRedeemed] = useState(0);

  const [pointValue, setPointValue] = useState(1);
  const [pointEarnRate, setPointEarnRate] = useState(10);
  const [shippingFee, setShippingFee] = useState(0);
  const [shippingFreeThreshold, setShippingFreeThreshold] = useState(1000);
  const [shippingEnabled, setShippingEnabled] = useState(true);
  
  const [paymentMethods, setPaymentMethods] = useState({
    cod: true,
    card: true,
    bkash: true,
    nagad: true,
  });

  const [form, setForm] = useState({
    fullName: "", email: "", phone: "",
    address: "", city: "", area: "", postalCode: "",
    paymentMethod: "cod",
    cardNumber: "", cardExpiry: "", cardCVC: "",
    bkashNumber: "", nagadNumber: "",
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    setItems(getCart());
    const savedPromo = localStorage.getItem("ag_promo");
    if (savedPromo) {
      try {
        const { code, percentage } = JSON.parse(savedPromo);
        if (code && percentage) {
          setPromoCode(code);
          setDiscountPercentage(percentage);
        }
      } catch (e) {}
    }
    
    fetch("/api/settings")
      .then((res) => res.json())
      .then((data) => {
        if (data) {
          if (data.reward_point_value) setPointValue(Number(data.reward_point_value));
          if (data.reward_point_earn_rate) setPointEarnRate(Number(data.reward_point_earn_rate));

          const pMethods = {
            cod: data.payment_cod_enabled !== "false",
            card: data.payment_stripe_enabled !== "false",
            bkash: data.payment_bkash_enabled !== "false",
            nagad: data.payment_nagad_enabled !== "false",
          };
          setPaymentMethods(pMethods);

          // If current selected method is disabled, select the first enabled one
          const methodEntries = Object.entries(pMethods);
          const firstAvailable = methodEntries.find(([_, enabled]) => enabled)?.[0] || "cod";
          setForm(f => ({ ...f, paymentMethod: pMethods[f.paymentMethod as keyof typeof pMethods] ? f.paymentMethod : firstAvailable }));

          // Shipping settings are now in the same public API call
          const enabled = data.shipping_enabled !== "false";
          const flatRate = Number(data.shipping_flat_rate || 10);
          const freeThreshold = Number(data.shipping_free_threshold || 150);
          setShippingEnabled(enabled);
          setShippingFreeThreshold(freeThreshold);
          if (enabled) setShippingFee(flatRate);
        }
      })
      .catch((err) => console.error("Failed to load settings", err));

    setMounted(true);
  }, []);

  const subtotal = cartTotal(items);
  const discountAmount = Math.round(subtotal * (discountPercentage / 100));
  const pointsDiscount = pointsRedeemedApplied ? pointsRedeemed * pointValue : 0;
  const preTaxAmount = Math.max(0, subtotal - discountAmount - pointsDiscount);
  const tax = preTaxAmount * 0.05; // 5% Standard Tax

  const effectiveShippingFee = shippingEnabled
    ? (shippingFreeThreshold > 0 && (subtotal - discountAmount) >= shippingFreeThreshold ? 0 : shippingFee)
    : 0;
  const shipping = effectiveShippingFee;
  const total = preTaxAmount + tax + shipping;
  const count = cartCount(items);

  const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) =>
    setForm((f) => ({ ...f, [k]: e.target.value }));

  const handlePlaceOrder = async (paymentIntentId?: string) => {
    setPlacing(true);
    try {
      const payload = {
        fullName: form.fullName,
        email: form.email,
        phone: form.phone,
        address: `${form.address}, ${form.area}, ${form.city} ${form.postalCode}`,
        paymentMethod: form.paymentMethod,
        totalAmount: total,
        tax: tax,
        shipping: shipping,
        promoCode: promoCode || undefined,
        items: items.map((item) => ({
          productId: item.productId,
          color: item.color,
          size: item.size,
          length: item.length,
          price: item.price,
          quantity: item.quantity,
          title: item.title,
        })),
        paymentDetails: {
          bkashNumber: form.bkashNumber,
          nagadNumber: form.nagadNumber,
          cardNumber: form.paymentMethod === "card" ? "Stripe Payment" : "",
          paymentIntentId: paymentIntentId || undefined,
        },
        pointsRedeemed: pointsRedeemedApplied ? pointsRedeemed : 0,
      };

      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const errorData = await res.json();
        throw new Error(errorData.message || "Failed to place order");
      }

      clearCart();
      setPlaced(true);
    } catch (err: any) {
      console.error(err);
      Swal.fire({ text: err.message || "Failed to place your order. Please try again.", confirmButtonColor: "#18181b", icon: "error" });
    } finally {
      setPlacing(false);
    }
  };


  if (!mounted) {
    return <div className="min-h-screen bg-white flex items-center justify-center"><div className="w-8 h-8 border-2 border-zinc-200 border-t-zinc-950 rounded-full animate-spin" /></div>;
  }

  if (items.length === 0 && !placed) {
    return (
      <div className="min-h-screen bg-zinc-50 flex flex-col items-center justify-center gap-6 px-6 text-center">
        <ShoppingBag className="w-14 h-14 text-zinc-300" />
        <h2 className="text-2xl font-black uppercase tracking-tight">Your cart is empty</h2>
        <Link href="/shop" className="bg-zinc-950 text-white px-10 py-4 text-xs font-bold tracking-widest uppercase hover:bg-zinc-800 transition-colors">
          Shop Now
        </Link>
      </div>
    );
  }

  // ORDER PLACED SUCCESS
  if (placed) {
    return (
      <div className="min-h-screen bg-zinc-50 flex flex-col items-center justify-center gap-8 px-6 text-center">
        <div className="w-24 h-24 rounded-full bg-zinc-950 flex items-center justify-center ring-8 ring-zinc-100 animate-bounce">
          <Check className="w-10 h-10 text-white" />
        </div>
        <div>
          <h1 className="text-3xl sm:text-4xl font-extrabold uppercase tracking-tight mb-3">Order Confirmed!</h1>
          <p className="text-zinc-400 text-sm font-light max-w-md mx-auto">
            Thank you, <strong className="text-zinc-700">{form.fullName || "valued customer"}</strong>! Your order has been placed successfully.
            You'll receive a confirmation at <strong className="text-zinc-700">{form.email || "your email"}</strong>.
          </p>
        </div>
        <div className="bg-white border border-zinc-100 px-8 py-6 max-w-sm w-full">
          <div className="flex justify-between text-xs mb-2 text-zinc-500"><span>Order Total</span><span className="font-black text-zinc-950">{formatPrice(total)}</span></div>
          <div className="flex justify-between text-xs text-zinc-500"><span>Payment</span><span className="font-bold text-zinc-700 uppercase">{form.paymentMethod === "cod" ? "Cash on Delivery" : form.paymentMethod === "card" ? "Credit / Debit Card" : form.paymentMethod}</span></div>
        </div>
        <div className="flex gap-4">
          <Link href="/" className="border border-zinc-950 text-zinc-950 px-8 py-3 text-xs font-bold tracking-widest uppercase hover:bg-zinc-50 transition-colors">Back to Home</Link>
          <Link href="/shop" className="bg-zinc-950 text-white px-8 py-3 text-xs font-bold tracking-widest uppercase hover:bg-zinc-800 transition-colors">Continue Shopping</Link>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col min-h-screen bg-zinc-50 text-zinc-950 font-sans antialiased">

      <Header />

      {/* STEPPER */}
      <div className="bg-white border-b border-zinc-100">
        <div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-center gap-0">
          {STEPS.map((s, i) => (
            <div key={s} className="flex items-center">
              <button
                onClick={() => i < step && setStep(i)}
                className={`flex items-center gap-2 text-[10px] font-bold uppercase tracking-widest transition-colors ${i === step ? "text-zinc-950" : i < step ? "text-zinc-500 cursor-pointer hover:text-zinc-800" : "text-zinc-300 cursor-default"}`}
              >
                <span className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-black border-2 transition-all ${i === step ? "bg-zinc-950 text-white border-zinc-950" : i < step ? "bg-white text-zinc-950 border-zinc-950" : "bg-white text-zinc-300 border-zinc-200"}`}>
                  {i < step ? <Check className="w-3 h-3" /> : i + 1}
                </span>
                <span className="hidden sm:block">{s}</span>
              </button>
              {i < STEPS.length - 1 && <div className={`w-12 sm:w-24 h-px mx-3 transition-colors ${i < step ? "bg-zinc-950" : "bg-zinc-200"}`} />}
            </div>
          ))}
        </div>
      </div>

      <main className="max-w-6xl mx-auto px-4 sm:px-6 py-10 w-full flex-1">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">

          {/* LEFT: FORM STEPS */}
          <div className="lg:col-span-7">

            {/* STEP 0: SHIPPING */}
            {step === 0 && (
              <div className="bg-white border border-zinc-100 p-6 sm:p-8 space-y-6">
                <div className="flex items-center gap-3 mb-2">
                  <MapPin className="w-5 h-5 text-zinc-400" />
                  <h2 className="text-sm font-black uppercase tracking-widest">Shipping Information</h2>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {([
                    { label: "Full Name *", key: "fullName", type: "text", placeholder: "Abdul Mazid", colSpan: true },
                    { label: "Email Address *", key: "email", type: "email", placeholder: "you@example.com", colSpan: false },
                    { label: "Phone Number *", key: "phone", type: "tel", placeholder: "+880 17XX XXXXXX", colSpan: false },
                    { label: "Street Address *", key: "address", type: "text", placeholder: "House no, Road, Area", colSpan: true },
                    { label: "City *", key: "city", type: "text", placeholder: "Dhaka", colSpan: false },
                    { label: "Area / Thana *", key: "area", type: "text", placeholder: "Gulshan", colSpan: false },
                    { label: "Postal Code", key: "postalCode", type: "text", placeholder: "1212", colSpan: false },
                  ] as { label: string; key: keyof typeof form; type: string; placeholder: string; colSpan: boolean }[]).map((f) => (
                    <div key={f.key} className={f.colSpan ? "sm:col-span-2" : ""}>
                      <label className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-1.5 block">{f.label}</label>
                      <input
                        type={f.type}
                        value={form[f.key]}
                        onChange={(e) => {
                          set(f.key)(e);
                          if (errors[f.key]) setErrors((errs) => ({ ...errs, [f.key]: "" }));
                        }}
                        placeholder={f.placeholder}
                        className={`w-full px-4 py-2 text-sm border bg-zinc-50 focus:bg-white focus:outline-none transition-all ${
                          errors[f.key] 
                            ? "border-red-500 focus:border-red-500 focus:ring-1 focus:ring-red-500" 
                            : "border-zinc-200 focus:border-zinc-950 focus:ring-1 focus:ring-zinc-950"
                        }`}
                      />
                      {errors[f.key] && (
                        <p className="text-red-500 text-[10px] mt-1 uppercase font-bold tracking-wider">{errors[f.key]}</p>
                      )}
                    </div>
                  ))}
                </div>

                <button
                  onClick={async () => {
                    const newErrors: Record<string, string> = {};
                    if (!form.fullName) newErrors.fullName = "Full Name is required";
                    if (!form.email) newErrors.email = "Email Address is required";
                    if (!form.phone) newErrors.phone = "Phone Number is required";
                    if (!form.address) newErrors.address = "Street Address is required";
                    if (!form.city) newErrors.city = "City is required";
                    if (!form.area) newErrors.area = "Area / Thana is required";

                    setErrors(newErrors);

                    if (Object.keys(newErrors).length > 0) {
                      return;
                    }

                    // Fetch reward points balance for returning customer
                    try {
                      const res = await fetch(`/api/customer/reward-points?email=${encodeURIComponent(form.email)}`);
                      if (res.ok) {
                        const data = await res.json();
                        setAvailablePoints(data.rewardPoints || 0);
                      }
                    } catch (err) {
                      console.error("Error fetching reward points:", err);
                    }

                    setStep(1);
                  }}
                  className="w-full bg-zinc-950 text-white py-4 text-xs font-black tracking-widest uppercase hover:bg-zinc-800 transition-colors flex items-center justify-center gap-2"
                >
                  Continue to Payment <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            )}

            {/* STEP 1: PAYMENT */}
            {step === 1 && (
              <div className="bg-white border border-zinc-100 p-6 sm:p-8 space-y-6">
                <div className="flex items-center gap-3 mb-2">
                  <CreditCard className="w-5 h-5 text-zinc-400" />
                  <h2 className="text-sm font-black uppercase tracking-widest">Payment Method</h2>
                </div>

                {/* Payment options */}
                {[
                  { value: "cod", label: "Cash on Delivery", desc: "Pay when your order arrives", enabled: paymentMethods.cod },
                  { value: "card", label: "Credit / Debit Card", desc: "Visa, Mastercard, Amex", enabled: paymentMethods.card },
                  { value: "bkash", label: "bKash", desc: "Send to merchant number", enabled: paymentMethods.bkash },
                  { value: "nagad", label: "Nagad", desc: "Pay via Nagad account", enabled: paymentMethods.nagad },
                ].filter(opt => opt.enabled).map((opt) => (
                  <label
                    key={opt.value}
                    className={`flex items-start gap-4 p-4 border-2 cursor-pointer transition-all ${form.paymentMethod === opt.value ? "border-zinc-950 bg-zinc-50" : "border-zinc-100 hover:border-zinc-300"}`}
                  >
                    <input type="radio" name="paymentMethod" value={opt.value} checked={form.paymentMethod === opt.value} onChange={set("paymentMethod")} className="mt-0.5" />
                    <div>
                      <p className="text-xs font-black uppercase tracking-wider text-zinc-900">{opt.label}</p>
                      <p className="text-[10px] text-zinc-400 font-light mt-0.5">{opt.desc}</p>
                    </div>
                  </label>
                ))}

                {/* Card fields */}
                {form.paymentMethod === "card" && (
                  <div className="pt-2 text-xs text-zinc-500">
                    <p>You will enter your card details securely via Stripe in the next step.</p>
                  </div>
                )}

                {form.paymentMethod === "bkash" && (
                  <div>
                    <label className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-1.5 block">bKash Number *</label>
                    <input 
                      type="tel" 
                      value={form.bkashNumber} 
                      onChange={(e) => {
                        set("bkashNumber")(e);
                        if (errors.bkashNumber) setErrors((errs) => ({ ...errs, bkashNumber: "" }));
                      }} 
                      placeholder="+880 1XXXXXXXXX" 
                      className={`w-full px-4 py-2 text-sm border bg-zinc-50 focus:bg-white focus:outline-none transition-all ${
                        errors.bkashNumber 
                          ? "border-red-500 focus:border-red-500 focus:ring-1 focus:ring-red-500" 
                          : "border-zinc-200 focus:border-zinc-950 focus:ring-1 focus:ring-zinc-950"
                      }`}
                    />
                    {errors.bkashNumber && (
                      <p className="text-red-500 text-[10px] mt-1 uppercase font-bold tracking-wider">{errors.bkashNumber}</p>
                    )}
                  </div>
                )}

                {form.paymentMethod === "nagad" && (
                  <div>
                    <label className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-1.5 block">Nagad Number *</label>
                    <input 
                      type="tel" 
                      value={form.nagadNumber} 
                      onChange={(e) => {
                        set("nagadNumber")(e);
                        if (errors.nagadNumber) setErrors((errs) => ({ ...errs, nagadNumber: "" }));
                      }} 
                      placeholder="+880 1XXXXXXXXX" 
                      className={`w-full px-4 py-2 text-sm border bg-zinc-50 focus:bg-white focus:outline-none transition-all ${
                        errors.nagadNumber 
                          ? "border-red-500 focus:border-red-500 focus:ring-1 focus:ring-red-500" 
                          : "border-zinc-200 focus:border-zinc-950 focus:ring-1 focus:ring-zinc-950"
                      }`}
                    />
                    {errors.nagadNumber && (
                      <p className="text-red-500 text-[10px] mt-1 uppercase font-bold tracking-wider">{errors.nagadNumber}</p>
                    )}
                  </div>
                )}

                <div className="flex gap-3">
                  <button onClick={() => setStep(0)} className="flex-1 border border-zinc-200 py-4 text-xs font-bold tracking-widest uppercase hover:bg-zinc-50 transition-colors">
                    Back
                  </button>
                  <button onClick={() => {
                    const newErrors: Record<string, string> = {};
                    if (form.paymentMethod === "bkash" && !form.bkashNumber) newErrors.bkashNumber = "bKash Number is required";
                    if (form.paymentMethod === "nagad" && !form.nagadNumber) newErrors.nagadNumber = "Nagad Number is required";
                    
                    setErrors(newErrors);
                    if (Object.keys(newErrors).length > 0) return;

                    setStep(2);
                  }} className="flex-[2] bg-zinc-950 text-white py-4 text-xs font-black tracking-widest uppercase hover:bg-zinc-800 transition-colors flex items-center justify-center gap-2">
                    Review Order <ChevronRight className="w-4 h-4" />
                  </button>
                </div>
              </div>
            )}

            {/* STEP 2: CONFIRM */}
            {step === 2 && (
              <div className="bg-white border border-zinc-100 p-6 sm:p-8 space-y-6">
                <h2 className="text-sm font-black uppercase tracking-widest flex items-center gap-2">
                  <Truck className="w-5 h-5 text-zinc-400" /> Review & Confirm
                </h2>

                {/* Shipping summary */}
                <div className="bg-zinc-50 p-4 space-y-1">
                  <p className="text-[10px] font-black uppercase tracking-widest text-zinc-400 mb-2">Shipping To</p>
                  <p className="text-sm font-bold text-zinc-900">{form.fullName}</p>
                  <p className="text-xs text-zinc-500">{form.address}, {form.area}, {form.city} {form.postalCode}</p>
                  <p className="text-xs text-zinc-500">{form.phone} · {form.email}</p>
                </div>

                {/* Payment summary */}
                <div className="bg-zinc-50 p-4">
                  <p className="text-[10px] font-black uppercase tracking-widest text-zinc-400 mb-2">Payment Method</p>
                  <p className="text-sm font-bold text-zinc-900">
                    {form.paymentMethod === "cod" ? "Cash on Delivery" : form.paymentMethod === "card" ? "Credit/Debit Card (Stripe)" : form.paymentMethod === "bkash" ? `bKash — ${form.bkashNumber}` : `Nagad — ${form.nagadNumber}`}
                  </p>
                </div>

                {/* Items list */}
                <div className="space-y-3">
                  <p className="text-[10px] font-black uppercase tracking-widest text-zinc-400">Items ({count})</p>
                  {items.map((item) => (
                    <div key={item.id} className="flex gap-3 items-center">
                      <div className="relative w-12 h-16 bg-zinc-100 border border-zinc-100 flex-shrink-0">
                        <Image src={item.thumbnail} alt={item.title} fill className="object-cover" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-xs font-bold uppercase tracking-wide text-zinc-900 line-clamp-1">{item.title}</p>
                        <p className="text-[10px] text-zinc-400">{item.color} · Size {item.size} {item.length ? `· ${item.length}` : ""} · Qty {item.quantity}</p>
                      </div>
                      <p className="text-xs font-black text-zinc-950 flex-shrink-0">{formatPrice(item.price * item.quantity)}</p>
                    </div>
                  ))}
                </div>

                <div className="flex gap-3 pt-2">
                  <button onClick={() => setStep(1)} className="flex-1 border border-zinc-200 py-4 text-xs font-bold tracking-widest uppercase hover:bg-zinc-50 transition-colors">
                    Back
                  </button>
                  {form.paymentMethod === "card" ? (
                    <div className="flex-[2]">
                       {/* Note: The StripeCheckout component renders its own 'Pay Now' button */}
                    </div>
                  ) : (
                    <button
                      onClick={() => handlePlaceOrder()}
                      disabled={placing}
                      className="flex-[2] bg-zinc-950 text-white py-4 text-xs font-black tracking-widest uppercase hover:bg-zinc-800 disabled:opacity-60 disabled:cursor-wait transition-all flex items-center justify-center gap-2"
                    >
                      {placing ? (
                        <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> Placing Order…</>
                      ) : (
                        <>Place Order · {formatPrice(total)}</>
                      )}
                    </button>
                  )}
                </div>

                {form.paymentMethod === "card" && (
                  <div className="pt-4 border-t border-zinc-100">
                    <StripeCheckout 
                      items={items}
                      email={form.email}
                      pointsRedeemed={pointsRedeemedApplied ? pointsRedeemed : 0}
                      onSuccess={(intentId) => handlePlaceOrder(intentId)}
                      onError={(err) => Swal.fire({ text: err, confirmButtonColor: "#18181b" })}
                    />
                  </div>
                )}
              </div>
            )}
          </div>

          {/* RIGHT: ORDER SUMMARY */}
          <div className="lg:col-span-5 space-y-6">
            <div className="bg-white border border-zinc-100 p-6 sticky top-24 space-y-5">
              <h2 className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Order Summary</h2>
              <div className="space-y-4 max-h-72 overflow-y-auto pr-1">
                {items.map((item) => (
                  <div key={item.id} className="flex gap-3 items-start">
                    <div className="relative flex-shrink-0">
                      <div className="relative w-14 h-20 bg-zinc-100 border border-zinc-100 overflow-hidden">
                        <Image src={item.thumbnail} alt={item.title} fill className="object-cover" />
                      </div>
                      <span className="absolute -top-1.5 -right-1.5 w-5 h-5 bg-zinc-950 text-white text-[9px] font-black rounded-full flex items-center justify-center">{item.quantity}</span>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-bold uppercase tracking-wide text-zinc-900 line-clamp-2 leading-snug">{item.title}</p>
                      <div className="flex justify-between mt-2">
                        <p className="text-xs text-zinc-500 font-medium">Qty: {item.quantity}</p>
                        <p className="text-xs font-black text-zinc-950 flex-shrink-0">{formatPrice(item.price * item.quantity)}</p>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Loyalty Reward Points Redemption Widget */}
              {availablePoints > 0 && (
                <div className="bg-zinc-50 border border-zinc-150 p-4 rounded-sm space-y-2.5">
                  <div className="flex items-center justify-between">
                    <span className="text-[10px] font-black uppercase tracking-wider text-zinc-900 flex items-center gap-1">
                      🌟 Reward Points
                    </span>
                    <span className="text-[10px] font-bold text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-full">
                      {availablePoints} Available
                    </span>
                  </div>
                  {!pointsRedeemedApplied ? (
                    <div className="flex gap-2">
                      <input
                        type="number"
                        min="1"
                        max={availablePoints}
                        value={redeemInput}
                        onChange={(e) => setRedeemInput(e.target.value)}
                        placeholder={`Max ${Math.min(availablePoints, Math.floor((subtotal - discountAmount) / pointValue))}`}
                        className="flex-1 px-3 py-2 text-xs border border-zinc-200 bg-white focus:outline-none focus:border-zinc-950 transition-all placeholder-zinc-350"
                      />
                      <button
                        onClick={() => {
                          const pts = parseInt(redeemInput);
                          if (!pts || pts <= 0) {
                            Swal.fire({ text: "Please enter a valid amount of points to redeem.", confirmButtonColor: "#18181b" });
                            return;
                          }
                          if (pts > availablePoints) {
                            Swal.fire({ text: `You only have ${availablePoints} points available.`, confirmButtonColor: "#18181b" });
                            return;
                          }
                          const maxRedeemable = Math.floor((subtotal - discountAmount) / pointValue);
                          if (pts > maxRedeemable) {
                            Swal.fire({ text: `You can only redeem up to ${maxRedeemable} points for this order.`, confirmButtonColor: "#18181b" });
                            return;
                          }
                          setPointsRedeemed(pts);
                          setPointsRedeemedApplied(true);
                        }}
                        className="bg-zinc-950 hover:bg-zinc-800 text-white text-[10px] font-bold px-4 py-2 uppercase tracking-wider transition-colors rounded-xs"
                      >
                        Redeem
                      </button>
                    </div>
                  ) : (
                    <div className="flex items-center justify-between text-xs bg-emerald-50 text-emerald-800 border border-emerald-100 p-2.5 rounded-xs">
                      <span className="font-semibold">Redeemed {pointsRedeemed} Points</span>
                      <button
                        onClick={() => {
                          setPointsRedeemed(0);
                          setPointsRedeemedApplied(false);
                          setRedeemInput("");
                        }}
                        className="text-emerald-850 hover:text-emerald-950 font-black cursor-pointer ml-2"
                      >
                        ✕
                      </button>
                    </div>
                  )}
                </div>
              )}

              {availablePoints === 0 && form.email && (
                <div className="bg-zinc-50 border border-zinc-150 p-4 rounded-sm text-center">
                  <span className="text-[9px] font-bold tracking-widest text-zinc-400 uppercase block mb-1">Loyalty Rewards</span>
                  <p className="text-[10px] text-zinc-500 font-light leading-relaxed">
                    Earn <span className="font-bold text-zinc-700">1 reward point</span> for every ${pointEarnRate} spent on this purchase!
                  </p>
                </div>
              )}

              <div className="border-t border-zinc-100 pt-4 space-y-2">
                <div className="flex justify-between text-xs text-zinc-500"><span>Subtotal</span><span className="font-bold text-zinc-700">{formatPrice(subtotal)}</span></div>
                <div className="flex justify-between text-xs text-zinc-500"><span>Shipping</span><span className={shipping === 0 ? "text-emerald-600 font-bold" : "font-bold text-zinc-700"}>{shipping === 0 ? "FREE" : formatPrice(shipping)}</span></div>
                <div className="flex justify-between text-xs text-zinc-500"><span>Tax (5%)</span><span className="font-bold text-zinc-700">{formatPrice(tax)}</span></div>
              </div>
              {discountPercentage > 0 && (
                <div className="flex justify-between items-center text-emerald-600 font-bold border-b border-zinc-100 pb-3">
                  <span className="flex items-center gap-1.5"><Tag className="w-3.5 h-3.5" /> Promo Discount ({discountPercentage}%)</span>
                  <span>-${discountAmount.toFixed(2)}</span>
                </div>
              )}
              {pointsRedeemedApplied && (
                <div className="flex justify-between items-center text-emerald-600 font-bold border-b border-zinc-100 pb-3">
                  <span className="flex items-center gap-1.5">🌟 Points Redeemed</span>
                  <span>-${(pointsRedeemed * pointValue).toFixed(2)}</span>
                </div>
              )}
              <div className="flex justify-between items-end border-t border-zinc-100 pt-6">
                <span className="text-sm font-black uppercase tracking-widest text-zinc-950">Total</span>
                <span className="text-lg font-black">{formatPrice(total)}</span>
              </div>

              {/* Pending Points Earner Note */}
              <div className="bg-indigo-50 border border-indigo-100 p-3 rounded-xs flex items-center justify-between text-[10px] font-bold text-indigo-700">
                <span>🌟 Points Earned on this Order:</span>
                <span className="bg-indigo-100 text-indigo-800 px-2 py-0.5 rounded-sm font-black">
                  +{Math.floor(total / pointEarnRate)} pts
                </span>
              </div>
            </div>
          </div>

        </div>
      </main>

      <Footer />

    </div>
  );
}
