// App.js
import { useState, useMemo, useCallback, Suspense, useEffect } from 'react'
import { Routes, Route, useLocation, useNavigate, Navigate } from 'react-router-dom'
import { ThemeProvider, CssBaseline, Box, Snackbar, Alert, useMediaQuery, Container, Fade, Grow, CircularProgress, Zoom, alpha } from '@mui/material'
import { createTheme } from '@mui/material/styles'
import { LocalizationProvider } from '@mui/x-date-pickers'
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
import { api } from './services/api'
import dayjs from 'dayjs'
import { styled } from '@mui/material/styles'
import { lazy } from 'react'
import PropTypes from 'prop-types'

// Import Header directly instead of lazy loading
import Header from './components/Header'

// Lazy load components
const PortfolioForm = lazy(() => import('./components/PortfolioForm'))
const ResultsSection = lazy(() => import('./components/ResultsSection'))
const ComparisonBar = lazy(() => import('./components/ComparisonBar'))
const SavePortfolioDialog = lazy(() => import('./components/SavePortfolioDialog'))
const ProfileSection = lazy(() => import('./components/member/ProfileSection'))
const LandingPage = lazy(() => import('./components/LandingPage'))
const MemberPage = lazy(() => import('./components/MemberPage'))

// Import smaller components directly
import LoadingOverlay from './components/LoadingOverlay'
import ErrorBoundary from './components/ErrorBoundary'

// Import new components
import { AuthProvider, useAuth } from './components/auth/AuthProvider'
import ProtectedRoute from './components/auth/ProtectedRoute'

// Loading component
const LoadingScreen = () => (
  <Fade in timeout={300}>
    <Box 
      sx={{ 
        height: '100%',
        minHeight: '-webkit-fill-available',
        width: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'column',
        gap: { xs: 1, sm: 2 },
        bgcolor: 'background.default',
        position: 'fixed',
        top: 0,
        left: 0,
        zIndex: 9999,
        px: { xs: 2, sm: 0 }
      }}
    >
      <Zoom in timeout={500}>
        <CircularProgress />
      </Zoom>
      <Fade in timeout={800}>
        <Box sx={{ 
          color: 'text.secondary',
          typography: 'body1',
          fontWeight: 500
        }}>
          Loading...
        </Box>
      </Fade>
    </Box>
  </Fade>
)

// Add styled components for better organization
const MainContainer = styled(Container)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  minHeight: '100vh',
  width: '100%',
  maxWidth: '100% !important',
  padding: 0,
  marginTop: { xs: 56, sm: 64 },
  position: 'relative',
  overflow: 'hidden',
  WebkitOverflowScrolling: 'touch',
  [theme.breakpoints.down('sm')]: {
    height: '100%',
    minHeight: '-webkit-fill-available',
    paddingBottom: theme.spacing(10),
  }
}))

const ContentContainer = styled(Box)(({ theme }) => ({
  flex: 1,
  display: 'flex',
  flexDirection: 'column',
  width: '100%',
  position: 'relative',
  overflow: 'auto',
  WebkitOverflowScrolling: 'touch',
  '-webkit-overflow-scrolling': 'touch',
  [theme.breakpoints.down('sm')]: {
    '&::-webkit-scrollbar': {
      display: 'none'
    },
    scrollbarWidth: 'none',
    msOverflowStyle: 'none',
    paddingBottom: theme.spacing(10),
  }
}))

const PageContainer = styled(Box)(({ theme }) => ({
  flex: 1,
  width: '100%',
  maxWidth: '100%',
  margin: '0 auto',
  padding: theme.spacing(2),
  [theme.breakpoints.down('sm')]: {
    padding: theme.spacing(1),
    paddingBottom: theme.spacing(12),
  }
}))

const TransitionPage = ({ children }) => (
  <Fade in timeout={400}>
    <Box sx={{ 
      height: '100%',
      opacity: 0,
      animation: 'fadeIn 0.4s ease-in-out forwards',
      '@keyframes fadeIn': {
        from: { opacity: 0 },
        to: { opacity: 1 }
      }
    }}>
      {children}
    </Box>
  </Fade>
)

// Create MemberRoute as a separate component that receives props
const MemberRoute = ({ 
  handleClearAll, 
  handleLoadPortfolio, 
  handleAddComparison, 
  activeView, 
  setActiveView, 
  results, 
  toggleColorMode, 
  mode, 
  handleHome,
  showLanding,
  setShowLanding
}) => {
  console.log('MemberRoute received toggleColorMode:', typeof toggleColorMode) // Debug log
  
  return (
    <TransitionPage>
      <MainContainer>
        <Header 
          onClearAll={handleClearAll}
          onLoadPortfolio={handleLoadPortfolio}
          onAddComparison={handleAddComparison}
          activeView={activeView}
          onViewChange={setActiveView}
          hasResults={!!results}
          onToggleTheme={toggleColorMode}  // Pass as onToggleTheme
          isDarkMode={mode === 'dark'}
          onHome={handleHome}
          showLanding={showLanding}
          setShowLanding={setShowLanding}
        />
        <PageContainer>
          <Suspense fallback={<LoadingScreen />}>
            <Fade in timeout={300}>
              <Box>
                <MemberPage toggleColorMode={toggleColorMode} />
              </Box>
            </Fade>
          </Suspense>
        </PageContainer>
      </MainContainer>
    </TransitionPage>
  )
}

MemberRoute.propTypes = {
  toggleColorMode: PropTypes.func.isRequired,
  // ... other prop types
}

