'use client';

import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { motion, AnimatePresence } from 'motion/react';
import {
  ChevronRight, 
  ChevronLeft, 
  CheckCircle, 
  Clock, 
  ShoppingBag, 
  Store, 
  Rocket,
  Package,
  Users,
  TrendingUp,
  MapPin,
  User,
  Phone,
  Globe,
  Building2,
  Truck,
  Check
} from 'lucide-react';
import { Container, Card } from '@/components/ui';

interface SelectableCardProps {
  icon: React.ReactNode;
  title: string | React.ReactNode;
  description?: string;
  value: string;
  selected: boolean;
  onClick: () => void;
}

function SelectableCard({ icon, title, description, selected, onClick }: SelectableCardProps) {
  const { i18n } = useTranslation();
  const isRTL = i18n.language === 'ar';
  
  return (
    <motion.button
      type="button"
      onClick={onClick}
      whileHover={{ scale: 1.02 }}
      whileTap={{ scale: 0.98 }}
      className={`relative w-full p-4 sm:p-6 rounded-xl border-2 transition-all ${
        selected
          ? 'border-[#3A4A9C] bg-[#3A4A9C]/5 shadow-lg'
          : 'border-gray-200 bg-white hover:border-gray-300 hover:shadow-md'
      }`}
      dir={isRTL ? 'rtl' : 'ltr'}
    >
      <div className="flex items-start gap-3 sm:gap-4">
        <div
          className={`flex-shrink-0 w-10 h-10 sm:w-12 sm:h-12 rounded-lg flex items-center justify-center transition-colors ${
            selected
              ? 'bg-[#3A4A9C] text-white'
              : 'bg-gray-100 text-gray-600'
          }`}
        >
          {icon}
        </div>
        <div className={`flex-1 min-w-0 ${isRTL ? 'text-right' : 'text-left'}`}>
          <h4 className={`font-semibold text-sm sm:text-base mb-1 ${selected ? 'text-[#3A4A9C]' : 'text-gray-900'}`}>
            {title}
          </h4>
          {description && (
            <p className="text-xs sm:text-sm text-gray-600">{description}</p>
          )}
        </div>
      </div>
      {selected && (
        <motion.div
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          className={`absolute top-3 ${isRTL ? 'left-3' : 'right-3'} sm:top-4 ${isRTL ? 'sm:left-4' : 'sm:right-4'}`}
        >
          <CheckCircle className="w-5 h-5 sm:w-6 sm:h-6 text-[#3A4A9C]" />
        </motion.div>
      )}
    </motion.button>
  );
}

interface CheckboxCardProps {
  icon: React.ReactNode;
  title: string;
  description?: string | React.ReactNode;
  checked: boolean;
  onChange: () => void;
}

