'use client';

import { useState, useEffect, useMemo } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ShoppingCart,
  Trash2,
  Plus,
  Minus,
  ArrowRight,
  Package,
  Tag,
  X,
  Loader2,
  AlertTriangle,
  ShoppingBag,
  RefreshCw,
  ChevronRight,
  Lock,
  ArrowLeft,
  Check,
} from 'lucide-react';
import {
  useCart,
  useUpdateCartItem,
  useRemoveCartItem,
  useClearCart,
  useApplyCoupon,
  useRemoveCoupon,
} from '@/hooks';
import { cn, formatIDR } from '@/lib/utils';
import type { CartItem } from '@/types';
import { RewardService, UserVoucher } from '@/lib/services/reward.service';
import { useUser } from '@/store/auth.store';

import Image from 'next/image';
// ── Shared Wrapper: Glass Card ─────────────────────────────────────────
function GlassCard({
  children,
  className,
  noPadding = false,
}: {
  children: React.ReactNode;
  className?: string;
  noPadding?: boolean;
}) {
  return (
    <div
      className={cn(
        'relative border border-white/50 bg-white/60 backdrop-blur-xl rounded-3xl shadow-sm overflow-hidden',
        !noPadding && 'p-6',
        className
      )}
    >
      {children}
    </div>
  );
}

// ── Inline remove confirm ──────────────────────────────────────────────
function RemoveConfirm({
  onConfirm,
  onCancel,
  isPending,
}: {
  onConfirm: () => void;
  onCancel: () => void;
  isPending: boolean;
}) {
  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="absolute inset-0 z-20 bg-white/90 backdrop-blur-md flex flex-col sm:flex-row items-center justify-center gap-4 border border-rose-200 rounded-2xl p-4 shadow-sm"
    >
      <p className="text-sm font-bold text-gray-900 tracking-wide">
        Hapus item ini?
      </p>
      <div className="flex items-center gap-2">
        <button
          onClick={onCancel}
          className="px-4 py-2 rounded-xl text-xs font-bold text-gray-600 bg-white border border-gray-200 hover:bg-gray-50 hover:text-gray-900 transition-all cursor-pointer shadow-sm"
        >
          Batal
        </button>
        <button
          onClick={onConfirm}
          disabled={isPending}
          className="px-4 py-2 rounded-xl text-xs font-bold text-white bg-rose-500 hover:bg-rose-600 transition-all flex items-center gap-2 disabled:opacity-50 cursor-pointer shadow-sm"
        >
          {isPending ? (
            <Loader2 className="w-3.5 h-3.5 animate-spin" />
          ) : (
            <Trash2 className="w-3.5 h-3.5" />
          )}
          Hapus
        </button>
      </div>
    </motion.div>
  );
}