function App() {
  // Get user's theme preference from localStorage or system preference
  const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)')
  const [mode, setMode] = useState(() => {
    // Try to get user data from localStorage
    const userData = localStorage.getItem('user')
    if (userData) {
      const user = JSON.parse(userData)
      // Set initial mode based on localStorage preference
      const storedPreference = localStorage.getItem(`theme_preference_${user.id}`)
      if (storedPreference) {
        return storedPreference === 'dark' ? 'dark' : 'light'
      }
    }
    // Fall back to system preference if no stored preference
    return prefersDarkMode ? 'dark' : 'light'
  })

  // Fetch user theme preference on mount
  useEffect(() => {
    const fetchUserTheme = async () => {
      const userData = localStorage.getItem('user')
      if (userData) {
        const user = JSON.parse(userData)
        try {
          const response = await fetch(`/api/user/preferences?user_id=${user.id}`, {
            headers: {
              'Content-Type': 'application/json',
            }
          })
          const data = await response.json()
          if (data.success) {
            const newMode = data.preferences.dark_mode ? 'dark' : 'light'
            setMode(newMode)
            // Store the preference in localStorage
            localStorage.setItem(`theme_preference_${user.id}`, newMode)
          }
        } catch (err) {
          console.error('Failed to fetch theme preference:', err)
        }
      }
    }

    fetchUserTheme()
  }, [])

  // Update toggleColorMode to also store preference
  const toggleColorMode = useCallback(() => {
    setMode((prevMode) => {
      const newMode = prevMode === 'light' ? 'dark' : 'light'
      // Store the new preference in localStorage if user is logged in
      const userData = localStorage.getItem('user')
      if (userData) {
        const user = JSON.parse(userData)
        localStorage.setItem(`theme_preference_${user.id}`, newMode)
      }
      return newMode
    })
  }, [])

  const [isLoading, setIsLoading] = useState(false)
  const [results, setResults] = useState(null)
  const [error, setError] = useState(null)
  const [notification, setNotification] = useState(null)
  const [portfolio, setPortfolio] = useState([{ ticker: '', weight: '' }])
  const [parameters, setParameters] = useState({
    startDate: dayjs().subtract(5, 'year').format('YYYY-MM-DD'),
    transactionCost: 0.001,
    benchmark: 'SPY'
  })
  const [activeView, setActiveView] = useState('portfolio')
  const [comparisonPortfolios, setComparisonPortfolios] = useState([])
  const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false)
  const location = useLocation()
  const [showLanding, setShowLanding] = useState(location.pathname === '/')
  const [pageTransition, setPageTransition] = useState(true)
  const [analysisProgress, setAnalysisProgress] = useState(0)
  const navigate = useNavigate()

  useEffect(() => {
    setPageTransition(true)
    // Reset transition state after animation
    const timer = setTimeout(() => {
      setPageTransition(false)
    }, 300)
    return () => clearTimeout(timer)
  }, [location.pathname])

  const theme = useMemo(() => {
    // First create a basic theme with just palette and typography
    const baseTheme = createTheme({
      palette: {
        mode,
        primary: {
          main: mode === 'light' ? '#1976d2' : '#90caf9',
          light: mode === 'light' ? '#42a5f5' : '#b3e5fc',
          dark: mode === 'light' ? '#1565c0' : '#64b5f6',
        },
        secondary: {
          main: mode === 'light' ? '#dc004e' : '#f48fb1',
          light: mode === 'light' ? '#ff4081' : '#f8bbd0',
          dark: mode === 'light' ? '#c51162' : '#f06292',
        },
        background: {
          default: mode === 'light' ? '#f5f5f5' : '#121212',
          paper: mode === 'light' ? '#ffffff' : '#1e1e1e',
        },
        text: {
          primary: mode === 'light' ? 'rgba(0, 0, 0, 0.87)' : '#ffffff',
          secondary: mode === 'light' ? 'rgba(0, 0, 0, 0.6)' : 'rgba(255, 255, 255, 0.7)',
        },
        divider: mode === 'light' ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)',
        error: {
          main: mode === 'light' ? '#d32f2f' : '#f44336',
          light: mode === 'light' ? '#ef5350' : '#e57373',
          dark: mode === 'light' ? '#c62828' : '#d32f2f',
        },
        success: {
          main: mode === 'light' ? '#2e7d32' : '#4caf50',
          light: mode === 'light' ? '#4caf50' : '#81c784',
          dark: mode === 'light' ? '#1b5e20' : '#388e3c',
        },
        warning: {
          main: mode === 'light' ? '#ed6c02' : '#ff9800',
          light: mode === 'light' ? '#ff9800' : '#ffb74d',
          dark: mode === 'light' ? '#e65100' : '#f57c00',
        },
        info: {
          main: mode === 'light' ? '#0288d1' : '#29b6f6',
          light: mode === 'light' ? '#03a9f4' : '#4fc3f7',
          dark: mode === 'light' ? '#01579b' : '#0288d1',
        },
      },
      shape: {
        borderRadius: 8
      },
      typography: {
        fontFamily: '"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
        h5: {
          fontWeight: 600,
          letterSpacing: 0.5,
        },
        h6: {
          fontWeight: 600,
        },
        subtitle1: {
          fontWeight: 500,
        },
        subtitle2: {
          fontWeight: 500,
        },
      },
    });

    // Then create the final theme with components using baseTheme
    return createTheme(baseTheme, {
      components: {
        MuiContainer: {
          styleOverrides: {
            root: {
              maxWidth: '100% !important',
              height: '100%',
              padding: '0 !important',
              backgroundColor: mode === 'light' ? '#f5f5f5' : '#121212',
              [`${baseTheme.breakpoints.down('sm')}`]: {
                height: '-webkit-fill-available',
              }
            },
          },
        },
        MuiBox: {
          styleOverrides: {
            root: {
              '&.content-container': {
                padding: baseTheme.spacing(2),
                gap: baseTheme.spacing(2),
                [`${baseTheme.breakpoints.up('sm')}`]: {
                  padding: baseTheme.spacing(3),
                },
                [`${baseTheme.breakpoints.up('md')}`]: {
                  padding: baseTheme.spacing(4),
                },
                [`${baseTheme.breakpoints.down('sm')}`]: {
                  gap: baseTheme.spacing(1.5),
                  padding: baseTheme.spacing(1.5),
                }
              }
            }
          }
        },
        MuiPaper: {
          styleOverrides: {
            root: {
              backgroundImage: 'none',
              transition: 'box-shadow 0.3s ease-in-out',
            },
            outlined: {
              borderColor: mode === 'light' ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)',
            },
          },
        },
        MuiAppBar: {
          styleOverrides: {
            root: {
              backgroundColor: mode === 'light' ? '#1976d2' : '#272727',
              backgroundImage: 'none',
            },
          },
        },
        MuiButton: {
          styleOverrides: {
            root: {
              borderRadius: 8,
              textTransform: 'none',
              fontWeight: 500,
              padding: '8px 16px',
              [`${baseTheme.breakpoints.down('sm')}`]: {
                padding: '6px 12px',
                fontSize: '0.875rem',
              },
            },
            contained: {
              boxShadow: 'none',
              '&:hover': {
                boxShadow: mode === 'light'
                  ? '0 2px 8px rgba(0,0,0,0.15)'
                  : '0 2px 8px rgba(0,0,0,0.4)',
              },
            },
          },
        },
        MuiTableCell: {
          styleOverrides: {
            root: {
              borderBottom: `1px solid ${mode === 'light' ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)'}`,
              padding: {
                xs: '8px',
                sm: '16px',
              },
            },
          },
        },
        MuiChip: {
          styleOverrides: {
            root: {
              fontWeight: 500,
              [baseTheme.breakpoints.down('sm')]: {
                fontSize: '0.75rem',
              },
            },
          },
        },
        MuiAlert: {
          styleOverrides: {
            root: {
              borderRadius: 8,
            },
          },
        },
        MuiCard: {
          styleOverrides: {
            root: {
              borderRadius: 12,
              transition: 'transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out',
              '&:hover': {
                transform: 'translateY(-2px)',
                boxShadow: mode === 'light' 
                  ? '0 4px 20px rgba(0,0,0,0.1)'
                  : '0 4px 20px rgba(0,0,0,0.3)',
              },
            },
          },
        },
        MuiTextField: {
          styleOverrides: {
            root: {
              '& .MuiOutlinedInput-root': {
                borderRadius: 8,
              },
            },
          },
        },
        MuiTypography: {
          styleOverrides: {
            h5: {
              [baseTheme.breakpoints.down('sm')]: {
                fontSize: '1.25rem',
              },
            },
            h6: {
              [baseTheme.breakpoints.down('sm')]: {
                fontSize: '1.1rem',
              },
            },
            body1: {
              [baseTheme.breakpoints.down('sm')]: {
                fontSize: '0.875rem',
              },
            },
            body2: {
              [baseTheme.breakpoints.down('sm')]: {
                fontSize: '0.8125rem',
              },
            },
          },
        },
      },
    });
  }, [mode]);

  const runAnalysis = async () => {
    try {
      setIsLoading(true)
      setAnalysisProgress(0)
      setError(null)

      // Prepare portfolios for comparison
      const portfoliosToCompare = []

      // Add current portfolio if it exists
      if (portfolio && portfolio.length > 0) {
        const currentPortfolio = portfolio
          .filter(stock => stock.ticker && stock.weight)
          .map(stock => ({
            ticker: stock.ticker.toUpperCase(),
            weight: parseFloat(stock.weight)
          }))

        if (currentPortfolio.length > 0) {
          portfoliosToCompare.push({
            name: 'Current Portfolio',
            portfolio: currentPortfolio
          })
        }
      }

      // Add benchmark portfolio if no comparison portfolios
      if (comparisonPortfolios.length === 0 && parameters.benchmark) {
        const benchmarkPortfolio = {
          name: parameters.benchmark,
          portfolio: [{ ticker: parameters.benchmark, weight: 100 }]
        };
        
        // Only add benchmark if it's different from the current portfolio
        const currentTickers = portfolio.map(stock => stock.ticker);
        if (!currentTickers.includes(parameters.benchmark)) {
          portfoliosToCompare.push(benchmarkPortfolio);
        }
      } else {
        // Add comparison portfolios
        portfoliosToCompare.push(...comparisonPortfolios)
      }

      if (portfoliosToCompare.length === 0) {
        throw new Error('No valid portfolios to analyze')
      }

      // Start progress polling
      const pollProgress = async () => {
        try {
          const progressResponse = await api.checkProgress()
          console.log('Progress response:', progressResponse) // Debug log
          
          if (progressResponse && typeof progressResponse.progress === 'number') {
            setAnalysisProgress(progressResponse.progress)
            
            if (progressResponse.status === 'failed') {
              throw new Error(progressResponse.error || 'Analysis failed')
            }
          }
        } catch (err) {
          console.warn('Progress check failed:', err)
        }
      }

      // Poll every second
      const progressInterval = setInterval(pollProgress, 1000)

      try {
        // Run comparison analysis
        const response = await api.compare({
          portfolios: portfoliosToCompare,
          startDate: parameters.startDate,
          transactionCost: parameters.transactionCost
        })

        clearInterval(progressInterval)

        if (!response.success) {
          throw new Error(response.error || 'Analysis failed')
        }

        // Run correlation analysis if needed
        let correlationData = { success: true, correlations: null }
        const firstPortfolio = portfoliosToCompare[0].portfolio
        if (firstPortfolio.length > 1) {
          correlationData = await api.getCorrelation({
            portfolio: firstPortfolio,
            startDate: parameters.startDate
          })
        }

        // Combine results
        const results = {
          comparison: response.comparison_results,
          dates: response.dates,
          correlations: correlationData.correlations,
          data_quality: response.data_quality
        }

        setResults(results)
        setActiveView('results')
      } catch (err) {
        throw err
      } finally {
        clearInterval(progressInterval)
      }
    } catch (err) {
      console.error('Analysis error:', err)
      
      let errorMessage = err.message
      if (err.message.includes('timeout')) {
        errorMessage = 'Please wait while we complete the analysis. This may take a few minutes for large portfolios or long date ranges.'
      }

      setError(errorMessage)
      setNotification({
        type: 'warning',
        message: errorMessage,
      })
    } finally {
      setIsLoading(false)
      setAnalysisProgress(0)
    }
  }

  const handleUpdatePortfolio = (newPortfolio) => {
    setPortfolio(newPortfolio)
  }

  const handleUpdateParameters = (newParameters) => {
    setParameters(prev => ({ ...prev, ...newParameters }))
  }

  const handleCloseNotification = () => {
    setNotification(null)
  }

  const handleClearAll = () => {
    setResults(null)
    setError(null)
    setNotification(null)
    setPortfolio([{ ticker: '', weight: '' }])
    setComparisonPortfolios([])
    setActiveView('portfolio')
  }

  const handleLoadPortfolio = (portfolioData) => {
    setPortfolio(portfolioData.portfolio.map(stock => ({
      ticker: stock.ticker,
      weight: stock.weight.toString()
    })))
  }

  const handleAddComparison = (portfolioData) => {
    const formattedPortfolio = {
      name: portfolioData.name,
      portfolio: portfolioData.portfolio.map(stock => ({
        ticker: stock.ticker.toUpperCase(),
        weight: parseFloat(stock.weight) / 100
      }))
    }
    setComparisonPortfolios(prev => [...prev, formattedPortfolio])
  }

  const handleRemoveComparison = (portfolioName) => {
    setComparisonPortfolios(prev => prev.filter(p => p.name !== portfolioName))
  }

  const handleSavePortfolio = async (portfolioData) => {
    try {
      const response = await api.savePortfolio({
        name: portfolioData.name,
        portfolio: portfolio.map(stock => ({
          ticker: stock.ticker,
          weight: parseFloat(stock.weight) / 100
        }))
      })

      if (!response.success) {
        throw new Error(response.error || 'Failed to save portfolio')
      }

      setNotification({
        type: 'success',
        message: 'Portfolio saved successfully'
      })
      setIsSaveDialogOpen(false)
    } catch (err) {
      setNotification({
        type: 'error',
        message: err.message || 'Failed to save portfolio'
      })
    }
  }

  const handleHome = useCallback(() => {
    setShowLanding(true)
  }, [])

  return (
    <ThemeProvider theme={theme}>
      <LocalizationProvider dateAdapter={AdapterDayjs}>
        <CssBaseline />
        <ErrorBoundary>
          <AuthProvider>
            <Suspense fallback={<LoadingScreen />}>
              <Routes>
                <Route 
                  path="/" 
                  element={
                    showLanding ? (
                      <Fade in timeout={800}>
                        <Box>
                          <Header 
                            onClearAll={handleClearAll}
                            onLoadPortfolio={handleLoadPortfolio}
                            onAddComparison={handleAddComparison}
                            activeView={activeView}
                            onViewChange={setActiveView}
                            hasResults={!!results}
                            onToggleTheme={toggleColorMode}
                            isDarkMode={mode === 'dark'}
                            onHome={handleHome}
                            showLanding={showLanding}
                            setShowLanding={setShowLanding}
                          />
                          <LandingPage 
                            onGetStarted={() => setShowLanding(false)} 
                            isDarkMode={mode === 'dark'}
                            onToggleTheme={toggleColorMode}
                          />
                        </Box>
                      </Fade>
                    ) : (
                      <TransitionPage>
                        <MainContainer>
                          <Header 
                            onClearAll={handleClearAll}
                            onLoadPortfolio={handleLoadPortfolio}
                            onAddComparison={handleAddComparison}
                            activeView={activeView}
                            onViewChange={setActiveView}
                            hasResults={!!results}
                            onToggleTheme={toggleColorMode}
                            isDarkMode={mode === 'dark'}
                            onHome={handleHome}
                            showLanding={showLanding}
                            setShowLanding={setShowLanding}
                          />
                          <PageContainer>
                            <Fade in={comparisonPortfolios.length > 0} unmountOnExit>
                              <Box sx={{ display: { xs: 'none', sm: 'block' } }}>
                                <ComparisonBar 
                                  portfolios={comparisonPortfolios}
                                  onRemove={handleRemoveComparison}
                                />
                              </Box>
                            </Fade>

                            <Box
                              sx={{
                                flex: 1,
                                display: 'flex',
                                flexDirection: 'column',
                                overflow: 'hidden',
                                mt: { xs: 1, sm: 0 }
                              }}
                            >
                              <Grow in={true} timeout={500}>
                                <Box
                                  sx={{
                                    flex: 1,
                                    display: 'flex',
                                    flexDirection: 'column',
                                    overflow: 'hidden'
                                  }}
                                >
                                  <Suspense fallback={<LoadingScreen />}>
                                    {activeView === 'portfolio' ? (
                                      <PortfolioForm
                                        portfolio={portfolio}
                                        parameters={parameters}
                                        onPortfolioChange={handleUpdatePortfolio}
                                        onParametersChange={handleUpdateParameters}
                                        onAnalyze={runAnalysis}
                                        isLoading={isLoading}
                                        error={error}
                                        comparisonPortfolios={comparisonPortfolios}
                                        onSave={() => setIsSaveDialogOpen(true)}
                                      />
                                    ) : (
                                      <ResultsSection 
                                        results={results}
                                        comparisonPortfolios={comparisonPortfolios}
                                        onRemoveComparison={handleRemoveComparison}
                                      />
                                    )}
                                  </Suspense>
                                </Box>
                              </Grow>
                            </Box>
                          </PageContainer>

                          <LoadingOverlay 
                            open={isLoading} 
                            progress={analysisProgress}
                          />
                          
                          <SavePortfolioDialog
                            open={isSaveDialogOpen}
                            onClose={() => setIsSaveDialogOpen(false)}
                            onSave={handleSavePortfolio}
                            portfolio={portfolio}
                          />

                          <Snackbar
                            open={notification !== null}
                            autoHideDuration={6000}
                            onClose={handleCloseNotification}
                            anchorOrigin={{ 
                              vertical: 'bottom', 
                              horizontal: 'center' 
                            }}
                            sx={{
                              bottom: { xs: 16, sm: 24 }
                            }}
                            TransitionComponent={Fade}
                          >
                            <Alert 
                              onClose={handleCloseNotification}
                              severity={notification?.type || 'info'}
                              variant="filled"
                              elevation={6}
                              sx={{
                                borderRadius: 2,
                                minWidth: { xs: '90vw', sm: 300 },
                                '& .MuiAlert-icon': {
                                  fontSize: '1.5rem',
                                },
                              }}
                            >
                              {notification?.message}
                            </Alert>
                          </Snackbar>
                        </MainContainer>
                      </TransitionPage>
                    )
                  } 
                />
                
                <Route 
                  path="/member" 
                  element={
                    <MemberRoute 
                      handleClearAll={handleClearAll}
                      handleLoadPortfolio={handleLoadPortfolio}
                      handleAddComparison={handleAddComparison}
                      activeView={activeView}
                      setActiveView={setActiveView}
                      results={results}
                      toggleColorMode={toggleColorMode}
                      mode={mode}
                      handleHome={handleHome}
                      showLanding={showLanding}
                      setShowLanding={setShowLanding}
                    />
                  }
                />
                
                <Route 
                  path="/member/profile" 
                  element={
                    <ProtectedRoute>
                      <TransitionPage>
                        <MainContainer>
                          <Header 
                            onClearAll={handleClearAll}
                            onLoadPortfolio={handleLoadPortfolio}
                            onAddComparison={handleAddComparison}
                            activeView={activeView}
                            onViewChange={setActiveView}
                            hasResults={!!results}
                            onToggleTheme={toggleColorMode}
                            isDarkMode={mode === 'dark'}
                            onHome={handleHome}
                            showLanding={showLanding}
                            setShowLanding={setShowLanding}
                          />
                          <PageContainer>
                            <Suspense fallback={<LoadingScreen />}>
                              <Fade in timeout={300}>
                                <Box>
                                  <MemberPage 
                                    toggleColorMode={toggleColorMode} 
                                  />
                                </Box>
                              </Fade>
                            </Suspense>
                          </PageContainer>
                        </MainContainer>
                      </TransitionPage>
                    </ProtectedRoute>
                  } 
                />
              </Routes>
            </Suspense>
          </AuthProvider>
        </ErrorBoundary>
      </LocalizationProvider>
    </ThemeProvider>
  )
}

