'use client';

import { useState, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { motion, AnimatePresence } from 'framer-motion';
import {
  BookUser,
  Loader2,
  ShoppingBag,
  // Truck,
  CreditCard,
  MapPin,
  Phone,
  User,
  Hash,
  Lock,
  CheckCircle2,
  Package,
  ArrowLeft,
  X,
  Tag,
} from 'lucide-react';
import { checkoutSchema, CheckoutSchema } from '@/lib/validations';
import { useCheckout } from '@/hooks/useOrder';
import { useCart, useApplyCoupon, useRemoveCoupon } from '@/hooks';
import { formatIDR, cn } from '@/lib/utils';
import { useUser } from '@/store/auth.store';
import Link from 'next/link';
import { useUserAddresses } from '@/hooks/useAddress';
import { UserAddress } from '@/lib/services/user.service';

import Image from 'next/image';
import {
  LOCATION_DATA,
  // COURIERS,
  PAYMENT_METHODS,
  BANKS,
  EWALLET_PROVIDERS,
  RETAIL_OUTLETS,
} from '@/lib/constants/checkout';
import { DarkInput, DarkTextarea } from '@/components/ui/form-elements';
import {
  FieldLabel,
  FieldError,
  DarkSelect,
  GlassSection,
  PaymentCard,
  CouponInput,
  SummaryRow,
} from './components/CheckoutUI';

// ── Page ───────────────────────────────────────────────────────────────
function CheckoutForm() {
  const { data: cart, isLoading: cartLoading } = useCart();
  const checkout = useCheckout();
  const applyCoupon = useApplyCoupon();
  const removeCoupon = useRemoveCoupon();
  const user = useUser();
  const { data: addresses, isLoading: addressLoading } = useUserAddresses();
  const searchParams = useSearchParams();
  const selectedItemsParam = searchParams.get('items');
  const buyVariantId = searchParams.get('buy_variant_id');

  let selectedItemIds = selectedItemsParam ? selectedItemsParam.split(',') : [];
  const cartItems = cart?.items ?? [];

  if (buyVariantId && cartItems.length > 0) {
    const matchedItem = cartItems.find(
      (item) => item.variant.id === buyVariantId
    );
    if (matchedItem) {
      selectedItemIds = [matchedItem.id];
    }
  }

  const [showAddressModal, setShowAddressModal] = useState<boolean>(false);

  const handleSelectAddress = (addr: UserAddress) => {
    setValue('recipient_name', addr.recipient_name);
    setValue('phone', addr.phone);
    setValue('province', addr.province);
    // Timeout kecil agar dropdown cascading state 'province' sempat ter-update
    setTimeout(() => {
      setValue('city', addr.city);
      setTimeout(() => {
        setValue('district', addr.district);
        setValue('village', addr.village);
        setValue('postal_code', addr.postal_code);
        setValue('address', addr.address);
      }, 50);
    }, 50);

    setShowAddressModal(false);
  };

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors },
  } = useForm<CheckoutSchema>({
    resolver: zodResolver(checkoutSchema),
    defaultValues: {
      shipping_courier: 'flat',
      shipping_service: 'regular',
      payment_method: 'manual_qris',
      province: '',
      city: '',
      district: '',
      village: '',
    },
  });

  // Watch fields for cascading dropdowns
  const paymentMethod = watch('payment_method');
  const needsBank = paymentMethod === 'virtual_account';
  const needsEwalletProvider = paymentMethod === 'ewallet';
  const needsRetailOutlet = paymentMethod === 'retail_outlet';
  const needsProvider = needsBank || needsEwalletProvider || needsRetailOutlet;

  const selectedProv = watch('province');
  const selectedCity = watch('city');
  const selectedDist = watch('district');

  // Generate scoped location arrays
  const availableCities = selectedProv
    ? LOCATION_DATA.cities[selectedProv] || []
    : [];
  const availableDistricts = selectedCity
    ? LOCATION_DATA.districts[selectedCity] || []
    : [];
  const availableVillages = selectedDist
    ? LOCATION_DATA.villages[selectedDist] || []
    : [];

  const displayItems =
    selectedItemIds.length > 0
      ? cartItems.filter((item) => selectedItemIds.includes(item.id))
      : cartItems;

  const onSubmit = (data: CheckoutSchema) => {
    checkout.mutate({
      ...data,
      ...(selectedItemIds.length > 0 ? { cart_item_ids: selectedItemIds } : {}),
      ...(cart?.coupon_code ? { coupon_code: cart.coupon_code } : {}),
    });
  };

  const cartSubtotal =
    selectedItemIds.length > 0
      ? displayItems.reduce((acc, item) => {
          const unitPrice =
            user?.user_type === 'agen' && item.variant.price_distributor
              ? Number(item.variant.price_distributor)
              : Number(item.unit_price);
          return acc + unitPrice * item.quantity;
        }, 0)
      : displayItems.reduce((acc, item) => {
          const unitPrice =
            user?.user_type === 'agen' && item.variant.price_distributor
              ? Number(item.variant.price_distributor)
              : Number(item.unit_price);
          return acc + unitPrice * item.quantity;
        }, 0) || Number(cart?.subtotal ?? 0);

  const couponDiscount = Number(cart?.coupon_discount ?? 0);
  const pointsDiscount = Number(cart?.points_discount ?? 0);

  const finalTotal = Math.max(
    0,
    cartSubtotal - couponDiscount - pointsDiscount
  );

  return (
    <div className="min-h-screen text-gray-900 relative overflow-hidden pb-24">
      <div className="relative z-10 max-w-6xl mx-auto px-4 sm:px-6 pt-6 sm:pt-10 lg:pt-16 space-y-6 sm:space-y-8">
        {/* ── Header & Breadcrumb ── */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 sm:gap-6 relative z-20"
        >
          <div className="absolute top-0 right-10 pointer-events-none opacity-20 hidden lg:block z-0">
            <Image
              src="/mascots/salto-happy.avif"
              alt="Salto Cool Mascot"
              className="w-32 h-32 object-contain"
              width={500}
              height={500}
            />
          </div>
          <div className="relative z-10">
            {/* Tombol Kembali ke Keranjang */}
            <Link
              href="/dashboard/user/cart"
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-white/60 backdrop-blur-md border border-gray-200 text-xs font-bold text-gray-500 hover:bg-yellow-50 hover:border-yellow-200 hover:text-yellow-600 transition-all mb-4 sm:mb-6 group shadow-sm"
            >
              <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
              Kembali ke Keranjang
            </Link>

            <h2 className="text-3xl sm:text-4xl font-black text-gray-900 tracking-tight leading-none mb-2">
              Penyelesaian <span className="text-[#FFD738]">Pesanan</span>
            </h2>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              Lengkapi informasi pengiriman dan metode pembayaran Anda
            </p>
          </div>
        </motion.div>

        <form onSubmit={handleSubmit(onSubmit)} noValidate>
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 lg:gap-8">
            {/* ── LEFT: Form ── */}
            <div className="lg:col-span-2 space-y-5 sm:space-y-6">
              {/* Shipping address */}
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-black text-gray-900 flex items-center gap-2">
                  <MapPin className="w-5 h-5 text-yellow-600" /> Alamat
                  Pengiriman
                </h3>
                <button
                  type="button"
                  onClick={() => setShowAddressModal(true)}
                  className="flex items-center gap-2 px-4 py-2 rounded-xl bg-white border border-gray-200 hover:bg-yellow-50 hover:text-yellow-600 hover:border-yellow-200 text-xs font-bold text-gray-600 transition-all shadow-sm"
                >
                  <BookUser className="w-4 h-4" /> Buku Alamat
                </button>
              </div>

              <GlassSection
                icon={MapPin}
                label="Alamat Pengiriman"
                delay={0.05}
              >
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-5">
                  <div className="sm:col-span-2">
                    <FieldLabel required>Nama Penerima</FieldLabel>
                    <DarkInput
                      {...register('recipient_name')}
                      icon={User}
                      placeholder="Nama lengkap penerima"
                      error={!!errors.recipient_name}
                    />
                    <FieldError message={errors.recipient_name?.message} />
                  </div>

                  <div>
                    <FieldLabel required>Nomor Telepon</FieldLabel>
                    <DarkInput
                      {...register('phone')}
                      icon={Phone}
                      type="tel"
                      placeholder="08XXXXXXXXXX"
                      error={!!errors.phone}
                    />
                    <FieldError message={errors.phone?.message} />
                  </div>

                  <div>
                    <FieldLabel required>Provinsi</FieldLabel>
                    <DarkSelect
                      {...register('province', {
                        onChange: () => {
                          setValue('city', '');
                          setValue('district', '');
                          setValue('village', '');
                          setValue('postal_code', '');
                        },
                      })}
                      error={!!errors.province}
                    >
                      <option value="">Pilih provinsi</option>
                      {LOCATION_DATA.provinces.map((p: string) => (
                        <option key={p} value={p}>
                          {p}
                        </option>
                      ))}
                    </DarkSelect>
                    <FieldError message={errors.province?.message} />
                  </div>

                  <div>
                    <FieldLabel required>Kota / Kabupaten</FieldLabel>
                    <DarkSelect
                      {...register('city', {
                        onChange: () => {
                          setValue('district', '');
                          setValue('village', '');
                          setValue('postal_code', '');
                        },
                      })}
                      disabled={!selectedProv}
                      error={!!errors.city}
                    >
                      <option value="">
                        {selectedProv ? 'Pilih kota' : 'Pilih provinsi dahulu'}
                      </option>
                      {availableCities.map((c: string) => (
                        <option key={c} value={c}>
                          {c}
                        </option>
                      ))}
                    </DarkSelect>
                    <FieldError message={errors.city?.message} />
                  </div>

                  <div>
                    <FieldLabel required>Kecamatan</FieldLabel>
                    <DarkSelect
                      {...register('district', {
                        onChange: () => {
                          setValue('village', '');
                          setValue('postal_code', '');
                        },
                      })}
                      disabled={!selectedCity}
                      error={!!errors.district}
                    >
                      <option value="">
                        {selectedCity ? 'Pilih kecamatan' : 'Pilih kota dahulu'}
                      </option>
                      {availableDistricts.map((d: string) => (
                        <option key={d} value={d}>
                          {d}
                        </option>
                      ))}
                    </DarkSelect>
                    <FieldError message={errors.district?.message} />
                  </div>

                  <div>
                    <FieldLabel required>Kelurahan / Desa</FieldLabel>
                    <DarkSelect
                      {...register('village', {
                        onChange: (e) => {
                          const villageObj = availableVillages.find(
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            (v: any) => v.name === e.target.value
                          );
                          if (villageObj)
                            setValue('postal_code', villageObj.zip);
                        },
                      })}
                      disabled={!selectedDist}
                    >
                      <option value="">
                        {selectedDist
                          ? 'Pilih kelurahan'
                          : 'Pilih kecamatan dahulu'}
                      </option>
                      {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
                      {availableVillages.map((v: any) => (
                        <option key={v.name} value={v.name}>
                          {v.name}
                        </option>
                      ))}
                    </DarkSelect>
                  </div>

                  <div>
                    <FieldLabel required>Kode Pos</FieldLabel>
                    <DarkInput
                      {...register('postal_code')}
                      icon={Hash}
                      maxLength={5}
                      placeholder="Kode pos (Otomatis/Manual)"
                      error={!!errors.postal_code}
                    />
                    <FieldError message={errors.postal_code?.message} />
                  </div>

                  <div className="sm:col-span-2">
                    <FieldLabel required>Alamat Lengkap</FieldLabel>
                    <DarkTextarea
                      {...register('address')}
                      rows={3}
                      placeholder="Nama jalan, gedung, patokan jalan..."
                      error={!!errors.address}
                    />
                    <FieldError message={errors.address?.message} />
                  </div>
                </div>
              </GlassSection>

              {/* Shipping courier */}
              {/* <GlassSection icon={Truck} label="Metode Pengiriman" delay={0.1}>
                <div className="grid sm:grid-cols-2 gap-5">
                  <div>
                    <FieldLabel required>Kurir Pengiriman</FieldLabel>
                    <DarkSelect
                      {...register('shipping_courier')}
                      error={!!errors.shipping_courier}
                    >
                      {COURIERS.map((c) => (
                        <option key={c.value} value={c.value}>
                          {c.label}
                        </option>
                      ))}
                    </DarkSelect>
                  </div>
                  <div>
                    <FieldLabel required>Layanan</FieldLabel>
                    <DarkSelect
                      {...register('shipping_service')}
                      error={!!errors.shipping_service}
                    >
                      <option value="regular">Reguler (2-3 Hari)</option>
                      <option value="express">Express (1 Hari)</option>
                      <option value="economy">Ekonomi (3-5 Hari)</option>
                    </DarkSelect>
                  </div>
                </div>
              </GlassSection> */}

              {/* Payment */}
              <GlassSection
                icon={CreditCard}
                label="Metode Pembayaran"
                delay={0.15}
              >
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4 mb-5 sm:mb-6">
                  {PAYMENT_METHODS.map((pm) => (
                    <PaymentCard
                      key={pm.value}
                      pm={pm}
                      // eslint-disable-next-line react-hooks/incompatible-library
                      checked={watch('payment_method') === pm.value}
                      register={register}
                    />
                  ))}
                </div>

                <AnimatePresence>
                  {needsProvider && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: 'auto', opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      className="mb-5 sm:mb-6 overflow-hidden"
                    >
                      <FieldLabel required>
                        {needsBank
                          ? 'Pilih Bank'
                          : needsEwalletProvider
                            ? 'Pilih E-Wallet'
                            : 'Pilih Toko'}
                      </FieldLabel>
                      <DarkSelect
                        {...register('payment_provider')}
                        error={!!errors.payment_provider}
                      >
                        <option value="">
                          {needsBank
                            ? 'Pilih bank untuk transfer'
                            : needsEwalletProvider
                              ? 'Pilih provider e-wallet'
                              : 'Pilih toko retail'}
                        </option>
                        {(needsBank
                          ? BANKS
                          : needsEwalletProvider
                            ? EWALLET_PROVIDERS
                            : RETAIL_OUTLETS
                        ).map((item) => (
                          <option key={item.value} value={item.value}>
                            {item.label}
                          </option>
                        ))}
                      </DarkSelect>
                      <FieldError message={errors.payment_provider?.message} />
                    </motion.div>
                  )}
                </AnimatePresence>

                <div>
                  <FieldLabel>Catatan Pesanan (Opsional)</FieldLabel>
                  <DarkTextarea
                    {...register('customer_notes')}
                    rows={2}
                    placeholder="Tinggalkan pesan untuk penjual..."
                  />
                </div>
              </GlassSection>
            </div>

            {/* ── RIGHT: Order summary ── */}
            <motion.div
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
              className="lg:col-span-1"
            >
              <div className="lg:sticky lg:top-24 space-y-6">
                {/* ── Coupon Block ── */}
                <GlassSection icon={Tag} label="Promo / Kupon" delay={0.25}>
                  <CouponInput
                    applied={cart?.coupon_code ?? null}
                    onApply={(code) => applyCoupon.mutate(code)}
                    onRemove={() => removeCoupon.mutate()}
                    isPending={applyCoupon.isPending || removeCoupon.isPending}
                  />
                </GlassSection>

                {/* ── Summary Block ── */}
                <div className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm">
                  <div className="flex items-center gap-3 px-5 sm:px-6 py-4 sm:py-5 border-b border-gray-200/50 bg-white/40">
                    <div className="p-2 bg-yellow-50 border border-yellow-200 rounded-xl shadow-sm">
                      <ShoppingBag className="w-4 h-4 text-yellow-600" />
                    </div>
                    <span className="text-sm font-bold text-gray-900 tracking-wide">
                      Ringkasan Pesanan
                    </span>
                  </div>

                  {/* Items List */}
                  <div className="p-5 sm:p-6 pb-2">
                    {cartLoading ? (
                      <div className="space-y-4">
                        {Array.from({ length: 3 }).map((_, i) => (
                          <div key={i} className="flex gap-4 animate-pulse">
                            <div className="w-12 h-12 rounded-xl bg-gray-200 shrink-0" />
                            <div className="flex-1 space-y-2 py-1">
                              <div className="h-3 rounded bg-gray-200 w-2/3" />
                              <div className="h-2 rounded bg-gray-200 w-1/3" />
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div className="space-y-4 mb-5 sm:mb-6">
                        {displayItems.map((item) => (
                          <div
                            key={item.id}
                            className="flex items-start gap-4 group"
                          >
                            <div className="w-12 h-12 rounded-xl border border-gray-200 bg-white shrink-0 flex items-center justify-center overflow-hidden shadow-sm">
                              {item.product?.image_url ? (
                                <Image
                                  src={item.product.image_url}
                                  alt={item.product.name}
                                  className="w-full h-full object-cover transition-all"
                                  width={500}
                                  height={500}
                                />
                              ) : (
                                <Package className="w-5 h-5 text-gray-400" />
                              )}
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="text-sm font-bold text-gray-900 truncate">
                                {item.product?.name ?? 'Produk'}
                              </p>
                              <p className="text-[10px] font-medium text-gray-500 mt-0.5">
                                {item.variant?.name}{' '}
                                <span className="text-gray-900 font-bold">
                                  × {item.quantity}
                                </span>
                              </p>
                            </div>
                            <span className="text-sm font-black text-gray-900 shrink-0">
                              {formatIDR(
                                (user?.user_type === 'agen' &&
                                item.variant.price_distributor
                                  ? Number(item.variant.price_distributor)
                                  : Number(item.unit_price)) * item.quantity
                              )}
                            </span>
                          </div>
                        ))}
                      </div>
                    )}

                    {/* Price breakdown */}
                    <div className="space-y-3 border-t border-gray-200 pt-5 pb-5 sm:pb-6">
                      <SummaryRow
                        label="Subtotal Produk"
                        value={formatIDR(cartSubtotal)}
                      />

                      {couponDiscount > 0 && (
                        <SummaryRow
                          label={`Diskon Kupon ${cart?.coupon_code ? `(${cart.coupon_code})` : ''}`}
                          value={`–${formatIDR(couponDiscount)}`}
                          accent
                        />
                      )}

                      {pointsDiscount > 0 && (
                        <SummaryRow
                          label="Diskon Poin"
                          value={`–${formatIDR(pointsDiscount)}`}
                          accent
                        />
                      )}

                      <SummaryRow label="Ongkos Kirim" value="Rp10.000" muted />
                      <div className="h-px bg-gray-200/50 my-4" />
                      <SummaryRow
                        label="Total Pembayaran"
                        value={formatIDR(finalTotal + 10000)}
                        highlight
                      />

                      {/* Poin yang didapatkan */}
                      {cartSubtotal > 0 && (
                        <div className="flex items-center justify-between mt-3 pt-3 border-t border-dashed border-yellow-200">
                          <span className="text-[11px] font-bold text-yellow-600 flex items-center gap-1.5">
                            ⭐ Poin yang didapatkan
                          </span>
                          <span className="text-xs font-black text-yellow-600">
                            +{Math.floor(cartSubtotal / 1000)} Poin
                          </span>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* CTA Checkout */}
                  <div className="px-5 sm:px-6 pb-5 sm:pb-6">
                    <motion.button
                      type="submit"
                      whileTap={{ scale: 0.98 }}
                      disabled={checkout.isPending || !cart?.items?.length}
                      className={cn(
                        'w-full py-4 rounded-xl font-bold text-sm tracking-wider flex items-center justify-center gap-2.5 transition-all shadow-sm cursor-pointer',
                        checkout.isPending || !cart?.items?.length
                          ? 'bg-gray-100 text-gray-400 border border-gray-200 cursor-not-allowed shadow-none'
                          : 'bg-[#FFD738] hover:bg-[#FFD738]/90 text-[#1C1D1F] shadow-md shadow-[#FFD738]/20'
                      )}
                    >
                      {checkout.isPending ? (
                        <>
                          <Loader2 className="w-4 h-4 animate-spin" /> Memproses
                          Pesanan...
                        </>
                      ) : (
                        <>
                          Bayar Sekarang <CreditCard className="w-4 h-4" />
                        </>
                      )}
                    </motion.button>

                    {/* Trust Signals */}
                    <div className="mt-5 flex items-center justify-center gap-4">
                      <div className="flex items-center gap-1.5 text-gray-500">
                        <Lock className="w-3.5 h-3.5" />
                        <span className="text-[10px] font-bold uppercase tracking-widest">
                          Transaksi Aman
                        </span>
                      </div>
                      <span className="w-1 h-1 rounded-full bg-gray-700" />
                      <div className="flex items-center gap-1.5 text-gray-500">
                        <CheckCircle2 className="w-3.5 h-3.5" />
                        <span className="text-[10px] font-bold uppercase tracking-widest">
                          Verifikasi Resmi
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>
          </div>
        </form>
      </div>

      <AnimatePresence>
        {showAddressModal && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="absolute inset-0 bg-white/60 backdrop-blur-sm"
              onClick={() => setShowAddressModal(false)}
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 10 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 10 }}
              className="relative bg-white border border-gray-200 rounded-2xl sm:rounded-3xl p-5 sm:p-6 w-[calc(100%-2rem)] sm:w-full max-w-lg overflow-hidden shadow-2xl z-10 max-h-[85vh] flex flex-col mx-4 sm:mx-0"
            >
              <div className="flex items-center justify-between mb-5 sm:mb-6 pb-4 border-b border-gray-200/50">
                <h3 className="text-lg font-black text-gray-900 tracking-wide">
                  Pilih Buku Alamat
                </h3>
                <button
                  type="button"
                  onClick={() => setShowAddressModal(false)}
                  className="p-2 bg-gray-50 rounded-full hover:bg-rose-50 hover:text-rose-600 transition-colors border border-gray-200 shadow-sm"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>

              <div className="overflow-y-auto pr-2 space-y-4 flex-1 custom-scrollbar">
                {addressLoading ? (
                  <div className="flex justify-center py-10">
                    <Loader2 className="w-6 h-6 animate-spin text-[#FFD738]" />
                  </div>
                ) : addresses && addresses.length > 0 ? (
                  addresses.map((addr) => (
                    <div
                      key={addr.id}
                      className="p-4 sm:p-5 rounded-2xl border border-gray-200 bg-white hover:border-yellow-400 hover:bg-yellow-50 transition-all group shadow-sm"
                    >
                      <div className="flex items-start justify-between mb-2">
                        <div className="flex items-center gap-2">
                          <span className="text-[10px] font-bold uppercase tracking-widest bg-gray-100 border border-gray-200 px-2 py-1 rounded-md text-gray-600">
                            {addr.label}
                          </span>
                          {addr.is_primary && (
                            <span className="text-[10px] font-bold uppercase tracking-widest bg-emerald-50 border border-emerald-200 text-emerald-600 px-2 py-1 rounded-md">
                              Utama
                            </span>
                          )}
                        </div>
                        <button
                          type="button"
                          onClick={() => handleSelectAddress(addr)}
                          className="text-xs font-bold bg-white border border-gray-200 text-gray-600 px-4 py-2 rounded-xl opacity-0 group-hover:opacity-100 transition-all hover:border-yellow-400 hover:bg-yellow-50 hover:text-yellow-700 shadow-sm"
                        >
                          Pilih Alamat
                        </button>
                      </div>
                      <p className="text-sm font-bold text-gray-900">
                        {addr.recipient_name}{' '}
                        <span className="text-gray-500 font-medium ml-2">
                          {addr.phone}
                        </span>
                      </p>
                      <p className="text-xs text-gray-500 mt-1 leading-relaxed">
                        {addr.address}, {addr.district}, {addr.city},{' '}
                        {addr.province} {addr.postal_code}
                      </p>
                    </div>
                  ))
                ) : (
                  <div className="text-center py-10">
                    <MapPin className="w-10 h-10 text-gray-600 mx-auto mb-3" />
                    <p className="text-sm font-bold text-gray-400">
                      Belum ada alamat tersimpan
                    </p>
                  </div>
                )}
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
}

export default function CheckoutPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen text-gray-900 flex items-center justify-center">
          Loading...
        </div>
      }
    >
      <CheckoutForm />
    </Suspense>
  );
}
