import { useState, useEffect } from 'react';
import { Check, ArrowLeft, Loader2, Globe2, TreePine, Waves, Factory, Wind, AlertCircle, Flame, Snowflake, Mountain, Sprout, Package, Droplet, Zap } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { createOffsetOrder, getPortfolios } from '../api/wrenClient';
import type { OffsetOrder as OffsetOrderType, Portfolio, OffsetProject } from '../types';
import { currencies, formatCurrency } from '../utils/currencies';
import { config } from '../utils/config';
import { sendContactFormEmail } from '../utils/email';
import { RadialProgress } from './RadialProgress';
import { PortfolioDonutChart } from './PortfolioDonutChart';
import { getProjectColor } from '../utils/portfolioColors';
import { CertificationBadge } from './CertificationBadge';
import { useCalculatorState } from '../hooks/useCalculatorState';

interface Props {
  tons: number;
  monetaryAmount?: number;
  onBack: () => void;
}

interface ProjectTypeIconProps {
  project: OffsetProject;
}

const ProjectTypeIcon = ({ project }: ProjectTypeIconProps) => {
  // Safely check if project exists
  if (!project || !project.name) {
    return <Globe2 className="text-blue-500" size={16} />;
  }

  const name = project.name.toLowerCase();

  // Match on project name to determine appropriate icon
  if (name.includes('rainforest') || name.includes('forest')) {
    return <TreePine className="text-green-600" size={16} />;
  } else if (name.includes('biochar') && name.includes('carbon removal')) {
    return <Flame className="text-orange-600" size={16} />;
  } else if (name.includes('refrigerant')) {
    return <Snowflake className="text-cyan-600" size={16} />;
  } else if (name.includes('rock weathering') || name.includes('enhanced weathering')) {
    return <Mountain className="text-amber-700" size={16} />;
  } else if (name.includes('rice paddies') || name.includes('paddies')) {
    return <Sprout className="text-green-500" size={16} />;
  } else if (name.includes('mangrove') || name.includes('blue carbon')) {
    return <Waves className="text-blue-600" size={16} />;
  } else if (name.includes('biomass storage') || name.includes('underground')) {
    return <Package className="text-amber-800" size={16} />;
  } else if (name.includes('bio-oil') || name.includes('oil')) {
    return <Droplet className="text-blue-700" size={16} />;
  } else if (name.includes('adipic') || name.includes('nitrous oxide') || name.includes('factory')) {
    return <Factory className="text-gray-600" size={16} />;
  } else if (name.includes('renewable') || name.includes('wind') || name.includes('solar')) {
    return <Wind className="text-green-500" size={16} />;
  } else if (name.includes('direct air capture') || name.includes('dac')) {
    return <Zap className="text-purple-600" size={16} />;
  } else {
    return <Globe2 className="text-blue-500" size={16} />;
  }
};