export default App


import { useState, useEffect } from 'react'
import {
  Box,
  Container,
  Typography,
  Button,
  Grid,
  Card,
  CardContent,
  useTheme,
  alpha,
  Stack,
  Fade,
  Zoom,
  Paper,
  Divider,
  useMediaQuery,
  IconButton,
  Tooltip,
  SpeedDial,
  SpeedDialAction,
  SpeedDialIcon,
  Backdrop,
  Chip,
  Rating,
  LinearProgress,
  Avatar,
  Fab,
  Slide,
  useScrollTrigger,
  Grow
} from '@mui/material'
import {
  Timeline,
  ShowChart,
  Compare,
  Analytics,
  TrendingUp,
  Assessment,
  AccountBalance,
  Speed,
  CloudSync,
  Autorenew,
  LinkedIn,
  Email,
  KeyboardArrowDown,
  Help,
  PlayArrow,
  Info,
  Star,
  Lightbulb,
  BarChart,
  Insights,
  KeyboardArrowUp,
  NewReleases,
  Update
} from '@mui/icons-material'
import Tutorial from './Tutorial'

const features = [
  {
    title: 'Portfolio Analysis',
    description: 'Analyze your investment portfolio with comprehensive metrics and performance indicators.',
    icon: Analytics,
    color: '#2196f3',
    details: [
      {
        left: [
          'Performance metrics',
          'Risk assessment tools'
        ],
        right: [
          'Historical analysis',
          'Custom date ranges'
        ]
      }
    ]
  },
  {
    title: 'Real-time Data',
    description: 'Access real-time market data and historical performance for accurate analysis.',
    icon: ShowChart,
    color: '#4caf50',
    details: [
      {
        left: [
          'Live market data',
          'Historical prices'
        ],
        right: [
          'Automated updates',
          'Data validation'
        ]
      }
    ]
  },
  {
    title: 'Portfolio Comparison',
    description: 'Compare multiple portfolios and benchmark against market indices.',
    icon: Compare,
    color: '#ff9800',
    details: [
      {
        left: [
          'Side-by-side comparison',
          'Benchmark analysis'
        ],
        right: [
          'Performance attribution',
          'Custom benchmarks'
        ]
      }
    ]
  },
  {
    title: 'Risk Assessment',
    description: 'Evaluate portfolio risk metrics and correlation analysis.',
    icon: Speed,
    color: '#f44336',
    details: [
      {
        left: [
          'Risk metrics calculation',
          'Correlation analysis'
        ],
        right: [
          'Volatility assessment',
          'Drawdown analysis'
        ]
      }
    ]
  },
  {
    title: 'Performance Tracking',
    description: 'Track portfolio performance over time with detailed metrics and charts.',
    icon: TrendingUp,
    color: '#9c27b0',
    details: [
      {
        left: [
          'Performance monitoring',
          'Interactive charts'
        ],
        right: [
          'Custom reporting',
          'Export capabilities'
        ]
      }
    ]
  },
  {
    title: 'Cloud Sync',
    description: 'Save and load your portfolios securely across devices.',
    icon: CloudSync,
    color: '#00bcd4',
    details: [
      {
        left: [
          'Secure storage',
          'Cross-device sync'
        ],
        right: [
          'Backup & restore',
          'Version history'
        ]
      }
    ]
  }
]