// ── Cart item card ─────────────────────────────────────────────────────
function CartItemCard({
  item,
  isSelected,
  onToggleSelect,
}: {
  item: CartItem;
  isSelected: boolean;
  onToggleSelect: () => void;
}) {
  const updateItem = useUpdateCartItem();
  const removeItem = useRemoveCartItem();
  const user = useUser();
  const [showConfirm, setShowConfirm] = useState(false);
  const [localQty, setLocalQty] = useState(item.quantity);

  const handleQtyChange = (newQty: number) => {
    if (newQty < 1 || newQty > item.variant.stock) return;
    setLocalQty(newQty);
    updateItem.mutate({
      itemId: item.id,
      quantity: newQty,
      notes: item.notes ?? undefined,
    });
  };

  const isPendingUpdate = updateItem.isPending;
  const isPendingRemove = removeItem.isPending;

  const unitPrice =
    user?.user_type === 'agen' && item.variant.price_distributor
      ? Number(item.variant.price_distributor)
      : Number(item.unit_price);

  const subtotal = unitPrice * localQty;

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, scale: 0.95, height: 0, marginBottom: 0 }}
      transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
      className={cn(
        'relative border bg-white/60 backdrop-blur-md rounded-2xl p-4 sm:p-5 transition-all duration-300 shadow-sm flex gap-3 sm:gap-4',
        isSelected
          ? 'border-yellow-300 bg-yellow-50'
          : 'border-white/50 hover:border-yellow-200 hover:bg-white'
      )}
    >
      <AnimatePresence>
        {showConfirm && (
          <RemoveConfirm
            onConfirm={() =>
              removeItem.mutate(item.id, {
                onSuccess: () => setShowConfirm(false),
              })
            }
            onCancel={() => setShowConfirm(false)}
            isPending={isPendingRemove}
          />
        )}
      </AnimatePresence>

      {/* ── Custom Checkbox ── */}
      <div className="pt-2 sm:pt-4 shrink-0">
        <button
          onClick={onToggleSelect}
          className={cn(
            'w-5 h-5 rounded-md border flex items-center justify-center transition-all shadow-sm',
            isSelected
              ? 'bg-[#FFD738] border-[#FFD738]'
              : 'border-gray-300 bg-white hover:border-yellow-400'
          )}
        >
          {isSelected && <Check className="w-3.5 h-3.5 text-[#1C1D1F]" />}
        </button>
      </div>

      <div className="flex-1 flex gap-4 sm:gap-5 min-w-0">
        {/* Product image */}
        <Link
          href={`/products/${item.product.slug}`}
          className="shrink-0 w-20 h-20 sm:w-28 sm:h-28 rounded-xl border border-gray-200 bg-white flex items-center justify-center overflow-hidden hover:border-yellow-400 transition-colors 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 duration-500 hover:scale-105"
              width={500}
              height={500}
            />
          ) : (
            <Package className="w-8 h-8 text-gray-300" />
          )}
        </Link>

        {/* Info */}
        <div className="flex-1 min-w-0 flex flex-col justify-between">
          <div className="flex items-start justify-between gap-3">
            <div className="min-w-0">
              <Link
                href={`/products/${item.product.slug}`}
                className="font-black text-gray-900 text-sm sm:text-base tracking-wide line-clamp-2 hover:text-yellow-600 transition-colors"
              >
                {item.product.name}
              </Link>
              <div className="flex items-center gap-2 mt-1.5 flex-wrap">
                <span className="text-[10px] font-bold text-yellow-700 border border-yellow-200 bg-yellow-50 px-2.5 py-0.5 rounded-md uppercase tracking-widest shadow-sm">
                  {item.variant.name}
                </span>
                <span className="text-[10px] font-mono font-medium text-gray-600 uppercase tracking-widest bg-white border border-gray-200 px-2 py-0.5 rounded-md shadow-sm">
                  {item.variant.sku}
                </span>
              </div>
              {item.notes && (
                <p className="text-[11px] text-gray-500 font-medium mt-2 tracking-wide line-clamp-1">
                  <span className="font-bold text-gray-700">Catatan:</span>{' '}
                  {item.notes}
                </p>
              )}
            </div>

            {/* Remove button */}
            <button
              onClick={() => setShowConfirm(true)}
              disabled={isPendingRemove}
              className="p-2 rounded-lg border border-transparent text-gray-400 hover:border-rose-200 hover:bg-rose-50 hover:text-rose-600 transition-all shrink-0 cursor-pointer shadow-sm"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          </div>

          {/* Qty + price row */}
          <div className="flex items-end sm:items-center justify-between mt-4 gap-3 flex-wrap">
            {/* Modern Qty stepper */}
            <div className="flex items-center bg-white border border-gray-200 rounded-lg p-1 shadow-sm">
              <button
                onClick={() => handleQtyChange(localQty - 1)}
                disabled={localQty <= 1 || isPendingUpdate}
                className="p-1.5 rounded-md text-gray-500 hover:bg-gray-50 hover:text-gray-900 disabled:opacity-20 transition-colors"
              >
                <Minus className="w-3.5 h-3.5" />
              </button>
              <div className="w-8 sm:w-10 flex items-center justify-center">
                {isPendingUpdate ? (
                  <Loader2 className="w-3.5 h-3.5 animate-spin text-yellow-600" />
                ) : (
                  <span className="font-bold text-gray-900 text-sm tabular-nums">
                    {localQty}
                  </span>
                )}
              </div>
              <button
                onClick={() => handleQtyChange(localQty + 1)}
                disabled={localQty >= item.variant.stock || isPendingUpdate}
                className="p-1.5 rounded-md text-gray-500 hover:bg-gray-50 hover:text-gray-900 disabled:opacity-20 transition-colors"
              >
                <Plus className="w-3.5 h-3.5" />
              </button>
            </div>

            {/* Subtotal */}
            <div className="text-right ml-auto">
              {localQty > 1 && (
                <p className="text-[10px] text-gray-500 font-bold tracking-wide mb-0.5">
                  {formatIDR(unitPrice)} × {localQty}
                </p>
              )}
              <p className="font-black text-gray-900 text-base sm:text-lg tracking-tight">
                {formatIDR(subtotal)}
              </p>
            </div>
          </div>
        </div>
      </div>
    </motion.div>
  );
}