export function MobileOffsetOrder({ tons, monetaryAmount, onBack }: Props) {
  const { state: savedState, saveState } = useCalculatorState();

  const [currentStep, setCurrentStep] = useState<'summary' | 'projects' | 'confirmation'>('summary');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [_success, setSuccess] = useState(false);
  const [order, setOrder] = useState<OffsetOrderType | null>(null);
  const [portfolio, setPortfolio] = useState<Portfolio | null>(null);
  const [loadingPortfolio, setLoadingPortfolio] = useState(true);
  const [offsetPercentage, setOffsetPercentage] = useState(
    savedState?.offsetPercentage ?? 100 // Default to 100% or use saved value
  );

  // Calculate price per ton (rounded up)
  const roundedPricePerTon = portfolio ? Math.ceil(portfolio.pricePerTon || 18) : 18;

  // Calculate the actual tons to offset based on percentage
  // If monetaryAmount is provided (custom amount), calculate tons from the monetary amount
  const baseTons = monetaryAmount ? (monetaryAmount / roundedPricePerTon) : tons;
  const actualOffsetTons = (baseTons * offsetPercentage) / 100;

  // Format tons for display
  const formatTons = (tons: number): string => {
    const fixed = tons.toFixed(2);
    const parts = fixed.split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return parts.join('.');
  };

  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    company: '',
    message: `I would like to offset ${formatTons(actualOffsetTons)} tons of CO2 from my yacht's emissions.`
  });

  // Update form message when percentage changes
  useEffect(() => {
    setFormData(prev => ({
      ...prev,
      message: `I would like to offset ${formatTons(actualOffsetTons)} tons of CO2 (${offsetPercentage}% of ${formatTons(tons)} tons) from my yacht's emissions.`
    }));
  }, [offsetPercentage, actualOffsetTons, tons]);

  // Save offset percentage and portfolio ID to localStorage
  useEffect(() => {
    if (savedState) {
      saveState({
        ...savedState,
        offsetPercentage,
        portfolioId: portfolio?.id,
      });
    }
  }, [offsetPercentage, portfolio, savedState, saveState]);

  useEffect(() => {
    if (!config.wrenApiKey) {
      setError('Carbon offset service is currently unavailable. Please use our contact form to request offsetting.');
      setLoadingPortfolio(false);
      return;
    }
    fetchPortfolio();
  }, []);

  const fetchPortfolio = async () => {
    try {
      const allPortfolios = await getPortfolios();
      
      if (!allPortfolios || allPortfolios.length === 0) {
        throw new Error('No portfolios available');
      }
      
      const puffinPortfolio = allPortfolios.find(p => 
        p.name.toLowerCase().includes('puffin') || 
        p.name.toLowerCase().includes('maritime')
      );
      
      if (puffinPortfolio) {
        console.log('[MobileOffsetOrder] Found Puffin portfolio with ID:', puffinPortfolio.id);
        setPortfolio(puffinPortfolio);
      } else {
        console.log('[MobileOffsetOrder] No Puffin portfolio found, using first available portfolio with ID:', allPortfolios[0].id);
        setPortfolio(allPortfolios[0]);
      }
    } catch (err) {
      setError('Failed to fetch portfolio information. Please try again.');
    } finally {
      setLoadingPortfolio(false);
    }
  };

  const handleOffsetOrder = async () => {
    if (!portfolio) return;
    
    setLoading(true);
    setError(null);
    
    try {
      if (config.wrenApiKey) {
        // Try to create real order if API key is available
        const newOrder = await createOffsetOrder(portfolio.id, actualOffsetTons, true); // Using dryRun for demo
        setOrder(newOrder);
      } else {
        // Create a mock order for demo purposes
        const mockOrder: OffsetOrderType = {
          id: 'DEMO-' + Date.now().toString().slice(-8),
          amountCharged: Math.round(offsetCost * 100), // Convert to cents
          currency: 'USD',
          tons: actualOffsetTons,
          portfolio: portfolio,
          status: 'completed',
          createdAt: new Date().toISOString(),
          dryRun: true
        };
        setOrder(mockOrder);
      }
      setSuccess(true);
      setCurrentStep('confirmation');
    } catch (err) {
      console.error('Error creating offset order:', err);
      // Even if API fails, show confirmation for demo
      const mockOrder: OffsetOrderType = {
        id: 'DEMO-' + Date.now().toString().slice(-8),
        amountCharged: Math.round(offsetCost * 100),
        currency: 'USD',
        tons: actualOffsetTons,
        portfolio: portfolio || {
          id: 0,
          name: 'Carbon Offset Portfolio',
          description: 'High-impact carbon removal projects',
          projects: [],
          pricePerTon: 18,
          currency: 'USD'
        },
        status: 'pending',
        createdAt: new Date().toISOString(),
        dryRun: true
      };
      setOrder(mockOrder);
      setSuccess(true);
      setCurrentStep('confirmation');
    } finally {
      setLoading(false);
    }
  };

  const renderPortfolioPrice = (portfolio: Portfolio) => {
    try {
      // Get the price per ton from the portfolio and round UP to next whole number
      const pricePerTon = Math.ceil(portfolio.pricePerTon || 18);
      return formatCurrency(pricePerTon, currencies.USD);
    } catch (err) {
      console.error('Error formatting portfolio price:', err);
      return formatCurrency(18, currencies.USD);
    }
  };

  // Calculate offset cost using the portfolio price (rounded UP to match display)
  const offsetCost = monetaryAmount || (portfolio ? actualOffsetTons * roundedPricePerTon : 0);

  const handleInputChange = (field: keyof typeof formData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleProceedToProjects = () => {
    setCurrentStep('projects');
  };

  const renderSummaryStep = () => (
    <motion.div
      className="space-y-6"
      initial={{ opacity: 0, x: 20 }}
      animate={{ opacity: 1, x: 0 }}
      exit={{ opacity: 0, x: -20 }}
    >
      {error && !config.wrenApiKey ? (
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-blue-900 mb-4">
            Contact Us for Offsetting
          </h3>
          <p className="text-blue-700 mb-4 text-sm">
            Our automated offsetting service is temporarily unavailable. Please fill out the form below and our team will help you offset your emissions.
          </p>
          <form onSubmit={async (e) => {
            e.preventDefault();
            setLoading(true);
            try {
              await sendContactFormEmail(formData, 'contact');
              setSuccess(true);
              setCurrentStep('confirmation');
            } catch (err) {
              setError('Failed to send request. Please try again.');
            } finally {
              setLoading(false);
            }
          }} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Name *
              </label>
              <input
                type="text"
                required
                value={formData.name}
                onChange={(e) => handleInputChange('name', e.target.value)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Email *
              </label>
              <input
                type="email"
                required
                value={formData.email}
                onChange={(e) => handleInputChange('email', e.target.value)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Phone
              </label>
              <input
                type="tel"
                value={formData.phone}
                onChange={(e) => handleInputChange('phone', e.target.value)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Message
              </label>
              <textarea
                rows={3}
                value={formData.message}
                onChange={(e) => handleInputChange('message', e.target.value)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <button
              type="submit"
              disabled={loading}
              className={`w-full flex items-center justify-center bg-blue-500 text-white py-3 rounded-lg transition-colors ${
                loading ? 'opacity-50 cursor-not-allowed' : 'hover:bg-blue-600'
              }`}
            >
              {loading ? (
                <>
                  <Loader2 className="animate-spin mr-2" size={20} />
                  Sending Request...
                </>
              ) : (
                'Send Offset Request'
              )}
            </button>
          </form>
        </div>
      ) : error ? (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex items-center space-x-2">
            <AlertCircle className="text-red-500" size={20} />
            <p className="text-red-700 text-sm">{error}</p>
          </div>
        </div>
      ) : loadingPortfolio ? (
        <div className="flex justify-center items-center py-12">
          <Loader2 className="animate-spin text-blue-500" size={32} />
          <span className="ml-2 text-gray-600">Loading portfolio information...</span>
        </div>
      ) : portfolio ? (
        <>
          {/* Offset Percentage Slider */}
          <div className="bg-white rounded-2xl p-6 shadow-sm mb-4">
            <h3 className="text-lg font-semibold mb-4">Choose Your Offset Amount</h3>
            <div className="space-y-4">
              <div>
                <div className="flex justify-between items-center mb-4">
                  <span className="text-gray-600">Offset Percentage:</span>
                  <span className="text-2xl font-bold text-blue-600">{offsetPercentage}%</span>
                </div>
                <div className="relative">
                  {/* Tick marks container - positioned below the slider */}
                  <div className="absolute top-1/2 -translate-y-1/2 left-0 w-full h-2 pointer-events-none flex justify-between items-center">
                    {[0, 25, 50, 75, 100].map((tick) => (
                      <div
                        key={tick}
                        className="w-[2px] h-2 rounded-full"
                        style={{
                          backgroundColor: tick <= offsetPercentage ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.2)'
                        }}
                      ></div>
                    ))}
                  </div>
                  {/* Slider - positioned above tick marks */}
                  <input
                    type="range"
                    min="0"
                    max="100"
                    value={offsetPercentage}
                    onChange={(e) => setOffsetPercentage(Number(e.target.value))}
                    className="relative z-10 w-full h-3 bg-gray-200 rounded-lg appearance-none cursor-pointer slider"
                    style={{
                      background: `linear-gradient(to right, #3b82f6 0%, #3b82f6 ${offsetPercentage}%, #e5e7eb ${offsetPercentage}%, #e5e7eb 100%)`
                    }}
                  />
                </div>
                <div className="relative mt-2 h-4">
                  <span className="text-xs text-gray-500 absolute left-0">0%</span>
                  <span className="text-xs text-gray-500 absolute left-1/4 -translate-x-1/2">25%</span>
                  <span className="text-xs text-gray-500 absolute left-1/2 -translate-x-1/2">50%</span>
                  <span className="text-xs text-gray-500 absolute left-3/4 -translate-x-1/2">75%</span>
                  <span className="text-xs text-gray-500 absolute right-0">100%</span>
                </div>
              </div>
              <div className="bg-blue-50 p-4 rounded-lg">
                <div className="flex justify-between items-center">
                  <span className="text-gray-700">CO₂ to Offset:</span>
                  <span className="text-xl font-bold text-blue-900">
                    {formatTons(actualOffsetTons)} tons
                  </span>
                </div>
                <div className="text-sm text-blue-600 mt-1">
                  {offsetPercentage}% of {formatTons(tons)} tons total emissions
                </div>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-2xl p-6 shadow-sm">
            <h3 className="text-lg font-semibold mb-4">Offset Summary</h3>

            <div className="space-y-4">
              <div className="flex justify-between items-center p-4 bg-blue-50 rounded-xl">
                <div>
                  <div className="font-semibold text-blue-900">CO₂ to Offset</div>
                  <div className="text-sm text-blue-600">From your yacht emissions</div>
                </div>
                <div className="text-xl font-bold text-blue-900 text-right">
                  {formatTons(actualOffsetTons)} tons
                </div>
              </div>

              <div className="flex justify-between items-center p-4 bg-green-50 rounded-xl">
                <div>
                  <div className="font-semibold text-green-900">Price per Ton</div>
                  <div className="text-sm text-green-600">Verified carbon credits</div>
                </div>
                <div className="text-xl font-bold text-green-900 text-right">
                  {renderPortfolioPrice(portfolio)}
                </div>
              </div>

              <div className="border-t pt-4">
                <div className="flex justify-between items-center">
                  <span className="text-lg font-semibold text-gray-900">Total Cost</span>
                  <span className="text-2xl font-bold text-gray-900 text-right">
                    {formatCurrency(offsetCost, currencies.USD)}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <div className="bg-gray-50 rounded-xl p-4">
            <h4 className="font-semibold text-gray-900 mb-2">Portfolio</h4>
            <p className="text-sm text-gray-600">{portfolio.name}</p>
            <p className="text-xs text-gray-500 mt-1">{portfolio.description}</p>
          </div>

          <button
            onClick={handleProceedToProjects}
            className="w-full bg-gradient-to-r from-blue-500 to-blue-600 text-white py-4 px-6 rounded-xl font-semibold text-lg shadow-md hover:shadow-lg transition-all"
          >
            View Projects & Continue
          </button>
        </>
      ) : null}
    </motion.div>
  );

  const renderProjectsStep = () => (
    <motion.div
      className="space-y-6"
      initial={{ opacity: 0, x: 20 }}
      animate={{ opacity: 1, x: 0 }}
      exit={{ opacity: 0, x: -20 }}
    >
      {portfolio && (
        <>
          <div className="bg-white rounded-2xl p-6 shadow-sm">
            <h3 className="text-lg font-semibold mb-2">{portfolio.name}</h3>
            <p className="text-sm text-gray-600">
              Your offset will be distributed across these verified carbon reduction projects
            </p>
          </div>

          {/* Portfolio Allocation Visualization */}
          {portfolio.projects && portfolio.projects.length > 0 && (
            <motion.div
              className="bg-white rounded-2xl p-6 shadow-sm"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
            >
              <h4 className="text-lg font-semibold text-gray-900 mb-6 text-center">Portfolio Distribution</h4>
              <PortfolioDonutChart
                projects={portfolio.projects}
                totalTons={actualOffsetTons}
              />
            </motion.div>
          )}

          {/* Project Cards */}
          {portfolio.projects && portfolio.projects.length > 0 && (
            <div className="bg-white rounded-2xl p-6 shadow-sm space-y-6">
              {portfolio.projects.map((project, index) => (
                <motion.div
                  key={project.id || `project-${index}`}
                  className="pb-6 border-b border-gray-200 last:border-b-0 last:pb-0"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.1 }}
                >
                  {project.imageUrl && (
                    <div className="relative h-32 -mx-6 mb-4 rounded-lg overflow-hidden">
                      <img
                        src={project.imageUrl}
                        alt={project.name}
                        className="w-full h-full object-cover"
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />
                      <div className="absolute bottom-2 left-3 right-3">
                        <h4 className="text-white font-semibold text-sm">{project.name}</h4>
                      </div>
                    </div>
                  )}

                  <div>
                    {!project.imageUrl && (
                      <h4 className="font-semibold text-gray-900 mb-2">{project.name}</h4>
                    )}

                    <div className="flex items-center justify-between mb-2">
                      <div className="flex items-center space-x-2">
                        <ProjectTypeIcon project={project} />
                        <span className="text-xs font-medium text-gray-600">
                          {project.type || 'Environmental Project'}
                        </span>
                      </div>
                      {project.percentage && (
                        <RadialProgress
                          percentage={project.percentage * 100}
                          size={48}
                          color={getProjectColor(index)}
                          delay={index * 0.1 + 0.3}
                        />
                      )}
                    </div>

                    <p className="text-sm text-gray-600 line-clamp-2 mb-2">
                      {project.shortDescription || project.description}
                    </p>

                    <CertificationBadge status={project.certificationStatus} size="sm" />
                  </div>
                </motion.div>
              ))}
            </div>
          )}

          <div className="bg-blue-50 rounded-xl p-4">
            <div className="flex items-center justify-between mb-2">
              <span className="font-medium text-blue-900">Total CO₂ Offset</span>
              <span className="font-bold text-blue-900">{formatTons(tons)} tons</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="font-medium text-blue-900">Portfolio Price</span>
              <span className="font-bold text-lg text-blue-900">
                {formatCurrency(offsetCost, currencies.USD)}
              </span>
            </div>
          </div>

          <button
            onClick={handleOffsetOrder}
            disabled={loading}
            className={`w-full bg-gradient-to-r from-green-500 to-green-600 text-white py-4 px-6 rounded-xl font-semibold text-lg shadow-md hover:shadow-lg transition-all ${
              loading ? 'opacity-50 cursor-not-allowed' : ''
            }`}
          >
            {loading ? (
              <div className="flex items-center justify-center">
                <Loader2 className="animate-spin mr-2" size={20} />
                Processing...
              </div>
            ) : (
              'Confirm Offset Order'
            )}
          </button>
        </>
      )}
    </motion.div>
  );

  const renderConfirmationStep = () => (
    <motion.div
      className="space-y-6 text-center"
      initial={{ opacity: 0, scale: 0.9 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.9 }}
    >
      <div className="bg-white rounded-2xl p-8 shadow-sm">
        <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
          <Check className="text-green-500" size={40} />
        </div>

        <h3 className="text-2xl font-bold text-gray-900 mb-4">
          {order ? 'Offset Order Successful!' : 'Request Sent!'}
        </h3>
        
        <p className="text-gray-600 mb-6">
          {order 
            ? "Your order has been processed successfully. You'll receive a confirmation email shortly."
            : "Your offset request has been sent. Our team will contact you shortly to complete the process."
          }
        </p>

        {order && (
          <div className="bg-gray-50 rounded-xl p-6 mb-6">
            <h4 className="font-semibold mb-4">Order Details</h4>
            <div className="space-y-3 text-left">
              <div className="flex justify-between">
                <span className="text-gray-600">Order ID:</span>
                <span className="font-mono font-medium">{order.id}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">CO₂ Offset:</span>
                <span className="font-medium">{order.tons} tons</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">Amount:</span>
                <span className="font-medium">
                  {formatCurrency(order.amountCharged / 100, currencies[order.currency])}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">Portfolio:</span>
                <span className="font-medium">{order.portfolio.name}</span>
              </div>
            </div>
          </div>
        )}

        {formData.email && (
          <div className="bg-blue-50 rounded-xl p-4 mb-6">
            <p className="text-sm text-blue-800">
              📧 {order 
                ? `A confirmation email has been sent to ${formData.email}`
                : `We'll contact you at ${formData.email}`
              }
            </p>
          </div>
        )}
      </div>

      <button
        onClick={onBack}
        className="w-full bg-gradient-to-r from-blue-500 to-blue-600 text-white py-4 px-6 rounded-xl font-semibold text-lg shadow-md hover:shadow-lg transition-all"
      >
        Back to Calculator
      </button>
    </motion.div>
  );

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-cyan-50">
      {/* Mobile Header */}
      <header
        className="bg-white/80 backdrop-blur-md shadow-sm sticky top-0 z-50"
      >
        <div className="flex items-center justify-between p-4">
          <motion.button
            onClick={currentStep === 'confirmation' ? onBack : () => {
              if (currentStep === 'projects') {
                setCurrentStep('summary');
              } else {
                onBack();
              }
            }}
            className="p-2 rounded-xl bg-gray-100 hover:bg-gray-200 transition-colors"
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
          >
            <ArrowLeft size={20} />
          </motion.button>
          
          <div className="flex items-center space-x-3">
            <h1 className="text-lg font-bold text-gray-900">
              {currentStep === 'summary' ? 'Order Summary' : 
               currentStep === 'projects' ? 'Project Portfolio' :
               'Order Confirmed'}
            </h1>
          </div>
          
          <div className="w-10"></div> {/* Spacer */}
        </div>

        {/* Progress Bar */}
        {currentStep !== 'confirmation' && (
          <div className="px-4 pb-3">
            <div className="flex items-center space-x-2">
              <div className={`flex-1 h-2 rounded-full ${
                ['summary', 'projects'].includes(currentStep) ? 'bg-blue-500' : 'bg-gray-200'
              }`} />
              <div className={`flex-1 h-2 rounded-full ${
                currentStep === 'projects' ? 'bg-blue-500' : 'bg-gray-200'
              }`} />
            </div>
          </div>
        )}
      </header>

      <div className="p-4 pb-20">
        <AnimatePresence mode="wait">
          {currentStep === 'summary' && renderSummaryStep()}
          {currentStep === 'projects' && renderProjectsStep()}
          {currentStep === 'confirmation' && renderConfirmationStep()}
        </AnimatePresence>
      </div>
    </div>
  );
}