const socialLinks = [
  { icon: Autorenew, label: 'Status', url: 'https://status.twinight.co' },
  { icon: LinkedIn, label: 'LinkedIn', url: 'https://linkedin.com' },
  { icon: Email, label: 'Email', url: 'mailto:philip@twinight.co' }
]

const statistics = [
  {
    value: '99%',
    label: 'Accuracy',
    icon: Timeline,
    color: '#2196f3'
  },
  {
    value: '24/7',
    label: 'Real-time Updates',
    icon: Insights,
    color: '#4caf50'
  },
  {
    value: '50+',
    label: 'Metrics',
    icon: BarChart,
    color: '#ff9800'
  }
]

// Update the testimonials data first
const testimonials = [
  {
    name: 'Sarah Chen',
    role: 'Senior Portfolio Manager',
    company: 'Capital Investments Ltd',
    avatar: null, // We'll use the first letter of the name
    rating: 5,
    comment: 'The real-time analytics and risk assessment tools have transformed how we manage client portfolios. The interface is intuitive and the insights are invaluable.',
    tags: ['Risk Analysis', 'Real-time Data']
  },
  {
    name: 'Michael Roberts',
    role: 'Investment Director',
    company: 'Quantum Fund Management',
    avatar: null,
    rating: 5,
    comment: 'Outstanding portfolio comparison features. Being able to analyze multiple strategies simultaneously has greatly improved our decision-making process.',
    tags: ['Portfolio Comparison', 'Strategy Analysis']
  },
  {
    name: 'Emma Thompson',
    role: 'Quantitative Analyst',
    company: 'Global Asset Management',
    avatar: null,
    rating: 5,
    comment: 'The correlation analysis and risk metrics are exactly what we needed. The platform has become an essential part of our daily workflow.',
    tags: ['Correlation Analysis', 'Risk Metrics']
  }
]

// Add What's New section data
const whatsNew = [
  {
    title: 'Real-time Analytics',
    description: 'Get instant insights with our new real-time analytics engine',
    icon: Update,
    color: '#00bcd4',
    tag: 'New'
  },
  {
    title: 'Enhanced Reporting',
    description: 'Export detailed reports with advanced visualization options',
    icon: Assessment,
    color: '#4caf50',
    tag: 'Updated'
  },
  {
    title: 'Smart Alerts',
    description: 'Set up custom alerts for portfolio performance thresholds',
    icon: NewReleases,
    color: '#ff9800',
    tag: 'Coming Soon'
  }
]

// Scroll to top component
function ScrollToTop() {
  const trigger = useScrollTrigger({
    disableHysteresis: true,
    threshold: 100
  })

  const handleClick = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  return (
    <Zoom in={trigger}>
      <Box
        role="presentation"
        sx={{
          position: 'fixed',
          bottom: 32,
          right: 32,
          zIndex: 1
        }}
      >
        <Fab
          color="primary"
          size="medium"
          aria-label="scroll back to top"
          onClick={handleClick}
          sx={{
            boxShadow: theme => `0 8px 16px ${alpha(theme.palette.primary.main, 0.25)}`
          }}
        >
          <KeyboardArrowUp />
        </Fab>
      </Box>
    </Zoom>
  )
}