// ── Coupon input ───────────────────────────────────────────────────────
function CouponInput({
  applied,
  onApply,
  onRemove,
  isPending,
}: {
  applied: string | null;
  onApply: (code: string) => void;
  onRemove: () => void;
  isPending?: boolean;
}) {
  const [code, setCode] = useState(applied ?? '');
  const [vouchers, setVouchers] = useState<UserVoucher[]>([]);
  const [loadingVouchers, setLoadingVouchers] = useState(true);

  useEffect(() => {
    RewardService.getVouchers()
      .then((res) => {
        setVouchers(res.data.filter((v) => v.status === 'ACTIVE'));
      })
      .catch((err) => console.error(err))
      .finally(() => setLoadingVouchers(false));
  }, []);

  const handleApply = async () => {
    if (!code.trim()) return;
    onApply(code.trim().toUpperCase());
  };

  if (applied) {
    return (
      <div className="flex items-center gap-3 border border-emerald-200 bg-emerald-50 rounded-xl px-4 py-3 shadow-sm">
        <div className="p-1.5 bg-emerald-100 rounded-lg shrink-0">
          <Tag className="w-4 h-4 text-emerald-600" />
        </div>
        <div className="flex-1">
          <p className="text-xs font-bold text-emerald-700 tracking-wide">
            {applied}
          </p>
          <p className="text-[10px] text-emerald-600 font-medium mt-0.5">
            Kupon berhasil diterapkan
          </p>
        </div>
        <button
          onClick={onRemove}
          disabled={isPending}
          className="p-1.5 rounded-lg text-emerald-600/60 hover:text-emerald-700 hover:bg-emerald-100 transition-colors disabled:opacity-50"
        >
          {isPending ? (
            <Loader2 className="w-4 h-4 animate-spin" />
          ) : (
            <X className="w-4 h-4" />
          )}
        </button>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-4">
      <div className="flex gap-2">
        <div className="relative flex-1 border border-gray-200 bg-white rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm">
          <Tag className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            value={code}
            onChange={(e) => setCode(e.target.value.toUpperCase())}
            onKeyDown={(e) => e.key === 'Enter' && handleApply()}
            placeholder="KODE KUPON..."
            className="w-full pl-10 pr-3 py-3 bg-transparent text-gray-900 text-xs font-bold placeholder:text-gray-400 focus:outline-none uppercase tracking-widest rounded-xl"
          />
        </div>
        <button
          onClick={handleApply}
          disabled={!code.trim() || isPending}
          className="px-5 py-3 rounded-xl bg-white border border-gray-200 hover:border-yellow-400 hover:bg-yellow-50 text-gray-600 hover:text-yellow-700 text-xs font-bold uppercase tracking-wider disabled:opacity-30 transition-all flex items-center gap-2 shadow-sm cursor-pointer"
        >
          {isPending ? (
            <Loader2 className="w-4 h-4 animate-spin" />
          ) : (
            'Terapkan'
          )}
        </button>
      </div>

      <div className="flex flex-col gap-2">
        <div className="flex items-center justify-between mt-2 mb-1">
          <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">
            Atau Pilih Kupon Anda:
          </p>
          {loadingVouchers && (
            <Loader2 className="w-3 h-3 text-gray-400 animate-spin" />
          )}
        </div>
        <div className="flex flex-col gap-2.5">
          {!loadingVouchers && vouchers.length === 0 ? (
            <div className="text-center p-4 border border-dashed border-gray-200 rounded-xl bg-gray-50">
              <p className="text-xs text-gray-500">
                Anda belum memiliki kupon aktif.
              </p>
            </div>
          ) : (
            vouchers.map((voucher) => (
              <button
                key={voucher.id}
                onClick={() => {
                  setCode(voucher.code);
                  onApply(voucher.code);
                }}
                disabled={isPending}
                className="flex items-center justify-between p-3 border border-gray-200 rounded-xl hover:border-yellow-400 hover:bg-yellow-50/50 transition-all group disabled:opacity-50 text-left bg-white shadow-sm cursor-pointer"
              >
                <div>
                  <p className="text-xs font-bold text-gray-900 tracking-wide group-hover:text-yellow-700 transition-colors">
                    {voucher.code}
                  </p>
                  <p className="text-[10px] text-gray-500 mt-0.5">
                    {voucher.pointItem?.name ||
                      `Diskon ${voucher.discount_type === 'PERCENTAGE' ? voucher.discount_value + '%' : formatIDR(voucher.discount_value)}`}
                  </p>
                </div>
                <div className="w-6 h-6 rounded-full bg-gray-100 group-hover:bg-yellow-100 flex items-center justify-center transition-colors">
                  <Check className="w-3.5 h-3.5 text-gray-400 group-hover:text-yellow-600 opacity-0 group-hover:opacity-100 transition-opacity" />
                </div>
              </button>
            ))
          )}
        </div>
      </div>
    </div>
  );
}

// ── Summary row ────────────────────────────────────────────────────────
function SummaryRow({
  label,
  value,
  highlight,
  accent,
}: {
  label: string;
  value: string;
  highlight?: boolean;
  accent?: boolean;
}) {
  return (
    <div className="flex items-center justify-between gap-2 py-1">
      <span
        className={cn(
          'text-xs tracking-wide',
          highlight ? 'font-bold text-gray-700' : 'font-medium text-gray-500'
        )}
      >
        {label}
      </span>
      <span
        className={cn(
          'font-black tabular-nums tracking-tight',
          highlight
            ? 'text-xl text-yellow-600'
            : accent
              ? 'text-sm text-emerald-600'
              : 'text-sm text-gray-900'
        )}
      >
        {value}
      </span>
    </div>
  );
}

// ── Clear cart dialog ──────────────────────────────────────────────────
function ClearCartDialog({
  onConfirm,
  onCancel,
  isPending,
}: {
  onConfirm: () => void;
  onCancel: () => void;
  isPending: boolean;
}) {
  return (
    <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-black/60 backdrop-blur-sm"
        onClick={onCancel}
      />
      <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-[#252629] border border-white/10 rounded-3xl p-6 w-full max-w-sm overflow-hidden shadow-2xl"
      >
        <div className="absolute top-0 left-1/2 -translate-x-1/2 w-32 h-32 bg-rose-500/20 blur-3xl pointer-events-none rounded-full" />
        <div className="flex items-center gap-4 mb-6 relative z-10">
          <div className="w-12 h-12 rounded-full border border-rose-500/20 bg-rose-500/10 flex items-center justify-center shrink-0">
            <AlertTriangle className="w-6 h-6 text-rose-400" />
          </div>
          <div>
            <h3 className="text-lg font-black text-white tracking-wide">
              Kosongkan Keranjang?
            </h3>
            <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest mt-0.5">
              Semua item akan dihapus
            </p>
          </div>
        </div>
        <div className="flex gap-3 relative z-10">
          <button
            onClick={onCancel}
            className="flex-1 py-3 px-4 rounded-xl text-xs font-bold text-gray-300 bg-white/5 border border-white/5 hover:bg-white/10 hover:text-white uppercase tracking-wider transition-all cursor-pointer"
          >
            Batal
          </button>
          <button
            onClick={onConfirm}
            disabled={isPending}
            className="flex-1 py-3 px-4 rounded-xl text-xs font-bold text-[#1C1D1F] bg-rose-400 hover:bg-rose-500 uppercase tracking-wider transition-all flex items-center justify-center gap-2 disabled:opacity-50 cursor-pointer"
          >
            {isPending ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Trash2 className="w-4 h-4" />
            )}
            Kosongkan
          </button>
        </div>
      </motion.div>
    </div>
  );
}

// ── Page ───────────────────────────────────────────────────────────────
export default function DashboardUserCartPage() {
  const router = useRouter();
  const user = useUser();
  const { data: cart, isLoading, isError, refetch } = useCart();
  const clearCart = useClearCart();
  const applyCoupon = useApplyCoupon();
  const removeCoupon = useRemoveCoupon();

  const [showClearDialog, setShowClearDialog] = useState(false);
  const [selectedItemIds, setSelectedItemIds] = useState<string[]>([]);
  const [isInitialized, setIsInitialized] = useState(false);

  const items = useMemo(() => cart?.items ?? [], [cart?.items]);
  const isEmpty = items.length === 0;

  // Initialize selected items (Select all by default)
  useEffect(() => {
    if (items.length > 0 && !isInitialized) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setSelectedItemIds(items.map((i) => i.id));
      setIsInitialized(true);
    }
  }, [items, isInitialized]);

  // ── Calculation ──
  // Filter items based on selections
  const checkedItems = items.filter((item) =>
    selectedItemIds.includes(item.id)
  );
  const checkedCount = checkedItems.reduce(
    (acc, item) => acc + item.quantity,
    0
  );

  // Calculate local subtotal based on selected items
  const localSubtotal = checkedItems.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);

  const couponDiscount = Number(cart?.coupon_discount ?? 0);
  const pointsDiscount = Number(cart?.points_discount ?? 0);
  // Calculate final total (ensure it doesn't go below 0)
  const localTotal = Math.max(
    0,
    localSubtotal - couponDiscount - pointsDiscount
  );

  // ── Handlers ──
  const isAllSelected =
    selectedItemIds.length === items.length && items.length > 0;

  const handleToggleAll = () => {
    if (isAllSelected) {
      setSelectedItemIds([]);
    } else {
      setSelectedItemIds(items.map((i) => i.id));
    }
  };

  const handleToggleItem = (id: string) => {
    setSelectedItemIds((prev) =>
      prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id]
    );
  };

  const handleCheckout = () => {
    if (selectedItemIds.length === 0) return;
    // Pass selected items via query string
    router.push(`/dashboard/user/checkout?items=${selectedItemIds.join(',')}`);
  };

  // ── Loading ────────────────────────────────────────────────────────
  if (isLoading) {
    return (
      <div className="max-w-5xl mx-auto space-y-6">
        <div className="grid lg:grid-cols-[1fr_340px] gap-6">
          <div className="space-y-4">
            {Array.from({ length: 3 }).map((_, i) => (
              <div
                key={i}
                className="border border-white/5 bg-[#252629]/40 rounded-2xl p-5 animate-pulse flex gap-5"
              >
                <div className="w-24 h-24 rounded-xl bg-white/5 shrink-0" />
                <div className="flex-1 space-y-3 py-1">
                  <div className="h-4 rounded bg-white/5 w-2/3" />
                  <div className="h-3 rounded bg-white/5 w-1/3" />
                  <div className="h-10 rounded-lg bg-white/5 w-32 mt-4" />
                </div>
              </div>
            ))}
          </div>
          <div className="h-96 rounded-3xl border border-white/5 bg-[#252629]/40 animate-pulse" />
        </div>
      </div>
    );
  }

  // ── Error ──────────────────────────────────────────────────────────
  if (isError) {
    return (
      <div className="max-w-5xl mx-auto py-24 text-center bg-[#252629]/40 backdrop-blur-xl border border-white/5 rounded-3xl">
        <div className="w-20 h-20 bg-rose-500/10 rounded-full flex items-center justify-center mx-auto mb-6">
          <AlertTriangle className="w-10 h-10 text-rose-400" />
        </div>
        <h3 className="font-black text-white text-2xl tracking-tight mb-2">
          Gagal Memuat Keranjang
        </h3>
        <p className="text-gray-400 text-sm mb-8">
          Terjadi kesalahan pada sistem saat mengambil data Anda.
        </p>
        <button
          onClick={() => refetch()}
          className="flex items-center justify-center gap-2 mx-auto px-6 py-3 rounded-xl bg-white/5 border border-white/10 text-white font-bold text-sm hover:bg-white/10 transition-all shadow-sm"
        >
          <RefreshCw className="w-4 h-4" />
          Coba Lagi
        </button>
      </div>
    );
  }

  // ── Empty cart ─────────────────────────────────────────────────────
  if (isEmpty) {
    return (
      <div className="max-w-5xl mx-auto space-y-6">
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
        >
          <h2 className="text-3xl font-black text-gray-900 tracking-tight leading-none mb-2">
            Keranjang <span className="text-[#FFD738]">Belanja</span>
          </h2>
          <p className="text-sm font-medium text-gray-500 tracking-wide">
            Belum ada item yang dipilih
          </p>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
        >
          <GlassCard className="py-24 flex flex-col items-center justify-center text-center">
            <div className="relative mb-8">
              <div className="w-24 h-24 rounded-full border border-gray-200 bg-white flex items-center justify-center shadow-sm">
                <ShoppingBag className="w-10 h-10 text-gray-400" />
              </div>
            </div>
            <p className="font-black text-gray-900 text-2xl tracking-tight mb-2">
              Keranjang Anda Kosong
            </p>
            <p className="text-sm font-medium text-gray-500 max-w-sm mb-8 leading-relaxed">
              Jelajahi berbagai produk terbaik kami dan tambahkan ke keranjang
              untuk mulai berbelanja.
            </p>
            <Link
              href="/products"
              className="inline-flex items-center justify-center gap-2.5 px-8 py-3.5 rounded-xl bg-[#FFD738] hover:bg-[#FFD738]/90 text-[#1C1D1F] font-bold text-sm tracking-wide transition-all shadow-lg shadow-[#FFD738]/20"
            >
              <Package className="w-4 h-4" />
              Lihat Produk Kami
              <ChevronRight className="w-4 h-4" />
            </Link>
          </GlassCard>
        </motion.div>
      </div>
    );
  }

  // ── Filled cart ────────────────────────────────────────────────────
  return (
    <>
      <div className="max-w-6xl mx-auto space-y-6">
        {/* ── Header ── */}
        <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"
        >
          <div className="absolute top-10 right-4 pointer-events-none opacity-20 hidden md:block z-0">
            <Image
              src="/mascots/salta-happy.avif"
              alt="Salta Mascot"
              className="w-32 h-32 object-contain drop-shadow-sm"
              width={500}
              height={500}
            />
          </div>
          <div className="relative z-10">
            <h2 className="text-3xl font-black text-gray-900 tracking-tight leading-none mb-2">
              Keranjang <span className="text-[#FFD738]">Belanja</span>
            </h2>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              {items.length} macam produk di keranjang Anda
            </p>
          </div>
          <button
            onClick={() => setShowClearDialog(true)}
            className="flex items-center gap-2 px-4 py-2 rounded-xl bg-white border border-rose-200 text-rose-600 font-bold text-xs uppercase tracking-wider hover:bg-rose-50 transition-all shadow-sm cursor-pointer relative z-10"
          >
            <Trash2 className="w-3.5 h-3.5" />
            Kosongkan Keranjang
          </button>
        </motion.div>

        {/* ── Main grid ── */}
        <div className="grid lg:grid-cols-[1fr_380px] gap-6 items-start pb-24 lg:pb-0">
          {/* LEFT: Items List */}
          <div className="space-y-4">
            {/* Pilih Semua Bar */}
            <div className="flex items-center justify-between bg-white/60 backdrop-blur-md border border-white/50 rounded-2xl px-5 py-4 shadow-sm">
              <label className="flex items-center gap-3 cursor-pointer group">
                <div
                  className={cn(
                    'w-5 h-5 rounded-md border flex items-center justify-center transition-all shadow-sm',
                    isAllSelected
                      ? 'bg-[#FFD738] border-[#FFD738]'
                      : 'border-gray-300 bg-white group-hover:border-yellow-400'
                  )}
                >
                  {isAllSelected && (
                    <Check className="w-3.5 h-3.5 text-[#1C1D1F]" />
                  )}
                </div>
                <span className="text-sm font-bold text-gray-600 group-hover:text-gray-900 transition-colors">
                  Pilih Semua ({items.length})
                </span>
                {/* Invisible native checkbox for accessibility */}
                <input
                  type="checkbox"
                  checked={isAllSelected}
                  onChange={handleToggleAll}
                  className="hidden"
                />
              </label>
            </div>

            <AnimatePresence mode="popLayout">
              {items.map((item) => (
                <CartItemCard
                  key={item.id}
                  item={item}
                  isSelected={selectedItemIds.includes(item.id)}
                  onToggleSelect={() => handleToggleItem(item.id)}
                />
              ))}
            </AnimatePresence>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.3 }}
              className="pt-4"
            >
              <Link
                href="/products"
                className="inline-flex items-center justify-center w-full sm:w-auto gap-2 px-6 py-3 rounded-full bg-white backdrop-blur-md border border-gray-200 text-sm font-bold text-gray-600 hover:bg-yellow-50 hover:border-yellow-300 hover:text-yellow-700 transition-all shadow-sm group"
              >
                <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
                Lanjutkan Belanja
              </Link>
            </motion.div>
          </div>

          {/* RIGHT: Summary Sidebar */}
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.12 }}
            className="lg:sticky lg:top-24 space-y-6"
          >
            {/* Coupon Block */}
            <GlassCard noPadding>
              <div className="flex items-center gap-3 px-6 py-4 border-b border-gray-200/50 bg-white/40">
                <Tag className="w-4 h-4 text-yellow-600" />
                <span className="text-xs font-bold text-gray-600 uppercase tracking-widest">
                  Promo / Kupon
                </span>
              </div>
              <div className="p-6">
                <CouponInput
                  applied={cart?.coupon_code ?? null}
                  onApply={(code) => applyCoupon.mutate(code)}
                  onRemove={() => removeCoupon.mutate()}
                  isPending={applyCoupon.isPending || removeCoupon.isPending}
                />
              </div>
            </GlassCard>

            {/* Summary Block */}
            <GlassCard noPadding>
              <div className="flex items-center gap-3 px-6 py-4 border-b border-gray-200/50 bg-white/40">
                <ShoppingCart className="w-4 h-4 text-yellow-600" />
                <span className="text-xs font-bold text-gray-600 uppercase tracking-widest">
                  Ringkasan Pesanan
                </span>
              </div>

              <div className="px-6 py-6 space-y-3">
                <SummaryRow
                  label={`Subtotal (${checkedCount} item)`}
                  value={formatIDR(localSubtotal)}
                />

                {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
                  />
                )}

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

              {/* Checkout CTA */}
              <div className="px-6 pb-6">
                <motion.button
                  whileTap={{ scale: 0.98 }}
                  onClick={handleCheckout}
                  disabled={selectedItemIds.length === 0}
                  className={cn(
                    'w-full py-4 rounded-xl font-bold text-sm uppercase tracking-wider flex items-center justify-center gap-2.5 transition-all shadow-sm cursor-pointer',
                    selectedItemIds.length === 0
                      ? 'bg-gray-100 border border-gray-200 text-gray-400 cursor-not-allowed'
                      : 'bg-[#FFD738] hover:bg-[#FFD738]/90 text-[#1C1D1F] shadow-md shadow-[#FFD738]/20'
                  )}
                >
                  {selectedItemIds.length === 0
                    ? 'Pilih Item Dulu'
                    : 'Lanjut ke Checkout'}
                  <ArrowRight 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">
                      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">
                    <Package className="w-3.5 h-3.5" />
                    <span className="text-[10px] font-bold uppercase tracking-widest">
                      Garansi Ori
                    </span>
                  </div>
                </div>
              </div>
            </GlassCard>
          </motion.div>
        </div>
      </div>

      {/* Mobile Sticky Footer */}
      <div className="lg:hidden fixed bottom-0 left-0 right-0 bg-white/90 backdrop-blur-2xl border-t border-gray-200 p-4 pb-safe flex items-center gap-4 z-30 rounded-t-3xl shadow-[0_-10px_40px_rgba(0,0,0,0.05)]">
        <div className="flex-1 px-2">
          <p className="text-[11px] font-bold text-gray-500 tracking-wider">
            Total Estimasi
          </p>
          <p className="text-xl font-black text-gray-900 tracking-tight">
            {formatIDR(localTotal)}
          </p>
        </div>
        <button
          onClick={handleCheckout}
          disabled={selectedItemIds.length === 0}
          className={cn(
            'flex items-center justify-center gap-2 px-6 py-3.5 rounded-xl font-bold text-sm transition-all shadow-sm',
            selectedItemIds.length === 0
              ? 'bg-gray-100 border border-gray-200 text-gray-400 cursor-not-allowed'
              : 'bg-[#FFD738] text-[#1C1D1F] shadow-md shadow-[#FFD738]/20'
          )}
        >
          Checkout
          <ArrowRight className="w-4 h-4" />
        </button>
      </div>

      {/* Clear dialog */}
      <AnimatePresence>
        {showClearDialog && (
          <ClearCartDialog
            onConfirm={() =>
              clearCart.mutate(undefined, {
                onSuccess: () => setShowClearDialog(false),
              })
            }
            onCancel={() => setShowClearDialog(false)}
            isPending={clearCart.isPending}
          />
        )}
      </AnimatePresence>
    </>
  );
}
