as it at least takes 15 seconds for processing, so slower the whole simulation, also i dont like it keep refreshing everytime when it update the progress....
dont use a small window, use an overlay instead so that it didnt flickering/refresh state frequnently, enhance it
return full updated code to me
import React, { useState } from 'react';
import {
  Box,
  Stepper,
  Step,
  StepLabel,
  Button,
  Typography,
  TextField,
  Paper,
  CircularProgress,
  Alert,
  Fade,
  Slide,
  Slider,
  Radio,
  RadioGroup,
  FormControlLabel,
  FormControl,
  FormLabel,
  Chip,
  IconButton,
  Tooltip,
  Stack,
  Divider,
  LinearProgress
} from '@mui/material';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import { api } from '../services/api';
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome';
import RocketLaunchIcon from '@mui/icons-material/RocketLaunch';
import SmartToyIcon from '@mui/icons-material/SmartToy';
import { keyframes } from '@mui/system';
import TipsAndUpdatesIcon from '@mui/icons-material/TipsAndUpdates';
import TimelineIcon from '@mui/icons-material/Timeline';
import { alpha } from '@mui/material/styles';
import CloseIcon from '@mui/icons-material/Close';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';

const SURVEY_STEPS = [
  {
    label: 'Investment Goal',
    question: 'What is your primary investment goal?',
    type: 'radio',
    options: [
      { value: 'growth', label: 'Growth', description: 'Focus on capital appreciation' },
      { value: 'income', label: 'Income', description: 'Focus on dividend yield' },
      { value: 'balanced', label: 'Balanced', description: 'Mix of growth and income' },
      { value: 'conservative', label: 'Conservative', description: 'Focus on capital preservation' }
    ]
  },
  {
    label: 'Risk Tolerance',
    question: 'What is your maximum acceptable drawdown (loss)?',
    type: 'slider',
    min: 5,
    max: 60,
    step: 5,
    defaultValue: 25,
    format: (value) => `${value}%`,
    helper: 'Maximum percentage loss you can tolerate in your portfolio value',
    marks: [
      { value: 5, label: 'Very Conservative' },
      { value: 20, label: 'Conservative' },
      { value: 35, label: 'Moderate' },
      { value: 50, label: 'Aggressive' },
      { value: 60, label: 'Very Aggressive' }
    ]
  },
  {
    label: 'Expected Return',
    question: 'What is your target annual return?',
    type: 'slider',
    min: 0,
    max: 50,
    step: 5,
    defaultValue: 15,
    format: (value) => `${value}%`,
    helper: 'Target annual return (higher returns typically involve more risk)',
    marks: [
      { value: 0, label: 'Treasury Rate' },
      { value: 15, label: 'Market Rate' },
      { value: 30, label: 'Above Market' },
      { value: 50, label: 'Aggressive Growth' }
    ]
  },
  {
    label: 'Investment Horizon',
    question: 'How long do you plan to hold this portfolio?',
    type: 'radio',
    options: [
      { value: 'short', label: '1-3 years', description: 'Short term' },
      { value: 'medium', label: '3-7 years', description: 'Medium term' },
      { value: 'long', label: '7+ years', description: 'Long term' }
    ]
  },
  {
    label: 'Preferences',
    question: 'Select or enter your investment preferences',
    type: 'chips',
    options: [
      { value: 'esg', label: 'ESG Focused' },
      { value: 'tech', label: 'Technology' },
      { value: 'dividend', label: 'Dividend Stocks' },
      { value: 'value', label: 'Value Stocks' },
      { value: 'growth', label: 'Growth Stocks' },
      { value: 'large_cap', label: 'Large Cap' },
      { value: 'mid_cap', label: 'Mid Cap' },
      { value: 'international', label: 'International' }
    ],
    helper: 'Select from common preferences or type your own'
  }
];

const FREE_FORM_MODE = 'free_form';
const GUIDED_MODE = 'guided';