function LandingPage({ onGetStarted, isDarkMode, onToggleTheme }) {
  const theme = useTheme()
  const [showTutorial, setShowTutorial] = useState(false)
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'))
  const [openSpeedDial, setOpenSpeedDial] = useState(false)
  const [showProgress, setShowProgress] = useState(false)

  // Add section visibility tracking
  const [visibleSections, setVisibleSections] = useState({
    features: false,
    whatsNew: false,
    testimonials: false
  })

  // Intersection Observer setup
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            setVisibleSections(prev => ({
              ...prev,
              [entry.target.id]: true
            }))
          }
        })
      },
      { threshold: 0.1 }
    )

    const sections = ['features', 'whatsNew', 'testimonials']
    sections.forEach(section => {
      const element = document.getElementById(section)
      if (element) observer.observe(element)
    })

    return () => observer.disconnect()
  }, [])

  const handleStartWithTutorial = () => {
    setShowTutorial(true)
  }

  const handleTutorialClose = (completed) => {
    setShowTutorial(false)
    if (completed) {
      onGetStarted()
    }
  }

  const handleSkipTutorial = () => {
    onGetStarted()
  }

  const scrollToFeatures = () => {
    document.getElementById('features').scrollIntoView({ behavior: 'smooth' })
  }

  const handleSpeedDialAction = (action) => {
    setOpenSpeedDial(false)
    switch (action) {
      case 'tutorial':
        handleStartWithTutorial()
        break
      case 'start':
        setShowProgress(true)
        setTimeout(() => {
          setShowProgress(false)
          handleSkipTutorial()
        }, 1500)
        break
      default:
        break
    }
  }

  // Update scroll handling in LandingPage
  useEffect(() => {
    // Lock body scroll when modals are open
    const lockScroll = () => {
      document.body.style.overflow = 'hidden'
      document.body.style.height = '100%'
      document.body.style.position = 'fixed'
      document.body.style.width = '100%'
    }

    const unlockScroll = () => {
      document.body.style.overflow = ''
      document.body.style.height = ''
      document.body.style.position = ''
      document.body.style.width = ''
    }

    if (showTutorial || openSpeedDial) {
      lockScroll()
    } else {
      unlockScroll()
    }

    return unlockScroll
  }, [showTutorial, openSpeedDial])

  return (
    <Box 
      sx={{ 
        minHeight: '100%',
        width: '100%',
        bgcolor: 'background.default',
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden', // Changed from auto
        WebkitOverflowScrolling: 'touch',
        [theme.breakpoints.down('sm')]: {
          minHeight: '-webkit-fill-available',
        }
      }}
    >
      {/* Content container with proper scrolling */}
      <Box
        sx={{
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          position: 'relative',
          zIndex: 1,
          overflow: 'auto', // Enable scrolling here
          WebkitOverflowScrolling: 'touch',
          '-webkit-overflow-scrolling': 'touch',
          [theme.breakpoints.down('sm')]: {
            '&::-webkit-scrollbar': {
              display: 'none'
            },
            scrollbarWidth: 'none',
            msOverflowStyle: 'none',
          }
        }}
      >
        {/* Hero Section */}
        <Box
          sx={{
            flex: 1,
            display: 'flex',
            alignItems: 'flex-start',
            pt: { xs: 4, sm: 8 },
            pb: { xs: 2, sm: 4 },
            position: 'relative',
            minHeight: { xs: 'auto', sm: '100vh' },
          }}
        >
          <Container 
            maxWidth="lg"
            sx={{
              px: { xs: 2, sm: 3, md: 4 },
              width: '100%',
              maxWidth: '100%',
            }}
          >
            <Grid container spacing={{ xs: 4, md: 6 }} alignItems="center">
              <Grid item xs={12} md={6}>
                <Fade in timeout={1000}>
                  <Box>
                    {/* Updated hero logo/icon design */}
                    <Box
                      sx={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: { xs: 80, md: 96 },
                        height: { xs: 80, md: 96 },
                        borderRadius: 3,
                        bgcolor: 'transparent',
                        mb: 3,
                        ml: { xs: 2, md: 4 },
                        position: 'relative',
                        '&::before': {
                          content: '""',
                          position: 'absolute',
                          inset: 0,
                          background: `linear-gradient(135deg, ${alpha(theme.palette.primary.main, 0.12)} 0%, ${alpha(theme.palette.primary.main, 0.05)} 100%)`,
                          borderRadius: 'inherit',
                        }
                      }}
                    >
                      <Box 
                        sx={{ 
                          position: 'relative',
                          width: '100%',
                          height: '100%',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center'
                        }}
                      >
                        <Analytics 
                          sx={{ 
                            fontSize: { xs: 48, md: 56 },
                            color: theme.palette.primary.main,
                            transform: 'rotate(-10deg)',
                            position: 'absolute',
                            left: '10%',
                            top: '50%',
                            marginTop: '-24px'
                          }} 
                        />
                        <Assessment 
                          sx={{ 
                            fontSize: { xs: 48, md: 56 },
                            color: alpha(theme.palette.primary.main, 0.7),
                            position: 'absolute',
                            right: '10%',
                            top: '50%',
                            marginTop: '-24px'
                          }} 
                        />
                      </Box>
                    </Box>

                    {/* Enhanced title with better alignment */}
                    <Typography
                      component="h1"
                      variant="h2"
                      sx={{
                        fontSize: { xs: '2rem', sm: '2.5rem', md: '3.5rem', lg: '4rem' },
                        fontWeight: 800,
                        color: theme.palette.primary.main,
                        mb: 1,
                        textAlign: { xs: 'center', md: 'left' },
                        ml: { xs: 0, md: 4 },
                        position: 'relative',
                        '&::after': {
                          content: '""',
                          position: 'absolute',
                          bottom: -4,
                          left: { xs: '50%', md: 0 },
                          transform: { xs: 'translateX(-50%)', md: 'none' },
                          width: { xs: '80px', md: '120px' },
                          height: '4px',
                          background: `linear-gradient(90deg, ${theme.palette.primary.main}, transparent)`,
                          borderRadius: 2
                        }
                      }}
                    >
                      Portfolio
                      <Box 
                        component="span" 
                        sx={{ 
                          display: 'block',
                          fontSize: { xs: '1.75rem', sm: '2rem', md: '3rem', lg: '3.5rem' },
                          background: `linear-gradient(135deg, ${theme.palette.text.primary} 0%, ${alpha(theme.palette.text.primary, 0.8)} 100%)`,
                          backgroundClip: 'text',
                          WebkitBackgroundClip: 'text',
                          WebkitTextFillColor: 'transparent',
                          position: 'relative',
                          pl: { md: '2px' }, // Slight padding for alignment
                          '&::after': {
                            content: '""',
                            position: 'absolute',
                            bottom: -8,
                            left: 0,
                            width: '40%',
                            height: 3,
                            background: `linear-gradient(90deg, ${theme.palette.primary.main}, transparent)`,
                            borderRadius: 1
                          }
                        }}
                      >
                        Analytics Platform
                      </Box>
                    </Typography>

                    {/* Description with proper alignment */}
                    <Typography
                      variant="h5"
                      color="text.secondary"
                      sx={{
                        mb: { xs: 3, md: 4 },
                        mt: { xs: 2, md: 3 }, // Added top margin for spacing
                        fontSize: { xs: '1rem', sm: '1.25rem', md: 'inherit' },
                        lineHeight: 1.6,
                        textAlign: { xs: 'center', md: 'left' },
                        ml: { xs: 0, md: 4 },
                        maxWidth: { xs: '100%', md: '80%' }, // Adjusted max width
                        px: { xs: 2, md: 0 }, // Added padding for mobile
                        position: 'relative',
                        '&::before': {
                          content: '""',
                          position: 'absolute',
                          top: -12,
                          left: { xs: '50%', md: 0 },
                          transform: { xs: 'translateX(-50%)', md: 'none' },
                          width: 40,
                          height: 2,
                          bgcolor: alpha(theme.palette.primary.main, 0.3),
                          borderRadius: 1
                        }
                      }}
                    >
                      Advanced portfolio analysis and comparison tools to optimize your investments
                      with real-time data and comprehensive metrics.
                    </Typography>

                    {/* Buttons aligned with icon */}
                    <Stack
                      direction={{ xs: 'column', sm: 'row' }}
                      spacing={2}
                      justifyContent={{ xs: 'center', md: 'flex-start' }}
                      sx={{ 
                        mb: { xs: 4, md: 0 },
                        ml: { xs: 0, md: 4 },
                        width: { xs: '100%', sm: 'auto' }
                      }}
                    >
                      <Button
                        variant="contained"
                        size="large"
                        onClick={handleStartWithTutorial}
                        startIcon={<Assessment />}
                        fullWidth={isMobile}
                        sx={{
                          py: 1.5,
                          px: 3,
                          fontSize: '1rem',
                          boxShadow: 2,
                          minHeight: { xs: 48, sm: 40 },
                          borderRadius: { xs: 2, sm: 2 },
                        }}
                      >
                        Start with Tutorial
                      </Button>
                      <Button
                        variant="outlined"
                        size="large"
                        onClick={handleSkipTutorial}
                        fullWidth={isMobile}
                        sx={{
                          py: 1.5,
                          px: 3,
                          fontSize: '1rem',
                          minHeight: { xs: 48, sm: 40 },
                          borderRadius: { xs: 2, sm: 2 },
                        }}
                      >
                        Skip Tutorial
                      </Button>
                    </Stack>
                  </Box>
                </Fade>
              </Grid>

              {/* Statistics cards with simpler, consistent styling */}
              <Grid item xs={12} md={6}>
                <Grid 
                  container 
                  spacing={{ xs: 1.5, sm: 3 }}
                  sx={{
                    px: { xs: 0, sm: 2 },
                    mx: { xs: 0, sm: 0 },
                    width: '100%',
                  }}
                >
                  {statistics.map((stat, index) => (
                    <Grid item xs={12} sm={4} key={stat.label}>
                      <Zoom in timeout={1000 + index * 200}>
                        <Paper
                          elevation={1}
                          sx={{
                            p: { xs: 2.5, sm: 3 },
                            height: '100%',
                            borderRadius: 2,
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            justifyContent: 'center',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            bgcolor: alpha(stat.color, theme.palette.mode === 'light' ? 0.05 : 0.1),
                            border: `1px solid ${alpha(stat.color, theme.palette.mode === 'light' ? 0.1 : 0.2)}`,
                            '&:hover': {
                              transform: { xs: 'none', sm: 'translateY(-8px)' },
                              bgcolor: alpha(stat.color, theme.palette.mode === 'light' ? 0.08 : 0.15),
                              boxShadow: { 
                                xs: 'none',
                                sm: `0 8px 24px ${alpha(stat.color, theme.palette.mode === 'light' ? 0.15 : 0.25)}`
                              },
                            }
                          }}
                        >
                          <Box
                            sx={{
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              width: 56,
                              height: 56,
                              borderRadius: 2,
                              bgcolor: alpha(stat.color, 0.1),
                              mb: 2
                            }}
                          >
                            <stat.icon sx={{ fontSize: 28, color: stat.color }} />
                          </Box>
                          <Typography 
                            variant="h3" 
                            component="div"
                            fontWeight="bold"
                            sx={{
                              color: stat.color,
                              fontSize: { xs: '2rem', sm: '2.5rem' },
                              lineHeight: 1.2,
                              mb: 1
                            }}
                          >
                            {stat.value}
                          </Typography>
                          <Typography 
                            variant="subtitle1"
                            color="text.secondary"
                            align="center"
                            sx={{
                              fontSize: { xs: '0.875rem', sm: '1rem' },
                              fontWeight: 500
                            }}
                          >
                            {stat.label}
                          </Typography>
                        </Paper>
                      </Zoom>
                    </Grid>
                  ))}
                </Grid>
              </Grid>
            </Grid>
          </Container>
        </Box>

        {/* What's New Section with improved spacing */}
        <Box
          id="whatsNew"
          sx={{
            py: { xs: 3, sm: 4 },
            position: 'relative',
            width: '100%',
          }}
        >
          <Box
            sx={{
              px: { xs: 2, sm: 3, md: 4 },
              maxWidth: 'lg',
              mx: 'auto',
              width: '100%',
            }}
          >
            <Slide direction="up" in={visibleSections.whatsNew} timeout={1000}>
              <Box>
                <Typography
                  variant="h3"
                  align="center"
                  fontWeight="bold"
                  sx={{ 
                    mb: { xs: 2, sm: 3 },
                    fontSize: { xs: '1.75rem', sm: '2.5rem' },
                    lineHeight: { xs: 1.3, sm: 1.2 },
                    background: `linear-gradient(120deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,
                    WebkitBackgroundClip: 'text',
                    WebkitTextFillColor: 'transparent',
                    position: 'relative',
                    display: 'inline-block',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    '&::after': {
                      content: '""',
                      position: 'absolute',
                      bottom: -8,
                      left: 0,
                      width: '100%',
                      height: 3,
                      background: `linear-gradient(90deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,
                      borderRadius: 2,
                      transform: visibleSections.whatsNew ? 'scaleX(1)' : 'scaleX(0)',
                      transformOrigin: 'left',
                      transition: 'transform 1.5s ease-out',
                    }
                  }}
                >
                  What's New
                </Typography>
                <Typography
                  variant="h6"
                  align="center"
                  color="text.secondary"
                  sx={{ mb: 6, maxWidth: 600, mx: 'auto' }}
                >
                  Latest updates and improvements to enhance your portfolio analysis experience
                </Typography>
                <Grid 
                  container 
                  spacing={{ xs: 1.5, sm: 3 }}
                  sx={{ 
                    width: '100%',
                    mx: 'auto',
                    px: { xs: 0, sm: 2 }
                  }}
                >
                  {whatsNew.map((item, index) => (
                    <Grid item xs={12} sm={6} md={4} key={item.title}>
                      <Grow
                        in={visibleSections.whatsNew}
                        timeout={1000 + index * 200}
                      >
                        <Card
                          elevation={theme.palette.mode === 'light' ? 1 : 2}
                          sx={{
                            height: '100%',
                            borderRadius: { xs: 2, sm: 4 },
                            p: { xs: 2.5, sm: 3 },
                            mx: { xs: 1, sm: 1 },
                            mb: { xs: 1, sm: 0 },
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            border: `1px solid ${alpha(item.color, theme.palette.mode === 'light' ? 0.1 : 0.2)}`,
                            bgcolor: theme.palette.mode === 'light' ? 'background.paper' : 'background.paper',
                            position: 'relative',
                            overflow: 'visible',
                            '&:hover': {
                              transform: { xs: 'none', sm: 'translateY(-8px)' },
                              boxShadow: `0 12px 28px ${alpha(item.color, theme.palette.mode === 'light' ? 0.2 : 0.3)}`,
                              '& .whats-new-icon': {
                                transform: 'scale(1.1)',
                                bgcolor: alpha(item.color, theme.palette.mode === 'light' ? 0.15 : 0.25),
                              }
                            }
                          }}
                        >
                          <Box
                            sx={{
                              position: 'absolute',
                              top: -16,
                              right: 16,
                              zIndex: 1
                            }}
                          >
                            <Chip
                              label={item.tag}
                              color={
                                item.tag === 'New' ? 'success' :
                                item.tag === 'Updated' ? 'primary' :
                                'warning'
                              }
                              size="small"
                              sx={{
                                fontWeight: 'bold',
                                boxShadow: theme => `0 4px 12px ${alpha(theme.palette.primary.main, 0.25)}`
                              }}
                            />
                          </Box>
                          <CardContent sx={{ p: 4 }}>
                            <Box
                              sx={{
                                display: 'flex',
                                alignItems: 'center',
                                mb: 2
                              }}
                            >
                              <Avatar
                                sx={{
                                  bgcolor: alpha(item.color, 0.1),
                                  color: item.color,
                                  width: 56,
                                  height: 56,
                                  mb: 2
                                }}
                              >
                                <item.icon sx={{ fontSize: 28 }} />
                              </Avatar>
                            </Box>
                            <Typography
                              variant="h5"
                              gutterBottom
                              fontWeight="bold"
                            >
                              {item.title}
                            </Typography>
                            <Typography
                              color="text.secondary"
                              sx={{ lineHeight: 1.6 }}
                            >
                              {item.description}
                            </Typography>
                          </CardContent>
                        </Card>
                      </Grow>
                    </Grid>
                  ))}
                </Grid>
              </Box>
            </Slide>
          </Box>
        </Box>

        {/* Features Section with improved spacing */}
        <Box 
          id="features" 
          sx={{ 
            py: { xs: 3, sm: 4 },
            position: 'relative',
            width: '100%',
          }}
        >
          <Box
            sx={{
              px: { xs: 2, sm: 3, md: 4 },
              maxWidth: 'lg',
              mx: 'auto',
              width: '100%',
            }}
          >
            <Typography
              variant="h3"
              align="center"
              fontWeight="bold"
              sx={{ 
                mb: { xs: 1.5, sm: 3 },
                fontSize: { xs: '1.5rem', sm: '2rem', md: '2.5rem' },
                lineHeight: { xs: 1.2, sm: 1.2 },
                px: { xs: 1, sm: 0 },
                width: '100%',
                maxWidth: '100%',
                textAlign: 'center',
                position: 'relative',
                left: '50%',
                transform: 'translateX(-50%)',
              }}
            >
              Features
            </Typography>
            <Typography
              variant="h6"
              align="center"
              color="text.secondary"
              sx={{ mb: 6, maxWidth: 600, mx: 'auto' }}
            >
              Powerful tools and analytics to optimize your investment strategy
            </Typography>
            <Grid 
              container 
              spacing={{ xs: 1.5, sm: 3 }}
              sx={{ 
                width: '100%',
                mx: 0,
                px: { xs: 0, sm: 2 }
              }}
            >
              {features.map((feature, index) => (
                <Grid 
                  item 
                  xs={12} 
                  sm={6} 
                  md={4} 
                  key={feature.title}
                >
                  <Card
                    elevation={theme.palette.mode === 'light' ? 1 : 2}
                    sx={{
                      height: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      borderRadius: 2,
                      overflow: 'hidden',
                      transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                      border: `1px solid ${alpha(feature.color, theme.palette.mode === 'light' ? 0.1 : 0.2)}`,
                      bgcolor: theme.palette.mode === 'light' ? 'background.paper' : 'background.paper',
                      '&:hover': {
                        transform: { xs: 'none', sm: 'translateY(-8px)' },
                        boxShadow: { 
                          xs: 'none',
                          sm: `0 12px 28px ${alpha(feature.color, theme.palette.mode === 'light' ? 0.2 : 0.3)}`
                        },
                      }
                    }}
                  >
                    <Box
                      sx={{
                        p: { xs: 2, sm: 3 },
                        background: `linear-gradient(135deg, ${alpha(feature.color, theme.palette.mode === 'light' ? 0.1 : 0.15)} 0%, ${alpha(feature.color, theme.palette.mode === 'light' ? 0.05 : 0.1)} 100%)`,
                      }}
                    >
                      <Box
                        className="feature-icon"
                        sx={{
                          display: 'inline-flex',
                          p: 2,
                          borderRadius: '50%',
                          bgcolor: alpha(feature.color, theme.palette.mode === 'light' ? 0.1 : 0.2),
                          mb: 2,
                          transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                        }}
                      >
                        <feature.icon
                          sx={{
                            fontSize: 44,
                            color: feature.color,
                          }}
                        />
                      </Box>
                      <Typography
                        gutterBottom
                        variant="h5"
                        component="h2"
                        fontWeight="bold"
                        sx={{
                          fontSize: { xs: '1.35rem', sm: '1.5rem' },
                          mb: 1.5
                        }}
                      >
                        {feature.title}
                      </Typography>
                      <Typography 
                        color="text.secondary" 
                        paragraph
                        sx={{
                          fontSize: { xs: '0.95rem', sm: '1rem' },
                          mb: 1
                        }}
                      >
                        {feature.description}
                      </Typography>
                    </Box>
                    <CardContent 
                      sx={{ 
                        p: { xs: 2, sm: 3 },
                        flex: 1,
                        display: 'flex',
                        flexDirection: 'column'
                      }}
                    >
                      <Grid 
                        container 
                        spacing={3}
                        sx={{
                          justifyContent: 'center',
                          alignItems: 'center'
                        }}
                      >
                        <Grid item xs={6}>
                          <Stack spacing={2.5}>
                            {feature.details[0].left.map((detail, i) => (
                              <Box
                                key={i}
                                sx={{
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: 1.5
                                }}
                              >
                                <Box
                                  sx={{
                                    width: 8,
                                    height: 8,
                                    borderRadius: '50%',
                                    bgcolor: feature.color,
                                    flexShrink: 0
                                  }}
                                />
                                <Typography 
                                  variant="body2" 
                                  color="text.secondary"
                                  sx={{
                                    fontSize: { xs: '0.875rem', sm: '0.95rem' },
                                    fontWeight: 500
                                  }}
                                >
                                  {detail}
                                </Typography>
                              </Box>
                            ))}
                          </Stack>
                        </Grid>
                        <Grid item xs={6}>
                          <Stack spacing={2.5}>
                            {feature.details[0].right.map((detail, i) => (
                              <Box
                                key={i}
                                sx={{
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: 1.5
                                }}
                              >
                                <Box
                                  sx={{
                                    width: 8,
                                    height: 8,
                                    borderRadius: '50%',
                                    bgcolor: feature.color,
                                    flexShrink: 0
                                  }}
                                />
                                <Typography 
                                  variant="body2" 
                                  color="text.secondary"
                                  sx={{
                                    fontSize: { xs: '0.875rem', sm: '0.95rem' },
                                    fontWeight: 500
                                  }}
                                >
                                  {detail}
                                </Typography>
                              </Box>
                            ))}
                          </Stack>
                        </Grid>
                      </Grid>
                    </CardContent>
                  </Card>
                </Grid>
              ))}
            </Grid>
          </Box>
        </Box>

        {/* Testimonials Section with improved spacing */}
        <Box 
          id="testimonials"
          sx={{ 
            py: { xs: 3, sm: 4 },
            position: 'relative',
            width: '100%',
          }}
        >
          <Box
            sx={{
              px: { xs: 2, sm: 3, md: 4 },
              maxWidth: 'lg',
              mx: 'auto',
              width: '100%',
            }}
          >
            <Typography
              variant="h3"
              align="center"
              fontWeight="bold"
              sx={{ 
                mb: { xs: 2, sm: 3 },
                fontSize: { xs: '1.75rem', sm: '2.5rem' },
                lineHeight: { xs: 1.3, sm: 1.2 },
                background: `linear-gradient(120deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                position: 'relative',
                display: 'inline-block',
                left: '50%',
                transform: 'translateX(-50%)',
                '&::after': {
                  content: '""',
                  position: 'absolute',
                  bottom: -8,
                  left: 0,
                  width: '100%',
                  height: 3,
                  background: `linear-gradient(90deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,
                  borderRadius: 2,
                  transform: visibleSections.testimonials ? 'scaleX(1)' : 'scaleX(0)',
                  transformOrigin: 'left',
                  transition: 'transform 0.8s ease-out',
                }
              }}
            >
              What Our Users Say
            </Typography>
            
            <Typography
              variant="h6"
              align="center"
              color="text.secondary"
              sx={{ mb: 6, maxWidth: 600, mx: 'auto' }}
            >
              Trusted by investment professionals worldwide to deliver accurate insights and powerful analytics
            </Typography>

            <Grid 
              container 
              spacing={{ xs: 2, sm: 3 }}
              sx={{ 
                width: { xs: 'calc(100% + 16px)', sm: '100%' },
                mx: { xs: -1, sm: 0 },
                px: { xs: 1, sm: 2 },
                mb: { xs: 3, sm: 4 }
              }}
            >
              {testimonials.map((testimonial, index) => (
                <Grid item xs={12} sm={6} md={4} key={index}>
                  <Card
                    elevation={0}
                    sx={{
                      height: '100%',
                      bgcolor: alpha(theme.palette.background.paper, theme.palette.mode === 'light' ? 0.6 : 0.4),
                      backdropFilter: 'blur(8px)',
                      border: `1px solid ${alpha(theme.palette.divider, theme.palette.mode === 'light' ? 0.1 : 0.2)}`,
                      borderRadius: 2,
                      overflow: 'hidden',
                      transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                      '&:hover': {
                        transform: { xs: 'none', sm: 'translateY(-8px)' },
                        bgcolor: theme.palette.background.paper,
                        boxShadow: { 
                          xs: 'none',
                          sm: theme.shadows[8]
                        },
                      }
                    }}
                  >
                    <CardContent 
                      sx={{ 
                        p: { xs: 2.5, sm: 3 },
                        '&:last-child': { pb: { xs: 2.5, sm: 3 } }
                      }}
                    >
                      <Box sx={{ mb: 2 }}>
                        <Rating 
                          value={testimonial.rating} 
                          readOnly 
                          size="small"
                          sx={{
                            color: theme.palette.primary.main,
                            opacity: 0.9
                          }}
                        />
                      </Box>
                      
                      <Typography
                        variant="body1"
                        sx={{ 
                          mb: 3,
                          color: alpha(theme.palette.text.primary, 0.87),
                          lineHeight: 1.6,
                          fontStyle: 'italic'
                        }}
                      >
                        "{testimonial.comment}"
                      </Typography>

                      <Stack direction="row" spacing={1} sx={{ mb: 3 }}>
                        {testimonial.tags.map((tag) => (
                          <Chip
                            key={tag}
                            label={tag}
                            size="small"
                            sx={{
                              bgcolor: alpha(theme.palette.primary.main, 0.1),
                              color: theme.palette.primary.main,
                              fontWeight: 500
                            }}
                          />
                        ))}
                      </Stack>

                      <Stack direction="row" spacing={2} alignItems="center">
                        <Avatar
                          className="testimonial-avatar"
                          sx={{
                            bgcolor: theme.palette.primary.main,
                            width: 48,
                            height: 48,
                            fontSize: '1.2rem',
                            fontWeight: 500,
                            transition: 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                          }}
                        >
                          {testimonial.name[0]}
                        </Avatar>
                        <Box>
                          <Typography variant="subtitle1" fontWeight="bold">
                            {testimonial.name}
                          </Typography>
                          <Typography 
                            variant="body2" 
                            color="text.secondary"
                            sx={{ mb: 0.5 }}
                          >
                            {testimonial.role}
                          </Typography>
                          <Typography 
                            variant="caption" 
                            color="text.secondary"
                            sx={{ 
                              display: 'flex',
                              alignItems: 'center',
                              gap: 0.5
                            }}
                          >
                            <Box
                              component="span"
                              sx={{
                                width: 6,
                                height: 6,
                                borderRadius: '50%',
                                bgcolor: theme.palette.success.main
                              }}
                            />
                            {testimonial.company}
                          </Typography>
                        </Box>
                      </Stack>
                    </CardContent>
                  </Card>
                </Grid>
              ))}
            </Grid>

            <Box 
              sx={{ 
                display: 'flex', 
                justifyContent: 'center',
                gap: 2
              }}
            >
              <Button
                variant="outlined"
                size="large"
                startIcon={<Star />}
                sx={{
                  borderRadius: 2,
                  py: 1,
                  px: 3,
                  minHeight: { xs: 48, sm: 40 },
                  fontSize: { xs: '0.875rem', sm: '1rem' },
                }}
              >
                View All Reviews
              </Button>
            </Box>
          </Box>
        </Box>

        {/* Footer with improved spacing */}
        <Box 
          component="footer" 
          sx={{ 
            py: { xs: 3, sm: 4 },
            position: 'relative',
            width: '100%',
          }}
        >
          <Box
            sx={{
              px: { xs: 2, sm: 3, md: 4 },
              maxWidth: 'lg',
              mx: 'auto',
              width: '100%',
            }}
          >
            <Stack
              direction="row"
              justifyContent="center"
              alignItems="center"
              spacing={2}
            >
              {socialLinks.map(({ icon: Icon, label, url }) => (
                <Tooltip key={label} title={label}>
                  <IconButton
                    href={url}
                    target="_blank"
                    rel="noopener noreferrer"
                    sx={{
                      color: 'text.secondary',
                      '&:hover': {
                        color: 'primary.main',
                      },
                    }}
                  >
                    <Icon />
                  </IconButton>
                </Tooltip>
              ))}
            </Stack>
            <Typography
              variant="body2"
              color="text.secondary"
              align="center"
              sx={{ mt: 2 }}
            >
              © {new Date().getFullYear()} Portfolio Analytics. All rights reserved.
            </Typography>
          </Box>
        </Box>
      </Box>

      {/* Quick Action Speed Dial */}
      <SpeedDial
        ariaLabel="Quick actions"
        sx={{ 
          position: 'fixed', 
          bottom: { xs: 24, sm: 16 }, // Adjusted for mobile
          right: { xs: 16, sm: 24 },
          zIndex: theme.zIndex.speedDial,
          '& .MuiSpeedDial-fab': {
            width: { xs: 40, sm: 56 },
            height: { xs: 40, sm: 56 },
          }
        }}
        icon={<SpeedDialIcon />}
        open={openSpeedDial}
        onOpen={() => setOpenSpeedDial(true)}
        onClose={() => setOpenSpeedDial(false)}
      >
        <SpeedDialAction
          icon={<Help />}
          tooltipTitle="Start Tutorial"
          onClick={() => handleSpeedDialAction('tutorial')}
        />
        <SpeedDialAction
          icon={<PlayArrow />}
          tooltipTitle="Quick Start"
          onClick={() => handleSpeedDialAction('start')}
        />
      </SpeedDial>

      {/* Loading Progress */}
      {showProgress && (
        <Box
          sx={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            zIndex: 9999
          }}
        >
          <LinearProgress />
        </Box>
      )}

      {/* Tutorial Dialog */}
      <Tutorial 
        open={showTutorial} 
        onClose={handleTutorialClose}
      />

      {/* Backdrop for SpeedDial */}
      <Backdrop open={openSpeedDial} />

      {/* Add proper bottom spacing */}
      <Box 
        sx={{ 
          height: { xs: 80, sm: 0 },
          width: '100%',
          flexShrink: 0, // Prevent shrinking
        }} 
      />
    </Box>
  )
}

