'use client';

import React, { useEffect, useState, useRef, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import api from '@/lib/api';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { SearchableSelect } from '@/components/SearchableSelect';
import { useCart } from '@/context/CartContext';
import { useSiteSettings } from '@/context/SiteSettingsContext';
import { useAuth } from '@/context/AuthContext';
import { trackBeginCheckout } from '@/lib/analytics';
import { Loader2, CreditCard, Landmark, Ticket, Trash2, ChevronRight, ChevronDown, Plus, Minus, Check } from 'lucide-react';

interface LocationItem {
  id: number;
  name: string;
}

interface DistrictItem extends LocationItem {
  division_id: number;
}

interface ShippingMethod {
  id: number;
  name: string;
  cost: number;
  pricing_type: string;
  estimated_days?: number;
}

// Helper to format saved address for checkout card display
function formatSavedAddressHtml(addr: any) {
  let streetLine = addr.street || '';
  let upazilaName = '';
  
  if (streetLine.includes(',')) {
    const parts = streetLine.split(',');
    if (parts.length > 2) {
      streetLine = parts.slice(0, parts.length - 1).join(', ').trim();
      upazilaName = parts[parts.length - 1].trim();
    } else {
      streetLine = parts[0].trim();
      upazilaName = parts[1].trim();
    }
  }

  const thanaZipCity = [
    upazilaName ? `${upazilaName} - ${addr.zip || ''}` : addr.zip || '',
    addr.city || ''
  ].filter(Boolean).join(', ');

  return {
    streetLine,
    thanaZipCity
  };
}

export default function CheckoutPage() {
  const router = useRouter();
  const { cartItems, subtotal, loading: cartLoading, clearCart, updateQuantity, removeItem } = useCart();
  const { formatPrice, settings } = useSiteSettings();
  const { user, loading: authLoading } = useAuth();

  const isCodEnabled = settings?.settings?.cod_enabled === undefined ? true : (settings.settings.cod_enabled === '1' || settings.settings.cod_enabled === 'true' || settings.settings.cod_enabled === true);
  const isSslcommerzEnabled = settings?.settings?.sslcommerz_enabled === '1' || settings?.settings?.sslcommerz_enabled === 'true' || settings?.settings?.sslcommerz_enabled === true;
  const isBkashEnabled = settings?.settings?.bkash_enabled === '1' || settings?.settings?.bkash_enabled === 'true' || settings?.settings?.bkash_enabled === true;
  const isNagadEnabled = settings?.settings?.nagad_enabled === '1' || settings?.settings?.nagad_enabled === 'true' || settings?.settings?.nagad_enabled === true;

  // Form State
  const [customerName, setCustomerName] = useState('');
  const [customerPhone, setCustomerPhone] = useState('');
  const [customerEmail, setCustomerEmail] = useState('');
  const [notes, setNotes] = useState('');
  const [checkoutStep, setCheckoutStep] = useState(1);
  const isSinglePage = settings?.settings?.enable_single_page_checkout !== 'off';
  
  // B2B Reseller Checkout States
  const isReseller = user?.role === 'reseller';
  const [isResellerOrder, setIsResellerOrder] = useState(true);
  const [customPrices, setCustomPrices] = useState<Record<number, number>>({});

  // Compute effective subtotal based on reseller mode and custom pricing
  const effectiveSubtotal = useMemo(() => {
    if (!isReseller) return subtotal;
    
    return cartItems.reduce((sum, item) => {
      const resellerCost = Number(item.reseller_price || 0);
      const priceToUse = isResellerOrder
        ? (customPrices[item.id] !== undefined ? customPrices[item.id] : item.price)
        : resellerCost;
      return sum + priceToUse * item.quantity;
    }, 0);
  }, [cartItems, subtotal, isReseller, isResellerOrder, customPrices]);

  // Compute B2B total commission
  const totalCommission = useMemo(() => {
    if (!isReseller || !isResellerOrder) return 0;
    
    return cartItems.reduce((sum, item) => {
      const resellerCost = Number(item.reseller_price || 0);
      const priceToUse = customPrices[item.id] !== undefined ? customPrices[item.id] : item.price;
      return sum + Math.max(0, priceToUse - resellerCost) * item.quantity;
    }, 0);
  }, [cartItems, isReseller, isResellerOrder, customPrices]);

  const validateStep1 = () => {
    if (!customerName.trim()) {
      alert("Please enter your full name.");
      return false;
    }
    if (!customerPhone.trim()) {
      alert("Please enter your phone number.");
      return false;
    }
    if (!selectedDistrict) {
      alert("Please select your delivery district.");
      return false;
    }
    if (!streetAddress.trim()) {
      alert("Please enter your delivery street address.");
      return false;
    }
    if (!sameAsShipping) {
      if (!selectedBillingDistrict) {
        alert("Please select your billing district.");
        return false;
      }
      if (!billingStreetAddress.trim()) {
        alert("Please enter your billing street address.");
        return false;
      }
    }
    return true;
  };

  const handleNextStep = () => {
    if (validateStep1()) {
      setCheckoutStep(2);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const handlePrevStep = () => {
    setCheckoutStep(1);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Shipping Location
  const [divisions, setDivisions] = useState<LocationItem[]>([]);
  const [districts, setDistricts] = useState<DistrictItem[]>([]);
  const [upazilas, setUpazilas] = useState<LocationItem[]>([]);
  const [selectedDivision, setSelectedDivision] = useState<number | ''>('');
  const [selectedDistrict, setSelectedDistrict] = useState<number | ''>('');
  const [selectedUpazila, setSelectedUpazila] = useState<number | ''>('');
  const [streetAddress, setStreetAddress] = useState('');
  const [loadingUpazilas, setLoadingUpazilas] = useState(false);

  // Saved addresses
  const [savedAddresses, setSavedAddresses] = useState<any[]>([]);
  const [selectedSavedAddressId, setSelectedSavedAddressId] = useState<number | null>(null);
  const pendingUpazilaNameRef = useRef<string | null>(null);
  const upazilasCacheRef = useRef<Record<number, LocationItem[]>>({});

  // Scroll position restoration
  const scrollRestoredRef = useRef(false);
  const pendingRestoreRef = useRef(false);
  const isRestoringRef = useRef(false); // pause scroll-save during smooth scroll
  const SCROLL_KEY = 'scroll_checkout';

  useEffect(() => {
    // Prevent browser/Next.js from auto-restoring scroll
    if (typeof window !== 'undefined') {
      history.scrollRestoration = 'manual';
      const saved = sessionStorage.getItem(SCROLL_KEY);
      if (saved && parseInt(saved, 10) > 0) {
        pendingRestoreRef.current = true;
        isRestoringRef.current = true; // block scroll-saving during loading
      }
    }
    const handleScrollSave = () => {
      if (isRestoringRef.current) return; // don't save during restoration
      sessionStorage.setItem(SCROLL_KEY, String(window.scrollY));
    };
    window.addEventListener('scroll', handleScrollSave, { passive: true });
    return () => window.removeEventListener('scroll', handleScrollSave);
  }, []);

  // Restore scroll after cart content is fully rendered
  useEffect(() => {
    if (cartLoading) return;
    if (!pendingRestoreRef.current) return;
    pendingRestoreRef.current = false;
    scrollRestoredRef.current = true;
    const saved = sessionStorage.getItem(SCROLL_KEY);
    if (!saved) {
      isRestoringRef.current = false;
      return;
    }
    const pos = parseInt(saved, 10);
    if (isNaN(pos) || pos <= 0) {
      isRestoringRef.current = false;
      return;
    }
    setTimeout(() => {
      isRestoringRef.current = true;
      window.scrollTo({ top: pos, behavior: 'smooth' });
      // Re-enable saving after smooth scroll animation finishes (~600ms)
      // and lock in the correct target position
      setTimeout(() => {
        isRestoringRef.current = false;
        sessionStorage.setItem(SCROLL_KEY, String(pos));
      }, 700);
    }, 120);
  }, [cartLoading]);

  // Billing Location
  const [sameAsShipping, setSameAsShipping] = useState(true);
  const [billingDistricts, setBillingDistricts] = useState<DistrictItem[]>([]);
  const [billingUpazilas, setBillingUpazilas] = useState<LocationItem[]>([]);
  const [selectedBillingDivision, setSelectedBillingDivision] = useState<number | ''>('');
  const [selectedBillingDistrict, setSelectedBillingDistrict] = useState<number | ''>('');
  const [selectedBillingUpazila, setSelectedBillingUpazila] = useState<number | ''>('');
  const [billingStreetAddress, setBillingStreetAddress] = useState('');
  const [loadingBillingUpazilas, setLoadingBillingUpazilas] = useState(false);

  // Shipping Methods
  const [shippingMethods, setShippingMethods] = useState<ShippingMethod[]>([]);
  const [selectedShippingMethod, setSelectedShippingMethod] = useState<number | ''>('');
  const [shippingCost, setShippingCost] = useState(0); // Default 0, auto-calculated on district select

  // Coupon
  const [couponCode, setCouponCode] = useState('');
  const [appliedCoupon, setAppliedCoupon] = useState<any>(null);
  const [discount, setDiscount] = useState(0);
  const [couponExpanded, setCouponExpanded] = useState(false);

  // Payment & Submit
  const [paymentMethod, setPaymentMethod] = useState<'cod' | 'sslcommerz' | 'bkash' | 'nagad'>('cod');
  const [agreeTerms, setAgreeTerms] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  const beginCheckoutTrackedRef = useRef(false);

  // Redirect if cart is empty
  useEffect(() => {
    if (!cartLoading && cartItems.length === 0) {
      router.push('/shop');
    }
  }, [cartItems, cartLoading]);

  // Track begin_checkout event when cart content is loaded
  useEffect(() => {
    if (!cartLoading && cartItems.length > 0 && !beginCheckoutTrackedRef.current) {
      beginCheckoutTrackedRef.current = true;
      trackBeginCheckout(cartItems, subtotal);
    }
  }, [cartItems, cartLoading, subtotal]);

  // Prefill authenticated customer details & load saved addresses
  useEffect(() => {
    if (user) {
      setCustomerName(user.name);
      setCustomerEmail(user.email);
      setCustomerPhone(user.phone || '');
      // addresses already loaded by AuthContext — no extra API call needed
      if (user.addresses) {
        setSavedAddresses(user.addresses);
      }
    }
  }, [user]);

  // Redirect to login if guest checkout is disabled and user is not authenticated
  useEffect(() => {
    if (!authLoading && !user && settings?.settings?.enable_guest_checkout === 'off') {
      router.push('/login?redirect=/checkout');
    }
  }, [user, authLoading, settings, router]);

  // Sync agreeTerms default state with settings
  useEffect(() => {
    if (settings?.settings?.enable_privacy_terms === 'on') {
      setAgreeTerms(false);
    } else {
      setAgreeTerms(true);
    }
  }, [settings]);

  // Set default payment method based on enabled options
  useEffect(() => {
    if (settings?.settings) {
      const isCod = settings.settings.cod_enabled === undefined ? true : (settings.settings.cod_enabled === '1' || settings.settings.cod_enabled === 'true' || settings.settings.cod_enabled === true);
      const isSsl = settings.settings.sslcommerz_enabled === '1' || settings.settings.sslcommerz_enabled === 'true' || settings.settings.sslcommerz_enabled === true;
      const isBka = settings.settings.bkash_enabled === '1' || settings.settings.bkash_enabled === 'true' || settings.settings.bkash_enabled === true;
      const isNag = settings.settings.nagad_enabled === '1' || settings.settings.nagad_enabled === 'true' || settings.settings.nagad_enabled === true;

      if (!isCod) {
        if (isSsl) setPaymentMethod('sslcommerz');
        else if (isBka) setPaymentMethod('bkash');
        else if (isNag) setPaymentMethod('nagad');
      }
    }
  }, [settings]);

  // Load Divisions & Districts on mount
  useEffect(() => {
    const loadLocations = async () => {
      try {
        const divRes = await api.get('/api/divisions');
        setDivisions(divRes.data || []);

        const distRes = await api.get('/api/districts');
        const allDistricts: DistrictItem[] = distRes.data || [];
        
        // Sort districts alphabetically by name
        allDistricts.sort((a, b) => a.name.localeCompare(b.name));
        
        setDistricts(allDistricts);
        setBillingDistricts(allDistricts);
      } catch (err) {
        console.error('Failed to load locations', err);
      }
    };
    loadLocations();
  }, []);

  // Shipping Upazilas loading
  useEffect(() => {
    if (!selectedDistrict) {
      setUpazilas([]);
      setSelectedUpazila('');
      return;
    }
    const loadUpazilas = async () => {
      const cacheHit = upazilasCacheRef.current[selectedDistrict];
      if (cacheHit) {
        setUpazilas(cacheHit);
        const pending = pendingUpazilaNameRef.current;
        if (pending) {
          const matchingUpazila = cacheHit.find(
            (u: any) => u.name.toLowerCase() === pending.toLowerCase()
          );
          if (matchingUpazila) {
            setSelectedUpazila(matchingUpazila.id);
          } else {
            setSelectedUpazila('');
          }
          pendingUpazilaNameRef.current = null;
        } else {
          setSelectedUpazila(prev => {
            if (prev && cacheHit.some((u: any) => u.id === prev)) return prev;
            return '';
          });
        }
        return;
      }

      setLoadingUpazilas(true);
      try {
        const res = await api.get(`/api/upazilas/${selectedDistrict}`);
        const data = res.data || [];
        upazilasCacheRef.current[selectedDistrict] = data;
        setUpazilas(data);
        
        const pending = pendingUpazilaNameRef.current;
        if (pending) {
          const matchingUpazila = data.find(
            (u: any) => u.name.toLowerCase() === pending.toLowerCase()
          );
          if (matchingUpazila) {
            setSelectedUpazila(matchingUpazila.id);
          } else {
            setSelectedUpazila('');
          }
          pendingUpazilaNameRef.current = null;
        } else {
          setSelectedUpazila(prev => {
            if (prev && data.some((u: any) => u.id === prev)) return prev;
            return '';
          });
        }
      } catch (err) {
        console.error('Failed to load upazilas', err);
      } finally {
        setLoadingUpazilas(false);
      }
    };
    loadUpazilas();
  }, [selectedDistrict]);

  // Shipping Methods loading & auto-calculation based on selected district and cart items (weight-based/flat rate)
  const cartItemsKey = cartItems.map(item => `${item.id}:${item.quantity}`).join(',');

  useEffect(() => {
    if (!selectedDistrict) {
      setShippingMethods([]);
      setSelectedShippingMethod('');
      setShippingCost(0);
      return;
    }
    const loadShipping = async () => {
      try {
        const res = await api.post('/api/shipping-methods', { district_id: selectedDistrict });
        const methods: ShippingMethod[] = res.data || [];
        setShippingMethods(methods);
        if (methods.length > 0) {
          setSelectedShippingMethod(methods[0].id);
          setShippingCost(methods[0].cost);
        } else {
          setSelectedShippingMethod('');
          setShippingCost(0);
        }
      } catch (err) {
        console.error('Failed to load shipping methods', err);
      }
    };
    loadShipping();
  }, [selectedDistrict, cartItemsKey]);

  // Billing Upazilas loading
  useEffect(() => {
    if (!selectedBillingDistrict) {
      setBillingUpazilas([]);
      setSelectedBillingUpazila('');
      return;
    }
    const loadUpazilas = async () => {
      const cacheHit = upazilasCacheRef.current[selectedBillingDistrict];
      if (cacheHit) {
        setBillingUpazilas(cacheHit);
        setSelectedBillingUpazila(prev => {
          if (prev && cacheHit.some((u: any) => u.id === prev)) return prev;
          return '';
        });
        return;
      }

      setLoadingBillingUpazilas(true);
      try {
        const res = await api.get(`/api/upazilas/${selectedBillingDistrict}`);
        const data = res.data || [];
        upazilasCacheRef.current[selectedBillingDistrict] = data;
        setBillingUpazilas(data);
        setSelectedBillingUpazila(prev => {
          if (prev && data.some((u: any) => u.id === prev)) return prev;
          return '';
        });
      } catch (err) {
        console.error('Failed to load upazilas', err);
      } finally {
        setLoadingBillingUpazilas(false);
      }
    };
    loadUpazilas();
  }, [selectedBillingDistrict]);

  // Auto-fill address from saved addresses selector
  const handleSelectSavedAddress = (addr: any) => {
    setSelectedSavedAddressId(addr.id);

    // Fill customer info
    if (user) {
      setCustomerName(user.name || '');
      setCustomerPhone(addr.phone || user.phone || '');
      setCustomerEmail(user.email || '');
    }

    // 1. Parse street address and upazila
    let streetLine = addr.street || '';
    let upazilaName = '';
    if (streetLine.includes(',')) {
      const parts = streetLine.split(',');
      if (parts.length > 2) {
        streetLine = parts.slice(0, parts.length - 1).join(', ').trim();
        upazilaName = parts[parts.length - 1].trim();
      } else {
        streetLine = parts[0].trim();
        upazilaName = parts[1].trim();
      }
    }
    setStreetAddress(streetLine);
    pendingUpazilaNameRef.current = upazilaName || null;

    // 2. Look up district by name
    const cityName = addr.city || '';
    const district = districts.find(
      (d) => d.name.toLowerCase() === cityName.toLowerCase()
    );

    if (district) {
      setSelectedDivision(district.division_id);
      setSelectedDistrict(district.id);

      // If the district didn't change, the useEffect checking selectedDistrict won't fire.
      // We manually look up and set the upazila from the already loaded upazilas state.
      if (selectedDistrict === district.id) {
        if (upazilaName) {
          const matchingUpazila = upazilas.find(
            (u: any) => u.name.toLowerCase() === upazilaName.toLowerCase()
          );
          if (matchingUpazila) {
            setSelectedUpazila(matchingUpazila.id);
          } else {
            setSelectedUpazila('');
          }
        } else {
          setSelectedUpazila('');
        }
        pendingUpazilaNameRef.current = null;
      }
    } else {
      setSelectedDivision('');
      setSelectedDistrict('');
      setSelectedUpazila('');
      pendingUpazilaNameRef.current = null;
    }
  };

  const handleDistrictChange = (districtId: number | '') => {
    setSelectedDistrict(districtId);
    setSelectedSavedAddressId(null);
    if (!districtId) {
      setSelectedDivision('');
      return;
    }
    const district = districts.find(d => d.id === districtId);
    if (district) {
      setSelectedDivision(district.division_id);
    }
  };

  const handleBillingDistrictChange = (districtId: number | '') => {
    setSelectedBillingDistrict(districtId);
    if (!districtId) {
      setSelectedBillingDivision('');
      return;
    }
    const district = billingDistricts.find(d => d.id === districtId);
    if (district) {
      setSelectedBillingDivision(district.division_id);
    }
  };

  // Update shipping cost when selected method changes
  const handleShippingMethodChange = (id: number) => {
    setSelectedShippingMethod(id);
    const method = shippingMethods.find(m => m.id === id);
    if (method) {
      setShippingCost(method.cost);
    }
  };

  // Quantity updates in Order Review
  const handleCheckoutQtyChange = async (itemId: number, currentQty: number, change: number) => {
    const nextQty = currentQty + change;
    if (nextQty < 1) return;
    try {
      await updateQuantity(itemId, nextQty);
    } catch (err: any) {
      console.error('Failed to update quantity', err);
      alert(err.message || 'Failed to update quantity. Please check product stock.');
    }
  };

  // Coupon application
  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) return;
    try {
      const res = await api.post('/api/coupon/apply', { coupon_code: couponCode.trim() });
      if (res.data.success) {
        setAppliedCoupon(res.data.coupon);
        setDiscount(res.data.discount);
        alert('Coupon code applied successfully!');
      }
    } catch (err: any) {
      alert(err.response?.data?.message || 'Failed to apply coupon');
      setAppliedCoupon(null);
      setDiscount(0);
    }
  };

  const handleRemoveCoupon = () => {
    setAppliedCoupon(null);
    setDiscount(0);
    setCouponCode('');
  };

  // Submit checkout order
  const handleSubmitOrder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!isSinglePage && checkoutStep === 1) {
      if (validateStep1()) {
        setCheckoutStep(2);
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
      return;
    }
    if (!selectedDivision || !selectedDistrict || !selectedUpazila || !selectedShippingMethod) {
      alert('Please complete all shipping address and method selectors.');
      return;
    }
    if (!agreeTerms) {
      alert('Please agree to the Terms and Conditions to place your order.');
      return;
    }

    setSubmitting(true);
    try {
      const payload = {
        customer_name: customerName,
        customer_phone: customerPhone,
        customer_email: customerEmail,
        selected_division_id: selectedDivision,
        selected_district_id: selectedDistrict,
        selected_upazila_id: selectedUpazila,
        street_address: streetAddress,
        selected_shipping_method_id: selectedShippingMethod,
        payment_method: paymentMethod,
        notes: notes,
        same_as_shipping: sameAsShipping,
        
        // Billing fields
        selected_billing_division_id: !sameAsShipping ? selectedBillingDivision : null,
        selected_billing_district_id: !sameAsShipping ? selectedBillingDistrict : null,
        selected_billing_upazila_id: !sameAsShipping ? selectedBillingUpazila : null,
        billing_street_address: !sameAsShipping ? billingStreetAddress : null,

        // Coupon code
        coupon_code: appliedCoupon ? appliedCoupon.code : null,

        // Reseller fields (B2B)
        is_reseller_order: isReseller ? isResellerOrder : false,
        reseller_selling_prices: isReseller ? customPrices : null,
      };

      const res = await api.post('/api/checkout', payload);
      
      if (res.data.success && res.data.redirect_url) {
        // Save order data for tracking in success page
        try {
          sessionStorage.setItem('last_order_tracking', JSON.stringify({
            id: res.data.order_id,
            order_number: res.data.order_number,
            total: Math.max((effectiveSubtotal + shippingCost) - discount, 0),
            shipping_fee: shippingCost,
            items: cartItems.map(item => ({
              product_id: item.product_id,
              name: item.name,
              price: item.price,
              quantity: item.quantity
            })),
            customer: {
              name: customerName,
              phone: customerPhone,
              email: customerEmail
            }
          }));
        } catch (e) {
          console.error('Failed to save order tracking data', e);
        }

        await clearCart();
        window.location.href = res.data.redirect_url;
      } else {
        alert(res.data.message || 'Failed to process checkout');
      }
    } catch (err: any) {
      alert(err.response?.data?.message || 'Failed to submit order. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const grandTotal = Math.max((effectiveSubtotal + shippingCost) - discount, 0);
  const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000';
  const imgUrl = (url: string) => url.startsWith('http') ? url : `${backendUrl}${url}`;

  if (cartLoading || authLoading) {
    return (
      <>
        <Header />
        <main className="bg-[#f5f5f5] min-h-screen pb-12 animate-pulse">
          {/* Breadcrumb & Title Skeleton */}
          <section className="checkout-page-breadcrumbs text-center py-2 sm:py-5 bg-white border-b border-slate-200/50 space-y-2">
            <div className="h-7 bg-slate-300 rounded w-32 mx-auto"></div>
            <div className="flex items-center justify-center gap-1.5 text-xs mt-1">
              <div className="h-4 bg-slate-200 rounded w-10"></div>
              <span className="text-slate-300">&gt;</span>
              <div className="h-4 bg-slate-200 rounded w-16"></div>
            </div>
          </section>

          <div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8">
            <div className="w-full flex flex-col lg:flex-row gap-6 items-start">
              
              {/* LEFT Side: Billing/Shipping form skeleton */}
              <div className="flex-1 w-full bg-white rounded-2xl p-6 border border-slate-200/60 shadow-xs space-y-6">
                <div className="h-6 bg-slate-300 rounded w-48"></div>
                
                {/* Form fields */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <div className="h-4 bg-slate-200 rounded w-28"></div>
                    <div className="h-11 bg-slate-100 rounded-lg w-full"></div>
                  </div>
                  <div className="space-y-1.5">
                    <div className="h-4 bg-slate-200 rounded w-28"></div>
                    <div className="h-11 bg-slate-100 rounded-lg w-full"></div>
                  </div>
                </div>

                <div className="space-y-1.5">
                  <div className="h-4 bg-slate-200 rounded w-28"></div>
                  <div className="h-11 bg-slate-100 rounded-lg w-full"></div>
                </div>

                {/* Dropdowns */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-1.5">
                    <div className="h-4 bg-slate-200 rounded w-20"></div>
                    <div className="h-11 bg-slate-100 rounded-lg w-full"></div>
                  </div>
                  <div className="space-y-1.5">
                    <div className="h-4 bg-slate-200 rounded w-20"></div>
                    <div className="h-11 bg-slate-100 rounded-lg w-full"></div>
                  </div>
                  <div className="space-y-1.5">
                    <div className="h-4 bg-slate-200 rounded w-20"></div>
                    <div className="h-11 bg-slate-100 rounded-lg w-full"></div>
                  </div>
                </div>

                <div className="space-y-1.5">
                  <div className="h-4 bg-slate-200 rounded w-28"></div>
                  <div className="h-24 bg-slate-100 rounded-lg w-full"></div>
                </div>
              </div>

              {/* RIGHT Side: Order summary skeleton */}
              <div className="w-full lg:w-[420px] shrink-0 bg-white rounded-2xl p-6 border border-slate-200/60 shadow-xs space-y-6">
                <div className="h-6 bg-slate-300 rounded w-36"></div>
                
                {/* Cart items list skeleton */}
                <div className="space-y-4">
                  {[...Array(2)].map((_, i) => (
                    <div key={i} className="flex gap-3 items-center">
                      <div className="h-16 w-16 bg-slate-200 rounded-lg"></div>
                      <div className="flex-1 space-y-2">
                        <div className="h-4 bg-slate-200 rounded w-3/4"></div>
                        <div className="h-3.5 bg-slate-150 rounded w-1/4"></div>
                      </div>
                      <div className="h-4 bg-slate-200 rounded w-12 text-right"></div>
                    </div>
                  ))}
                </div>

                <div className="border-t border-slate-100 pt-4 space-y-3">
                  <div className="flex justify-between">
                    <div className="h-4 bg-slate-200 rounded w-16"></div>
                    <div className="h-4 bg-slate-200 rounded w-12"></div>
                  </div>
                  <div className="flex justify-between">
                    <div className="h-4 bg-slate-200 rounded w-24"></div>
                    <div className="h-4 bg-slate-200 rounded w-10"></div>
                  </div>
                  <div className="flex justify-between pt-2 border-t border-slate-100">
                    <div className="h-5 bg-slate-300 rounded w-20"></div>
                    <div className="h-5 bg-slate-300 rounded w-16"></div>
                  </div>
                </div>

                {/* Payment & CTA */}
                <div className="space-y-3 pt-2">
                  <div className="h-4 bg-slate-200 rounded w-32"></div>
                  <div className="flex gap-2">
                    <div className="h-11 bg-slate-100 rounded-lg flex-1"></div>
                    <div className="h-11 bg-slate-100 rounded-lg flex-1"></div>
                  </div>
                  <div className="h-12 bg-slate-350 rounded-xl w-full"></div>
                </div>
              </div>

            </div>
          </div>
        </main>
        <div className="hidden sm:block">
          <Footer />
        </div>
      </>
    );
  }

  return (
    <>
      <Header />
      <main className="bg-[#f5f5f5] min-h-screen pb-24 sm:pb-12 font-open-sans">
        
        {/* ── Breadcrumb & Title ── */}
        <section className="checkout-page-breadcrumbs text-center py-2 sm:py-5 bg-white border-b border-slate-200/50">
          <h1 className="text-[20px] sm:text-[24px] font-bold text-slate-800">Checkout</h1>
          <div className="hidden sm:flex items-center justify-center gap-1.5 text-[14px] text-slate-400 mt-1 font-medium">
            <Link href="/" className="hover:text-secondary transition-colors">Home</Link>
            <span>&gt;</span>
            <span className="text-secondary">Checkout</span>
          </div>
        </section>

        {!user && (
          <div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8 mt-2 sm:mt-5">
            <div className="checkout-alert bg-[#f8f9fa] border border-slate-300/80 rounded-xl pt-2 px-3 pb-3 sm:py-0 sm:px-6 w-full min-h-[68px] sm:min-h-0 sm:h-[73px] text-center sm:text-left flex flex-col sm:flex-row items-center justify-center sm:justify-between gap-1.5 sm:gap-3">
              <p className="text-[14px] sm:text-[16px] font-medium text-[#666666] font-open-sans">
                Have any account? please login or register
              </p>
              <div className="flex gap-3">
                <Link
                  href="/login?redirect=/checkout"
                  className="px-5 py-1.5 bg-white border border-secondary text-[#222831] rounded-lg text-[12px] sm:text-[14px] font-semibold hover:bg-slate-50 transition-colors shadow-xs font-open-sans"
                >
                  Login
                </Link>
                <Link
                  href="/register?redirect=/checkout"
                  className="px-5 py-1.5 bg-secondary text-white rounded-lg text-[12px] sm:text-[14px] font-semibold hover:bg-secondary-dark transition-colors shadow-xs font-open-sans"
                >
                  Register
                </Link>
              </div>
            </div>
          </div>
        )}

        <div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8 flex flex-col justify-center items-center">
          {!isSinglePage && (
            <div className="flex items-center justify-center gap-4 sm:gap-8 mb-6 sm:mb-8 bg-white border border-slate-200/60 rounded-2xl py-4 px-6 shadow-sm max-w-3xl mx-auto w-full">
              <button
                type="button"
                onClick={handlePrevStep}
                className={`flex items-center gap-2 pb-1 border-b-2 transition-all cursor-pointer ${
                  checkoutStep === 1 ? 'border-secondary text-secondary' : 'border-transparent text-slate-400'
                }`}
              >
                <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-black border ${
                  checkoutStep === 1 ? 'bg-secondary text-white border-secondary' : 'bg-slate-100 text-slate-500'
                }`}>1</span>
                <span className="text-xs sm:text-sm font-bold font-open-sans">Delivery Info</span>
              </button>
              <div className="h-[1px] w-8 sm:w-16 bg-slate-200"></div>
              <button
                type="button"
                onClick={handleNextStep}
                className={`flex items-center gap-2 pb-1 border-b-2 transition-all cursor-pointer ${
                  checkoutStep === 2 ? 'border-secondary text-secondary' : 'border-transparent text-slate-400'
                }`}
              >
                <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-black border ${
                  checkoutStep === 2 ? 'bg-secondary text-white border-secondary' : 'bg-slate-100 text-slate-500'
                }`}>2</span>
                <span className="text-xs sm:text-sm font-bold font-open-sans">Payment & Order</span>
              </button>
            </div>
          )}
          <form onSubmit={handleSubmitOrder} className="w-full flex flex-col lg:flex-row justify-center items-start gap-4 lg:gap-6">
            
            {/* LEFT COLUMN: Shipping info, addresses, methods (717px) */}
            {(isSinglePage || checkoutStep === 1) && (
              <div className={`w-full max-w-full space-y-4 lg:space-y-5 ${isSinglePage ? 'lg:w-[717px]' : 'max-w-3xl mx-auto'}`}>
              
              {/* 1. Order Review */}
              <div className="checkout-order-review bg-white p-4 rounded-2xl border border-slate-200/60 shadow-sm space-y-4 mt-4 lg:mt-5">
                <div className="flex items-center gap-2 border-l-4 border-secondary pl-3 mb-4">
                  <h2 className="text-[14px] sm:text-base font-semibold text-slate-850 font-open-sans">Order review</h2>
                </div>

                <div className="divide-y divide-slate-100">
                  {cartItems.map(item => (
                    <div key={item.id} className="py-4 flex items-center justify-between gap-4 first:pt-0 last:pb-0">
                      {/* Left: Thumbnail & Details */}
                      <div className="flex items-start gap-3 sm:gap-4 flex-1 min-w-0 min-h-[50.41px] sm:min-h-[55.99px]">
                        {/* Thumbnail */}
                        <div className="w-[50.41px] sm:w-[55.99px] h-[50.41px] sm:h-[55.99px] border border-slate-200 rounded-md overflow-hidden flex-shrink-0 bg-white flex items-center justify-center">
                          <img
                            src={imgUrl(item.image_url)}
                            alt={item.name}
                            className="w-full h-full object-contain rounded-sm"
                          />
                        </div>

                        {/* Details */}
                        <div className="checkout-order-details space-y-1 sm:space-y-1.5 flex-1 min-w-0 text-[#666666] font-open-sans text-[12px] sm:text-[14px] font-normal">
                          <span className="font-open-sans font-medium text-[12px] sm:text-[14px] text-[#666666] block truncate">{item.name}</span>
                          
                          {/* Variant Options */}
                          {item.options && Object.keys(item.options).length > 0 && (
                            <div className="flex gap-1.5 flex-wrap mt-1">
                              {Object.entries(item.options).map(([key, val]) => (
                                <span key={key} className="text-[10px] font-semibold bg-slate-100 border border-slate-200/60 text-slate-500 px-2 py-0.5 rounded-md">
                                  {key}: {val}
                                </span>
                              ))}
                            </div>
                          )}

                          {/* Gift badge if price is 0 */}
                          {Number(item.price) === 0 && (
                            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-[#e6f7f4] text-[#00a685] select-none">
                              Gift
                            </span>
                          )}

                          {/* Qty & Price Row */}
                          <div className="flex items-center gap-3.5 flex-wrap">
                            <span className="text-[12px] sm:text-[14px] font-normal font-open-sans text-[#666666]">Qty:</span>
                            
                            {/* Quantity Selector */}
                            <div className="flex items-center border border-slate-200/80 rounded-md h-7 sm:h-8 px-1 bg-slate-50/50 justify-between w-[90px]">
                              <button
                                type="button"
                                onClick={() => handleCheckoutQtyChange(item.id, item.quantity, -1)}
                                className="w-5 h-5 sm:w-6 sm:h-6 flex items-center justify-center text-[#666666] hover:bg-slate-100/80 rounded transition-colors font-normal text-xs sm:text-sm cursor-pointer select-none"
                              >
                                -
                              </button>
                              <span className="text-[12px] sm:text-[14px] font-normal text-[#666666] font-open-sans">{item.quantity}</span>
                              <button
                                type="button"
                                onClick={() => handleCheckoutQtyChange(item.id, item.quantity, 1)}
                                className="w-5 h-5 sm:w-6 sm:h-6 flex items-center justify-center text-[#666666] hover:bg-slate-100/80 rounded transition-colors font-normal text-xs sm:text-sm cursor-pointer select-none"
                              >
                                +
                              </button>
                            </div>

                             {/* Item Price */}
                             {isReseller ? (
                               isResellerOrder ? (
                                 <div className="flex flex-col gap-1 ml-2">
                                   <div className="flex items-center gap-1.5">
                                     <span className="text-[11px] text-[#666666] font-bold">Retail Price:</span>
                                     <div className="flex items-center">
                                       <span className="text-xs text-[#666666] mr-0.5">৳</span>
                                       <input
                                         type="number"
                                         value={customPrices[item.id] !== undefined ? customPrices[item.id] : item.price}
                                         min={Number(item.reseller_price || 0)}
                                         onChange={(e) => {
                                           const val = Number(e.target.value);
                                           setCustomPrices(prev => ({ ...prev, [item.id]: val }));
                                         }}
                                         className="w-[70px] h-7 border border-slate-200 rounded px-1 text-xs text-slate-800 focus:outline-none focus:ring-1 focus:ring-emerald-500 font-poppins"
                                       />
                                     </div>
                                   </div>
                                   <div className="text-[10px] text-emerald-600 font-bold bg-emerald-50 px-1.5 py-0.5 rounded border border-emerald-100/60 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-0.5">
                                     <span>Reseller Cost: ৳{Number(item.reseller_price || 0)}</span>
                                     <span>Profit: ৳{Math.max(0, (customPrices[item.id] !== undefined ? customPrices[item.id] : item.price) - Number(item.reseller_price || 0)) * item.quantity}</span>
                                   </div>
                                 </div>
                               ) : (
                                 <div className="flex flex-col ml-2">
                                   <span className="text-[11px] font-black text-slate-800 line-through decoration-slate-400 font-open-sans">
                                     {formatPrice(item.price)}
                                     <span className="text-[9px] text-slate-400 font-normal no-underline ml-1">(Retail)</span>
                                   </span>
                                   <span className="text-[10px] text-emerald-600 font-bold">
                                     Reseller Cost: {formatPrice(Number(item.reseller_price || 0))}
                                   </span>
                                   <span className="text-[9px] text-emerald-700 font-bold bg-emerald-50 px-1.5 py-0.5 rounded border border-emerald-100/60 mt-0.5">
                                     Profit: {formatPrice(Math.max(0, item.price - Number(item.reseller_price || 0)) * item.quantity)}
                                   </span>
                                 </div>
                               )
                             ) : (
                               <span className="text-[12px] sm:text-[14px] font-semibold text-[#666666] font-open-sans ml-2 mt-1.5">
                                 {formatPrice(item.price * item.quantity)}
                               </span>
                             )}
                           </div>
                          </div>
                        </div>

                      {/* Far Right: Delete button (solid red square box) */}
                      <button
                        type="button"
                        onClick={() => removeItem(item.id)}
                        className="w-8 h-8 flex items-center justify-center bg-[#ef4444] hover:bg-[#dc2626] text-white rounded-lg transition-colors flex-shrink-0 cursor-pointer shadow-sm hover:shadow"
                      >
                        <Trash2 className="h-4.5 w-4.5" />
                      </button>
                    </div>
                  ))}
                </div>
              </div>

              {/* 2 & 3. Shipping and Saved Addresses Combined Card Container */}
              <div className="bg-white p-6 rounded-2xl border border-slate-200/60 shadow-sm space-y-6">
                

                
                {/* Saved Addresses Section (Only if savedAddresses.length > 0) */}
                {savedAddresses.length > 0 && (
                  <div className="space-y-4">
                    <div className="flex items-center gap-2 border-l-4 border-secondary pl-3">
                      <h2 className="text-[14px] sm:text-base font-semibold text-slate-850 font-open-sans">Saved Addresses</h2>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      {savedAddresses.map((addr) => {
                        const isSelected = selectedSavedAddressId === addr.id;
                        const label = addr.country || 'Saved Address';
                        const { streetLine, thanaZipCity } = formatSavedAddressHtml(addr);
                        return (
                          <div
                            key={addr.id}
                            onClick={() => handleSelectSavedAddress(addr)}
                            className={`address_box border rounded-xl p-4 cursor-pointer relative transition-all bg-white ${
                              isSelected
                                ? 'border-secondary'
                                : 'border-slate-200 hover:border-slate-300'
                            }`}
                          >
                            <label className="flex items-center gap-2 mb-1 cursor-pointer select-none">
                              <input
                                type="radio"
                                name="saved_address_id"
                                checked={isSelected}
                                readOnly
                                className="text-secondary focus:ring-secondary h-4 w-4 cursor-pointer accent-secondary"
                              />
                              <span className="text-[12px] sm:text-[14px] font-bold text-secondary font-open-sans">
                                {label} Address
                              </span>
                            </label>
                            <address className="text-[12px] sm:text-[14px] text-[#666666] leading-[120%] mt-1 font-open-sans italic">
                              {user?.name}<br />
                              {streetLine}<br />
                              {thanaZipCity}
                              {addr.phone && (
                                <>
                                  <br />Phone: {addr.phone}
                                </>
                              )}
                            </address>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* Shipping Address Section */}
                <div className="space-y-4">
                  <div className="flex items-center gap-2 border-l-4 border-secondary pl-3">
                    <h2 className="text-[14px] sm:text-base font-semibold text-slate-850 font-open-sans">Shipping Address</h2>
                  </div>
                  
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    {/* Name */}
                    <div className="w-full">
                      <input
                        type="text"
                        required
                        name="customer_name"
                        autoComplete="name"
                        placeholder="Your Full Name *"
                        value={customerName}
                        onChange={(e) => {
                          setCustomerName(e.target.value);
                          setSelectedSavedAddressId(null);
                        }}
                        className="w-full text-[12px] sm:text-[15px] font-medium px-4 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:outline-none transition-all shadow-sm"
                      />
                    </div>

                    {/* Phone */}
                    <div className="flex rounded-xl overflow-hidden border border-slate-200 focus-within:border-secondary bg-white transition-all shadow-sm">
                      <div className="bg-[#f8f9fa] px-4 py-3 text-slate-650 font-medium border-r border-slate-200 flex items-center justify-center text-[12px] sm:text-[15px] select-none">
                        88
                      </div>
                      <input
                        type="text"
                        required
                        name="customer_phone"
                        autoComplete="tel"
                        value={customerPhone}
                        onChange={(e) => {
                          setCustomerPhone(e.target.value);
                          setSelectedSavedAddressId(null);
                        }}
                        className="flex-1 px-4 py-3 bg-white text-[12px] sm:text-[15px] font-medium text-slate-800 focus:outline-none placeholder-slate-400"
                        placeholder="017********"
                      />
                    </div>
                  </div>

                  {/* Delivery address */}
                  <div className="w-full">
                    <input
                      type="text"
                      required
                      name="street_address"
                      autoComplete="street-address"
                      placeholder="ex: House no. / building / street / area"
                      value={streetAddress}
                      onChange={(e) => {
                        setStreetAddress(e.target.value);
                        setSelectedSavedAddressId(null);
                      }}
                      className="w-full text-[12px] sm:text-[15px] font-medium px-4 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:outline-none transition-all shadow-sm"
                    />
                  </div>

                  {/* Location Selectors: District & Thana side-by-side */}
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    {/* District */}
                    <div>
                      <SearchableSelect
                        options={districts}
                        value={selectedDistrict}
                        onChange={handleDistrictChange}
                        placeholder="Select District"
                        required
                        textSizeClass="text-[12px] sm:text-[15px]"
                      />
                    </div>

                    {/* Area / Upazila */}
                    <div>
                      <SearchableSelect
                        options={upazilas}
                        value={selectedUpazila}
                        onChange={(val) => {
                          setSelectedUpazila(val);
                          setSelectedSavedAddressId(null);
                        }}
                        placeholder="Select Thana (Optional)"
                        disabled={!selectedDistrict || loadingUpazilas}
                        loading={loadingUpazilas}
                        required
                        textSizeClass="text-[12px] sm:text-[15px]"
                      />
                    </div>
                  </div>

                </div>

              </div>

              {/* 4. Billing Address Selector */}
              <div className="bg-white p-5 rounded-2xl border border-slate-200/60 shadow-sm space-y-4">
                <div className="flex items-center justify-between border-l-4 border-secondary pl-3">
                  <h2 className="text-[14px] sm:text-base font-semibold text-slate-850 font-open-sans">Billing Address</h2>
                  <button
                    type="button"
                    onClick={() => setSameAsShipping(!sameAsShipping)}
                    className={`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-all ${
                      sameAsShipping ? 'border-secondary bg-secondary' : 'border-slate-350 bg-white'
                    }`}
                  >
                    {sameAsShipping && <span className="text-[10px] text-white font-bold">✓</span>}
                  </button>
                </div>
                
                {/* Billing fields if NOT same */}
                {!sameAsShipping && (
                  <div className="border-t border-slate-100 pt-4 space-y-4">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      {/* District */}
                      <div>
                        <SearchableSelect
                          options={billingDistricts}
                          value={selectedBillingDistrict}
                          onChange={handleBillingDistrictChange}
                          placeholder="Select District"
                          required
                          textSizeClass="text-[12px] sm:text-[15px]"
                        />
                      </div>

                      {/* Upazila */}
                      <div>
                        <SearchableSelect
                          options={billingUpazilas}
                          value={selectedBillingUpazila}
                          onChange={setSelectedBillingUpazila}
                          placeholder="Select Thana (Optional)"
                          disabled={!selectedBillingDistrict || loadingBillingUpazilas}
                          loading={loadingBillingUpazilas}
                          required
                          textSizeClass="text-[12px] sm:text-[15px]"
                        />
                      </div>
                    </div>

                    <div className="w-full">
                      <input
                        type="text"
                        required
                        name="billing_street_address"
                        autoComplete="street-address"
                        placeholder="Billing Street Address"
                        value={billingStreetAddress}
                        onChange={(e) => setBillingStreetAddress(e.target.value)}
                        className="w-full text-[12px] sm:text-[15px] font-medium px-4 py-3 bg-white border border-slate-200 rounded-xl focus:border-secondary focus:outline-none shadow-sm"
                      />
                    </div>
                  </div>
                )}
              </div>

              {/* 5. Shipping Method Selector */}
              {false && (
                <div className="hidden" hidden>
                  <div className="flex items-center gap-2 border-l-4 border-secondary pl-3 mb-4">
                    <h2 className="text-base font-semibold text-slate-850">Shipping Method</h2>
                  </div>

                  {selectedDistrict ? (
                    shippingMethods.length > 0 ? (
                      <div className="space-y-3">
                        {shippingMethods.map(method => {
                          const isSelected = selectedShippingMethod === method.id;
                          return (
                            <label
                              key={method.id}
                              className={`border p-4 rounded-xl flex items-center justify-between cursor-pointer transition-all bg-slate-50/10 ${
                                isSelected ? 'border-secondary bg-secondary/10/5' : 'border-slate-200 hover:border-slate-350'
                              }`}
                            >
                              <div className="flex items-center gap-3">
                                <input
                                  type="radio"
                                  name="shipping_method"
                                  checked={isSelected}
                                  onChange={() => handleShippingMethodChange(method.id)}
                                  className="text-secondary focus:ring-secondary h-4 w-4 cursor-pointer"
                                />
                                <div>
                                  <span className={`text-xs font-bold block ${isSelected ? 'text-secondary' : 'text-slate-800'}`}>
                                    {method.name}
                                  </span>
                                  <span className="text-xxs text-slate-400">
                                    {method.pricing_type === 'weight_based' ? '⚖️ Weight-based pricing' : '🚚 Flat rate'}
                                    {method.estimated_days && ` • Estimated delivery: ${method.estimated_days} days`}
                                  </span>
                                </div>
                              </div>
                              <span className={`text-xs font-extrabold ${isSelected ? 'text-secondary' : 'text-slate-700'}`}>
                                {formatPrice(method.cost)}
                              </span>
                            </label>
                          );
                        })}
                      </div>
                    ) : (
                      <p className="text-xs text-rose-500 bg-rose-50 p-3 rounded-lg text-center border border-dashed border-rose-200">
                        No shipping methods configured for this location.
                      </p>
                    )
                  ) : (
                    <p className="text-xs text-slate-400 bg-slate-50 p-3 rounded-lg text-center border border-dashed border-slate-200">
                      Select a District to calculate shipping fees.
                    </p>
                  )}
                </div>
              )}

                  {!isSinglePage && (
                    <div className="pt-4 flex justify-end">
                      <button
                        type="button"
                        onClick={handleNextStep}
                        className="px-6 py-3 bg-secondary hover:bg-secondary-dark text-white font-bold rounded-xl shadow transition-colors flex items-center gap-2 cursor-pointer font-open-sans"
                      >
                        <span>Next Step: Payment</span>
                        <span>➔</span>
                      </button>
                    </div>
                  )}
                </div>
              )}

              {/* RIGHT COLUMN: Payment, Coupon, notes, pricing summary (506.42px) */}
              {(isSinglePage || checkoutStep === 2) && (
                <div className={`w-full max-w-full space-y-4 lg:space-y-5 ${isSinglePage ? 'lg:w-[506.42px]' : 'max-w-3xl mx-auto'}`}>
                  {!isSinglePage && (
                    <div className="pb-4">
                      <button
                        type="button"
                        onClick={handlePrevStep}
                        className="px-4 py-2 border border-slate-350 hover:bg-slate-50 text-slate-700 font-bold rounded-xl transition-colors flex items-center gap-2 cursor-pointer font-open-sans text-xs sm:text-sm"
                      >
                        <span>⬅ Back to Delivery Details</span>
                      </button>
                    </div>
                  )}
              
              {/* 6. Payment method */}
              <div className="checkout-payment-method single-details-box bg-white p-4 sm:p-6 rounded-2xl border border-slate-200/60 shadow-sm space-y-4 mt-0 lg:mt-5">
                <div className="flex items-center gap-2 border-l-4 border-secondary pl-3 mb-4">
                  <h2 className="text-[14px] sm:text-base font-semibold text-slate-850 font-open-sans">Payment method</h2>
                </div>

                <div className="grid grid-cols-2 gap-2 sm:gap-3">
                  {/* COD */}
                  {isCodEnabled && (
                    <div
                      onClick={() => setPaymentMethod('cod')}
                      className={`payment-option flex items-center justify-between h-[44.2px] py-[6px] px-2 sm:px-[12px] border rounded-lg cursor-pointer transition-all ${
                        paymentMethod === 'cod'
                          ? 'border-secondary bg-[#DDE8FF]'
                          : 'border-slate-200 hover:border-slate-350 bg-white'
                      }`}
                    >
                      <div className="flex items-center gap-1.5 sm:gap-2.5">
                        <img
                          src="/images/cod.png"
                          alt="COD"
                          className="w-[22px] h-[22px] sm:w-[26px] sm:h-[26px] rounded shrink-0 object-contain"
                        />
                        <span className="text-[12px] sm:text-[14px] font-medium text-[#666666] font-open-sans whitespace-nowrap">
                          Cash On Delivery
                        </span>
                      </div>
                      {paymentMethod === 'cod' && (
                        <div className="w-3.5 h-3.5 sm:w-4 sm:h-4 rounded-full bg-secondary text-white flex items-center justify-center shrink-0">
                           <Check className="h-2.5 w-2.5 stroke-[3.5]" />
                        </div>
                      )}
                    </div>
                  )}

                  {/* Online Payment */}
                  {isSslcommerzEnabled && (
                    <div
                      onClick={() => setPaymentMethod('sslcommerz')}
                      className={`payment-option flex items-center justify-between h-[44.2px] py-[6px] px-2 sm:px-[12px] border rounded-lg cursor-pointer transition-all ${
                        paymentMethod === 'sslcommerz'
                          ? 'border-secondary bg-[#DDE8FF]'
                          : 'border-slate-200 hover:border-slate-350 bg-white'
                      }`}
                    >
                      <div className="flex items-center gap-1.5 sm:gap-2.5">
                        <span className="text-sm sm:text-[18px] leading-none select-none">💳</span>
                        <span className="text-[12px] sm:text-[14px] font-medium text-[#666666] font-open-sans whitespace-nowrap">
                          Online Payment
                        </span>
                      </div>
                      {paymentMethod === 'sslcommerz' && (
                        <div className="w-3.5 h-3.5 sm:w-4 sm:h-4 rounded-full bg-secondary text-white flex items-center justify-center shrink-0">
                           <Check className="h-2.5 w-2.5 stroke-[3.5]" />
                        </div>
                      )}
                    </div>
                  )}

                  {/* bKash */}
                  {isBkashEnabled && (
                    <div
                      onClick={() => setPaymentMethod('bkash')}
                      className={`payment-option flex items-center justify-between h-[44.2px] py-[6px] px-2 sm:px-[12px] border rounded-lg cursor-pointer transition-all ${
                        paymentMethod === 'bkash'
                          ? 'border-secondary bg-[#DDE8FF]'
                          : 'border-slate-200 hover:border-slate-350 bg-white'
                      }`}
                    >
                      <div className="flex items-center gap-1.5 sm:gap-2.5">
                        <img
                          src="/images/bkash.png"
                          alt="Bkash"
                          className="w-[22px] h-[22px] sm:w-[26px] sm:h-[26px] rounded shrink-0 object-contain"
                        />
                        <span className="text-[12px] sm:text-[14px] font-medium text-[#666666] font-open-sans whitespace-nowrap">
                          Bkash
                        </span>
                      </div>
                      {paymentMethod === 'bkash' && (
                        <div className="w-3.5 h-3.5 sm:w-4 sm:h-4 rounded-full bg-secondary text-white flex items-center justify-center shrink-0">
                           <Check className="h-2.5 w-2.5 stroke-[3.5]" />
                        </div>
                      )}
                    </div>
                  )}

                  {/* Nagad */}
                  {isNagadEnabled && (
                    <div
                      onClick={() => setPaymentMethod('nagad')}
                      className={`payment-option flex items-center justify-between h-[44.2px] py-[6px] px-2 sm:px-[12px] border rounded-lg cursor-pointer transition-all ${
                        paymentMethod === 'nagad'
                          ? 'border-secondary bg-[#DDE8FF]'
                          : 'border-slate-200 hover:border-slate-350 bg-white'
                      }`}
                    >
                      <div className="flex items-center gap-1.5 sm:gap-2.5">
                        <img
                          src="/images/nagad.png"
                          alt="Nagad"
                          className="w-[22px] h-[22px] sm:w-[26px] sm:h-[26px] rounded shrink-0 object-contain"
                        />
                        <span className="text-[12px] sm:text-[14px] font-medium text-[#666666] font-open-sans whitespace-nowrap">
                          Nagad
                        </span>
                      </div>
                      {paymentMethod === 'nagad' && (
                        <div className="w-3.5 h-3.5 sm:w-4 sm:h-4 rounded-full bg-secondary text-white flex items-center justify-center shrink-0">
                           <Check className="h-2.5 w-2.5 stroke-[3.5]" />
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>

              {/* 7. Coupon Accordion */}
              <div className="border border-slate-200 rounded-xl bg-white overflow-hidden shadow-sm">
                <div
                  onClick={() => setCouponExpanded(!couponExpanded)}
                  className="p-[12px] flex items-center justify-between cursor-pointer hover:bg-slate-50 transition-colors select-none bg-white"
                >
                  <span className="text-[14px] font-medium text-[#222831] font-open-sans">
                    Have any coupon or gift voucher?
                  </span>
                  <ChevronDown className={`h-4 w-4 text-[#222831] transition-transform ${couponExpanded ? 'rotate-180' : ''}`} />
                </div>
                {couponExpanded && (
                  <div className="p-4 border-t border-slate-100 bg-slate-50/50">
                    {appliedCoupon ? (
                      <div className="flex items-center justify-between bg-emerald-50 border border-emerald-200 p-3 rounded-xl">
                        <div className="flex items-center gap-2">
                          <span className="text-base select-none">🎟️</span>
                          <div>
                            <span className="text-[12px] sm:text-[14px] font-bold text-emerald-800">{appliedCoupon.code}</span>
                            <span className="text-[10px] text-emerald-500 block">Saved {formatPrice(discount)}</span>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={handleRemoveCoupon}
                          className="text-[10px] font-extrabold text-rose-500 hover:text-rose-700 cursor-pointer"
                        >
                          Remove
                        </button>
                      </div>
                    ) : (
                      <div className="flex gap-2">
                        <input
                          type="text"
                          placeholder="Enter code..."
                          value={couponCode}
                          onChange={(e) => setCouponCode(e.target.value)}
                          className="w-full text-[12px] sm:text-[14px] px-3 py-2 border border-slate-200 rounded-xl focus:outline-none focus:border-secondary bg-white font-open-sans"
                        />
                        <button
                          type="button"
                          onClick={handleApplyCoupon}
                          className="px-4 py-2 bg-slate-900 text-white rounded-xl text-[12px] sm:text-[14px] font-bold hover:bg-slate-800 transition-colors cursor-pointer font-open-sans"
                        >
                          Apply
                        </button>
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* 8. Pricing Summary */}
              <div className="bg-white p-6 border border-slate-200 rounded-2xl shadow-sm space-y-4">
                <div className="space-y-3 text-xs">
                  <div className="flex justify-between text-slate-500 font-semibold text-[15px] font-open-sans">
                    <span>Sub total</span>
                    <span>{formatPrice(effectiveSubtotal)}</span>
                  </div>
                  {isReseller && isResellerOrder && (
                    <div className="flex justify-between text-emerald-600 font-bold text-[15px] font-open-sans">
                      <span>Reseller Profit</span>
                      <span>{formatPrice(totalCommission)}</span>
                    </div>
                  )}
                  <div className="flex justify-between text-slate-500 font-semibold text-[15px] font-open-sans">
                    <span>Delivery cost</span>
                    <span>{formatPrice(shippingCost)}</span>
                  </div>
                  {discount > 0 && (
                    <div className="flex justify-between text-emerald-600 font-semibold font-open-sans">
                      <span>Discount</span>
                      <span>-{formatPrice(discount)}</span>
                    </div>
                  )}
                  <div className="flex justify-between text-slate-900 font-semibold border-t border-slate-100 pt-3 text-[16px] font-open-sans">
                    <span>Total</span>
                    <span>{formatPrice(grandTotal)}</span>
                  </div>
                </div>
              </div>

              {/* 9. Special Notes */}
              <div className="bg-white p-5 pb-3 rounded-2xl border border-slate-200/60 shadow-sm space-y-2.5">
                <div className="flex items-center gap-2 border-l-4 border-secondary pl-3">
                  <h2 className="text-[14px] sm:text-base font-semibold text-slate-850 font-open-sans">Special notes <span className="text-slate-450 font-normal text-[12px]">(Optional)</span></h2>
                </div>
                <textarea
                  rows={3}
                  maxLength={90}
                  placeholder="Instructions for delivery..."
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  className="w-full text-[12px] sm:text-[15px] px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:border-secondary focus:bg-white focus:outline-none transition-all resize-none font-open-sans"
                ></textarea>
                <div className="text-right text-[10px] text-slate-400 font-medium font-open-sans select-none -mt-1">
                  {notes.length} / 90 characters
                </div>
              </div>

              {/* Terms and Privacy Checkbox */}
              {settings?.settings?.enable_privacy_terms === 'on' && (
                <div className="bg-white p-5 rounded-2xl border border-slate-200/60 shadow-sm flex items-start gap-3">
                  <input
                    type="checkbox"
                    id="privacy-terms-checkbox"
                    checked={agreeTerms}
                    onChange={(e) => setAgreeTerms(e.target.checked)}
                    className="mt-1 h-4.5 w-4.5 rounded border-slate-300 text-secondary focus:ring-secondary cursor-pointer"
                  />
                  <label htmlFor="privacy-terms-checkbox" className="text-[12px] text-slate-650 cursor-pointer leading-relaxed select-none font-open-sans">
                    I have read and agree to the{' '}
                    <a
                      href={settings?.settings?.privacy_policy_link || '#'}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-secondary hover:underline font-bold"
                    >
                      Privacy Policy
                    </a>{' '}
                    and{' '}
                    <a
                      href={settings?.settings?.terms_of_service_link || '#'}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-secondary hover:underline font-bold"
                    >
                      Terms of Service
                    </a>.
                  </label>
                </div>
              )}

              {/* 10. Place Order */}
              <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-slate-200 p-4 shadow-lg z-50 sm:static sm:bg-transparent sm:border-t-0 sm:p-0 sm:shadow-none sm:z-auto">
                <button
                  type="submit"
                  disabled={submitting || !agreeTerms}
                  className="checkout-order-review-button shake-btn sticky-wrapper rsi-shake w-full h-12 inline-flex items-center justify-center gap-2 bg-secondary hover:bg-secondary-dark disabled:opacity-50 disabled:cursor-not-allowed text-white text-[12px] sm:text-sm font-bold rounded-lg transition-all uppercase tracking-wider cursor-pointer shadow-sm hover:shadow-md font-open-sans"
                >
                  {submitting ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      <span>Placing Order...</span>
                    </>
                  ) : (
                    <span>Place Order</span>
                  )}
                </button>
              </div>

                </div>
              )}

            </form>
        </div>
      </main>
      <div className="hidden sm:block">
        <Footer />
      </div>
      <style>{`
        @keyframes rsi-shake {
          0%, 80%, 100% { transform: rotate(0deg); }
          82%, 86%, 90%, 94%, 98% { transform: rotate(-2deg); }
          84%, 88%, 92%, 96% { transform: rotate(2deg); }
        }
        .rsi-shake { animation: rsi-shake 2s infinite ease-in-out; }
      `}</style>
    </>
  );
}

// Helper to format prices
function fmt(x: number | null | undefined) {
  if (x == null || isNaN(Number(x))) return '0.00';
  return Number(x).toLocaleString('en-BD', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