const glowAnimation = keyframes`
  0% { box-shadow: 0 0 5px rgba(25, 118, 210, 0.2); }
  50% { box-shadow: 0 0 20px rgba(25, 118, 210, 0.6); }
  100% { box-shadow: 0 0 5px rgba(25, 118, 210, 0.2); }
`;

const floatAnimation = keyframes`
  0% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0px); }
`;

const pulseAnimation = keyframes`
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
`;

const shimmerAnimation = keyframes`
  0% { background-position: -1000px 0; }
  100% { background-position: 1000px 0; }
`;

const progressAnimation = keyframes`
  from {
    background-position: 0 0;
  }
  to {
    background-position: 100% 0;
  }
`;

const fadeAnimation = keyframes`
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

const TipCard = ({ tip }) => (
  <Fade in={true}>
    <Paper
      elevation={0}
      sx={{
        p: 2,
        mt: 2,
        bgcolor: theme => alpha(theme.palette.info.main, 0.05),
        border: '1px solid',
        borderColor: theme => alpha(theme.palette.info.main, 0.1),
        borderRadius: 2,
        display: 'flex',
        alignItems: 'flex-start',
        gap: 1
      }}
    >
      <TipsAndUpdatesIcon 
        color="info" 
        sx={{ 
          mt: 0.5,
          animation: `${pulseAnimation} 2s infinite`
        }} 
      />
      <Typography variant="body2" color="text.secondary">
        {tip}
      </Typography>
    </Paper>
  </Fade>
);

const INVESTMENT_TIPS = {
  'Investment Goal': "Consider both short-term needs and long-term objectives when selecting your goal. A balanced approach often provides flexibility for changing market conditions.",
  'Risk Tolerance': "Historical data shows that markets typically recover from downturns. Consider your emotional comfort with temporary losses versus your financial capacity to bear them.",
  'Expected Return': "Higher returns generally require accepting higher risk. The S&P 500's long-term average return is around 10% annually.",
  'Investment Horizon': "Longer investment horizons typically allow for more aggressive strategies as you have more time to recover from market downturns.",
  'Preferences': "Diversification across different sectors and styles can help reduce portfolio risk. Consider including some contrarian choices to your usual preferences."
};

const MainContainer = ({ children }) => (
  <Box sx={{ 
    height: '100%',
    maxHeight: '85vh',
    display: 'flex',
    flexDirection: 'column',
    overflow: 'hidden',
    bgcolor: 'background.default',
    position: 'relative',
    '& > *': {
      flexShrink: 0
    },
    '& > .scroll-container': {
      flexShrink: 1,
      overflow: 'auto'
    }
  }}>
    {children}
  </Box>
);

const HeaderPaper = ({ children }) => (
  <Paper 
    elevation={0} 
    variant="outlined" 
    sx={{ 
      mb: { xs: 2, sm: 3 },
      p: { xs: 2, sm: 3 },
      bgcolor: 'background.default',
      position: 'relative',
      overflow: 'hidden',
      '&::before': {
        content: '""',
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: theme => 
          `linear-gradient(45deg, ${alpha(theme.palette.primary.main, 0.05)}, ${alpha(theme.palette.primary.light, 0.1)})`,
        zIndex: 0
      }
    }}
  >
    {children}
  </Paper>
);

const ModeSelectionButton = ({ mode, currentMode, icon: Icon, title, description, onClick }) => (
  <Button
    variant={currentMode === mode ? "contained" : "outlined"}
    onClick={onClick}
    sx={{ 
      flex: { xs: '0 0 auto', sm: 1 },
      height: { xs: '60px', sm: 'auto' },
      py: { xs: 1, sm: 2 },
      px: { xs: 2, sm: 2 },
      display: 'flex',
      flexDirection: { xs: 'row', sm: 'column' },
      alignItems: 'center',
      gap: { xs: 2, sm: 1 },
      animation: currentMode === mode ? `${glowAnimation} 2s infinite` : 'none',
      transition: 'all 0.3s ease-in-out',
      '&:hover': {
        transform: 'translateY(-2px)'
      }
    }}
  >
    <Icon sx={{ fontSize: { xs: '1.5rem', sm: '2rem' } }} />
    <Box sx={{ textAlign: { xs: 'left', sm: 'center' } }}>
      <Typography variant="subtitle1" sx={{ 
        fontWeight: 'bold',
        fontSize: { xs: '0.9rem', sm: '1rem' }
      }}>
        {title}
      </Typography>
      <Typography 
        variant="caption" 
        sx={{ 
          display: 'block',
          fontSize: { xs: '0.75rem', sm: '0.8rem' }
        }}
      >
        {description}
      </Typography>
    </Box>
  </Button>
);

const gradientButtonStyles = {
  flex: 1,
  py: 1.5,
  background: theme => 
    `linear-gradient(45deg, ${theme.palette.primary.main}, ${theme.palette.primary.dark})`,
  transition: 'all 0.3s ease-in-out',
  '&:not(:disabled):hover': {
    transform: 'scale(1.02)',
    boxShadow: 4
  }
};

function PortfolioSurvey({ onPortfolioGenerated, onClose, onUpdatePortfolio }) {
  const [activeStep, setActiveStep] = useState(0);
  const [answers, setAnswers] = useState({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [selectedChips, setSelectedChips] = useState([]);
  const [customPreference, setCustomPreference] = useState('');
  const [surveyMode, setSurveyMode] = useState(GUIDED_MODE);
  const [freeFormInput, setFreeFormInput] = useState('');
  const [showTip, setShowTip] = useState(true);
  const [generationProgress, setGenerationProgress] = useState(0);
  const [isGenerating, setIsGenerating] = useState(false);

  const handleNext = () => {
    if (activeStep === SURVEY_STEPS.length - 1) {
      generatePortfolio();
    } else {
      setActiveStep((prev) => prev + 1);
    }
  };

  const handleBack = () => {
    setActiveStep((prev) => prev - 1);
  };

  const handleAnswerChange = (event) => {
    setAnswers({
      ...answers,
      [SURVEY_STEPS[activeStep].label]: event.target.value
    });
  };

  const renderStepContent = (step) => {
    const content = (
      <>
        {step.type === 'radio' && (
          <FormControl component="fieldset">
            <RadioGroup
              value={answers[step.label] || ''}
              onChange={handleAnswerChange}
            >
              {step.options.map((option) => (
                <FormControlLabel
                  key={option.value}
                  value={option.value}
                  control={<Radio />}
                  label={
                    <Box>
                      <Typography variant="body1">{option.label}</Typography>
                      <Typography variant="caption" color="text.secondary">
                        {option.description}
                      </Typography>
                    </Box>
                  }
                />
              ))}
            </RadioGroup>
          </FormControl>
        )}

        {step.type === 'slider' && (
          <Box sx={{ px: 2, mt: 4 }}>
            <Slider
              value={answers[step.label] || step.defaultValue}
              onChange={(_, value) => 
                setAnswers(prev => ({ ...prev, [step.label]: value }))
              }
              min={step.min}
              max={step.max}
              step={step.step}
              marks
              valueLabelDisplay="on"
              valueLabelFormat={step.format}
            />
            <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
              {step.helper}
            </Typography>
          </Box>
        )}

        {step.type === 'chips' && (
          <Box sx={{ mt: 2 }}>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
              {step.helper}
            </Typography>
            
            <Box sx={{ mb: 2 }}>
              <TextField
                fullWidth
                size="small"
                variant="outlined"
                placeholder="Type custom preference and press Enter"
                value={customPreference}
                onChange={(e) => setCustomPreference(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && customPreference.trim()) {
                    handleChipClick(customPreference.trim(), true);
                    setCustomPreference('');
                    e.preventDefault();
                  }
                }}
                InputProps={{
                  endAdornment: (
                    <Button
                      size="small"
                      disabled={!customPreference.trim()}
                      onClick={() => {
                        if (customPreference.trim()) {
                          handleChipClick(customPreference.trim(), true);
                          setCustomPreference('');
                        }
                      }}
                    >
                      Add
                    </Button>
                  )
                }}
              />
            </Box>

            <Box sx={{ 
              display: 'flex', 
              flexWrap: 'wrap', 
              gap: 1,
              minHeight: 100,
              maxHeight: 200,
              overflowY: 'auto',
              p: 1,
              bgcolor: 'background.default',
              borderRadius: 1
            }}>
              {step.options.map((option) => (
                <Chip
                  key={option.value}
                  label={option.label}
                  onClick={() => handleChipClick(option.value)}
                  color={selectedChips.includes(option.value) ? "primary" : "default"}
                  variant={selectedChips.includes(option.value) ? "filled" : "outlined"}
                  sx={{ m: 0.5 }}
                />
              ))}
              {selectedChips
                .filter(chip => !step.options.find(opt => opt.value === chip))
                .map((customChip) => (
                  <Chip
                    key={customChip}
                    label={customChip}
                    color="primary"
                    variant="filled"
                    onDelete={() => handleChipClick(customChip)}
                    sx={{ m: 0.5 }}
                  />
                ))}
            </Box>
          </Box>
        )}
      </>
    );

    return (
      <Box>
        {content}
        {showTip && INVESTMENT_TIPS[step.label] && (
          <TipCard tip={INVESTMENT_TIPS[step.label]} />
        )}
      </Box>
    );
  };

  const isStepValid = (step, value) => {
    if (!value && value !== 0) return false;
    
    switch (step.type) {
      case 'radio':
        return Boolean(value);
      case 'slider':
        return typeof value === 'number';
      case 'chips':
        return selectedChips.length > 0;
      default:
        return typeof value === 'string' && value.trim().length > 0;
    }
  };

  const currentStep = SURVEY_STEPS[activeStep];
  const isLastStep = activeStep === SURVEY_STEPS.length - 1;
  const canProceed = isStepValid(currentStep, answers[currentStep.label]);

  const handleChipClick = (value, isCustom = false) => {
    let newSelectedChips;
    
    if (isCustom) {
      if (selectedChips.includes(value)) {
        return;
      }
      newSelectedChips = [...selectedChips, value];
    } else {
      newSelectedChips = selectedChips.includes(value)
        ? selectedChips.filter(v => v !== value)
        : [...selectedChips, value];
    }
    
    setSelectedChips(newSelectedChips);
    setAnswers(prev => ({
      ...prev,
      [SURVEY_STEPS[activeStep].label]: newSelectedChips
    }));
  };

  const simulateProgress = () => {
    setIsGenerating(true);
    setGenerationProgress(0);
    
    let startTime = null;
    let animationFrameId = null;
    let lastProgress = 0;
    
    const animate = (timestamp) => {
      if (!startTime) startTime = timestamp;
      const progress = timestamp - startTime;
      const duration = 8000; // Increased duration for more visible progression
      
      // Multi-stage easing for more natural progression
      const calculateProgress = (p) => {
        if (p < 0.3) {
          // Slow start - analyzing phase
          return p * 30; // Max 30%
        } else if (p < 0.6) {
          // Medium speed - processing phase
          return 30 + (p - 0.3) * 40; // 30% to 70%
        } else {
          // Slower end - optimization phase
          return 70 + (p - 0.6) * 20; // 70% to 90%
        }
      };
      
      let progressPercent = Math.min(1, progress / duration);
      progressPercent = calculateProgress(progressPercent);
      
      // Add subtle randomization
      const randomFactor = Math.random() * 0.3;
      progressPercent = Math.min(90, progressPercent + randomFactor);
      
      if (progressPercent - lastProgress >= 0.5) {
        lastProgress = progressPercent;
        setGenerationProgress(progressPercent);
      }
      
      if (progressPercent < 90) {
        animationFrameId = requestAnimationFrame(animate);
      }
    };
    
    animationFrameId = requestAnimationFrame(animate);
    
    return () => {
      if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }
    };
  };

  const handlePortfolioResponse = async (response) => {
    if (response.success && response.portfolio) {
      setGenerationProgress(prev => {
        const remaining = 100 - prev;
        return prev + remaining;
      });
      
      await new Promise(resolve => setTimeout(resolve, 300));

      const formattedPortfolio = response.portfolio.portfolio.map(holding => ({
        ticker: holding.ticker,
        weight: holding.weight.toString()
      }));
      
      onUpdatePortfolio(formattedPortfolio);

      setError({
        severity: 'success',
        message: 'Portfolio generated successfully!'
      });

      await new Promise(resolve => setTimeout(resolve, 700));

      onPortfolioGenerated({
        holdings: response.portfolio.portfolio,
        reasoning: response.portfolio.reasoning,
        metadata: response.portfolio.metadata
      });
    } else {
      throw new Error(response.error || 'Failed to generate portfolio');
    }
  };

  const generatePortfolio = async () => {
    setLoading(true);
    setError(null);
    const cleanup = simulateProgress();

    try {
      const formattedRequirements = `