// Add keyframes for animations
const keyframes = `
  @keyframes pulse {
    0% { transform: translate(-50%, -50%) scale(1); opacity: 0.5; }
    50% { transform: translate(-50%, -50%) scale(1.5); opacity: 0.2; }
    100% { transform: translate(-50%, -50%) scale(1); opacity: 0.5; }
  }
`

// Add styles to document
const style = document.createElement('style')
style.innerHTML = keyframes
document.head.appendChild(style)

export default LandingPage

import { useState, useCallback } from 'react'
import {
  AppBar,
  Toolbar,
  IconButton,
  Typography,
  Button,
  Menu,
  MenuItem,
  Box,
  Tooltip,
  Divider,
  useTheme,
  styled,
  Fade,
  Badge,
  Snackbar,
  Alert,
  Avatar
} from '@mui/material'
import {
  Menu as MenuIcon,
  DarkMode,
  LightMode,
  SaveAlt,
  Compare,
  Delete,
  Assessment,
  ArrowBack,
  Folder,
  ShowChart,
  TrendingUp,
  BarChart,
  Analytics,
  AccountBalance,
  Person
} from '@mui/icons-material'
import LoadPortfolioDialog from './LoadPortfolioDialog'
import { useNavigate, useLocation } from 'react-router-dom'
import { useAuth } from './auth/AuthProvider'
import { alpha } from '@mui/material/styles'

