// LandingPage.jsx
import { useState, useEffect, useCallback, memo } from 'react'
import {
  Box,
  Container,
  Typography,
  Button,
  Grid,
  Card,
  CardContent,
  useTheme,
  alpha,
  Stack,
  Paper,
  Divider,
  useMediaQuery,
  IconButton,
  Tooltip,
  Chip,
  Rating,
  LinearProgress,
  Avatar,
  Fab,
  useScrollTrigger,
  Backdrop,
} from '@mui/material'
import {
  Timeline,
  ShowChart,
  Compare,
  Analytics,
  TrendingUp,
  Assessment,
  AccountBalance,
  Speed,
  CloudSync,
  Autorenew,
  LinkedIn,
  Email,
  KeyboardArrowUp,
  Star,
  Lightbulb,
  BarChart,
  Insights,
  NewReleases,
  Update,
} from '@mui/icons-material'
import Tutorial from './Tutorial'
import MobileLanding from './MobileLanding'

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 (
    <Backdrop open={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>
    </Backdrop>
  )
}

// Add this new component for the TradingView widget
function TradingViewWidget() {
  const theme = useTheme();

  useEffect(() => {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://s3.tradingview.com/external-embedding/embed-widget-ticker-tape.js';
    script.async = true;
    script.innerHTML = JSON.stringify({
      symbols: [
        {
          proName: "FOREXCOM:SPXUSD",
          title: "S&P 500 Index"
        },
        {
          description: "Nvidia Corporation",
          proName: "NASDAQ:NVDA"
        },
        {
          description: "Microsoft Corporation",
          proName: "NASDAQ:MSFT"
        },
        {
          description: "Meta Platforms, Inc.",
          proName: "NASDAQ:META"
        },
        {
          description: "Alphabet Inc.",
          proName: "NASDAQ:GOOGL"
        },
        {
          description: "Coinbase Global, Inc.",
          proName: "NASDAQ:COIN"
        },
        {
          description: "Amazon.com, Inc.",
          proName: "NASDAQ:AMZN"
        },
        {
          description: "Apple Inc.",
          proName: "NASDAQ:AAPL"
        },
        {
          description: "Tesla, Inc.",
          proName: "NASDAQ:TSLA"
        }
      ],
      showSymbolLogo: true,
      isTransparent: true,
      displayMode: "adaptive",
      colorTheme: theme.palette.mode,
      locale: "en"
    });

    // Create a container reference
    const container = document.createElement('div');
    container.className = 'tradingview-widget-container__widget';
    
    // Find the parent element and append both container and script
    const widgetContainer = document.querySelector('.tradingview-widget-container');
    if (widgetContainer) {
      widgetContainer.appendChild(container);
      widgetContainer.appendChild(script);
    }

    // Cleanup function
    return () => {
      if (widgetContainer) {
        if (container && container.parentNode === widgetContainer) {
          widgetContainer.removeChild(container);
        }
        if (script && script.parentNode === widgetContainer) {
          widgetContainer.removeChild(script);
        }
      }
    };
  }, [theme.palette.mode]);

  return (
    <Box sx={{ width: '100%', height: 'auto', position: 'relative', zIndex: 2 }}>
      <div className="tradingview-widget-container">
        {/* Remove the div here since we're creating it dynamically */}
      </div>
    </Box>
  );
}
const LandingPage = ({ onGetStarted, isDarkMode, onToggleTheme }) => {
  const theme = useTheme()
  const [tutorialState, setTutorialState] = useState({
    isOpen: false,
    currentStep: 0,
    isCompleted: false
  });
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'))
  const [openSpeedDial, setOpenSpeedDial] = useState(false)
  const [showProgress, setShowProgress] = useState(false)

  // Memoize handlers
  const handleStartWithTutorial = useCallback(() => {
    setTutorialState(prev => {
      if (!prev.isOpen) {
        return {
          isOpen: true,
          currentStep: 0,
          isCompleted: false
        };
      }
      return prev;
    });
  }, []);

  const handleTutorialClose = useCallback((completed) => {
    setTutorialState({
      isOpen: false,
      currentStep: 0,
      isCompleted: completed
    });

    if (completed) {
      setTimeout(() => {
        onGetStarted();
      }, 300);
    }
  }, [onGetStarted]);

  const handleTutorialStepChange = useCallback((step) => {
    setTutorialState(prev => ({
      ...prev,
      currentStep: step
    }));
  }, []);

  const handleSkipTutorial = useCallback(() => {
    setShowProgress(true)
    setTimeout(() => {
      setShowProgress(false)
      onGetStarted()
    }, 1500)
  }, [onGetStarted])

  // Prevent tutorial from showing on initial render
  const [initialRender, setInitialRender] = useState(true)
  useEffect(() => {
    if (initialRender) {
      setInitialRender(false)
    }
  }, [])

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

  // Original desktop version
  const DesktopLanding = () => (
    <Box
      sx={{
        minHeight: '100vh',
        bgcolor: 'background.default',
        overflow: 'hidden',
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
        margin: 0,
        padding: 0,
        '&::before': {
          content: '""',
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: theme.palette.mode === 'light'
            ? `linear-gradient(45deg, ${alpha(theme.palette.primary.light, 0.03)}, ${alpha(theme.palette.primary.main, 0.03)})`
            : `linear-gradient(45deg, ${alpha(theme.palette.primary.dark, 0.03)}, ${alpha(theme.palette.primary.main, 0.03)})`,
          zIndex: 0,
          pointerEvents: 'none',
        }
      }}
    >
      {/* Add TradingView Widget at the top */}
      <TradingViewWidget />

      {/* Content container */}
      <Box
        sx={{
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          position: 'relative',
          zIndex: 1,
          bgcolor: 'background.default',
          margin: 0,
          padding: 0,
          '& > *': {
            marginBottom: 0,
          },
        }}
      >
        {/* Hero Section */}
        <Box
          sx={{
            flex: 1,
            display: 'flex',
            alignItems: 'center',
            pb: { xs: 4, md: 6 },
            bgcolor: 'background.default',
            position: 'relative',
          }}
        >
          <Container maxWidth="lg" sx={{ px: { xs: 2, sm: 4, md: 8 }, position: 'relative', zIndex: 1 }}>
            <Grid container spacing={{ xs: 4, md: 6 }} alignItems="center">
              <Grid item xs={12} md={6}>
                <Box sx={{ position: 'relative' }}>
                  {/* Enhanced title with animations */}
                  <Typography
                    component="h1"
                    variant="h2"
                    sx={{
                      fontSize: { xs: '2.5rem', sm: '3rem', md: '4rem', lg: '4.5rem' },
                      fontWeight: 800,
                      textAlign: { xs: 'center', md: 'left' },
                      ml: { xs: 0, md: 4 },
                      position: 'relative',
                      '& .highlight': {
                        position: 'relative',
                        display: 'inline-block',
                        background: `linear-gradient(135deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,
                        backgroundClip: 'text',
                        WebkitBackgroundClip: 'text',
                        WebkitTextFillColor: 'transparent',
                        animation: 'gradient 4s linear infinite',
                        '@keyframes gradient': {
                          '0%': { backgroundPosition: '0% center' },
                          '100%': { backgroundPosition: '200% center' },
                        },
                      },
                    }}
                  >
                    <span className="highlight">Portfolio AI</span>
                  </Typography>

                  {/* Enhanced description with animation - removed background effects */}
                  <Typography
                    variant="h5"
                    sx={{
                      mb: { xs: 3, md: 4 },
                      mt: { xs: 2, md: 3 },
                      fontSize: { xs: '1.1rem', sm: '1.25rem', md: '1.5rem' },
                      lineHeight: 1.6,
                      textAlign: { xs: 'center', md: 'left' },
                      ml: { xs: 0, md: 4 },
                      maxWidth: { xs: '100%', md: '80%' },
                      px: { xs: 2, md: 0 },
                      color: alpha(theme.palette.text.secondary, 0.9),
                      position: 'relative',
                      '& .highlight': {
                        color: theme.palette.primary.main,
                        fontWeight: 600,
                        position: 'relative',
                      },
                    }}
                  >
                    <span className="highlight">Advanced portfolio analysis</span> and comparison tools to optimize your investments with <span className="highlight">real-time data</span> and comprehensive metrics.
                  </Typography>

                  {/* Action buttons with enhanced animations */}
                  <Stack
                    direction={{ xs: 'column', sm: 'row' }}
                    spacing={2}
                    justifyContent={{ xs: 'center', md: 'flex-start' }}
                    sx={{
                      ml: { xs: 0, md: 4 },
                      '& .MuiButton-root': {
                        transition: 'all 0.3s ease',
                        transform: 'translateY(0)',
                        '&:hover': {
                          transform: 'translateY(-4px)',
                          boxShadow: `0 8px 16px ${alpha(theme.palette.primary.main, 0.25)}`,
                        },
                      },
                    }}
                  >
                    <Button
                      variant="contained"
                      size="large"
                      onClick={handleStartWithTutorial}
                      startIcon={<Assessment />}
                      sx={{
                        py: 1.8,
                        px: 4,
                        fontSize: '1.1rem',
                        fontWeight: 600,
                        borderRadius: 3,
                        background: `linear-gradient(45deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,
                        backgroundSize: '200% auto',
                        animation: 'gradient 3s infinite',
                        '@keyframes gradient': {
                          '0%': { backgroundPosition: '0% center' },
                          '50%': { backgroundPosition: '100% center' },
                          '100%': { backgroundPosition: '0% center' },
                        },
                      }}
                    >
                      Start with Tutorial
                    </Button>
                    <Button
                      variant="outlined"
                      size="large"
                      onClick={handleSkipTutorial}
                      sx={{
                        py: 1.8,
                        px: 4,
                        fontSize: '1.1rem',
                        fontWeight: 500,
                        borderRadius: 3,
                        borderWidth: 2,
                        borderColor: theme.palette.primary.main,
                        color: theme.palette.primary.main,
                        position: 'relative',
                        overflow: 'hidden',
                        '&::after': {
                          content: '""',
                          position: 'absolute',
                          top: 0,
                          left: 0,
                          width: '100%',
                          height: '100%',
                          background: alpha(theme.palette.primary.main, 0.1),
                          transform: 'translateX(-100%)',
                          transition: 'transform 0.3s ease',
                        },
                        '&:hover::after': {
                          transform: 'translateX(0)',
                        },
                      }}
                    >
                      Skip Tutorial
                    </Button>
                  </Stack>
                </Box>
              </Grid>

              {/* Enhanced Statistics Cards */}
              <Grid item xs={12} md={6}>
                <Grid container spacing={2}>
                  {statistics.map((stat, index) => (
                    <Grid item xs={12} sm={4} key={stat.label}>
                      <Paper
                        elevation={0}
                        sx={{
                          p: 3,
                          height: '100%',
                          borderRadius: 4,
                          background: `linear-gradient(135deg, ${alpha(stat.color, 0.1)}, ${alpha(stat.color, 0.05)})`,
                          backdropFilter: 'blur(8px)',
                          border: `1px solid ${alpha(stat.color, 0.2)}`,
                          transition: 'all 0.3s ease',
                          transform: 'translateY(0)',
                          '&:hover': {
                            transform: 'translateY(-8px)',
                            boxShadow: `0 12px 24px ${alpha(stat.color, 0.2)}`,
                            '& .stat-icon': {
                              transform: 'scale(1.1) rotate(10deg)',
                            },
                          },
                        }}
                      >
                        <Box
                          className="stat-icon"
                          sx={{
                            width: 56,
                            height: 56,
                            borderRadius: '50%',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            background: `linear-gradient(135deg, ${stat.color}, ${alpha(stat.color, 0.8)})`,
                            mb: 2,
                            transition: 'transform 0.3s ease',
                          }}
                        >
                          <stat.icon sx={{ fontSize: 28, color: 'white' }} />
                        </Box>
                        <Typography
                          variant="h3"
                          sx={{
                            fontWeight: 700,
                            color: stat.color,
                            mb: 1,
                            fontSize: { xs: '2rem', sm: '2.5rem' },
                          }}
                        >
                          {stat.value}
                        </Typography>
                        <Typography
                          variant="subtitle1"
                          sx={{
                            color: alpha(theme.palette.text.primary, 0.7),
                            fontWeight: 500,
                          }}
                        >
                          {stat.label}
                        </Typography>
                      </Paper>
                    </Grid>
                  ))}
                </Grid>
              </Grid>
            </Grid>
          </Container>
        </Box>

        {/* What's New Section with improved spacing */}
        <Box
          id="whatsNew"
          sx={{
            py: { xs: 6, md: 8 },
            bgcolor: 'background.default',
            position: 'relative',
            mt: 0,
            mb: 0,
          }}
        >
          <Container
            maxWidth="lg"
            sx={{
              px: { xs: 4, sm: 6, md: 8 },
            }}
          >
            <Box>
              <Typography
                variant="h3"
                align="center"
                fontWeight="bold"
                sx={{
                  mb: { xs: 3, md: 4 },
                  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: 'scaleX(1)',
                    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={4}
                sx={{
                  mx: 'auto',
                  width: 'calc(100% + 32px)',
                  ml: -2,
                  mr: -2,
                }}
              >
                {whatsNew.map((item, index) => (
                  <Grid item xs={12} md={4} key={item.title}>
                    <Card
                      elevation={theme.palette.mode === 'light' ? 1 : 2}
                      sx={{
                        height: '100%',
                        borderRadius: 4,
                        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: '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>
                  </Grid>
                ))}
              </Grid>
            </Box>
          </Container>
        </Box>

        {/* Features Section with improved spacing */}
        <Box id="features" sx={{ py: { xs: 6, md: 8 }, position: 'relative', mb: -8, bgcolor: 'background.default' }}>
          <Container
            maxWidth="lg"
            sx={{
              px: { xs: 4, sm: 6, md: 8 },
            }}
          >
            <Typography
              variant="h3"
              align="center"
              fontWeight="bold"
              sx={{
                mb: { xs: 3, md: 4 },
                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: 'scaleX(1)',
                  transformOrigin: 'left',
                  transition: 'transform 1.5s ease-out',
                },
              }}
            >
              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={4}
              sx={{
                mx: 'auto',
                width: 'calc(100% + 32px)',
                ml: -2,
                mr: -2,
              }}
            >
              {features.map((feature, index) => (
                <Grid item xs={12} sm={6} md={4} key={feature.title} sx={{ px: { xs: 2, sm: 3, md: 4 } }}>
                  <Card
                    elevation={theme.palette.mode === 'light' ? 1 : 2}
                    sx={{
                      height: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      borderRadius: 4,
                      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: 'translateY(-8px)',
                        boxShadow: `0 12px 28px ${alpha(
                          feature.color,
                          theme.palette.mode === 'light' ? 0.2 : 0.3
                        )}`,
                        '& .feature-icon': {
                          transform: 'scale(1.1)',
                          bgcolor: alpha(
                            feature.color,
                            theme.palette.mode === 'light' ? 0.15 : 0.25
                          ),
                        },
                      },
                    }}
                  >
                    <Box
                      sx={{
                        p: 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={{
                        flexGrow: 1,
                        display: 'flex',
                        alignItems: 'center',
                        p: 3,
                        pt: 2.5,
                        pb: 3,
                      }}
                    >
                      <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>
          </Container>
        </Box>

        {/* Testimonials Section with improved spacing */}
        <Box
          id="testimonials"
          sx={{
            py: { xs: 6, md: 8 },
            bgcolor:
              theme.palette.mode === 'light'
                ? alpha(theme.palette.primary.main, 0.02)
                : alpha(theme.palette.primary.dark, 0.02),
            position: 'relative',
            mt: 0,
            borderTop: `1px solid ${alpha(
              theme.palette.divider,
              0.1
            )}`,
            zIndex: 1,
          }}
        >
          <Container maxWidth="lg">
            <Typography
              variant="h3"
              align="center"
              fontWeight="bold"
              sx={{
                mb: { xs: 3, md: 4 },
                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: 'scaleX(1)',
                  transformOrigin: 'left',
                  transition: 'transform 1.5s 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={3} sx={{ mb: 4 }}>
              {testimonials.map((testimonial, index) => (
                <Grid item xs={12} 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: 3,
                      transition:
                        'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                      '&:hover': {
                        transform: 'translateY(-8px)',
                        bgcolor: theme.palette.background.paper,
                        boxShadow: theme.shadows[8],
                        '& .testimonial-avatar': {
                          transform: 'scale(1.1)',
                        },
                      },
                    }}
                  >
                    <CardContent sx={{ p: 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,
                }}
              >
                View All Reviews
              </Button>
            </Box>
          </Container>
        </Box>

        {/* Footer with improved spacing */}
        <Box
          component="footer"
          sx={{
            py: 4,
            mt: 'auto',
            position: 'relative',
            marginBottom: 0,
            borderTop: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
          }}
        >
          <Container
            maxWidth="lg"
            sx={{
              px: { xs: 4, sm: 6, md: 8 },
            }}
          >
            <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>
          </Container>
        </Box>
      </Box>

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

      {/* Tutorial Dialog */}
      {!initialRender && (
        <Tutorial 
          open={tutorialState.isOpen}
          currentStep={tutorialState.currentStep}
          onStepChange={handleTutorialStepChange}
          onClose={handleTutorialClose}
          isCompleted={tutorialState.isCompleted}
        />
      )}

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

      {/* Scroll To Top */}
      <ScrollToTop />
    </Box>
  )

  return isMobile ? (
    <MobileLanding
      theme={theme}
      features={features}
      socialLinks={socialLinks}
      handleStartWithTutorial={handleStartWithTutorial}
      handleSkipTutorial={handleSkipTutorial}
      handleSpeedDialAction={handleSpeedDialAction}
      showTutorial={tutorialState.isOpen}
      handleTutorialClose={handleTutorialClose}
      openSpeedDial={openSpeedDial}
      setOpenSpeedDial={setOpenSpeedDial}
    />
  ) : (
    <DesktopLanding />
  )
}

export default memo(LandingPage) // Memoize the component



import { useState, useCallback, useEffect, memo, useMemo } from 'react'
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  Stepper,
  Step,
  StepLabel,
  StepContent,
  Paper,
  useTheme,
  IconButton,
  Zoom,
  alpha,
  Fade
} from '@mui/material'
import {
  HelpOutline,
  AccountBalance,
  Settings,
  CompareArrows,
  Assessment,
  Close,
  KeyboardArrowRight,
  KeyboardArrowLeft,
  CheckCircleOutline
} from '@mui/icons-material'
import PropTypes from 'prop-types'

const tutorialSteps = [
  {
    label: 'Welcome to Portfolio AI',
    icon: AccountBalance,
    content: (
      <>
        <Typography variant="h6" color="primary" gutterBottom>
          Let's get you started!
        </Typography>
        <Typography paragraph>
          Portfolio AI helps you make better investment decisions through:
        </Typography>
        <Box component="ul" sx={{ pl: 2 }}>
          <li>Advanced portfolio analysis</li>
          <li>Real-time market data</li>
          <li>Risk assessment tools</li>
          <li>Performance tracking</li>
        </Box>
        <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
          This quick tutorial will show you how to make the most of these features.
        </Typography>
      </>
    )
  },
  {
    label: 'Create Your Portfolio',
    icon: AccountBalance,
    content: (
      <>
        <Typography variant="h6" color="primary" gutterBottom>
          Build Your Investment Portfolio
        </Typography>
        <Typography paragraph>
          Getting started is easy:
        </Typography>
        <Box component="ul" sx={{ pl: 2 }}>
          <li>
            <Typography component="span" fontWeight="bold">Add Assets:</Typography>
            {' '}Enter stock tickers (e.g., AAPL, GOOGL)
          </li>
          <li>
            <Typography component="span" fontWeight="bold">Set Allocations:</Typography>
            {' '}Assign percentage weights to each holding
          </li>
          <li>
            <Typography component="span" fontWeight="bold">Import Data:</Typography>
            {' '}Use CSV import for bulk portfolio creation
          </li>
          <li>
            <Typography component="span" fontWeight="bold">Save & Name:</Typography>
            {' '}Store portfolios for future analysis
          </li>
        </Box>
        <Paper 
          elevation={0} 
          sx={{ 
            p: 2, 
            mt: 2, 
            bgcolor: (theme) => alpha(theme.palette.primary.main, 0.05),
            border: '1px dashed',
            borderColor: 'primary.main'
          }}
        >
          <Typography variant="body2" color="primary">
            💡 Pro Tip: Use the bulk import feature to quickly add multiple assets from your spreadsheet
          </Typography>
        </Paper>
      </>
    )
  },
  {
    label: 'Configure Analysis',
    icon: Settings,
    content: (
      <>
        <Typography paragraph>
          Set your analysis parameters:
        </Typography>
        <Box component="ul" sx={{ pl: 2 }}>
          <li>Choose a historical start date for analysis</li>
          <li>Select a benchmark index (e.g., S&P 500)</li>
          <li>Adjust transaction costs if needed</li>
          <li>Configure rebalancing options</li>
        </Box>
      </>
    )
  },
  {
    label: 'Compare Portfolios',
    icon: CompareArrows,
    content: (
      <>
        <Typography paragraph>
          Analyze multiple portfolios:
        </Typography>
        <Box component="ul" sx={{ pl: 2 }}>
          <li>Load saved portfolios from "My Portfolios"</li>
          <li>Add portfolios to comparison</li>
          <li>Compare against market benchmarks</li>
          <li>View side-by-side performance metrics</li>
        </Box>
      </>
    )
  },
  {
    label: 'Analyze Results',
    icon: Assessment,
    content: (
      <>
        <Typography paragraph>
          Explore comprehensive analysis results:
        </Typography>
        <Box component="ul" sx={{ pl: 2 }}>
          <li>Performance metrics (returns, risk, ratios)</li>
          <li>Portfolio correlation analysis</li>
          <li>Rebalancing impact analysis</li>
          <li>Drawdown analysis and recovery periods</li>
        </Box>
      </>
    )
  }
]

function Tutorial({ 
  open, 
  currentStep, 
  onStepChange, 
  onClose, 
  isCompleted 
}) {
  const theme = useTheme();

  const handleNext = useCallback(() => {
    onStepChange(currentStep + 1);
  }, [currentStep, onStepChange]);

  const handleBack = useCallback(() => {
    onStepChange(currentStep - 1);
  }, [currentStep, onStepChange]);

  const handleClose = useCallback((event, reason) => {
    if (reason === 'backdropClick') return;
    onClose(false);
  }, [onClose]);

  const handleFinish = useCallback(() => {
    onClose(true);
  }, [onClose]);

  const progress = useMemo(() => {
    return Math.round((currentStep / (tutorialSteps.length - 1)) * 100);
  }, [currentStep]);

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="sm"
      fullWidth
      TransitionComponent={Zoom}
      PaperProps={{
        elevation: 8,
        sx: {
          borderRadius: 2,
          bgcolor: 'background.paper',
          minHeight: '60vh',
          maxHeight: '80vh',
          overflowY: 'auto',
          position: 'relative'
        }
      }}
      disableEscapeKeyDown
    >
      <Box
        sx={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          height: 4,
          bgcolor: alpha(theme.palette.primary.main, 0.1),
          overflow: 'hidden'
        }}
      >
        <Box
          sx={{
            width: `${progress}%`,
            height: '100%',
            bgcolor: 'primary.main',
            transition: 'width 0.3s ease'
          }}
        />
      </Box>

      <DialogTitle>
        <Box sx={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'space-between',
          pb: 1
        }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <HelpOutline color="primary" />
            <Typography variant="h6">
              Getting Started
            </Typography>
          </Box>
          <IconButton 
            onClick={() => handleClose(null, 'closeButton')}
            size="small"
            sx={{
              color: 'text.secondary',
              '&:hover': {
                color: 'text.primary',
                bgcolor: alpha(theme.palette.text.primary, 0.05)
              }
            }}
          >
            <Close />
          </IconButton>
        </Box>
      </DialogTitle>

      <DialogContent>
        <Box sx={{ mt: 2 }}>
          <Stepper 
            activeStep={currentStep} 
            orientation="vertical"
            sx={{
              '& .MuiStepLabel-root': {
                padding: '16px 0'
              }
            }}
          >
            {tutorialSteps.map((step, index) => (
              <Step key={step.label}>
                <StepLabel
                  StepIconComponent={() => (
                    <Box
                      sx={{
                        width: 32,
                        height: 32,
                        borderRadius: '50%',
                        bgcolor: index <= currentStep ? 'primary.main' : 'action.disabled',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: index <= currentStep ? 'white' : 'text.disabled',
                        transition: 'all 0.3s ease',
                        boxShadow: index <= currentStep ? `0 2px 8px ${alpha(theme.palette.primary.main, 0.25)}` : 'none'
                      }}
                    >
                      {index < currentStep ? (
                        <CheckCircleOutline fontSize="small" />
                      ) : (
                        <step.icon fontSize="small" />
                      )}
                    </Box>
                  )}
                >
                  <Typography variant="subtitle1" sx={{ fontWeight: 500 }}>
                    {step.label}
                  </Typography>
                </StepLabel>
                <StepContent>
                  <Box sx={{ mb: 2, mt: 1 }}>
                    {step.content}
                  </Box>
                  <Box sx={{ display: 'flex', gap: 1, mt: 2 }}>
                    <Button
                      disabled={index === 0}
                      onClick={handleBack}
                      variant="outlined"
                      size="small"
                      startIcon={<KeyboardArrowLeft />}
                    >
                      Back
                    </Button>
                    <Button
                      variant="contained"
                      onClick={index === tutorialSteps.length - 1 ? handleFinish : handleNext}
                      size="small"
                      endIcon={index === tutorialSteps.length - 1 ? <CheckCircleOutline /> : <KeyboardArrowRight />}
                    >
                      {index === tutorialSteps.length - 1 ? 'Get Started' : 'Next'}
                    </Button>
                  </Box>
                </StepContent>
              </Step>
            ))}
          </Stepper>
        </Box>

        {currentStep === tutorialSteps.length && (
          <Fade in>
            <Paper 
              square 
              elevation={0} 
              sx={{ 
                p: 3, 
                bgcolor: 'background.default',
                borderRadius: 2,
                border: `1px solid ${alpha(theme.palette.primary.main, 0.1)}`
              }}
            >
              <Typography variant="h6" color="primary" gutterBottom>
                Congratulations! 🎉
              </Typography>
              <Typography paragraph>
                You're all set to start using Portfolio AI. Ready to begin your investment journey?
              </Typography>
              <Button 
                onClick={handleFinish} 
                variant="contained"
                startIcon={<CheckCircleOutline />}
                sx={{
                  mt: 2,
                  boxShadow: `0 4px 12px ${alpha(theme.palette.primary.main, 0.25)}`
                }}
              >
                Get Started
              </Button>
            </Paper>
          </Fade>
        )}
      </DialogContent>
    </Dialog>
  );
}

Tutorial.propTypes = {
  open: PropTypes.bool.isRequired,
  currentStep: PropTypes.number.isRequired,
  onStepChange: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired,
  isCompleted: PropTypes.bool.isRequired
};

export default memo(Tutorial);

whenever I clicked back or next in the tutorial, it will refresh once include the background landing page as well
thinking again the flow then enhance the state

return me full updated code for each part