Investment Profile:
- Primary Goal: ${answers['Investment Goal']}
- Risk Tolerance: Maximum drawdown of ${answers['Risk Tolerance']}%
- Target Return: ${answers['Expected Return']}% annually
- Investment Horizon: ${answers['Investment Horizon']}
- Investment Preferences: ${Array.isArray(answers['Preferences']) 
    ? answers['Preferences'].join(', ') 
    : selectedChips.join(', ') || 'No specific preferences'}

Additional Notes:
- Please provide a diversified portfolio with 5-8 holdings
- Include a mix of ETFs and individual stocks
- Consider current market conditions
- Explain the reasoning behind each allocation
- Focus on major US exchanges (NYSE, NASDAQ)
- Ensure total weight is exactly 100%
`;

      const response = await api.generatePortfolio(formattedRequirements);
      await handlePortfolioResponse(response);
    } catch (err) {
      cleanup();
      setGenerationProgress(0);
      setError({
        severity: 'error',
        message: err.message.includes('Invalid ticker symbols')
          ? 'Some stocks could not be validated. Trying again with different symbols...'
          : err.message
      });
      
      if (err.message.includes('Invalid ticker symbols')) {
        setTimeout(() => {
          generatePortfolio();
        }, 1500);
      }
    } finally {
      cleanup();
      setIsGenerating(false);
      setLoading(false);
    }
  };

  const handleFreeFormSubmit = async () => {
    setLoading(true);
    setError(null);
    const cleanup = simulateProgress();

    try {
      const response = await api.generatePortfolio(freeFormInput);
      await handlePortfolioResponse(response);
    } catch (err) {
      setError({
        severity: 'error',
        message: err.message
      });
    } finally {
      cleanup();
      setIsGenerating(false);
      setLoading(false);
    }
  };

  const GenerationProgress = () => {
    const getProgressColor = (progress) => {
      if (progress < 30) return 'primary';
      if (progress < 70) return 'secondary';
      return 'success';
    };

    const getProgressMessage = (progress) => {
      if (progress < 30) return 'Analyzing market data and conditions...';
      if (progress < 50) return 'Processing investment parameters...';
      if (progress < 70) return 'Optimizing asset allocations...';
      if (progress < 90) return 'Finalizing portfolio strategy...';
      return 'Portfolio successfully generated!';
    };

    return (
      <Fade in={isGenerating} timeout={300}>
        <Paper
          elevation={3}
          sx={{
            position: 'sticky',
            bottom: 0,
            left: 0,
            right: 0,
            p: 3,
            mt: 2,
            bgcolor: 'background.paper',
            borderRadius: '16px 16px 0 0',
            boxShadow: theme => `0 -4px 20px ${alpha(theme.palette.primary.main, 0.1)}`,
            zIndex: 10,
            transition: 'all 0.3s ease-in-out',
            transform: isGenerating ? 'translateY(0)' : 'translateY(20px)'
          }}
        >
          <Box sx={{ mb: 2 }}>
            <Typography variant="h6" gutterBottom sx={{ 
              display: 'flex', 
              alignItems: 'center', 
              gap: 1,
              color: theme => theme.palette[getProgressColor(generationProgress)].main
            }}>
              <TimelineIcon 
                color="inherit" 
                sx={{ 
                  animation: `${pulseAnimation} 2s infinite`,
                  transform: 'scale(1.2)'
                }} 
              />
              Creating Your Portfolio
            </Typography>
            
            <Box sx={{ position: 'relative', mt: 3, mb: 2 }}>
              <LinearProgress
                variant="determinate"
                value={generationProgress}
                sx={{
                  height: 8,
                  borderRadius: 4,
                  bgcolor: theme => alpha(theme.palette[getProgressColor(generationProgress)].main, 0.12),
                  '& .MuiLinearProgress-bar': {
                    borderRadius: 4,
                    background: theme => `linear-gradient(45deg, 
                      ${theme.palette[getProgressColor(generationProgress)].main},
                      ${theme.palette[getProgressColor(generationProgress)].light}
                    )`,
                    transition: 'transform 0.4s ease-in-out'
                  }
                }}
              />
              <Typography 
                variant="caption" 
                sx={{ 
                  position: 'absolute',
                  right: 0,
                  top: -20,
                  color: 'text.secondary',
                  fontWeight: 'medium'
                }}
              >
                {Math.round(generationProgress)}%
              </Typography>
            </Box>

            <Typography 
              variant="body2" 
              color="text.secondary"
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 1,
                mt: 2,
                animation: `${fadeAnimation} 0.5s ease-in-out`
              }}
            >
              <AutoAwesomeIcon 
                sx={{ 
                  color: theme => theme.palette[getProgressColor(generationProgress)].main,
                  animation: `${pulseAnimation} 2s infinite`
                }} 
              />
              {getProgressMessage(generationProgress)}
            </Typography>
          </Box>

          <Fade in={generationProgress >= 30} timeout={800}>
            <Box sx={{ mt: 2 }}>
              <Stepper 
                activeStep={Math.floor(generationProgress / 25)} 
                alternativeLabel
                sx={{ mt: 2 }}
              >
                <Step>
                  <StepLabel>Analysis</StepLabel>
                </Step>
                <Step>
                  <StepLabel>Processing</StepLabel>
                </Step>
                <Step>
                  <StepLabel>Optimization</StepLabel>
                </Step>
                <Step>
                  <StepLabel>Completion</StepLabel>
                </Step>
              </Stepper>
            </Box>
          </Fade>
        </Paper>
      </Fade>
    );
  };

  return (
    <MainContainer>
      <HeaderPaper>
        <Stack spacing={2} sx={{ position: 'relative', zIndex: 1 }}>
          <Box sx={{ 
            display: 'flex', 
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 1,
            mb: { xs: 1, sm: 2 }
          }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <SmartToyIcon 
                color="primary" 
                sx={{ 
                  animation: `${floatAnimation} 3s ease-in-out infinite`,
                  fontSize: { xs: '1.5rem', sm: '2rem' }
                }} 
              />
              <Typography 
                variant="h5" 
                sx={{ 
                  fontSize: { xs: '1.25rem', sm: '1.5rem' }
                }}
              >
                AI Portfolio Creator
              </Typography>
            </Box>
            <IconButton onClick={onClose} size="small">
              <CloseIcon />
            </IconButton>
          </Box>
          
          <Typography 
            variant="body1" 
            color="text.secondary" 
            sx={{ 
              mb: { xs: 1, sm: 2 },
              fontSize: { xs: '0.9rem', sm: '1rem' }
            }}
          >
            Choose how you'd like to create your portfolio
          </Typography>

          <Stack 
            direction={{ xs: 'column', sm: 'row' }} 
            spacing={2}
            sx={{ width: '100%' }}
          >
            <ModeSelectionButton
              mode={GUIDED_MODE}
              currentMode={surveyMode}
              icon={AutoAwesomeIcon}
              title="Guided Survey"
              description="Step-by-step creation"
              onClick={() => setSurveyMode(GUIDED_MODE)}
            />
            <ModeSelectionButton
              mode={FREE_FORM_MODE}
              currentMode={surveyMode}
              icon={RocketLaunchIcon}
              title="Free Form"
              description="Describe your needs freely"
              onClick={() => setSurveyMode(FREE_FORM_MODE)}
            />
          </Stack>
        </Stack>
      </HeaderPaper>

      {surveyMode === GUIDED_MODE ? (
        <>
          <Stepper 
            activeStep={activeStep} 
            sx={{ 
              mb: 4, 
              px: 2,
              position: 'sticky',
              top: 0,
              bgcolor: 'background.paper',
              zIndex: 1,
              py: 2,
              borderBottom: 1,
              borderColor: 'divider'
            }}
          >
            {SURVEY_STEPS.map((step) => (
              <Step key={step.label}>
                <StepLabel>{step.label}</StepLabel>
              </Step>
            ))}
          </Stepper>

          <Box 
            className="scroll-container"
            sx={{ 
              flex: 1,
              overflowY: 'auto',
              px: { xs: 2, sm: 4 },
              pb: 4,
              '&::-webkit-scrollbar': {
                width: '8px',
                display: { xs: 'none', sm: 'block' }
              },
              '&::-webkit-scrollbar-track': {
                background: theme => alpha(theme.palette.primary.main, 0.05),
                borderRadius: '8px',
              },
              '&::-webkit-scrollbar-thumb': {
                background: theme => alpha(theme.palette.primary.main, 0.2),
                borderRadius: '8px',
                '&:hover': {
                  background: theme => alpha(theme.palette.primary.main, 0.3),
                }
              },
              scrollBehavior: 'smooth',
              scrollPaddingBottom: '100px'
            }}
          >
            <Slide direction="left" in={true} mountOnEnter unmountOnExit>
              <Box sx={{ maxWidth: '800px', mx: 'auto' }}>
                <Typography variant="h5" gutterBottom color="primary">
                  {currentStep.question}
                </Typography>
                {renderStepContent(currentStep)}
              </Box>
            </Slide>
          </Box>

          {error && (
            <Fade in={true}>
              <Alert 
                severity={error.severity || 'error'} 
                sx={{ mx: 2, mb: 2 }}
                action={
                  error.severity === 'error' && (
                    <Button 
                      color="inherit" 
                      size="small" 
                      onClick={() => setError(null)}
                    >
                      Dismiss
                    </Button>
                  )
                }
              >
                {error.message}
              </Alert>
            </Fade>
          )}

          <Box sx={{ 
            position: 'sticky',
            bottom: 0,
            display: 'flex', 
            gap: 2, 
            p: 2,
            borderTop: 1,
            borderColor: 'divider',
            bgcolor: 'background.paper',
            zIndex: 2,
            boxShadow: '0 -4px 6px -1px rgba(0,0,0,0.1)'
          }}>
            <Button
              variant="outlined"
              onClick={onClose}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button
              disabled={activeStep === 0 || loading}
              onClick={handleBack}
              variant="outlined"
            >
              Back
            </Button>
            <Button
              variant="contained"
              onClick={handleNext}
              disabled={!canProceed || loading}
              sx={gradientButtonStyles}
            >
              {loading ? (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <CircularProgress size={24} color="inherit" />
                  <Typography>Creating your portfolio...</Typography>
                </Box>
              ) : isLastStep ? (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <AutoAwesomeIcon />
                  <Typography>Generate Portfolio</Typography>
                </Box>
              ) : (
                'Next'
              )}
            </Button>
          </Box>
        </>
      ) : (
        <Box sx={{ 
          flex: 1, 
          display: 'flex', 
          flexDirection: 'column',
          overflow: 'hidden',
          p: 2
        }}>
          <Fade in={true}>
            <Paper
              elevation={0}
              variant="outlined"
              sx={{
                p: 3,
                flex: 1,
                display: 'flex',
                flexDirection: 'column',
                overflow: 'hidden',
                position: 'relative'
              }}
            >
              <Typography variant="h5" gutterBottom sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: 1,
                color: 'primary.main'
              }}>
                <RocketLaunchIcon />
                Describe Your Dream Portfolio
              </Typography>
              
              <Box sx={{ 
                flex: 1,
                display: 'flex',
                flexDirection: 'column',
                minHeight: '300px',
                position: 'relative'
              }}>
                <TextField
                  multiline
                  fullWidth
                  value={freeFormInput}
                  onChange={(e) => setFreeFormInput(e.target.value)}
                  placeholder={`Example:
