import { useState, useEffect, useRef, useLayoutEffect, useCallback } 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,
  CircularProgress
} 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'
import { debounce } from 'lodash'
import PropTypes from 'prop-types'

const HEADER_HEIGHT = { xs: 56, sm: 64 }
const MOBILE_SPACING = { xs: 2, sm: 3 }
const SECTION_SPACING = { xs: 6, sm: 8, md: 10 }

const ANIMATION_DURATION = {
  xs: 400,
  sm: 600,
  md: 800,
  lg: 1000
}

const ANIMATION_VARIANTS = {
  fadeIn: {
    initial: { opacity: 0, y: 20 },
    animate: { opacity: 1, y: 0 },
    exit: { opacity: 0, y: -20 }
  },
  slideUp: {
    initial: { opacity: 0, y: 40 },
    animate: { opacity: 1, y: 0 },
    exit: { opacity: 0, y: -40 }
  },
  scaleUp: {
    initial: { opacity: 0, scale: 0.9 },
    animate: { opacity: 1, scale: 1 },
    exit: { opacity: 0, scale: 0.9 }
  }
}

const TRANSITION_EASING = 'cubic-bezier(0.4, 0, 0.2, 1)'

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'
  }
]

// First, add a consistent header style component
const SectionHeader = ({ title, subtitle, visible = true }) => {
  const theme = useTheme()
  
  return (
    <Box sx={{ mb: 6, textAlign: 'center' }}>
      <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',
          '&::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: visible ? 'scaleX(1)' : 'scaleX(0)',
            transformOrigin: 'left',
            transition: 'transform 0.8s ease-out',
          }
        }}
      >
        {title}
      </Typography>
      {subtitle && (
        <Typography
          variant="h6"
          align="center"
          color="text.secondary"
          sx={{ 
            maxWidth: 600, 
            mx: 'auto',
            opacity: visible ? 1 : 0,
            transform: visible ? 'translateY(0)' : 'translateY(20px)',
            transition: 'all 0.8s ease-out',
            transitionDelay: '0.2s'
          }}
        >
          {subtitle}
        </Typography>
      )}
    </Box>
  )
}