function CheckboxCard({ icon, title, description, checked, onChange }: CheckboxCardProps) {
  const { i18n } = useTranslation();
  const isRTL = i18n.language === 'ar';
  
  return (
    <motion.button
      type="button"
      onClick={onChange}
      whileHover={{ scale: 1.02 }}
      whileTap={{ scale: 0.98 }}
      className={`relative w-full p-5 rounded-xl border-2 transition-all ${
        checked
          ? 'border-[#3A4A9C] bg-[#3A4A9C]/5'
          : 'border-gray-200 bg-white hover:border-gray-300'
      }`}
      dir={isRTL ? 'rtl' : 'ltr'}
    >
      <div className="flex items-center gap-4">
        <div
          className={`flex-shrink-0 w-10 h-10 rounded-lg flex items-center justify-center transition-colors ${
            checked
              ? 'bg-[#3A4A9C] text-white'
              : 'bg-gray-100 text-gray-600'
          }`}
        >
          {icon}
        </div>
        <div className="flex-1 min-w-0">
          <h4 className={`font-medium text-sm ${checked ? 'text-[#3A4A9C]' : 'text-gray-900'}`}>
            {title}
          </h4>
          {description && (
            <p className="text-xs text-gray-600 mt-0.5">{description}</p>
          )}
        </div>
        <div
          className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${
            checked
              ? 'bg-[#3A4A9C] border-[#3A4A9C]'
              : 'bg-white border-gray-300'
          }`}
        >
          {checked && (
            <motion.svg
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              className="w-3 h-3 text-white"
              viewBox="0 0 12 12"
              fill="none"
            >
              <path
                d="M10 3L4.5 8.5L2 6"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </motion.svg>
          )}
        </div>
      </div>
    </motion.button>
  );
}

export function LeadFormSection() {
  const { t, i18n } = useTranslation();
  const isRTL = i18n.language === 'ar';
  const [step, setStep] = useState(1);
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    businessType: '',
    volume: '',
    city: '',
    name: '',
    phone: '',
    website: '',
    services: [] as string[],
    company: '',
  });

  const isMoroccoPhoneValid = (value: string) => {
    if (!/^\d*$/.test(value)) return false;
    if (value.startsWith('0')) return /^0[5678]\d{8}$/.test(value);
    return /^[5678]\d{8}$/.test(value);
  };

  const isPhoneValid = formData.phone.length === 0 ? false : isMoroccoPhoneValid(formData.phone);
  const [phoneValidationVisible, setPhoneValidationVisible] = useState(false);

  const isWebsiteValid = (() => {
    const value = formData.website.trim();
    if (!value) return true;
    if (/\s/.test(value)) return false;
    const candidate = /^https?:\/\//i.test(value) ? value : `https://${value}`;
    try {
      const url = new URL(candidate);
      if (!url.hostname.includes('.')) return false;
      if (!/[a-z]{2,}$/i.test(url.hostname.split('.').pop() ?? '')) return false;
      return true;
    } catch {
      return false;
    }
  })();

  const totalSteps = 3;

  // Show phone validation only after the user stops typing (or on blur).
  // This avoids flashing "invalid" while the user is still entering digits.
  useEffect(() => {
    if (!formData.phone) {
      setPhoneValidationVisible(false);
      return;
    }

    setPhoneValidationVisible(false);
    const id = setTimeout(() => setPhoneValidationVisible(true), 600);
    return () => clearTimeout(id);
  }, [formData.phone]);

  const handleNext = () => {
    if (step < totalSteps) setStep(step + 1);
  };

  const handleBack = () => {
    if (step > 1) setStep(step - 1);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitError(null);
    setSubmitting(true);

    try {
      const res = await fetch('/api/leads', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          lang: i18n.language,
        }),
      });

      if (!res.ok) {
        setSubmitError('Erreur lors de l’envoi. Veuillez réessayer.');
        return;
      }

      setSubmitted(true);
    } catch {
      setSubmitError('Erreur réseau. Veuillez réessayer.');
    } finally {
      setSubmitting(false);
    }
  };

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

  const toggleService = (service: string) => {
    setFormData(prev => ({
      ...prev,
      services: prev.services.includes(service)
        ? prev.services.filter(s => s !== service)
        : [...prev.services, service]
    }));
  };

  const businessTypes = [
    {
      value: 'ecommerce',
      icon: <ShoppingBag className="w-6 h-6" />,
      title: t('leadForm.businessType.ecommerce', 'E-commerce'),
      description: t('leadForm.businessType.ecommerceDesc', 'Online store owner')
    },
    {
      value: 'reseller',
      icon: <Store className="w-6 h-6" />,
      title: t('leadForm.businessType.reseller', 'Reseller'),
      description: t('leadForm.businessType.resellerDesc', 'Dropshipping or wholesale')
    },
    {
      value: 'beginner',
      icon: <Rocket className="w-6 h-6" />,
      title: t('leadForm.businessType.beginner', 'Starting Out'),
      description: t('leadForm.businessType.beginnerDesc', 'New to e-commerce')
    },
  ];

	  const volumeOptions = [
	    {
	      value: '<50',
	      icon: <Package className="w-5 h-5" />,
	      title: <span className="font-poppins">{t('leadForm.volume.option1', '< 50 orders/month')}</span>,
	      description: t('leadForm.volume.option1Desc', 'Just getting started')
	    },
	    {
	      value: '50-200',
	      icon: <Users className="w-5 h-5" />,
	      title: <span className="font-poppins">{t('leadForm.volume.option2', '50-200 orders/month')}</span>,
	      description: t('leadForm.volume.option2Desc', 'Growing business')
	    },
	    {
	      value: '200-500',
	      icon: <TrendingUp className="w-5 h-5" />,
	      title: <span className="font-poppins">{t('leadForm.volume.option3', '200-500 orders/month')}</span>,
	      description: t('leadForm.volume.option3Desc', 'Established business')
	    },
	    {
	      value: '>500',
	      icon: <Building2 className="w-5 h-5" />,
	      title: <span className="font-poppins">{t('leadForm.volume.option4', '> 500 orders/month')}</span>,
	      description: t('leadForm.volume.option4Desc', 'High-volume business')
	    },
	  ];

  const serviceOptions = [
    {
      value: 'ramassage',
      icon: <Truck className="w-5 h-5" />,
      title: t('leadForm.services.ramassage', 'Pickup'),
      description: t('leadForm.services.ramassageDesc', 'Pickup service')
    },
    {
      value: 'stockage',
      icon: <Package className="w-5 h-5" />,
      title: t('leadForm.services.stockage', 'Storage'),
      description: t('leadForm.services.stockageDesc', 'Storage service')
    },
    {
      value: 'affiliate',
      icon: <Users className="w-5 h-5" />,
      title: t('leadForm.services.affiliate', 'Affiliate'),
      description: t('leadForm.services.affiliateDesc', 'Affiliate program')
    },
  ];

  if (submitted) {
    return (
      <section id="lead-form" className="py-24 bg-gradient-to-b from-white to-blue-50/30">
        <Container size="md">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.5 }}
          >
            <Card className="p-16 text-center bg-gradient-to-br from-green-50 to-emerald-50 border-2 border-green-200 shadow-2xl">
              <div className="w-24 h-24 bg-gradient-to-br from-green-400 to-emerald-500 rounded-full flex items-center justify-center mx-auto mb-8 shadow-lg">
                <CheckCircle className="w-14 h-14 text-white" />
              </div>
              <h3 className="text-3xl font-bold text-gray-900 mb-4">
                {t('leadForm.success', 'Demande envoyée avec succès !')}
              </h3>
              <p className="text-lg text-gray-600 mb-8 max-w-md mx-auto">
                {t('leadForm.successMessage', 'Notre équipe vous contactera dans les 15 prochaines minutes.')}
              </p>
              <button
                onClick={() => {
                  setSubmitted(false);
                  setStep(1);
                  setFormData({
                    businessType: '',
                    volume: '',
                    city: '',
                    name: '',
                    phone: '',
                    website: '',
                    services: [],
                    company: '',
                  });
                }}
                className="text-[#3A4A9C] font-semibold hover:underline"
              >
                {t('leadForm.submitAnother', 'Soumettre une autre demande')}
              </button>
            </Card>
          </motion.div>
        </Container>
      </section>
    );
  }

  return (
    <section id="lead-form" className="py-24 bg-gradient-to-b from-white to-blue-50/30 relative overflow-hidden">
      {/* Background Pattern */}
      <div className="absolute inset-0 opacity-[0.02]" style={{
        backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%233A4A9C' fill-opacity='1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
      }} />

      <Container size="md" className="relative z-10">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.6 }}
          className="text-center mb-12"
        >
          <div className="inline-block px-5 py-2 bg-gradient-to-r from-[#3A4A9C]/10 to-blue-100 rounded-full mb-6">
            <span className="text-sm font-semibold text-[#3A4A9C] flex items-center gap-2">
              <Clock className="w-4 h-4" />
              {t('leadForm.badge', 'Réponse en moins de 15 minutes')}
            </span>
          </div>
          <h2 className="text-4xl sm:text-5xl font-bold text-gray-900 mb-4">
            {t('leadForm.title')}
          </h2>
          <p className="text-lg text-gray-600 max-w-2xl mx-auto">
            {t('leadForm.subtitle')}
          </p>
        </motion.div>

        <Card className="p-6 sm:p-10 bg-white shadow-2xl border border-gray-100">
          {/* Modern Stepper - Mobile Optimized */}
          <div className="mb-8 sm:mb-12">
            {/* Desktop Stepper (hidden on mobile) */}
            <div className="hidden sm:flex items-center justify-center max-w-2xl mx-auto">
              {[...Array(totalSteps)].map((_, i) => {
                const stepLabels = [
                  t('leadForm.step1Label', 'Business Info'),
                  t('leadForm.step2Label', 'Contact Details'),
                  t('leadForm.step3Label', 'Review & Submit')
                ];
                
                return (
                  <div key={i} className="flex items-center">
                    {/* Step Circle */}
                    <div className="flex flex-col items-center">
                      <motion.div
                        initial={{ scale: 0.8 }}
                        animate={{ scale: 1 }}
                        className={`relative w-14 h-14 rounded-full flex items-center justify-center font-semibold transition-all duration-300 ${
                          i + 1 < step
                            ? 'bg-[#3A4A9C] text-white shadow-md'
                            : i + 1 === step
                            ? 'bg-[#3A4A9C] text-white shadow-lg ring-4 ring-[#3A4A9C]/20'
                            : 'bg-gray-200 text-gray-400'
                        }`}
                      >
                        {i + 1 < step ? (
                          <Check className="w-6 h-6" strokeWidth={3} />
                        ) : (
                          <span className="text-base">{i + 1}</span>
                        )}
                      </motion.div>
                      <div className={`mt-3 text-sm font-medium whitespace-nowrap transition-colors ${
                        i + 1 <= step ? 'text-[#3A4A9C]' : 'text-gray-400'
                      }`}>
                        {stepLabels[i]}
                      </div>
                    </div>
                    
                    {/* Connector Line */}
                    {i < totalSteps - 1 && (
                      <div className="flex items-center mx-4 mb-8">
                        <motion.div
                          initial={{ scaleX: 0 }}
                          animate={{ scaleX: 1 }}
                          transition={{ delay: 0.2 }}
                          className={`h-1 w-24 rounded-full transition-all duration-500 ${
                            i + 1 < step ? 'bg-[#3A4A9C]' : 'bg-gray-200'
                          }`}
                        />
                      </div>
                    )}
                  </div>
                );
              })}
            </div>

            {/* Mobile Stepper (compact version) */}
            <div className="sm:hidden">
              <div className="flex items-center justify-center mb-6">
                {[...Array(totalSteps)].map((_, i) => (
                  <div key={i} className="flex items-center">
                    {/* Step Circle */}
                    <motion.div
                      initial={{ scale: 0.8 }}
                      animate={{ scale: 1 }}
                      className={`relative w-10 h-10 rounded-full flex items-center justify-center font-semibold text-sm transition-all duration-300 ${
                        i + 1 < step
                          ? 'bg-[#3A4A9C] text-white shadow-md'
                          : i + 1 === step
                          ? 'bg-[#3A4A9C] text-white shadow-lg ring-4 ring-[#3A4A9C]/20'
                          : 'bg-gray-200 text-gray-400'
                      }`}
                    >
                      {i + 1 < step ? (
                        <Check className="w-4 h-4" strokeWidth={3} />
                      ) : (
                        <span className="text-sm">{i + 1}</span>
                      )}
                    </motion.div>
                    
                    {/* Connector Line */}
                    {i < totalSteps - 1 && (
                      <motion.div
                        initial={{ scaleX: 0 }}
                        animate={{ scaleX: 1 }}
                        transition={{ delay: 0.2 }}
                        className={`h-0.5 w-16 mx-2 transition-all duration-500 ${
                          i + 1 < step ? 'bg-[#3A4A9C]' : 'bg-gray-200'
                        }`}
                      />
                    )}
                  </div>
                ))}
              </div>
              {/* Mobile Step Label - Only show current step */}
              <div className="text-center">
                <div className="inline-block px-4 py-2 bg-[#3A4A9C]/10 rounded-full">
                  <span className="text-sm font-semibold text-[#3A4A9C]">
                    {step === 1 && t('leadForm.step1Label', 'Business Info')}
                    {step === 2 && t('leadForm.step2Label', 'Contact Details')}
                    {step === 3 && t('leadForm.step3Label', 'Review & Submit')}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <form onSubmit={handleSubmit}>
            {/* Honeypot (hidden). Real users never see/fill this. */}
            <div style={{ position: 'absolute', left: '-10000px', top: 'auto', width: 1, height: 1, overflow: 'hidden' }} aria-hidden="true">
              <label htmlFor="company">Company</label>
              <input
                id="company"
                name="company"
                type="text"
                tabIndex={-1}
                autoComplete="off"
                value={formData.company}
                onChange={(e) => updateField('company', e.target.value)}
              />
            </div>

            <AnimatePresence mode="wait">
              {/* Step 1: Business Type & Volume */}
              {step === 1 && (
                <motion.div
                  key="step1"
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: -20 }}
                  transition={{ duration: 0.3 }}
                  className="space-y-8"
                >
                  <div>
                    <label className="block text-lg font-semibold text-gray-900 mb-4">
                      {t('leadForm.businessType.label', 'What type of business do you run?')}
                    </label>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      {businessTypes.map((type) => (
                        <SelectableCard
                          key={type.value}
                          icon={type.icon}
                          title={type.title}
                          description={type.description}
                          value={type.value}
                          selected={formData.businessType === type.value}
                          onClick={() => updateField('businessType', type.value)}
                        />
                      ))}
                    </div>
                  </div>

                  <div>
                    <label className="block text-lg font-semibold text-gray-900 mb-4">
                      {t('leadForm.volume.label', 'What\'s your monthly order volume?')}
                    </label>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {volumeOptions.map((option) => (
                        <SelectableCard
                          key={option.value}
                          icon={option.icon}
                          title={option.title}
                          description={option.description}
                          value={option.value}
                          selected={formData.volume === option.value}
                          onClick={() => updateField('volume', option.value)}
                        />
                      ))}
                    </div>
                  </div>
                </motion.div>
              )}

              {/* Step 2: Contact Information */}
              {step === 2 && (
                <motion.div
                  key="step2"
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: -20 }}
                  transition={{ duration: 0.3 }}
                  className="space-y-6"
                >
                  <div>
                    <label htmlFor="name" className="block text-sm font-semibold text-gray-700 mb-3">
                      {t('leadForm.name.label', 'Full Name')} <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <div className={`absolute ${isRTL ? 'right-4' : 'left-4'} top-1/2 -translate-y-1/2 text-gray-400`}>
                        <User className="w-5 h-5" />
                      </div>
                      <input
                        id="name"
                        type="text"
                        value={formData.name}
                        onChange={(e) => updateField('name', e.target.value.slice(0, 120))}
                        placeholder={t('leadForm.name.placeholder', 'Enter your full name')}
                        required
                        maxLength={120}
                        className={`w-full ${isRTL ? 'pr-12 pl-4' : 'pl-12 pr-4'} py-4 bg-gray-50 border-2 border-gray-200 rounded-xl text-base focus:outline-none focus:ring-2 focus:ring-[#3A4A9C]/20 focus:border-[#3A4A9C] transition-all ${isRTL ? 'text-right' : 'text-left'}`}
                        aria-label={t('leadForm.name.label', 'Full Name')}
                      />
                    </div>
                  </div>

                  <div>
                    <label htmlFor="phone" className="block text-sm font-semibold text-gray-700 mb-3">
                      {t('leadForm.phone.label', 'Phone Number')} <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <div className={`absolute ${isRTL ? 'right-4' : 'left-4'} top-1/2 -translate-y-1/2 text-gray-400`}>
                        <Phone className="w-5 h-5" />
                      </div>
                      <input
                        id="phone"
                        type="tel"
                        value={formData.phone}
                        inputMode="numeric"
                        pattern="[0-9 ]*"
                        onBlur={() => {
                          if (formData.phone) setPhoneValidationVisible(true);
                        }}
                        onChange={(e) => {
                          const raw = e.target.value;
                          if (raw.includes('+')) return;
                          if (/[^0-9\s]/.test(raw)) return;

	                          const digits = raw.replace(/\s+/g, '');
	                          if (digits.length === 0) {
	                            updateField('phone', '');
	                            return;
	                          }

	                          const first = digits[0];
	                          if (!['0', '5', '6', '7', '8'].includes(first)) return;

	                          // If starts with 0, second digit must be 5/6/7/8 (allow just "0" while typing)
	                          if (first === '0' && digits.length >= 2) {
	                            const second = digits[1];
	                            if (!['5', '6', '7', '8'].includes(second)) return;
	                          }

	                          const maxLen = first === '0' ? 10 : 9;
	                          updateField('phone', digits.slice(0, maxLen));
	                        }}
	                        placeholder={t('leadForm.phone.placeholder', '06XXXXXXXX')}
	                        required
	                        maxLength={10}
	                        className={`w-full ${isRTL ? 'pr-12 pl-4' : 'pl-12 pr-4'} py-4 bg-gray-50 border-2 border-gray-200 rounded-xl text-base focus:outline-none focus:ring-2 focus:ring-[#3A4A9C]/20 focus:border-[#3A4A9C] transition-all ${isRTL ? 'text-right' : 'text-left'}`}
	                        aria-label={t('leadForm.phone.label', 'Phone Number')}
                      />
                    </div>
                    {formData.phone.length > 0 && phoneValidationVisible && (
                      <p className={`mt-2 text-xs ${isPhoneValid ? 'text-green-600' : 'text-red-600'}`}>
                        {isPhoneValid
                          ? t('leadForm.phone.valid', 'Numéro valide')
                          : t('leadForm.phone.invalid', 'Numéro invalide')}
                      </p>
                    )}
                  </div>

                  <div>
                    <label htmlFor="website" className="block text-sm font-semibold text-gray-700 mb-3">
                      {t('leadForm.website.label', 'Website')}
                    </label>
                    <div className="relative">
                      <div className={`absolute ${isRTL ? 'right-4' : 'left-4'} top-1/2 -translate-y-1/2 text-gray-400`}>
                        <Globe className="w-5 h-5" />
                      </div>
                      <input
                        id="website"
                        type="url"
                        value={formData.website}
                        onChange={(e) => updateField('website', e.target.value.slice(0, 200))}
                        placeholder={t('leadForm.website.placeholder', 'https://yourwebsite.com')}
                        maxLength={200}
                        className={`w-full ${isRTL ? 'pr-12 pl-4' : 'pl-12 pr-4'} py-4 bg-gray-50 border-2 border-gray-200 rounded-xl text-base focus:outline-none focus:ring-2 focus:ring-[#3A4A9C]/20 focus:border-[#3A4A9C] transition-all ${isRTL ? 'text-right' : 'text-left'}`}
                        aria-label={t('leadForm.website.label', 'Website')}
                      />
                    </div>
                    {!isWebsiteValid && (
                      <p className="mt-2 text-xs text-red-600">
                        {t('leadForm.website.validation', 'Format invalide. Exemples: https://example.com, example.com, www.example.com')}
                      </p>
                    )}
                  </div>

                  <div>
                    <label htmlFor="city" className="block text-sm font-semibold text-gray-700 mb-3">
                      {t('leadForm.city.label', 'City')} <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <div className={`absolute ${isRTL ? 'right-4' : 'left-4'} top-1/2 -translate-y-1/2 text-gray-400`}>
                        <MapPin className="w-5 h-5" />
                      </div>
                      <input
                        id="city"
                        type="text"
                        value={formData.city}
                        onChange={(e) => updateField('city', e.target.value.slice(0, 120))}
                        placeholder={t('leadForm.city.placeholder', 'Casablanca, Rabat, etc.')}
                        required
                        maxLength={120}
                        className={`w-full ${isRTL ? 'pr-12 pl-4' : 'pl-12 pr-4'} py-4 bg-gray-50 border-2 border-gray-200 rounded-xl text-base focus:outline-none focus:ring-2 focus:ring-[#3A4A9C]/20 focus:border-[#3A4A9C] transition-all ${isRTL ? 'text-right' : 'text-left'}`}
                        aria-label={t('leadForm.city.label', 'City')}
                      />
                    </div>
                  </div>
                </motion.div>
              )}

              {/* Step 3: Services & Review */}
              {step === 3 && (
                <motion.div
                  key="step3"
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: -20 }}
                  transition={{ duration: 0.3 }}
                  className="space-y-8"
                >
                  <div>
                    <label className="block text-lg font-semibold text-gray-900 mb-2">
                      {t('leadForm.services.label', 'Which services are you interested in?')}
                    </label>
                    <p className="text-sm text-gray-600 mb-4">
                      {t('leadForm.services.subtitle', 'Select all that apply')}
                    </p>
                    <div className="space-y-3">
                      {serviceOptions.map((service) => (
                        <CheckboxCard
                          key={service.value}
                          icon={service.icon}
                          title={service.title}
                          description={service.description}
                          checked={formData.services.includes(service.value)}
                          onChange={() => toggleService(service.value)}
                        />
                      ))}
                    </div>
                  </div>

                  <div className="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-xl p-6 border-2 border-blue-100">
                    <h3 className="font-semibold text-lg text-gray-900 mb-4 flex items-center gap-2">
                      <CheckCircle className="w-5 h-5 text-[#3A4A9C]" />
                      {t('leadForm.review.title', 'Review Your Information')}
                    </h3>
                    <div className="space-y-3 text-sm">
                      <div className="flex justify-between items-center py-2 border-b border-blue-200/50">
                        <span className="text-gray-600 font-medium">{t('leadForm.review.businessType', 'Business Type')}:</span>
                        <span className="font-semibold text-gray-900">
                          {businessTypes.find(b => b.value === formData.businessType)?.title || '-'}
                        </span>
                      </div>
	                      <div className="flex justify-between items-center py-2 border-b border-blue-200/50">
	                        <span className="text-gray-600 font-medium">{t('leadForm.review.volume', 'Monthly Volume')}:</span>
	                        <span className="font-semibold text-gray-900 font-poppins">{formData.volume || '-'}</span>
	                      </div>
                      <div className="flex justify-between items-center py-2 border-b border-blue-200/50">
                        <span className="text-gray-600 font-medium">{t('leadForm.review.name', 'Name')}:</span>
                        <span className="font-semibold text-gray-900">{formData.name || '-'}</span>
                      </div>
                      <div className="flex justify-between items-center py-2 border-b border-blue-200/50">
                        <span className="text-gray-600 font-medium">{t('leadForm.review.phone', 'Phone')}:</span>
                        <span className="font-semibold text-gray-900 font-mono">{formData.phone || '-'}</span>
                      </div>
                      {formData.website && (
                        <div className="flex justify-between items-center py-2 border-b border-blue-200/50">
                          <span className="text-gray-600 font-medium">{t('leadForm.review.website', 'Website')}:</span>
                          <span className="font-semibold text-gray-900">{formData.website}</span>
                        </div>
                      )}
                      <div className="flex justify-between items-center py-2 border-b border-blue-200/50">
                        <span className="text-gray-600 font-medium">{t('leadForm.review.city', 'City')}:</span>
                        <span className="font-semibold text-gray-900">{formData.city || '-'}</span>
                      </div>
                      {formData.services.length > 0 && (
                        <div className="py-2">
                          <span className="text-gray-600 font-medium block mb-2">{t('leadForm.review.services', 'Services')}:</span>
                          <div className="flex flex-wrap gap-2">
                            {formData.services.map(service => (
                              <span key={service} className="px-3 py-1 bg-[#3A4A9C] text-white text-xs font-medium rounded-full">
                                {serviceOptions.find(s => s.value === service)?.title}
                              </span>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* Navigation Buttons */}
            <div className={`flex ${isRTL ? 'flex-row-reverse' : ''} justify-between mt-8 gap-4`}>
              {submitError && (
                <div className="flex-1 text-sm text-red-600" role="alert">
                  {submitError}
                </div>
              )}
              {step > 1 && (
                <button
                  type="button"
                  onClick={handleBack}
                  disabled={submitting}
                  className={`flex items-center gap-2 px-6 py-3 border-2 border-gray-300 rounded-xl text-gray-700 hover:bg-gray-50 transition-all font-medium ${isRTL ? 'flex-row-reverse' : ''}`}
                >
                  {isRTL ? <ChevronRight className="w-5 h-5" /> : <ChevronLeft className="w-5 h-5" />}
                  <span>{t('leadForm.back', 'Back')}</span>
                </button>
              )}

              {step < totalSteps ? (
                <button
                  type="button"
                  onClick={handleNext}
	                  disabled={
	                    submitting ||
	                    (step === 1 && (!formData.businessType || !formData.volume)) ||
	                    (step === 2 && (!formData.name || !formData.phone || !formData.city || !isPhoneValid || !isWebsiteValid))
	                  }
                  className={`flex items-center gap-2 px-6 py-3 bg-[#3A4A9C] text-white rounded-xl hover:bg-[#2d3a7a] transition-all ${step === 1 ? 'ml-auto' : ''} shadow-lg hover:shadow-xl font-medium disabled:opacity-50 disabled:cursor-not-allowed ${isRTL ? 'flex-row-reverse' : ''}`}
                >
                  <span>{t('leadForm.next', 'Next')}</span>
                  {isRTL ? <ChevronLeft className="w-5 h-5" /> : <ChevronRight className="w-5 h-5" />}
                </button>
              ) : (
	                <button
	                  type="submit"
	                  disabled={submitting || !isPhoneValid || !isWebsiteValid}
	                  className={`px-8 py-3 bg-gradient-to-r from-[#3A4A9C] to-[#2d3a7a] text-white rounded-xl hover:shadow-xl transition-all shadow-lg font-semibold flex items-center gap-2 ${isRTL ? 'flex-row-reverse' : ''}`}
	                >
                  <span>{submitting ? t('leadForm.submitting', 'Sending...') : t('leadForm.submit', 'Submit Request')}</span>
                  <CheckCircle className="w-5 h-5" />
                </button>
              )}
            </div>
          </form>
        </Card>
      </Container>
    </section>
  );
}