I'm looking for a growth-oriented portfolio with a focus on technology and healthcare sectors.
- Investment horizon: 5-10 years
- Risk tolerance: moderate to high
- Target return: around 12% annually
- Prefer large-cap stocks with some exposure to emerging markets
- ESG considerations are important
- Need some dividend income (at least 2% yield)`}
                  sx={{ 
                    flex: 1,
                    '& .MuiInputBase-root': {
                      height: '100%',
                      resize: 'vertical',
                      minHeight: '200px',
                      maxHeight: '600px'
                    },
                    '& .MuiInputBase-input': {
                      height: '100% !important',
                      overflow: 'auto !important',
                    },
                    '& .MuiOutlinedInput-root': {
                      transition: 'all 0.3s ease-in-out',
                      '&:hover': {
                        bgcolor: 'background.default'
                      },
                      '&.Mui-focused': {
                        boxShadow: 2
                      }
                    }
                  }}
                  InputProps={{
                    sx: {
                      '&::after': {
                        content: '""',
                        position: 'absolute',
                        right: 0,
                        bottom: 0,
                        width: '20px',
                        height: '20px',
                        cursor: 'se-resize',
                        backgroundImage: 'linear-gradient(135deg, transparent 50%, rgba(0,0,0,0.1) 50%)',
                        borderBottomRightRadius: '4px'
                      }
                    }
                  }}
                />
              </Box>
            </Paper>
          </Fade>

          {error && (
            <Fade in={true}>
              <Alert 
                severity={error.severity || 'error'} 
                sx={{ 
                  mb: 2,
                  animation: error.severity === 'success' ? `${glowAnimation} 2s infinite` : 'none'
                }}
                action={
                  error.severity === 'error' && (
                    <Button color="inherit" size="small" onClick={() => setError(null)}>
                      Dismiss
                    </Button>
                  )
                }
              >
                {error.message}
              </Alert>
            </Fade>
          )}

          <Box sx={{ 
            display: 'flex', 
            gap: 2,
            borderTop: 1,
            borderColor: 'divider',
            pt: 2
          }}>
            <Button
              variant="outlined"
              onClick={onClose}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button
              variant="contained"
              onClick={handleFreeFormSubmit}
              disabled={!freeFormInput.trim() || loading}
              sx={gradientButtonStyles}
            >
              {loading ? (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <CircularProgress size={24} color="inherit" />
                  <Typography>Creating your portfolio...</Typography>
                </Box>
              ) : (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <AutoAwesomeIcon />
                  <Typography>Generate Portfolio</Typography>
                </Box>
              )}
            </Button>
          </Box>
        </Box>
      )}
      {isGenerating && (
        <Box sx={{
          position: 'sticky',
          bottom: 0,
          left: 0,
          right: 0,
          zIndex: 3
        }}>
          <GenerationProgress />
        </Box>
      )}
    </MainContainer>
  );
}

export default PortfolioSurvey;