import React, { useState, useEffect, useCallback, useRef } from 'react';
import { X, CheckCircle, User, Phone, MapPin, ArrowRight, Lock, Scale, Loader2, Truck, Gift } from 'lucide-react';
import { Product, CartItem, Order, SiteSettings } from '../types';
import { pushToDataLayer } from '../utils/tagmeneger';
import { api } from '../lib/api';
import { getDisplayName } from '../lib/displayName';

// API Base URL
const API_BASE = '/api';

// Resolve current store slug from subdomain or localStorage
const getStoreSlug = (): string => {
  try {
    const parts = window.location.hostname.split('.');
    if (parts.length >= 2 && parts[0] !== 'www' && parts[0] !== 'localhost' && !/^\d+$/.test(parts[0])) return parts[0];
    return localStorage.getItem('preview_store_slug') || '';
  } catch { return ''; }
};

interface CheckoutPopupProps {
  product?: Product;
  selectedSize?: string;
  cartItems?: CartItem[];
  settings?: SiteSettings;
  onClose: () => void;
  addOrder: (order: Order) => void;
}

const CheckoutPopup: React.FC<CheckoutPopupProps> = ({
  product,
  selectedSize: initialSize,
  cartItems,
  settings,
  onClose,
  addOrder
}) => {
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    address: ''
  });

  const defaultDeliveryZones = [
    { id: 'inside_ctg', name: 'inside Dhaka', charge: 70 },
    { id: 'outside_ctg', name: 'Outside Dhaka', charge: 130 }
  ];
  const deliveryZones = settings?.deliveryZones?.length ? settings.deliveryZones : defaultDeliveryZones;

  const [selectedZoneId, setSelectedZoneId] = useState(deliveryZones[0]?.id);
  const selectedZone = deliveryZones.find(z => z.id === selectedZoneId) || deliveryZones[0];

  const [localSelectedSize, setLocalSelectedSize] = useState(initialSize || (product?.sizes?.[0] || ''));
  const [isSubmitted, setIsSubmitted] = useState(false);
  const isSubmittedRef = useRef(false);
  const [isLoading, setIsLoading] = useState(false);
  const [hasInteracted, setHasInteracted] = useState(false);
  const [phoneError, setPhoneError] = useState('');
  const [stockChecking, setStockChecking] = useState(false);
  const [stockErrors, setStockErrors] = useState<string[]>([]);

  const sessionIdRef = useRef<string>(localStorage.getItem('shophyfast_checkout_session') || `SID-${Math.random().toString(36).substr(2, 9)}-${Date.now()}`);
  const orderIdRef = useRef<string>(`ORD-${Date.now()}`);
  const nameInputRef = useRef<HTMLInputElement>(null);
  const leadSaveTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
  const beginCheckoutSentRef = useRef(false);

  // Check if selected size has free delivery
  const isFreeDeliveryEligible = useCallback((): boolean => {
    if (!product || !localSelectedSize) return false;

    if (product.priceConfigs && product.priceConfigs[localSelectedSize]) {
      return product.priceConfigs[localSelectedSize].freeDelivery === true;
    }

    const isKgSize = localSelectedSize.includes('কেজি') || localSelectedSize.includes('kg');
    return isKgSize && product.freeDeliveryEnabled === true;
  }, [product, localSelectedSize]);

  const getCurrentPrice = () => {
    if (!product) return 0;
    
    // Parse price configs if it's a string (from DB)
    let parsedConfigs: any = {};
    try {
      parsedConfigs = typeof product.priceConfigs === 'string' 
        ? JSON.parse(product.priceConfigs) 
        : (product.priceConfigs || {});
    } catch { }
    
    // Check price configs first (new system)
    if (parsedConfigs[localSelectedSize]?.salePrice !== undefined) {
      return parsedConfigs[localSelectedSize].salePrice;
    }
    
    // Check legacy priceMap
    let parsedMap: any = {};
    try {
      parsedMap = typeof product.priceMap === 'string'
        ? JSON.parse(product.priceMap)
        : (product.priceMap || {});
    } catch { }
    
    if (parsedMap[localSelectedSize] !== undefined) {
      return parsedMap[localSelectedSize];
    }
    
    return product.price || 0;
  };

  const currentPrice = product
    ? getCurrentPrice()
    : 0;

  const subtotal = product
    ? currentPrice
    : (cartItems?.reduce((acc, it) => acc + (it.currentPrice * it.quantity), 0) || 0);

  const [couponCode, setCouponCode] = useState('');
  const [appliedCoupon, setAppliedCoupon] = useState<{code: string, amount: number} | null>(null);
  const [couponError, setCouponError] = useState('');
  
  const freeDeliveryEligible = isFreeDeliveryEligible();
  const deliveryCharge = freeDeliveryEligible ? 0 : (selectedZone?.charge || 0);
  
  // Calculate total with discount
  const discountAmount = appliedCoupon ? appliedCoupon.amount : 0;
  const total = Math.max(0, subtotal + deliveryCharge - discountAmount);

  const handleApplyCoupon = () => {
    if (!couponCode.trim()) return;
    setCouponError('');
    
    const validCoupon = settings?.marketingCoupons?.find(c => c.code.toLowerCase() === couponCode.trim().toLowerCase());
    if (!validCoupon) {
      setCouponError('❌ ইনভ্যালিড কুপন কোড');
      setAppliedCoupon(null);
      return;
    }
    
    const desc = validCoupon.discountDesc;
    let amount = 0;
    
    if (desc.includes('%')) {
      const match = desc.match(/(\d+)%/);
      if (match) {
        amount = Math.round(subtotal * (parseInt(match[1]) / 100));
      }
    } else {
      const match = desc.match(/(\d+)/);
      if (match) {
        amount = parseInt(match[1]);
      }
    }
    
    if (amount > 0) {
      amount = Math.min(amount, subtotal);
      setAppliedCoupon({ code: validCoupon.code, amount });
    } else {
      setCouponError('❌ এই কুপনটি ব্যবহার করা যাচ্ছে না');
      setAppliedCoupon(null);
    }
  };

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

  // Phone number validation function
  const validatePhone = (phone: string): { isValid: boolean; cleanNumber: string; error: string } => {
    let numbers = phone.replace(/\D/g, '');

    if (numbers.startsWith('880')) {
      if (numbers.length >= 13) {
        numbers = numbers.substring(3);
        if (numbers.length === 10) {
          numbers = '0' + numbers;
        }
      }
      else if (numbers.length > 3) {
        numbers = numbers.substring(3);
      }
      else {
        numbers = '';
      }
    }

    if (numbers.length === 10 && !numbers.startsWith('01')) {
      numbers = '0' + numbers;
    }

    numbers = numbers.slice(0, 11);

    if (numbers.length === 0) {
      return { isValid: false, cleanNumber: '', error: '' };
    }

    if (numbers.length < 11) {
      return { isValid: false, cleanNumber: numbers, error: `${11 - numbers.length} digits remaining` };
    }

    if (!numbers.startsWith('01')) {
      return { isValid: false, cleanNumber: numbers, error: 'Must start with 01' };
    }

    const thirdDigit = numbers.charAt(2);
    if (!['3', '4', '5', '6', '7', '8', '9'].includes(thirdDigit)) {
      return { isValid: false, cleanNumber: numbers, error: 'Invalid mobile number' };
    }

    return { isValid: true, cleanNumber: numbers, error: '' };
  };

  // Handle phone change
  const handlePhoneChange = (value: string) => {
    const validation = validatePhone(value);
    setFormData(prev => ({ ...prev, phone: validation.cleanNumber }));
    setPhoneError(validation.error);
    setHasInteracted(true);
  };

  // Format phone for display
  const getFormattedPhone = () => {
    if (formData.phone.length === 11) {
      return formData.phone.replace(/(\d{4})(\d{3})(\d{4})/, '$1-$2-$3');
    }
    return formData.phone;
  };

  // Check stock before submitting order
  const checkStockBeforeOrder = async (): Promise<boolean> => {
    setStockChecking(true);
    setStockErrors([]);

    try {
      const errors: string[] = [];

      if (product) {
        const stockCheck = await api.products.checkStock(product.id, 1, localSelectedSize);

        if (!stockCheck.success) {
          console.warn('Stock check API failed, proceeding with order');
        } else if (stockCheck.available === false) {
          const available = typeof stockCheck.stock === 'number' ? stockCheck.stock : 0;
          errors.push(`${product.nameBangla || product.name} এ স্টক নেই (${localSelectedSize}) — বর্তমান স্টক: ${available}`);
        }
      } else if (cartItems) {
        for (const item of cartItems) {
          const productId = (item as any).productId || item.id;
          const quantity = item.quantity || 1;
          const size = (item as any).selectedSize || '';
          const stockCheck = await api.products.checkStock(productId, quantity, size);

          if (stockCheck.success && stockCheck.available === false) {
            const available = typeof stockCheck.stock === 'number' ? stockCheck.stock : 0;
            errors.push(`${item.nameBangla || item.name} — স্টক কম: ${available} টি আছে, ${quantity} টি চাওয়া হয়েছে`);
          }
        }
      }

      if (errors.length > 0) {
        setStockErrors(errors);
        return false;
      }

      return true;
    } catch (error) {
      console.error('Error checking stock:', error);
      return true;
    } finally {
      setStockChecking(false);
    }
  };

  // Save lead to PHP API
  const saveLeadToAPI = useCallback(async () => {
    const validation = validatePhone(formData.phone);
    if (!validation.isValid) return;

    try {
      const productContext = product
        ? `${product.nameBangla || product.name} (${localSelectedSize})`
        : cartItems?.map(item => `${(item as any).nameBangla || item.name} (${(item as any).selectedSize || ''})`).join(', ');

      const locationText = selectedZone ? selectedZone.name : '';
      const fullAddress = formData.address
        ? `${formData.address} (${locationText})`
        : null;

      const payload = {
        phone: validation.cleanNumber,
        customer_name: formData.name || null,
        address: fullAddress,
        product_context: productContext,
        status: 'partial_entry',
        store_slug: getStoreSlug(),
      };

      const response = await fetch(`${API_BASE}/shop/leads`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Tenant-Slug': getStoreSlug() },
        body: JSON.stringify(payload)
      });

      if (!response.ok) throw new Error('Failed to save lead');

      const data = await response.json();
      if (!data.success) console.error('Lead save error:', data.error);
    } catch (err) {
      console.error('Lead save failed:', err);
    }
  }, [formData, product, cartItems, localSelectedSize, selectedZone]);

  // =====================================================
  // ✅ BEGIN_CHECKOUT EVENT - This is the fix!
  // =====================================================
  useEffect(() => {
    // Don't send if already sent
    if (beginCheckoutSentRef.current) return;

    // Prepare checkout items for GTM
    const checkoutItems = product ? [{
      item_name: product.nameBangla || product.name,
      item_id: product.id,
      price: currentPrice,
      quantity: 1,
      item_category: product.category,
      item_variant: localSelectedSize
    }] : (cartItems || []).map(item => ({
      item_name: item.nameBangla || item.name,
      item_id: item.id,
      price: item.currentPrice,
      quantity: item.quantity,
      item_category: item.category,
      item_variant: item.selectedSize
    }));

    // Push begin_checkout event to GTM
    pushToDataLayer('begin_checkout', {
      event: 'begin_checkout',
      ecommerce: {
        currency: 'BDT',
        value: total,
        items: checkoutItems,
        checkout_step: 1,
        checkout_option: 'Cash on Delivery'
      }
    });

    console.log('✅ begin_checkout event sent to GTM', {
      total,
      itemsCount: checkoutItems.length,
      items: checkoutItems
    });

    beginCheckoutSentRef.current = true;

  }, [product, cartItems, currentPrice, localSelectedSize, total]);

  // Lead auto-save for incomplete orders
  useEffect(() => {
    if (!hasInteracted) return;

    const validation = validatePhone(formData.phone);
    if (!validation.isValid) return;

    if (leadSaveTimeoutRef.current) {
      clearTimeout(leadSaveTimeoutRef.current);
    }

    leadSaveTimeoutRef.current = setTimeout(() => {
      if (!isSubmittedRef.current) {
        saveLeadToAPI();
      }
    }, 3000);

    return () => {
      if (leadSaveTimeoutRef.current) {
        clearTimeout(leadSaveTimeoutRef.current);
      }
    };
  }, [formData, hasInteracted, saveLeadToAPI]);

  // Save lead when popup closes
  useEffect(() => {
    const handleBeforeUnload = () => {
      const validation = validatePhone(formData.phone);
      if (validation.isValid && !isSubmittedRef.current) {
        saveLeadToAPI();
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
      const validation = validatePhone(formData.phone);
      if (validation.isValid && !isSubmittedRef.current) {
        saveLeadToAPI();
      }
    };
  }, [formData, saveLeadToAPI]);

  // Session storage and focus
  useEffect(() => {
    if (!localStorage.getItem('shophyfast_checkout_session')) {
      localStorage.setItem('shophyfast_checkout_session', sessionIdRef.current);
    }

    // Lock scroll without breaking fixed positioning
    // Store scroll position so we can restore it on close
    const scrollY = window.scrollY;
    document.documentElement.dataset.scrollY = String(scrollY);
    document.documentElement.style.overflow = 'hidden';
    document.body.style.overflow = 'hidden';

    // Only auto-focus on desktop (avoids keyboard scroll jump on mobile)
    const isMobile = window.innerWidth < 768;
    if (!isMobile) {
      setTimeout(() => {
        nameInputRef.current?.focus();
      }, 300);
    }

    return () => {
      // Restore scroll lock and position
      document.documentElement.style.overflow = '';
      document.body.style.overflow = '';
      const savedScrollY = Number(document.documentElement.dataset.scrollY || 0);
      delete document.documentElement.dataset.scrollY;
      window.scrollTo({ top: savedScrollY, behavior: 'instant' as ScrollBehavior });
    };
  }, []);

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    setHasInteracted(true);
  };

  // Close popup after order completion
  const redirectToShop = () => {
    onClose();
  };

  // =====================================================
  // ✅ handleSubmit
  // =====================================================
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validate phone number
    const validation = validatePhone(formData.phone);
    if (!validation.isValid) {
      alert('Please provide a valid 11-digit mobile number (e.g., 017XXXXXXXX)');
      return;
    }

    setIsLoading(true);

    try {
      // STEP 1: Check stock availability
      const stockAvailable = await checkStockBeforeOrder();

      if (!stockAvailable) {
        setIsLoading(false);
        return;
      }

      // STEP 2: Prepare order items
      const items = product ? [{
        productId: product.id,
        name: product.name,
        price: currentPrice,
        quantity: 1,
        size: localSelectedSize
      }] : (cartItems?.map(it => ({
        productId: it.id,
        name: it.name,
        price: it.currentPrice,
        quantity: it.quantity,
        size: it.selectedSize
      })) || []);

      const locationText = selectedZone ? selectedZone.name : '';
      const fullAddress = `${formData.address} (${locationText})`;

      // STEP 3: Create order payload
      const orderPayload = {
        id: orderIdRef.current,
        session_id: sessionIdRef.current,
        customer_name: formData.name || 'Anonymous',
        phone: validation.cleanNumber,
        address: fullAddress,
        items: items,
        subtotal: subtotal,
        delivery_charge: deliveryCharge,
        total: total,
        status: 'Confirmed Order',
        source: 'Checkout Popup',
        confirmed_at: new Date().toISOString(),
        store_slug: getStoreSlug(),
      };

      console.log('📦 Sending order to orders.php:', orderPayload);

      // Mapped for Laravel backend expects items as product_id, name, qty, price
      const mappedItems = items.map(item => ({
        product_id: item.productId,
        name: item.name,
        qty: item.quantity,
        price: item.price
      }));

      const finalOrderPayload = {
        ...orderPayload,
        customer_name: orderPayload.customer_name,
        customer_phone: orderPayload.phone,
        customer_address: orderPayload.address,
        payment_method: 'cod',
        items: mappedItems,
        notes: appliedCoupon ? `Applied Coupon: ${appliedCoupon.code} (Discount: ৳${appliedCoupon.amount})` : null
      };

      // STEP 4: Save order to Laravel API
      const orderResponse = await fetch(`${API_BASE}/shop/checkout`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Tenant-Slug': getStoreSlug() },
        body: JSON.stringify(finalOrderPayload)
      });

      const orderData = await orderResponse.json();

      console.log('📦 Orders.php response:', orderData);

      if (!orderData.success && !orderResponse.ok) {
        console.error('Validation errors:', orderData.errors);
        throw new Error(orderData.message || orderData.error || 'Order save failed');
      } else if (!orderData.success) {
        throw new Error(orderData.error || 'Order save failed');
      }

      console.log('✅ Order saved successfully:', orderData);

      // STEP 5: Delete lead after order confirmation
      try {
        const deleteResponse = await fetch(`${API_BASE}/shop/leads?phone=${validation.cleanNumber}`, {
          method: 'DELETE',
          headers: { 'X-Tenant-Slug': getStoreSlug() }
        });

        const deleteData = await deleteResponse.json();
        console.log('🗑️ Lead deleted after order confirmation:', deleteData);
      } catch (deleteErr) {
        console.error('Error deleting lead:', deleteErr);
      }

      localStorage.removeItem('shophyfast_checkout_session');

      // ✅ Purchase event (already exists)
      pushToDataLayer('purchase', {
        transaction_id: orderIdRef.current,
        value: total,
        currency: 'BDT',
        tax: 0,
        shipping: deliveryCharge,
        items: items.map(item => ({
          item_name: item.name,
          item_id: item.productId,
          price: item.price,
          quantity: item.quantity
        }))
      });

      console.log('✅ purchase event sent to GTM', { transaction_id: orderIdRef.current, total });

      setIsSubmitted(true);
      isSubmittedRef.current = true;

      // Add order to local state
      addOrder({
        id: orderIdRef.current,
        session_id: sessionIdRef.current,
        customerName: formData.name,
        phone: validation.cleanNumber,
        address: fullAddress,
        items,
        subtotal,
        deliveryCharge,
        total,
        status: 'Confirmed Order',
        source: 'Checkout Popup',
        date: new Date().toISOString(),
        confirmed_at: new Date().toISOString()
      });

      setTimeout(redirectToShop, 2000);

    } catch (err: any) {
      console.error('❌ Order save error:', err);
      alert('Could not complete order. Please try again. Error: ' + err.message);
    } finally {
      setIsLoading(false);
    }
  };

  if (isSubmitted) {
    return (
      <div className="fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-slate-950/95 backdrop-blur-3xl animate-fade-in">
        <div className="bg-white dark:bg-slate-900 rounded-[40px] p-10 max-w-lg w-full text-center shadow-2xl border border-slate-100 dark:border-slate-800 animate-scale-up">
          <div className="w-20 h-20 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto mb-8 shadow-inner">
            <CheckCircle size={48} />
          </div>
          <h2 className="text-2xl font-black mb-4 font-bangla text-slate-900 dark:text-white">Order Successful!</h2>
          <p className="text-slate-500 mb-4 font-bangla">Our representative will call you shortly to confirm the order.</p>

          <div className="flex items-center justify-center gap-2 text-themePrimary mt-6">
            <Loader2 size={20} className="animate-spin" />
            <span className="text-sm font-medium">Redirecting to shop...</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 z-[10000] flex items-center justify-center p-4 sm:p-6">
      <div className="fixed inset-0 bg-slate-950/80 backdrop-blur-xl" onClick={onClose} />

      <div className="relative z-10 w-full max-w-4xl bg-white dark:bg-slate-900 rounded-[24px] md:rounded-[40px] shadow-[0_50px_100px_rgba(0,0,0,0.4)] flex flex-col overflow-hidden max-h-[90vh]">

        {/* Close Button */}
        <div className="absolute top-3 right-3 md:top-4 md:right-4 z-[60]">
          <button onClick={onClose} className="p-2.5 bg-white border border-slate-200 dark:bg-slate-800 dark:border-slate-700 rounded-full hover:bg-themePrimary hover:text-white focus:outline-none transition-colors shadow-lg">
            <X size={20} strokeWidth={2.5} />
          </button>
        </div>

        <div className="flex flex-col md:flex-row w-full h-full overflow-y-auto">

          {/* Product Section - Left Side */}
          <div className="w-full md:w-1/2 p-6 md:p-8 bg-white dark:bg-slate-900 border-b md:border-b-0 md:border-r dark:border-slate-800">
            <h3 className="text-xl font-black mb-6 flex items-center gap-2">
              <span className="w-1 h-8 bg-themePrimary rounded-full"></span>
              Your Order
            </h3>

            {product ? (
              <div className="space-y-6">
                <div className="flex gap-4 items-center">
                  <img src={product.image} className="w-20 h-20 rounded-xl object-cover shadow-md" alt={product.name} />
                  <div>
                    <h4 className="font-black text-lg font-bangla">{getDisplayName(product.nameBangla, product.name)}</h4>
                    <p className="text-sm text-slate-500">{localSelectedSize}</p>

                    {freeDeliveryEligible && (
                      <div className="inline-flex items-center gap-1 mt-2 bg-green-100 text-green-700 px-2 py-1 rounded-full text-xs font-black">
                        <Truck size={12} /> Free Delivery
                      </div>
                    )}
                  </div>
                </div>

                <div className="pt-2">
                  <p className="text-sm font-black mb-3">Select Weight</p>
                  <div className="flex flex-wrap gap-2">
                    {product.sizes?.map((size) => {
                      const hasFreeDelivery = product.priceConfigs?.[size]?.freeDelivery === true;

                      return (
                        <button
                          key={size}
                          onClick={() => {
                            setLocalSelectedSize(size);
                            setHasInteracted(true);
                          }}
                          className={`relative px-4 py-2 rounded-xl font-bold text-sm transition-all border-2 ${localSelectedSize === size
                            ? 'bg-themePrimary border-themePrimary text-white'
                            : 'bg-slate-100 border-transparent text-slate-600 hover:border-themePrimary/30'
                            }`}
                        >
                          {size}
                          {hasFreeDelivery && (
                            <span className="absolute -top-2 -right-2 bg-green-600 text-white text-[8px] px-1.5 py-0.5 rounded-full whitespace-nowrap">
                              FREE
                            </span>
                          )}
                        </button>
                      );
                    })}
                  </div>
                </div>
              </div>
            ) : (
              <div className="space-y-3">
                {cartItems?.map((item) => (
                  <div key={item.id} className="flex gap-3 items-center p-3 bg-slate-50 rounded-xl">
                    <img src={item.image} className="w-16 h-16 object-cover rounded-lg" alt={item.name} />
                    <div>
                      <h4 className="font-black font-bangla">{getDisplayName(item.nameBangla, item.name)}</h4>
                      <p className="text-sm text-slate-500">{item.selectedSize}</p>
                      <p className="font-black text-themePrimary">৳{item.currentPrice}</p>
                    </div>
                  </div>
                ))}
              </div>
            )}

            <div className="mt-6 pt-6 border-t space-y-3">
              <div className="flex justify-between text-lg">
                <span className="text-slate-600">Total</span>
                <span className="font-black text-themePrimary">৳{total}</span>
              </div>

              {!freeDeliveryEligible && (
                <div className="flex justify-between text-sm text-slate-500">
                  <span>Delivery Charge</span>
                  <span>+ ৳{deliveryCharge}</span>
                </div>
              )}

              {freeDeliveryEligible && (
                <div className="flex items-center gap-2 text-green-600 text-sm font-bold">
                  <Truck size={16} />
                  <span>Free Delivery</span>
                </div>
              )}
            </div>

            {/* Stock Error Display */}
            {stockErrors.length > 0 && (
              <div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-xl">
                <p className="text-red-600 font-black mb-2">⚠️ Stock Error</p>
                {stockErrors.map((error, index) => (
                  <p key={index} className="text-sm text-red-500 mb-1">• {error}</p>
                ))}
              </div>
            )}
          </div>

          {/* Form Section - Right Side */}
          <div className="w-full md:w-1/2 p-6 md:p-8">
            <h3 className="text-xl font-black mb-6 flex items-center gap-2">
              <span className="w-1 h-8 bg-themePrimary rounded-full"></span>
              Delivery Information
            </h3>

            <form onSubmit={handleSubmit} className="space-y-4">
              {/* ✅ 1. Name Field */}
              <div>
                <label className="text-xs font-black text-slate-400 mb-1 block">Your Name *</label>
                <input
                  ref={nameInputRef}
                  type="text"
                  required
                  className="w-full px-4 py-3 bg-slate-50 border-2 border-transparent focus:border-themePrimary rounded-xl font-bold"
                  value={formData.name}
                  onChange={(e) => handleInputChange('name', e.target.value)}
                  placeholder="Enter your name"
                  autoComplete="name"
                />
              </div>

              {/* ✅ 2. Phone Field */}
              <div>
                <label className="text-xs font-black text-slate-400 mb-1 block">
                  Mobile Number (11 digits) *
                </label>
                <input
                  type="tel"
                  required
                  maxLength={14}
                  className="w-full px-4 py-3 bg-slate-50 border-2 border-transparent focus:border-themePrimary rounded-xl font-bold"
                  value={formData.phone}
                  onChange={(e) => handlePhoneChange(e.target.value)}
                  placeholder="017XXXXXXXX"
                  autoComplete="tel"
                />
                {formData.phone.length > 0 && (
                  <div className="mt-1">
                    {phoneError ? (
                      <p className="text-xs text-red-500">{phoneError}</p>
                    ) : (
                      formData.phone.length === 11 && (
                        <p className="text-xs text-green-600">
                          ✅ {getFormattedPhone()}
                        </p>
                      )
                    )}
                  </div>
                )}
              </div>

              {/* ✅ 3. Address Field */}
              <div>
                <label className="text-xs font-black text-slate-400 mb-1 block">Address *</label>
                <textarea
                  required
                  className="w-full px-4 py-3 bg-slate-50 border-2 border-transparent focus:border-themePrimary rounded-xl font-bold min-h-[80px]"
                  value={formData.address}
                  onChange={(e) => handleInputChange('address', e.target.value)}
                  placeholder="House number, Road, Area"
                />
              </div>

              {/* ✅ 4. Delivery Location Selector */}
              <div>
                <label className="text-xs font-black text-slate-500 mb-2 block uppercase tracking-wider">
                  📍 Delivery Location *
                </label>
                <div className="flex flex-col gap-3">
                  {deliveryZones.map(zone => (
                    <button
                      key={zone.id}
                      type="button"
                      onClick={() => setSelectedZoneId(zone.id)}
                      className={`w-full flex items-center justify-between px-4 py-3 rounded-xl border-2 font-bold transition-all ${selectedZoneId === zone.id
                        ? 'bg-themePrimary/10 border-themePrimary text-themePrimary'
                        : 'bg-slate-50 border-slate-200 text-slate-600 hover:border-themePrimary/30'
                        }`}
                    >
                      <div className="flex items-center gap-3">
                        <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${selectedZoneId === zone.id ? 'border-themePrimary' : 'border-slate-300'}`}>
                          {selectedZoneId === zone.id && <div className="w-2.5 h-2.5 bg-themePrimary rounded-full" />}
                        </div>
                        <span className="font-bangla text-[15px]">{zone.name}</span>
                      </div>
                      <span className="font-black text-sm">
                        {freeDeliveryEligible ? 'বিনামূল্যে' : `৳${zone.charge} ডেলিভারি`}
                      </span>
                    </button>
                  ))}
                </div>
              </div>

              {/* Delivery Charge Summary */}
              <div className="space-y-2">
                <div className={`p-3 rounded-xl text-sm flex items-center justify-between ${freeDeliveryEligible
                  ? 'bg-green-50 text-green-800'
                  : 'bg-blue-50 text-blue-800'
                  }`}>
                  <span className="font-bold flex items-center gap-2">
                    {freeDeliveryEligible ? <Truck size={16} /> : <MapPin size={16} />}
                    {freeDeliveryEligible
                      ? 'এই product এ ফ্রি ডেলিভারি'
                      : selectedZone?.name}
                  </span>
                  {!freeDeliveryEligible && (
                    <span className="font-black">৳{deliveryCharge}</span>
                  )}
                </div>
                
                {/* Coupon Code Input */}
                {settings?.marketingCoupons && settings.marketingCoupons.length > 0 && (
                  <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 mt-2">
                    {appliedCoupon ? (
                      <div className="flex items-center justify-between bg-green-50 text-green-700 p-2 rounded-lg border border-green-200">
                        <div className="flex items-center gap-2">
                          <Gift size={16} />
                          <span className="font-bold text-sm">Coupon applied: {appliedCoupon.code}</span>
                        </div>
                        <div className="flex items-center gap-3">
                          <span className="font-black text-sm">-৳{appliedCoupon.amount}</span>
                          <button type="button" onClick={handleRemoveCoupon} className="text-red-500 hover:text-red-700">
                            <X size={16} />
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div>
                        <div className="flex gap-2">
                          <input
                            type="text"
                            placeholder="Have a coupon code?"
                            value={couponCode}
                            onChange={(e) => {
                              setCouponCode(e.target.value);
                              setCouponError('');
                            }}
                            className="flex-1 bg-white border border-slate-200 rounded-lg px-3 py-2 text-sm font-bold focus:outline-none focus:border-themePrimary"
                          />
                          <button
                            type="button"
                            onClick={handleApplyCoupon}
                            disabled={!couponCode.trim()}
                            className="bg-slate-800 text-white px-4 py-2 rounded-lg text-sm font-bold disabled:opacity-50"
                          >
                            Apply
                          </button>
                        </div>
                        {couponError && <p className="text-xs text-red-500 mt-1">{couponError}</p>}
                      </div>
                    )}
                  </div>
                )}
                
                {appliedCoupon && (
                  <div className="flex justify-between items-center px-2 pt-2 text-sm">
                    <span className="text-slate-500 font-bold">Discount</span>
                    <span className="text-green-600 font-black">-৳{appliedCoupon.amount}</span>
                  </div>
                )}
              </div>


              {/* Note about lead saving */}
              <p className="text-[10px] text-slate-400 text-center">
                * Your information will be saved. We will assist you even if you don't complete the order.
              </p>

              {/* Order Button */}
              <button
                type="submit"
                disabled={isLoading || stockChecking}
                className="w-full py-4 bg-themePrimary hover:bg-themeHover text-white rounded-xl font-black text-lg mt-4 flex items-center justify-center gap-2 disabled:opacity-50"
              >
                {isLoading || stockChecking ? (
                  <>
                    <Loader2 className="animate-spin" size={20} />
                    {stockChecking ? 'Checking Stock...' : 'Processing...'}
                  </>
                ) : (
                  'Complete Order'
                )}
              </button>
            </form>
          </div>
        </div>
      </div>

    </div>
  );
};

export default CheckoutPopup;