const StyledAppBar = styled(AppBar)(({ theme }) => ({
  background: theme.palette.mode === 'light' 
    ? 'linear-gradient(120deg, #1976d2 0%, #1565c0 100%)'
    : 'linear-gradient(120deg, #272727 0%, #1a1a1a 100%)',
  boxShadow: theme.palette.mode === 'light'
    ? '0 2px 8px rgba(0,0,0,0.15)'
    : '0 2px 8px rgba(0,0,0,0.4)',
  position: 'fixed',
  top: 0,
  left: 0,
  right: 0,
  width: '100%',
  zIndex: 1200,
  height: { xs: 56, sm: 64 },
}))

const StyledToolbar = styled(Toolbar)(({ theme }) => ({
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  gap: 0.5,
  padding: theme.spacing(0, 1.5),
  minHeight: { xs: 56, sm: 64 },
  [theme.breakpoints.down('sm')]: {
    padding: theme.spacing(0, 1),
  },
}))

const LogoSection = styled(Box)(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  gap: theme.spacing(1),
  cursor: 'pointer',
  flex: 1,
  [theme.breakpoints.down('sm')]: {
    '& .MuiTypography-root': {
      fontSize: '0.9rem',
      maxWidth: '140px',
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
    },
    '& .logo-box': {
      width: 28,
      height: 28,
      minWidth: 28,
      marginRight: theme.spacing(0.5),
    },
    '& .logo-icon': {
      fontSize: '1.2rem',
    },
  },
}))

const ActionButtons = styled(Box)(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  gap: theme.spacing(1),
  [theme.breakpoints.down('sm')]: {
    display: 'none',
  },
}))

const MobileMenu = styled(Box)(({ theme }) => ({
  display: 'none',
  [theme.breakpoints.down('sm')]: {
    display: 'flex',
    '& .MuiIconButton-root': {
      padding: theme.spacing(1),
    },
  },
}))