// Update the section visibility tracking to use a ref to prevent multiple animations
const useVisibilityTracker = (ref) => {
  const [isVisible, setIsVisible] = useState(false)
  const wasVisibleRef = useRef(false)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !wasVisibleRef.current) {
          setIsVisible(true)
          wasVisibleRef.current = true
        }
      },
      {
        threshold: 0.1,
        rootMargin: '-50px'
      }
    )

    if (ref.current) {
      observer.observe(ref.current)
    }

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

  return isVisible
}

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)
  const contentRef = useRef(null)
  const [scrolled, setScrolled] = useState(false)

  // Add section visibility tracking with refs
  const featuresRef = useRef(null)
  const whatsNewRef = useRef(null)
  const testimonialsRef = useRef(null)
  
  const whatsNewVisible = useVisibilityTracker(whatsNewRef)
  const featuresVisible = useVisibilityTracker(featuresRef)
  const testimonialsVisible = useVisibilityTracker(testimonialsRef)

  // Improved scroll handling
  useLayoutEffect(() => {
    const content = contentRef.current
    if (!content) return

    const handleScroll = debounce(() => {
      const scrollPosition = content.scrollTop
      setScrolled(scrollPosition > 50)

      // Check each section's visibility
      const checkVisibility = (ref, sectionId) => {
        if (ref.current) {
          const rect = ref.current.getBoundingClientRect()
          const isVisible = rect.top < window.innerHeight && rect.bottom >= 0
          setVisibleSections(prev => ({
            ...prev,
            [sectionId]: isVisible
          }))
        }
      }

      checkVisibility(featuresRef, 'features')
      checkVisibility(whatsNewRef, 'whatsNew')
      checkVisibility(testimonialsRef, 'testimonials')
    }, 100)

    content.addEventListener('scroll', handleScroll)
    // Initial check
    handleScroll()

    return () => {
      content.removeEventListener('scroll', handleScroll)
      handleScroll.cancel()
    }
  }, [])

  // Prevent body scroll when modals are open
  useLayoutEffect(() => {
    const handleTouchMove = (e) => {
      if (showTutorial || openSpeedDial) {
        e.preventDefault()
      }
    }

    document.body.style.overflow = (showTutorial || openSpeedDial) ? 'hidden' : ''
    document.addEventListener('touchmove', handleTouchMove, { passive: false })

    return () => {
      document.body.style.overflow = ''
      document.removeEventListener('touchmove', handleTouchMove)
    }
  }, [showTutorial, openSpeedDial])

  // Scroll to top handler
  const handleScrollToTop = useCallback(() => {
    if (contentRef.current) {
      contentRef.current.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    }
  }, [])

  // Section scroll handler
  const scrollToSection = useCallback((sectionRef) => {
    if (sectionRef.current) {
      const yOffset = -80 // Account for header height
      const element = sectionRef.current
      const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset
      
      contentRef.current?.scrollTo({
        top: y,
        behavior: 'smooth'
      })
    }
  }, [])

  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
    }
  }

  const SectionContainer = ({ children, visible, delay = 0 }) => (
    <Fade 
      in={visible} 
      timeout={ANIMATION_DURATION.md}
      style={{ 
        transitionDelay: `${delay}ms`,
        transitionTimingFunction: TRANSITION_EASING
      }}
    >
      <Box sx={{ opacity: 0, animation: `fadeIn 0.8s ${TRANSITION_EASING} forwards` }}>
        {children}
      </Box>
    </Fade>
  )

  const CardHoverStyles = {
    transform: { xs: 'none', sm: 'translateY(-8px)' },
    boxShadow: theme => `0 12px 28px ${alpha(theme.palette.primary.main, theme.palette.mode === 'light' ? 0.2 : 0.3)}`,
    transition: `all 0.3s ${TRANSITION_EASING}`,
    '& .card-icon': {
      transform: 'scale(1.1)',
      transition: `transform 0.3s ${TRANSITION_EASING}`
    }
  }

  useEffect(() => {
    const handleScroll = debounce(() => {
      const scrollPosition = contentRef.current?.scrollTop || 0
      
      // Parallax effect for hero section
      const heroSection = document.querySelector('.hero-section')
      if (heroSection) {
        const yPos = scrollPosition * 0.5
        heroSection.style.transform = `translateY(${yPos}px)`
      }

      // Fade effects for sections
      const sections = document.querySelectorAll('.animate-section')
      sections.forEach(section => {
        const rect = section.getBoundingClientRect()
        const isVisible = rect.top < window.innerHeight * 0.8
        if (isVisible) {
          section.style.opacity = '1'
          section.style.transform = 'translateY(0)'
        }
      })
    }, 16)

    contentRef.current?.addEventListener('scroll', handleScroll)
    return () => contentRef.current?.removeEventListener('scroll', handleScroll)
  }, [])

  const LoadingAnimation = () => (
    <Box
      sx={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        minHeight: 200,
        animation: `pulse 1.5s ${TRANSITION_EASING} infinite`
      }}
    >
      <CircularProgress />
    </Box>
  )

  const ScrollProgress = () => {
    const [progress, setProgress] = useState(0)

    useEffect(() => {
      const handleScroll = () => {
        const totalHeight = contentRef.current?.scrollHeight - contentRef.current?.clientHeight
        const currentScroll = contentRef.current?.scrollTop
        setProgress((currentScroll / totalHeight) * 100)
      }

      contentRef.current?.addEventListener('scroll', handleScroll)
      return () => contentRef.current?.removeEventListener('scroll', handleScroll)
    }, [])

    return (
      <LinearProgress
        variant="determinate"
        value={progress}
        sx={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          height: 2,
          zIndex: theme.zIndex.appBar + 1,
          backgroundColor: 'transparent',
          '& .MuiLinearProgress-bar': {
            background: `linear-gradient(90deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`
          }
        }}
      />
    )
  }

  return (
    <Box 
      sx={{ 
        height: '100vh',
        width: '100%',
        bgcolor: theme.palette.mode === 'light' ? '#f5f5f5' : '#121212',
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        overflow: 'hidden',
        paddingTop: 'env(safe-area-inset-top)',
        paddingBottom: 'env(safe-area-inset-bottom)',
        paddingLeft: 'env(safe-area-inset-left)',
        paddingRight: 'env(safe-area-inset-right)',
      }}
    >
      {/* Scrollable content container with improved background color */}
      <Box
        ref={contentRef}
        sx={{
          height: '100%',
          width: '100%',
          overflow: 'auto',
          WebkitOverflowScrolling: 'touch',
          scrollBehavior: 'smooth',
          bgcolor: 'inherit',
          [theme.breakpoints.down('sm')]: {
            '&::-webkit-scrollbar': {
              display: 'none'
            },
            scrollbarWidth: 'none',
            msOverflowStyle: 'none',
          },
          [theme.breakpoints.up('sm')]: {
            '&::-webkit-scrollbar': {
              width: '8px',
              background: 'transparent'
            },
            '&::-webkit-scrollbar-thumb': {
              background: theme.palette.mode === 'light' 
                ? alpha(theme.palette.primary.main, 0.2)
                : alpha(theme.palette.primary.main, 0.3),
              borderRadius: '4px',
              '&:hover': {
                background: theme.palette.mode === 'light'
                  ? alpha(theme.palette.primary.main, 0.3)
                  : alpha(theme.palette.primary.main, 0.4)
              }
            }
          }
        }}
      >
        {/* Hero Section with improved mobile spacing */}
        <Box
          sx={{
            minHeight: {
              xs: `calc(100vh - ${HEADER_HEIGHT.xs}px)`,
              sm: `calc(100vh - ${HEADER_HEIGHT.sm}px)`
            },
            display: 'flex',
            alignItems: 'center',
            pt: { 
              xs: `calc(${HEADER_HEIGHT.xs}px + ${theme.spacing(2)})`,
              sm: `calc(${HEADER_HEIGHT.sm}px + ${theme.spacing(4)})` 
            },
            pb: MOBILE_SPACING,
            px: MOBILE_SPACING,
            position: 'relative',
            overflow: 'hidden'
          }}
        >
          <Container maxWidth="lg">
            <Grid container spacing={{ xs: 4, md: 6 }} alignItems="center">
              {/* Hero content - Left column */}
              <Grid item xs={12} md={6}>
                <Fade 
                  in 
                  timeout={ANIMATION_DURATION.md}
                  style={{ transitionTimingFunction: TRANSITION_EASING }}
                >
                  <Box>
                    {/* Logo animation */}
                    <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',
                        },
                        animation: `pulse 2s ${TRANSITION_EASING} infinite`,
                        '@keyframes pulse': {
                          '0%': { transform: 'scale(1)' },
                          '50%': { transform: 'scale(1.05)' },
                          '100%': { transform: 'scale(1)' }
                        }
                      }}
                    >
                      <Box sx={{ position: 'relative' }}>
                        <Analytics 
                          sx={{ 
                            fontSize: { xs: 48, md: 56 },
                            color: theme.palette.primary.main,
                            transform: 'rotate(-10deg)',
                            position: 'absolute',
                            left: '-20px'
                          }} 
                        />
                        <Assessment 
                          sx={{ 
                            fontSize: { xs: 48, md: 56 },
                            color: alpha(theme.palette.primary.main, 0.7),
                            position: 'absolute',
                            right: '-20px'
                          }} 
                        />
                      </Box>
                    </Box>

                    {/* Title with gradient animation */}
                    <Typography
                      variant="h1"
                      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 },
                        '&::after': {
                          content: '""',
                          position: 'absolute',
                          bottom: -4,
                          left: 0,
                          width: '100%',
                          height: 4,
                          background: `linear-gradient(90deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,
                          animation: `gradientShift 3s ${TRANSITION_EASING} infinite`
                        },
                        '@keyframes gradientShift': {
                          '0%': { backgroundPosition: '0% 50%' },
                          '50%': { backgroundPosition: '100% 50%' },
                          '100%': { backgroundPosition: '0% 50%' }
                        }
                      }}
                    >
                      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%)`,
                          WebkitBackgroundClip: 'text',
                          WebkitTextFillColor: 'transparent'
                        }}
                      >
                        Analytics Platform
                      </Box>
                    </Typography>

                    {/* Description */}
                    <Typography
                      variant="h5"
                      color="text.secondary"
                      sx={{
                        mb: { xs: 3, md: 4 },
                        fontSize: { xs: '1rem', sm: '1.25rem' },
                        textAlign: { xs: 'center', md: 'left' },
                        ml: { xs: 0, md: 4 }
                      }}
                    >
                      Advanced portfolio analysis and comparison tools to optimize your investments
                      with real-time data and comprehensive metrics.
                    </Typography>

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

              {/* Statistics Cards - Right column */}
              <Grid item xs={12} md={6}>
                <Grid container spacing={3}>
                  {statistics.map((stat, index) => (
                    <Grid item xs={12} sm={4} key={stat.label}>
                      <Zoom 
                        in 
                        timeout={ANIMATION_DURATION.md + index * 200}
                        style={{ 
                          transitionDelay: `${index * 100}ms`,
                          transitionTimingFunction: TRANSITION_EASING
                        }}
                      >
                        <Paper
                          elevation={1}
                          sx={{
                            p: 3,
                            height: '100%',
                            borderRadius: 2,
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            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)}`,
                            transition: 'transform 0.3s ease-in-out',
                            '&:hover': {
                              transform: 'translateY(-8px)'
                            }
                          }}
                        >
                          <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' },
                              mb: 1
                            }}
                          >
                            {stat.value}
                          </Typography>
                          <Typography 
                            variant="subtitle1"
                            color="text.secondary"
                            align="center"
                          >
                            {stat.label}
                          </Typography>
                        </Paper>
                      </Zoom>
                    </Grid>
                  ))}
                </Grid>
              </Grid>
            </Grid>
          </Container>
        </Box>

        {/* What's New Section */}
        <Box
          ref={whatsNewRef}
          id="whatsNew"
          sx={{ 
            py: SECTION_SPACING,
            px: MOBILE_SPACING,
            scrollMarginTop: {
              xs: HEADER_HEIGHT.xs + 16,
              sm: HEADER_HEIGHT.sm + 24
            }
          }}
        >
          <Container maxWidth="lg">
            <SectionHeader
              title="What's New"
              subtitle="Latest updates and improvements to enhance your portfolio analysis experience"
              visible={whatsNewVisible}
            />
            
            <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}>
                  <Box sx={{ position: 'relative', pt: 2 }}>
                    <Grow
                      in={whatsNewVisible}
                      timeout={800 + index * 200}
                      style={{
                        transformOrigin: 'center top'
                      }}
                    >
                      <Card
                        sx={{
                          height: '100%',
                          borderRadius: { xs: 2, sm: 4 },
                          position: 'relative',
                          transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                          '&:hover': {
                            transform: { xs: 'none', sm: 'translateY(-8px)' },
                            boxShadow: `0 12px 28px ${alpha(item.color, theme.palette.mode === 'light' ? 0.2 : 0.3)}`,
                          }
                        }}
                      >
                        <Box
                          sx={{
                            position: 'absolute',
                            top: -10,
                            right: 16,
                            zIndex: 10,
                            pointerEvents: 'none',
                          }}
                        >
                          <Chip
                            label={item.tag}
                            size="small"
                            sx={{
                              fontWeight: 'bold',
                              px: 1,
                              height: 24,
                              backgroundColor: item.tag === 'New' 
                                ? theme.palette.success.main
                                : item.tag === 'Updated'
                                  ? theme.palette.primary.main
                                  : theme.palette.warning.main,
                              color: '#fff',
                              boxShadow: theme => `0 4px 12px ${alpha(
                                item.tag === 'New' 
                                  ? theme.palette.success.main 
                                  : item.tag === 'Updated'
                                    ? theme.palette.primary.main
                                    : theme.palette.warning.main,
                                0.25
                              )}`,
                              border: '2px solid',
                              borderColor: theme.palette.background.paper,
                              '& .MuiChip-label': {
                                px: 1,
                                lineHeight: '20px',
                              }
                            }}
                          />
                        </Box>

                        <CardContent 
                          sx={{ 
                            p: { xs: 2.5, sm: 3 },
                            '&:last-child': { pb: { xs: 2.5, sm: 3 } }
                          }}
                        >
                          <Box
                            sx={{
                              display: 'flex',
                              alignItems: 'center',
                              mb: 2
                            }}
                          >
                            <Avatar
                              className="whats-new-icon"
                              sx={{
                                bgcolor: alpha(item.color, 0.1),
                                color: item.color,
                                width: 56,
                                height: 56,
                                mb: 2,
                                transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                '&:hover': {
                                  transform: 'scale(1.1)',
                                  bgcolor: alpha(item.color, theme.palette.mode === 'light' ? 0.15 : 0.25),
                                }
                              }}
                            >
                              <item.icon sx={{ fontSize: 28 }} />
                            </Avatar>
                          </Box>
                          <Typography
                            variant="h5"
                            gutterBottom
                            fontWeight="bold"
                            sx={{
                              fontSize: { xs: '1.25rem', sm: '1.5rem' }
                            }}
                          >
                            {item.title}
                          </Typography>
                          <Typography
                            color="text.secondary"
                            sx={{ 
                              lineHeight: 1.6,
                              fontSize: { xs: '0.875rem', sm: '1rem' }
                            }}
                          >
                            {item.description}
                          </Typography>
                        </CardContent>
                      </Card>
                    </Box>
                  </Grid>
              ))}
            </Grid>
          </Container>
        </Box>

        {/* Features Section */}
        <Box
          ref={featuresRef}
          id="features"
          sx={{ 
            py: SECTION_SPACING,
            px: MOBILE_SPACING,
            scrollMarginTop: {
              xs: HEADER_HEIGHT.xs + 16,
              sm: HEADER_HEIGHT.sm + 24
            }
          }}
        >
          <Container maxWidth="lg">
            <SectionHeader
              title="Features"
              subtitle="Powerful tools and analytics to optimize your investment strategy"
              visible={featuresVisible}
            />
            <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}>
                  <Fade 
                    in={featuresVisible} 
                    timeout={800 + index * 200}
                    style={{ transformOrigin: 'center top' }}
                  >
                    <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>
                  </Fade>
                </Grid>
              ))}
            </Grid>
          </Container>
        </Box>

        {/* Testimonials Section */}
        <Box
          ref={testimonialsRef}
          id="testimonials"
          sx={{ 
            py: SECTION_SPACING,
            px: MOBILE_SPACING,
            scrollMarginTop: {
              xs: HEADER_HEIGHT.xs + 16,
              sm: HEADER_HEIGHT.sm + 24
            }
          }}
        >
          <Container maxWidth="lg">
            <SectionHeader
              title="What Our Users Say"
              subtitle="Trusted by investment professionals worldwide to deliver accurate insights and powerful analytics"
              visible={testimonialsVisible}
            />
            
            <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}>
                  <Fade in={testimonialsVisible} timeout={1000 + index * 200}>
                    <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]
                          },
                          '& .testimonial-avatar': {
                            transform: 'scale(1.1)',
                          }
                        }
                      }}
                    >
                      <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>
                  </Fade>
                </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>
          </Container>
        </Box>

        {/* Improved mobile SpeedDial and ScrollToTop positioning */}
        <Zoom in={scrolled}>
          <Box
            onClick={handleScrollToTop}
            sx={{
              position: 'fixed',
              bottom: {
                xs: 'max(140px, env(safe-area-inset-bottom) + 140px)',
                sm: 32
              },
              right: {
                xs: 'max(16px, env(safe-area-inset-right) + 16px)',
                sm: 32
              },
              zIndex: theme.zIndex.speedDial + 1
            }}
          >
            <Fab
              color="primary"
              size="medium"
              aria-label="scroll to top"
              sx={{
                boxShadow: `0 8px 16px ${alpha(theme.palette.primary.main, 0.25)}`,
                '&:hover': {
                  boxShadow: `0 12px 24px ${alpha(theme.palette.primary.main, 0.35)}`
                }
              }}
            >
              <KeyboardArrowUp />
            </Fab>
          </Box>
        </Zoom>

        <SpeedDial
          ariaLabel="Quick actions"
          sx={{ 
            position: 'fixed', 
            bottom: {
              xs: 'max(16px, env(safe-area-inset-bottom) + 16px)',
              sm: 32
            },
            right: {
              xs: 'max(16px, env(safe-area-inset-right) + 16px)',
              sm: 32
            },
            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)}
          FabProps={{
            sx: {
              bgcolor: theme.palette.primary.main,
              '&:hover': {
                bgcolor: theme.palette.primary.dark
              }
            }
          }}
        >
          <SpeedDialAction
            icon={<Help />}
            tooltipTitle="Start Tutorial"
            onClick={() => handleSpeedDialAction('tutorial')}
          />
          <SpeedDialAction
            icon={<PlayArrow />}
            tooltipTitle="Quick Start"
            onClick={() => handleSpeedDialAction('start')}
          />
        </SpeedDial>

        {/* Improved Backdrop for SpeedDial */}
        <Backdrop 
          open={openSpeedDial} 
          sx={{ 
            zIndex: theme.zIndex.speedDial - 1,
            backgroundColor: alpha(theme.palette.background.default, 0.7),
            backdropFilter: 'blur(4px)'
          }}
          onClick={() => setOpenSpeedDial(false)}
        />

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

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

        {/* Footer with improved mobile spacing */}
        <Box 
          component="footer" 
          sx={{ 
            py: { xs: 4, sm: 6 },
            px: MOBILE_SPACING,
            bgcolor: theme.palette.mode === 'light' 
              ? alpha(theme.palette.primary.main, 0.03)
              : alpha(theme.palette.primary.main, 0.1),
            borderTop: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
            mt: 'auto',
            width: '100%',
            position: 'relative',
            paddingBottom: {
              xs: 'max(80px, env(safe-area-inset-bottom) + 80px)',
              sm: theme.spacing(6)
            }
          }}
        >
          <Container 
            maxWidth="lg"
            sx={{
              display: 'flex',
              flexDirection: 'column',
              gap: { xs: 4, sm: 6 }
            }}
          >
            <Grid 
              container 
              spacing={{ xs: 3, md: 4 }}
              alignItems="flex-start"
              justifyContent="space-between"
            >
              <Grid item xs={12} md={4}>
                <Stack spacing={2}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box
                      sx={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: 40,
                        height: 40,
                        borderRadius: 2,
                        bgcolor: alpha(theme.palette.primary.main, 0.1),
                      }}
                    >
                      <Analytics sx={{ color: theme.palette.primary.main }} />
                    </Box>
                    <Typography variant="h6" fontWeight="bold">
                      Portfolio Analytics
                    </Typography>
                  </Box>
                  <Typography 
                    variant="body2" 
                    color="text.secondary" 
                    sx={{ 
                      maxWidth: 300,
                      display: { xs: 'none', md: 'block' }
                    }}
                  >
                    Advanced portfolio analysis tools for modern investors. Make data-driven decisions with confidence.
                  </Typography>
                </Stack>
              </Grid>
              
              <Grid item xs={12} md={8}>
                <Stack
                  direction={{ xs: 'column', sm: 'row' }}
                  justifyContent={{ xs: 'center', sm: 'flex-end' }}
                  alignItems="center"
                  spacing={{ xs: 2, sm: 4 }}
                >
                  {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',
                            transform: 'translateY(-2px)',
                          },
                          transition: 'all 0.2s ease-in-out'
                        }}
                      >
                        <Icon />
                      </IconButton>
                    </Tooltip>
                  ))}
                </Stack>
              </Grid>
            </Grid>

            <Divider sx={{ opacity: 0.1 }} />

            <Box 
              sx={{ 
                display: 'flex',
                flexDirection: { xs: 'column', sm: 'row' },
                justifyContent: 'space-between',
                alignItems: 'center',
                gap: { xs: 2, sm: 0 }
              }}
            >
              <Typography
                variant="body2"
                color="text.secondary"
                sx={{ 
                  textAlign: { xs: 'center', sm: 'left' }
                }}
              >
                © {new Date().getFullYear()} Portfolio Analytics. All rights reserved.
              </Typography>
              
              <Stack 
                direction="row" 
                spacing={2}
                sx={{
                  justifyContent: { xs: 'center', sm: 'flex-end' }
                }}
              >
                <Button
                  variant="text"
                  color="inherit"
                  size="small"
                  sx={{ color: 'text.secondary' }}
                >
                  Privacy Policy
                </Button>
                <Button
                  variant="text"
                  color="inherit"
                  size="small"
                  sx={{ color: 'text.secondary' }}
                >
                  Terms of Service
                </Button>
              </Stack>
            </Box>
          </Container>
        </Box>
      </Box>
    </Box>
  )
}

// PropTypes validation
LandingPage.propTypes = {
  onGetStarted: PropTypes.func.isRequired,
  isDarkMode: PropTypes.bool.isRequired,
  onToggleTheme: PropTypes.func.isRequired
}

export default LandingPage

[plugin:vite:react-babel] C:\Users\calvi\Downloads\top\src\components\LandingPage.jsx: Expected corresponding JSX closing tag for <Grow>. (1051:20)
  1054 |             </Grid>
C:/Users/calvi/Downloads/top/src/components/LandingPage.jsx:1051:20
1049|                          </CardContent>
1050|                        </Card>
1051|                      </Box>
   |                      ^
1052|                    </Grid>
1053|                ))}
    at constructor (C:\Users\calvi\Downloads\top\node_modules\@babel\parser\lib\index.js:359:19)
    at JSXParserMixin.raise (C:\Users\calvi\Downloads\top\node_modules\@babel\parser\lib\index.js:3266:19)
    at JSXParserMixin.jsxParseElementAt (C:\Users\calvi\Downloads\top\node_modules\@babel\parser\lib\index.js:6781:16)

fix and also delete redundant/duplicate code, as the code is a bit too messy, and return full updated code