function Header({
  onClearAll,
  onLoadPortfolio,
  onAddComparison,
  activeView,
  onViewChange,
  hasResults,
  onToggleTheme,
  isDarkMode,
  onHome,
  showLanding,
  setShowLanding,
  onGetStarted
}) {
  const theme = useTheme()
  const navigate = useNavigate()
  const location = useLocation()
  const { user } = useAuth()
  const [anchorEl, setAnchorEl] = useState(null)
  const [isLoadDialogOpen, setIsLoadDialogOpen] = useState(false)
  const [loadMode, setLoadMode] = useState('load')
  const [notification, setNotification] = useState(null)

  const isPortfolioPage = !location.pathname.startsWith('/member')
  const isLandingPage = location.pathname === '/' && showLanding
  const showPortfolioButton = !isLandingPage && !showLanding && (!isPortfolioPage || (isPortfolioPage && activeView !== 'results'))
  const showPortfolioActions = isPortfolioPage && user && !isLandingPage && !showLanding

  const handleLogoClick = useCallback(() => {
    if (location.pathname.startsWith('/member')) {
      navigate('/')
      onHome?.()
    } else if (location.pathname === '/') {
      onHome?.()
    }
  }, [navigate, location.pathname, onHome])

  const handleMenuOpen = useCallback((event) => {
    setAnchorEl(event.currentTarget)
  }, [])

  const handleMenuClose = useCallback(() => {
    setAnchorEl(null)
  }, [])

  const handleLoadPortfolio = useCallback((portfolioData) => {
    handleMenuClose()
    setIsLoadDialogOpen(false)
    setTimeout(() => {
      if (loadMode === 'load') {
        onLoadPortfolio(portfolioData)
      } else {
        onAddComparison(portfolioData)
      }
    }, 100)
  }, [loadMode, onLoadPortfolio, onAddComparison])

  const handleOpenLoadDialog = useCallback((mode) => {
    handleMenuClose()
    setLoadMode(mode)
    // Delay opening dialog to ensure menu is closed
    setTimeout(() => {
      setIsLoadDialogOpen(true)
    }, 100)
  }, [])

  const handleCloseLoadDialog = useCallback(() => {
    setIsLoadDialogOpen(false)
  }, [])

  const handleClearAll = useCallback(() => {
    handleMenuClose()
    onClearAll()
    setNotification({
      type: 'success',
      message: 'All data cleared successfully'
    })
  }, [onClearAll])

  const handleCloseNotification = useCallback(() => {
    setNotification(null)
  }, [])

  const handleViewChange = useCallback(() => {
    handleMenuClose()
    onViewChange(activeView === 'portfolio' ? 'results' : 'portfolio')
  }, [activeView, onViewChange])

  const handleMemberAreaClick = () => {
    if (user) {
      navigate('/member/profile')
    } else {
      navigate('/member')
    }
  }

  const handlePortfolioClick = useCallback(() => {
    if (showLanding) {
      onGetStarted?.()
    } else if (location.pathname !== '/') {
      navigate('/')
    }
  }, [navigate, location.pathname, showLanding, onGetStarted])

  return (
    <>
      <Fade in timeout={400}>
        <StyledAppBar position="static">
          <StyledToolbar>
            <Fade in timeout={600}>
              <LogoSection onClick={handleLogoClick}>
                <Box
                  className="logo-box"
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    width: 40,
                    height: 40,
                    borderRadius: '12px',
                    bgcolor: 'rgba(255, 255, 255, 0.1)',
                    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                  }}
                >
                  <Box sx={{ position: 'relative', width: 24, height: 24 }}>
                    <BarChart 
                      className="logo-icon"
                      sx={{ 
                        position: 'absolute',
                        fontSize: 24,
                        color: 'white',
                        opacity: 0.5,
                        transform: 'scale(0.85) translateX(-2px)'
                      }} 
                    />
                    <TrendingUp 
                      className="logo-icon"
                      sx={{ 
                        position: 'absolute',
                        fontSize: 24,
                        color: 'white',
                        transform: 'scale(0.9) translateX(2px)'
                      }} 
                    />
                  </Box>
                </Box>
                <Typography variant="h6" component="div" sx={{ fontWeight: 600 }}>
                  Portfolio Analytics
                </Typography>
              </LogoSection>
            </Fade>

            <Fade in timeout={800}>
              <ActionButtons>
                {showPortfolioButton && (
                  <Tooltip title="Go to Portfolio">
                    <Button
                      color="inherit"
                      startIcon={<ShowChart />}
                      onClick={handlePortfolioClick}
                    >
                      Portfolio
                    </Button>
                  </Tooltip>
                )}

                {showPortfolioActions && (
                  <>
                    <Tooltip title="Load Portfolio">
                      <Button
                        color="inherit"
                        startIcon={<Folder />}
                        onClick={() => handleOpenLoadDialog('load')}
                      >
                        Load
                      </Button>
                    </Tooltip>

                    <Tooltip title="Compare Portfolio">
                      <Button
                        color="inherit"
                        startIcon={<Compare />}
                        onClick={() => handleOpenLoadDialog('compare')}
                      >
                        Compare
                      </Button>
                    </Tooltip>

                    {hasResults && (
                      <Tooltip title={activeView === 'portfolio' ? 'View Results' : 'Edit Portfolio'}>
                        <Button
                          color="inherit"
                          startIcon={activeView === 'portfolio' ? <Assessment /> : <ArrowBack />}
                          onClick={handleViewChange}
                        >
                          {activeView === 'portfolio' ? 'Results' : 'Portfolio'}
                        </Button>
                      </Tooltip>
                    )}

                    <Divider orientation="vertical" flexItem sx={{ mx: 1, bgcolor: 'rgba(255,255,255,0.12)' }} />

                    <Tooltip title="Clear Portfolio">
                      <Button
                        color="inherit"
                        startIcon={<Delete />}
                        onClick={handleClearAll}
                      >
                        Clear
                      </Button>
                    </Tooltip>
                  </>
                )}

                <Divider orientation="vertical" flexItem sx={{ mx: 1, bgcolor: 'rgba(255,255,255,0.12)' }} />

                <Tooltip title={user ? 'Profile' : 'Member Area'}>
                  <IconButton 
                    color="inherit" 
                    onClick={handleMemberAreaClick}
                    size="large"
                    sx={{
                      bgcolor: user ? alpha(theme.palette.primary.light, 0.2) : 'transparent',
                      '&:hover': {
                        bgcolor: user ? alpha(theme.palette.primary.light, 0.3) : alpha(theme.palette.primary.light, 0.1),
                      }
                    }}
                  >
                    {user ? (
                      <Avatar 
                        sx={{ 
                          width: 28, 
                          height: 28,
                          fontSize: '1rem',
                          bgcolor: 'primary.main'
                        }}
                      >
                        {user.username.charAt(0).toUpperCase()}
                      </Avatar>
                    ) : (
                      <Person />
                    )}
                  </IconButton>
                </Tooltip>

                <Tooltip title={isDarkMode ? 'Light Mode' : 'Dark Mode'}>
                  <IconButton 
                    color="inherit" 
                    onClick={onToggleTheme} 
                    size="large"
                  >
                    <Fade in={isDarkMode}>
                      <LightMode sx={{ position: 'absolute' }} />
                    </Fade>
                    <Fade in={!isDarkMode}>
                      <DarkMode sx={{ position: 'absolute' }} />
                    </Fade>
                  </IconButton>
                </Tooltip>
              </ActionButtons>
            </Fade>

            <Fade in timeout={800}>
              <MobileMenu>
                <IconButton
                  color="inherit"
                  onClick={handleMenuOpen}
                  size="large"
                  edge="end"
                >
                  <MenuIcon />
                </IconButton>
              </MobileMenu>
            </Fade>
          </StyledToolbar>

          <Menu
            id="mobile-menu"
            anchorEl={anchorEl}
            open={Boolean(anchorEl)}
            onClose={handleMenuClose}
            TransitionComponent={Fade}
            keepMounted
            PaperProps={{
              elevation: 3,
              sx: {
                mt: 1,
                minWidth: 200,
                borderRadius: 2,
                backgroundColor: theme.palette.background.paper,
              }
            }}
          >
            {[
              showPortfolioButton && (
                <MenuItem 
                  key="portfolio"
                  onClick={() => {
                    handleMenuClose()
                    handlePortfolioClick()
                  }}
                >
                  <ShowChart sx={{ mr: 2 }} /> Portfolio
                </MenuItem>
              ),
              
              showPortfolioActions && [
                <MenuItem 
                  key="load"
                  onClick={() => handleOpenLoadDialog('load')}
                >
                  <Folder sx={{ mr: 2 }} /> Load Portfolio
                </MenuItem>,
                <MenuItem 
                  key="compare"
                  onClick={() => handleOpenLoadDialog('compare')}
                >
                  <Compare sx={{ mr: 2 }} /> Compare Portfolio
                </MenuItem>,
                hasResults && (
                  <MenuItem 
                    key="view"
                    onClick={handleViewChange}
                  >
                    {activeView === 'portfolio' ? (
                      <>
                        <Assessment sx={{ mr: 2 }} /> View Results
                      </>
                    ) : (
                      <>
                        <ArrowBack sx={{ mr: 2 }} /> Edit Portfolio
                      </>
                    )}
                  </MenuItem>
                ),
                <MenuItem 
                  key="clear"
                  onClick={handleClearAll}
                >
                  <Delete sx={{ mr: 2 }} /> Clear Portfolio
                </MenuItem>,
                <Divider key="divider" />
              ],
              
              <MenuItem 
                key="member"
                onClick={handleMemberAreaClick}
              >
                <Person sx={{ mr: 2 }} /> {user ? 'Profile' : 'Member Area'}
              </MenuItem>,
              
              <MenuItem 
                key="theme"
                onClick={onToggleTheme}
              >
                {isDarkMode ? (
                  <>
                    <LightMode sx={{ mr: 2 }} /> Light Mode
                  </>
                ) : (
                  <>
                    <DarkMode sx={{ mr: 2 }} /> Dark Mode
                  </>
                )}
              </MenuItem>
            ].flat().filter(Boolean)}
          </Menu>
        </StyledAppBar>
      </Fade>

      <LoadPortfolioDialog
        open={isLoadDialogOpen}
        onClose={handleCloseLoadDialog}
        onLoad={handleLoadPortfolio}
        mode={loadMode}
      />

      <Snackbar
        open={notification !== null}
        autoHideDuration={3000}
        onClose={handleCloseNotification}
        anchorOrigin={{ 
          vertical: 'bottom', 
          horizontal: 'center' 
        }}
        sx={{
          bottom: { xs: 16, sm: 24 }
        }}
        TransitionComponent={Fade}
      >
        <Alert 
          onClose={handleCloseNotification}
          severity={notification?.type || 'info'}
          variant="filled"
          elevation={6}
          sx={{
            borderRadius: 2,
            minWidth: { xs: '90vw', sm: 300 },
            '& .MuiAlert-icon': {
              fontSize: '1.5rem',
            },
          }}
        >
          {notification?.message}
        </Alert>
      </Snackbar>
    </>
  )
}

export default Header

enhance the mobile/responsive interface experience and return me the full updated code