import React, { Component, useState, useMemo, useEffect, useRef } from 'react'
import {
  Box,
  Container,
  Typography,
  TextField,
  Button,
  Paper,
  Grid,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  ButtonGroup,
  Alert,
  Snackbar,
  Menu,
  MenuItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Divider,
  Tooltip as MuiTooltip,
  useTheme,
  ThemeProvider,
  createTheme,
  useMediaQuery,
  Tab,
  Tabs,
  Stepper,
  Step,
  StepLabel,
  StepContent,
  Backdrop,
  Fade,
  Popper,
  ClickAwayListener,
  Chip,
  Slider,
  CircularProgress,
  CssBaseline,
  LinearProgress
} from '@mui/material'
import {
  Delete as DeleteIcon,
  Add as AddIcon,
  Save as SaveIcon,
  Upload as LoadIcon,
  Download as ExportIcon,
  Brightness4 as DarkModeIcon,
  Brightness7 as LightModeIcon,
  Info as InfoIcon,
  AutoGraph as RebalanceIcon,
  Close as CloseIcon,
  Compare as CompareIcon,
  Help as HelpIcon,
  DeleteSweep as DeleteSweepIcon,
  Cached as CachedIcon,
  TrendingUp as TrendingUpIcon,
  Assessment as AssessmentIcon,
  Star as StarIcon,
  Edit as EditIcon,
  Check as CheckIcon,
  ShowChart as ShowChartIcon,
  CompareArrows as CompareArrowsIcon,
  HelpOutline as HelpOutlineIcon,
  Refresh as RefreshIcon,
  Warning as WarningIcon,
  Shield as ShieldIcon,
} from '@mui/icons-material'
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  BarChart,
  Bar,
  ReferenceLine,
  ScatterChart,
  Scatter
} from 'recharts'
import { alpha } from '@mui/material/styles';
import { styled } from '@mui/material/styles';

// Add this constant at the top of the file, after imports
const COLORS = [
  '#FF6B6B',  // Coral Red
  '#4ECDC4',  // Turquoise
  '#FFD93D',  // Yellow
  '#95A5A6',  // Gray
  '#8E44AD',  // Purple
  '#E67E22',  // Orange
  '#2ECC71',  // Emerald
  '#E74C3C',  // Red
  '#3498DB',  // Blue
  '#F1C40F'   // Gold
];

const formatValue = (value, format) => {
  if (value == null) return 'N/A';
  try {
    switch (format) {
      case 'currency':
        return `$${value.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
      case 'percent':
        return `${(value * 100).toFixed(2)}%`;
      case 'decimal':
        return value.toFixed(2);
      case 'ratio':
        return value.toFixed(2);
      default:
        return value.toString();
    }
  } catch (err) {
    console.error(`Error formatting value: ${value} with format: ${format}`, err);
    return 'N/A';
  }
};

class ErrorBoundary extends Component {
  constructor(props) {
    super(props)
    this.state = { hasError: false, error: null, errorInfo: null }
  }

  static getDerivedStateFromError(error) {
    return { hasError: true }
  }

  componentDidCatch(error, errorInfo) {
    this.setState({
      error: error,
      errorInfo: errorInfo
    })
    
    // You could also log the error to an error reporting service here
    console.error('Error caught by boundary:', error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      return (
        <Box sx={{ p: 3, textAlign: 'center' }}>
          <Paper sx={{ p: 3, maxWidth: 600, mx: 'auto' }}>
            <Typography variant="h5" color="error" gutterBottom>
              Something went wrong
            </Typography>
            <Typography variant="body1" gutterBottom>
              The application encountered an unexpected error. Please try refreshing the page.
            </Typography>
            <Button
              variant="contained"
              onClick={() => window.location.reload()}
              sx={{ mt: 2 }}
            >
              Refresh Page
            </Button>
            {process.env.NODE_ENV === 'development' && (
              <Box sx={{ mt: 3, textAlign: 'left' }}>
                <Typography variant="subtitle2" color="error">
                  {this.state.error && this.state.error.toString()}
                </Typography>
                <Typography variant="caption" component="pre" sx={{ mt: 1 }}>
                  {this.state.errorInfo && this.state.errorInfo.componentStack}
                </Typography>
              </Box>
            )}
          </Paper>
        </Box>
      )
    }

    return this.props.children
  }
}

function Tutorial({ open, onClose }) {
  const [activeStep, setActiveStep] = useState(0)

  const tutorialSteps = [
    {
      label: 'Create Portfolio',
      description: 'Start by adding stocks to your portfolio. Enter the ticker symbol and allocation weight for each stock. The total weight must sum to 100%.',
    },
    {
      label: 'Set Parameters',
      description: 'Choose a benchmark (default is SPY) and select a start date for backtesting. You can use the preset date ranges or enter a custom date.',
    },
    {
      label: 'Run Backtest',
      description: 'Click "Run Backtest" to analyze your portfolio. The system will calculate performance metrics and compare your portfolio against the benchmark.',
    },
    {
      label: 'Analyze Results',
      description: 'View your results in three sections: Performance Metrics, Attribution Analysis, and Rebalancing Analysis. Each tab provides different insights into your portfolio\'s performance.',
    },
    {
      label: 'Save and Export',
      description: 'You can save your portfolio for future use or export the results to CSV format for further analysis.',
    },
  ]

  const handleNext = () => {
    setActiveStep((prev) => prev + 1)
  }

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

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
    >
      <DialogTitle>
        How to Use the Portfolio Backtester
        <IconButton
          onClick={onClose}
          sx={{ position: 'absolute', right: 8, top: 8 }}
        >
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <DialogContent>
        <Stepper activeStep={activeStep} orientation="vertical">
          {tutorialSteps.map((step, index) => (
            <Step key={step.label}>
              <StepLabel>{step.label}</StepLabel>
              <StepContent>
                <Typography>{step.description}</Typography>
                <Box sx={{ mb: 2 }}>
                  <div>
                    <Button
                      variant="contained"
                      onClick={handleNext}
                      sx={{ mt: 1, mr: 1 }}
                    >
                      {index === tutorialSteps.length - 1 ? 'Finish' : 'Continue'}
                    </Button>
                    <Button
                      disabled={index === 0}
                      onClick={handleBack}
                      sx={{ mt: 1, mr: 1 }}
                    >
                      Back
                    </Button>
                  </div>
                </Box>
              </StepContent>
            </Step>
          ))}
        </Stepper>
      </DialogContent>
    </Dialog>
  )
}

function HelpTooltip({ title, children }) {
  const [anchorEl, setAnchorEl] = useState(null)

  const handleClick = (event) => {
    setAnchorEl(anchorEl ? null : event.currentTarget)
  }

  const open = Boolean(anchorEl)

  return (
    <ClickAwayListener onClickAway={() => setAnchorEl(null)}>
      <Box sx={{ display: 'inline' }}>
        <IconButton size="small" onClick={handleClick}>
          <HelpIcon fontSize="small" />
        </IconButton>
        <Popper
          open={open}
          anchorEl={anchorEl}
          placement="top"
          transition
          sx={{ zIndex: 1500 }}
        >
          {({ TransitionProps }) => (
            <Fade {...TransitionProps} timeout={350}>
              <Paper sx={{ p: 2, maxWidth: 300 }}>
                <Typography variant="body2">{title}</Typography>
              </Paper>
            </Fade>
          )}
        </Popper>
      </Box>
    </ClickAwayListener>
  )
}

function LoadingOverlay() {
  return (
    <Backdrop
      sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
      open={true}
    >
      <Box sx={{ textAlign: 'center' }}>
        <CircularProgress color="inherit" />
        <Typography sx={{ mt: 2 }}>Processing...</Typography>
      </Box>
    </Backdrop>
  );
}

// Add loading state component
const LoadingState = ({ message = "Processing..." }) => (
  <Box 
    sx={{ 
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      bgcolor: 'rgba(0,0,0,0.3)',
      backdropFilter: 'blur(4px)',
      zIndex: 1200
    }}
  >
    <Paper 
      sx={{ 
        p: 3, 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center',
        gap: 2
      }}
    >
      <CircularProgress />
      <Typography>{message}</Typography>
    </Paper>
  </Box>
);

// Add transitions for smoother UI updates
const ResultsSection = ({ children }) => (
  <Fade in={Boolean(children)} timeout={500}>
    <Box>{children}</Box>
  </Fade>
);

// First, let's organize the components into logical sections
const PortfolioSection = ({ 
  portfolio, 
  handleInputChange, 
  handleRemoveStock, 
  handleAddStock,
  isMobile, 
  helpTexts,
  isPortfolioB = false,  // Add this prop
  title = "Portfolio Composition"  // Add this prop
}) => (
  <Paper sx={{ p: 2, mb: 2 }}>
    <Box sx={{ display: 'flex', alignItems: 'center', mb: 2, justifyContent: 'space-between' }}>
      <Box sx={{ display: 'flex', alignItems: 'center' }}>
        <Typography variant="h6">{title}</Typography>
        <HelpTooltip title={helpTexts.portfolio} />
      </Box>
      <Button
        startIcon={<AddIcon />}
        onClick={handleAddStock}
        size={isMobile ? "small" : "medium"}
        variant="outlined"
      >
        Add Stock
      </Button>
    </Box>
    
    <Grid container spacing={isMobile ? 1 : 2}>
      {portfolio.map((stock, index) => (
        <Grid item xs={12} key={index} container spacing={1} alignItems="center">
          <Grid item xs={isMobile ? 12 : 5}>
            <TextField
              fullWidth
              label="Ticker"
              value={stock.ticker}
              onChange={(e) => handleInputChange(index, 'ticker', e.target.value)}
              size={isMobile ? "small" : "medium"}
            />
          </Grid>
          <Grid item xs={isMobile ? 10 : 5}>
            <TextField
              fullWidth
              label="Weight (%)"
              type="number"
              value={stock.weight}
              onChange={(e) => handleInputChange(index, 'weight', e.target.value)}
              size={isMobile ? "small" : "medium"}
            />
          </Grid>
          <Grid item xs={isMobile ? 2 : 2}>
            <IconButton 
              onClick={() => handleRemoveStock(index)} 
              disabled={portfolio.length === 1}
              size={isMobile ? "small" : "medium"}
              color="error"
            >
              <DeleteIcon />
            </IconButton>
          </Grid>
        </Grid>
      ))}
    </Grid>
  </Paper>
);

const BacktestParametersSection = ({ 
  benchmark, 
  startDate, 
  transactionCost,
  setBenchmark,
  setStartDate,
  setTransactionCost,
  handleDatePreset,
  datePresets,
  isMobile,
  helpTexts,
  showBenchmark = true  // Add this prop
}) => (
  <Paper sx={{ p: 2, mb: 2 }}>
    <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
      <Typography variant="h6">Backtest Parameters</Typography>
      <HelpTooltip title={helpTexts.dateRange} />
    </Box>
    
    <Grid container spacing={2}>
      <Grid item xs={12}>
        <Typography variant="subtitle2" gutterBottom>Date Range Presets</Typography>
        <ButtonGroup 
          variant="outlined" 
          size={isMobile ? "small" : "medium"}
          sx={{ 
            mb: 2,
            display: 'flex',
            flexWrap: 'wrap',
            gap: 1,
            '& > button': {
              flexGrow: isMobile ? 1 : 0
            }
          }}
        >
          {Object.entries(datePresets).map(([label, days]) => (
            <Button key={label} onClick={() => handleDatePreset(days)}>
              {label}
            </Button>
          ))}
        </ButtonGroup>
      </Grid>
      
      {showBenchmark && (
        <Grid item xs={12} md={4}>
          <TextField
            fullWidth
            label="Benchmark"
            value={benchmark}
            onChange={(e) => setBenchmark(e.target.value)}
            size={isMobile ? "small" : "medium"}
            helperText="e.g., SPY for S&P 500"
          />
        </Grid>
      )}
      
      <Grid item xs={12} md={showBenchmark ? 4 : 6}>
        <TextField
          fullWidth
          type="date"
          label="Start Date"
          value={startDate}
          onChange={(e) => setStartDate(e.target.value)}
          InputLabelProps={{ shrink: true }}
          size={isMobile ? "small" : "medium"}
        />
      </Grid>
      
      <Grid item xs={12} md={showBenchmark ? 4 : 6}>
        <TextField
          fullWidth
          type="number"
          label="Transaction Cost (%)"
          value={transactionCost * 100}
          onChange={(e) => setTransactionCost(parseFloat(e.target.value) / 100)}
          InputProps={{
            inputProps: { min: 0, max: 100, step: 0.01 }
          }}
          helperText="Cost per trade as percentage"
          size={isMobile ? "small" : "medium"}
        />
      </Grid>
    </Grid>
  </Paper>
);

// Add this theme configuration at the top of the file after imports
const getTheme = (darkMode) => createTheme({
  palette: {
    mode: darkMode ? 'dark' : 'light',
    primary: {
      main: darkMode ? '#90caf9' : '#1976d2',
      light: darkMode ? '#b3e5fc' : '#42a5f5',
      dark: darkMode ? '#648dae' : '#1565c0',
    },
    secondary: {
      main: darkMode ? '#f48fb1' : '#dc004e',
      light: darkMode ? '#f6a5c0' : '#e33371',
      dark: darkMode ? '#bf5f82' : '#9a0036',
    },
    error: {
      main: darkMode ? '#f44336' : '#d32f2f',
      light: darkMode ? '#e57373' : '#ef5350',
      dark: darkMode ? '#d32f2f' : '#c62828',
    },
    warning: {
      main: darkMode ? '#ffa726' : '#ed6c02',
      light: darkMode ? '#ffb74d' : '#ff9800',
      dark: darkMode ? '#f57c00' : '#e65100',
    },
    info: {
      main: darkMode ? '#29b6f6' : '#0288d1',
      light: darkMode ? '#4fc3f7' : '#03a9f4',
      dark: darkMode ? '#0288d1' : '#01579b',
    },
    success: {
      main: darkMode ? '#66bb6a' : '#2e7d32',
      light: darkMode ? '#81c784' : '#4caf50',
      dark: darkMode ? '#388e3c' : '#1b5e20',
    },
    background: {
      default: darkMode ? '#121212' : '#f5f5f5',
      paper: darkMode ? '#1e1e1e' : '#ffffff',
      elevation1: darkMode ? '#242424' : '#ffffff',
      elevation2: darkMode ? '#2a2a2a' : '#f5f5f5',
    },
    text: {
      primary: darkMode ? '#ffffff' : '#000000',
      secondary: darkMode ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.6)',
      disabled: darkMode ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.38)',
    },
    divider: darkMode ? 'rgba(255, 255, 255, 0.12)' : 'rgba(0, 0, 0, 0.12)',
    action: {
      active: darkMode ? '#ffffff' : '#000000',
      hover: darkMode ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.04)',
      selected: darkMode ? 'rgba(255, 255, 255, 0.16)' : 'rgba(0, 0, 0, 0.08)',
      disabled: darkMode ? 'rgba(255, 255, 255, 0.3)' : 'rgba(0, 0, 0, 0.26)',
      disabledBackground: darkMode ? 'rgba(255, 255, 255, 0.12)' : 'rgba(0, 0, 0, 0.12)',
    },
  },
  typography: {
    fontFamily: '"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
    h1: {
      fontSize: '2.5rem',
      fontWeight: 600,
      lineHeight: 1.2,
    },
    h2: {
      fontSize: '2rem',
      fontWeight: 600,
      lineHeight: 1.3,
    },
    h3: {
      fontSize: '1.75rem',
      fontWeight: 600,
      lineHeight: 1.3,
    },
    h4: {
      fontSize: '1.5rem',
      fontWeight: 600,
      lineHeight: 1.4,
    },
    h5: {
      fontSize: '1.25rem',
      fontWeight: 600,
      lineHeight: 1.4,
    },
    h6: {
      fontSize: '1rem',
      fontWeight: 600,
      lineHeight: 1.4,
    },
    subtitle1: {
      fontSize: '1rem',
      fontWeight: 500,
      lineHeight: 1.5,
    },
    subtitle2: {
      fontSize: '0.875rem',
      fontWeight: 500,
      lineHeight: 1.57,
    },
    body1: {
      fontSize: '1rem',
      lineHeight: 1.5,
    },
    body2: {
      fontSize: '0.875rem',
      lineHeight: 1.43,
    },
    button: {
      textTransform: 'none',
      fontWeight: 500,
    },
    caption: {
      fontSize: '0.75rem',
      lineHeight: 1.66,
    },
  },
  shape: {
    borderRadius: 8,
  },
  transitions: {
    duration: {
      shortest: 150,
      shorter: 200,
      short: 250,
      standard: 300,
      complex: 375,
      enteringScreen: 225,
      leavingScreen: 195,
    },
  },
  components: {
    MuiPaper: {
      styleOverrides: {
        root: ({ theme }) => ({
          transition: theme.transitions.create(['background-color', 'box-shadow']),
          backgroundImage: 'none',
        }),
      },
    },
    MuiButton: {
      styleOverrides: {
        root: {
          textTransform: 'none',
          borderRadius: 8,
        },
      },
    },
    MuiCard: {
      styleOverrides: {
        root: {
          borderRadius: 12,
        },
      },
    },
    MuiTableCell: {
      styleOverrides: {
        root: ({ theme }) => ({
          borderBottom: `1px solid ${theme.palette.divider}`,
        }),
      },
    },
    MuiTooltip: {
      styleOverrides: {
        tooltip: {
          fontSize: '0.75rem',
          padding: '8px 12px',
          borderRadius: 4,
        },
      },
    },
    MuiChip: {
      styleOverrides: {
        root: {
          borderRadius: 6,
        },
      },
    },
  },
});

// Update the correlation matrix color function
const getCorrelationColor = (value, isDarkMode) => {
  if (value === 1 && isDarkMode) return '#333333';  // Darker diagonal in dark mode
  if (value === 1 && !isDarkMode) return '#f0f0f0'; // Lighter diagonal in light mode
  
  const intensity = Math.abs(value) * 100;
  if (isDarkMode) {
    return value > 0 
      ? `hsl(120, ${intensity}%, ${15 + (intensity * 0.3)}%)`  // Green scale
      : `hsl(0, ${intensity}%, ${15 + (intensity * 0.3)}%)`;   // Red scale
  } else {
    return value > 0 
      ? `hsl(120, ${intensity}%, ${100 - (intensity * 0.5)}%)` // Green scale
      : `hsl(0, ${intensity}%, ${100 - (intensity * 0.5)}%)`;  // Red scale
  }
};

// Add metric descriptions object
const metricDescriptions = {
  // Performance Metrics
  cagr: 'Compound Annual Growth Rate - The geometric mean annual return over the investment period.',
  annual_volatility: 'Standard deviation of returns, annualized to measure risk/variability.',
  max_drawdown: 'Largest peak-to-trough decline in portfolio value.',
  sharpe_ratio: 'Risk-adjusted return relative to risk-free rate. Higher is better.',
  sortino_ratio: 'Similar to Sharpe ratio but only penalizes downside volatility.',
  calmar_ratio: 'Annual return divided by maximum drawdown. Higher values indicate better risk-adjusted performance.',
  
  // Risk Metrics
  beta: 'Measure of portfolio volatility compared to the market. >1 means more volatile than market.',
  alpha: 'Excess return compared to what would be predicted by CAPM. Positive is better.',
  r_squared: 'Percentage of portfolio returns explained by benchmark movements.',
  tracking_error: 'Standard deviation of difference between portfolio and benchmark returns.',
  information_ratio: 'Active return divided by tracking error. Higher values indicate better risk-adjusted active returns.',
  
  // Statistical Metrics
  arithmetic_mean: 'Simple average of returns.',
  geometric_mean: 'Compound rate of return that represents the actual experienced return.',
  downside_deviation: 'Standard deviation of negative returns only.',
  var_historical: 'Maximum loss expected at 95% confidence level based on historical data.',
  cvar: 'Average loss when losses exceed VaR (also known as Expected Shortfall).',
  
  // Attribution Metrics
  benchmark_correlation: 'Degree of co-movement with benchmark. 1 is perfect correlation.',
  active_return: 'Portfolio return minus benchmark return.',
  sector_attribution: 'Contribution to return from sector allocation decisions.',
  factor_attribution: 'Contribution to return from various risk factors.',
  
  // Rebalancing Metrics
  transaction_cost: 'Cost incurred when buying or selling securities.',
  rebalancing_impact: 'Effect of different rebalancing frequencies on returns and risk.',
  turnover: 'Percentage of portfolio value that is traded annually.',
  cost_percentage: 'Transaction costs as a percentage of portfolio value.'
};

// Add a custom tooltip component
const MetricTooltip = ({ title, description }) => (
  <MuiTooltip
    title={
      <Box sx={{ p: 1 }}>
        <Typography variant="subtitle2" gutterBottom>{title}</Typography>
        <Typography variant="body2">{description}</Typography>
      </Box>
    }
    arrow
    placement="top"
  >
    <InfoIcon fontSize="small" sx={{ ml: 1, color: 'action.active', cursor: 'help' }} />
  </MuiTooltip>
);

// Add a Quick Actions Menu component
const QuickActionsMenu = ({ onAction }) => {
  const actions = [
    { 
      label: 'Load Example Portfolio', 
      icon: <RebalanceIcon />,
      description: 'Load a pre-configured example portfolio',
      action: 'loadExample'
    },
    { 
      label: 'Clear Portfolio', 
      icon: <DeleteSweepIcon />,
      description: 'Clear all current portfolio entries',
      action: 'clear'
    },
    { 
      label: 'Export Results', 
      icon: <ExportIcon />,
      description: 'Export current results to CSV',
      action: 'export'
    },
    { 
      label: 'Clear Cache', 
      icon: <CachedIcon />,
      description: 'Clear cached data for fresh results',
      action: 'clearCache'
    }
  ];

  return (
    <Paper sx={{ p: 2, mb: 2 }}>
      <Typography variant="h6" gutterBottom>Quick Actions</Typography>
      <Grid container spacing={2}>
        {actions.map(({ label, icon, description, action }) => (
          <Grid item xs={6} sm={3} key={action}>
            <Button
              variant="outlined"
              onClick={() => onAction(action)}
              fullWidth
              sx={{ 
                height: '100%', 
                p: 2,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                gap: 1
              }}
            >
              {icon}
              <Typography variant="button">{label}</Typography>
              <Typography 
                variant="caption" 
                color="text.secondary"
                align="center"
              >
                {description}
              </Typography>
            </Button>
          </Grid>
        ))}
      </Grid>
    </Paper>
  );
};

// Add a Portfolio Summary component
const PortfolioSummary = ({ portfolio, totalWeight }) => {
  const validStocks = portfolio.filter(stock => stock.ticker && stock.weight);
  const isValidWeight = Math.abs(totalWeight - 100) <= 0.01;

  return (
    <Paper sx={{ p: 2, mb: 2 }}>
      <Typography variant="h6" gutterBottom>Portfolio Summary</Typography>
      <Grid container spacing={2}>
        <Grid item xs={12} md={4}>
          <Paper 
            elevation={3} 
            sx={{ 
              p: 2, 
              bgcolor: 'background.default',
              borderRadius: 1
            }}
          >
            <Typography variant="subtitle2" color="textSecondary">
              Active Positions
            </Typography>
            <Typography variant="h4">
              {validStocks.length}
            </Typography>
          </Paper>
        </Grid>
        <Grid item xs={12} md={4}>
          <Paper 
            elevation={3} 
            sx={{ 
              p: 2, 
              bgcolor: 'background.default',
              borderRadius: 1
            }}
          >
            <Typography variant="subtitle2" color="textSecondary">
              Total Weight
            </Typography>
            <Typography 
              variant="h4" 
              color={isValidWeight ? 'success.main' : 'error.main'}
            >
              {totalWeight.toFixed(1)}%
            </Typography>
          </Paper>
        </Grid>
        <Grid item xs={12} md={4}>
          <Paper 
            elevation={3} 
            sx={{ 
              p: 2, 
              bgcolor: 'background.default',
              borderRadius: 1
            }}
          >
            <Typography variant="subtitle2" color="textSecondary">
              Status
            </Typography>
            <Chip
              label={isValidWeight ? "Ready" : "Invalid Weights"}
              color={isValidWeight ? "success" : "error"}
              sx={{ mt: 1 }}
            />
          </Paper>
        </Grid>
      </Grid>
    </Paper>
  );
};

// Add a Results Summary component
const ResultsSummary = ({ results }) => {
  if (!results) return null;

  const metrics = results.portfolio_metrics;
  const benchmarkMetrics = results.benchmark_metrics;

  const summaryCards = [
    {
      title: 'Total Return',
      value: ((metrics.end_balance / metrics.start_balance - 1) * 100).toFixed(2) + '%',
      benchmark: ((benchmarkMetrics.end_balance / benchmarkMetrics.start_balance - 1) * 100).toFixed(2) + '%',
      icon: <TrendingUpIcon />,
      color: 'primary'
    },
    {
      title: 'Risk Level',
      value: metrics.annual_volatility > 0.2 ? 'High' : metrics.annual_volatility > 0.1 ? 'Medium' : 'Low',
      benchmark: benchmarkMetrics.annual_volatility > 0.2 ? 'High' : benchmarkMetrics.annual_volatility > 0.1 ? 'Medium' : 'Low',
      icon: <AssessmentIcon />,
      color: metrics.annual_volatility > 0.2 ? 'error' : metrics.annual_volatility > 0.1 ? 'warning' : 'success'
    },
    {
      title: 'Performance',
      value: metrics.sharpe_ratio > 1 ? 'Excellent' : metrics.sharpe_ratio > 0.5 ? 'Good' : 'Poor',
      benchmark: benchmarkMetrics.sharpe_ratio > 1 ? 'Excellent' : benchmarkMetrics.sharpe_ratio > 0.5 ? 'Good' : 'Poor',
      icon: <StarIcon />,
      color: metrics.sharpe_ratio > 1 ? 'success' : metrics.sharpe_ratio > 0.5 ? 'warning' : 'error'
    }
  ];

  return (
    <Paper sx={{ p: 2, mb: 2 }}>
      <Typography variant="h6" gutterBottom>Quick Overview</Typography>
      <Grid container spacing={2}>
        {summaryCards.map(({ title, value, benchmark, icon, color }) => (
          <Grid item xs={12} md={4} key={title}>
            <Paper 
              elevation={3} 
              sx={{ 
                p: 2,
                bgcolor: `${color}.main`,
                color: 'white'
              }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                {icon}
                <Typography variant="subtitle1" sx={{ ml: 1 }}>
                  {title}
                </Typography>
              </Box>
              <Typography variant="h5">
                {value}
              </Typography>
              <Typography variant="caption">
                Benchmark: {benchmark}
              </Typography>
            </Paper>
          </Grid>
        ))}
      </Grid>
    </Paper>
  );
};

// Move all hooks to the top of the App component
function App() {
  // Theme and UI state
  const [darkMode, setDarkMode] = useState(
    window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
  );
  
  // Create theme
  const themeMemo = useMemo(() => getTheme(darkMode), [darkMode]);
  
  // Use themeMemo instead of theme
  const isMobile = useMediaQuery(themeMemo.breakpoints.down('sm'));

  // Portfolio state
  const [portfolio, setPortfolio] = useState([{ ticker: '', weight: '' }]);
  const [portfolioB, setPortfolioB] = useState([{ ticker: '', weight: '' }]);
  const [benchmark, setBenchmark] = useState('SPY');
  const [startDate, setStartDate] = useState(
    new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  );
  const [transactionCost, setTransactionCost] = useState(0.001);

  // Results state
  const [results, setResults] = useState(null);
  const [attribution, setAttribution] = useState(null);
  const [rebalancingResults, setRebalancingResults] = useState(null);
  const [correlationData, setCorrelationData] = useState(null);
  const [comparisonResults, setComparisonResults] = useState(null);
  const [correlationType, setCorrelationType] = useState('pearson');

  // UI control state
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [totalWeight, setTotalWeight] = useState(0);
  const [totalWeightB, setTotalWeightB] = useState(0);
  const [weightError, setWeightError] = useState(false);
  const [selectedTab, setSelectedTab] = useState(0);
  const [tutorialOpen, setTutorialOpen] = useState(false);
  const [comparisonDialogOpen, setComparisonDialogOpen] = useState(false);
  const [comparisonMode, setComparisonMode] = useState('benchmark');
  const [savedPortfolios, setSavedPortfolios] = useState([]);
  const [notification, setNotification] = useState({
    open: false,
    message: '',
    severity: 'info',
    duration: 3000
  });

  // Parameters state
  const [backtestParameters, setBacktestParameters] = useState({
    showBenchmark: true
  });

  // Fix the table row text node issue
  const renderTableRow = (content) => (
    <TableRow>
      <TableCell>{content}</TableCell>
    </TableRow>
  );

  // Move useEffect hooks after all useState hooks
  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleChange = (e) => setDarkMode(e.matches);
    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, []);

  useEffect(() => {
    // Clear results when changing modes
    setResults(null);
    setAttribution(null);
    setRebalancingResults(null);
    setCorrelationData(null);
    setComparisonResults(null);
    
    // Reset selected tab
    setSelectedTab(0);
    
    // Show notification
    setNotification({
      open: true,
      message: `Switched to ${comparisonMode === 'benchmark' ? 'Benchmark Analysis' : 'Portfolio Comparison'} mode`,
      severity: 'info',
      duration: 2000
    });
  }, [comparisonMode]);

  // Fix the alpha reference issue in getMetricColor
  const getMetricColor = (value, isPositive) => {
    if (value === null || value === undefined) return 'inherit';
    return isPositive ? 
      (value >= 0 ? 'success.main' : 'error.main') :
      (value >= 0 ? 'error.main' : 'success.main');
  };

  const metricDescriptions = {
    annual_return: 'The yearly return of the portfolio, annualized from the total return over the period.',
    annual_volatility: 'A measure of the portfolio\'s risk, showing how much the returns fluctuate from the mean.',
    sharpe_ratio: 'Risk-adjusted return metric. Higher is better. Calculated as (return - risk_free_rate) / volatility.',
    sortino_ratio: 'Similar to Sharpe ratio but only considers downside volatility. Higher is better.',
    max_drawdown: 'The maximum observed loss from a peak to a trough. Shows worst-case scenario.',
    beta: 'Measure of portfolio\'s volatility compared to the market. >1 means more volatile than market.',
    alpha: 'Excess return of the portfolio relative to the benchmark. Higher is better.'
  }

  const datePresets = {
    '1M': 30,
    '3M': 90,
    '6M': 180,
    '1Y': 365,
    '3Y': 1095,
    '5Y': 1825,
  }

  const handleDatePreset = (days) => {
    const date = new Date()
    date.setDate(date.getDate() - days)
    setStartDate(date.toISOString().split('T')[0])
  }

  // Fix the validateWeights function
  const validateWeights = () => {
    const sum = portfolio.reduce((acc, stock) => acc + (parseFloat(stock.weight) || 0), 0);
    setTotalWeight(sum);
    setWeightError(Math.abs(sum - 100) > 0.01);
    return Math.abs(sum - 100) <= 0.01;
  };

  // Add validation for second portfolio
  const validateWeightsB = () => {
    const sum = portfolioB.reduce((acc, stock) => acc + (parseFloat(stock.weight) || 0), 0);
    setTotalWeightB(sum);
    return Math.abs(sum - 100) <= 0.01;
  };

  const handleAddStock = () => {
    setPortfolio([...portfolio, { ticker: '', weight: '' }])
  }

  const handleRemoveStock = (index) => {
    const newPortfolio = portfolio.filter((_, i) => i !== index)
    setPortfolio(newPortfolio)
  }

  const validateTicker = async (ticker) => {
    try {
      const response = await fetch('http://localhost:5000/api/validate-ticker', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ticker })
      })
      const data = await response.json()
      return data.valid
    } catch (err) {
      return false
    }
  }

  // Clean up the handleInputChange function
  const handleInputChange = async (index, field, value) => {
    const newPortfolio = [...portfolio];
    newPortfolio[index][field] = value;
    setPortfolio(newPortfolio);
    
    if (field === 'weight') {
      validateWeights();
    } else if (field === 'ticker' && value.trim()) {
      // Debounce ticker validation
      const debounceValidation = setTimeout(async () => {
        const isValid = await validateTicker(value.trim());
        if (!isValid) {
          setNotification({
            open: true,
            message: `Invalid ticker: ${value}`,
            severity: 'warning',
            duration: 4000
          });
        }
      }, 1000);
      return () => clearTimeout(debounceValidation);
    }
  };

  const formatMetricValue = (value, format) => {
    if (value == null) return 'N/A';
    try {
      switch (format) {
        case 'currency':
          return `$${value.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
        case 'percent':
          return `${(value * 100).toFixed(2)}%`;
        case 'ratio':
          return value.toFixed(3);  // More precision for ratios
        case 'decimal':
          return value.toFixed(2);
        default:
          return value.toString();
      }
    } catch (err) {
      console.error(`Error formatting value: ${value} with format: ${format}`, err);
      return 'N/A';
    }
  };

  const getMetricDescription = (key) => {
    const shortDescriptions = {
      annual_return: 'Annualized Return',
      annual_volatility: 'Annualized Volatility',
      sharpe_ratio: 'Sharpe Ratio',
      sortino_ratio: 'Sortino Ratio',
      max_drawdown: 'Maximum Drawdown',
      beta: 'Beta (Market Sensitivity)',
      alpha: 'Alpha (Excess Return)'
    }
    return shortDescriptions[key] || key.replace(/_/g, ' ').toUpperCase()
  }

  const fetchAttribution = async () => {
    try {
      const response = await fetch('http://localhost:5000/api/attribution', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          portfolio: portfolio.map(stock => ({
            ticker: stock.ticker.toUpperCase(),
            weight: parseFloat(stock.weight) / 100
          })),
          benchmark,
          startDate
        })
      })
      
      const data = await response.json()
      if (data.success) {
        setAttribution(data.attribution)
      }
    } catch (err) {
      setNotification({
        open: true,
        message: 'Failed to fetch attribution analysis',
        severity: 'error',
        duration: 5000
      })
    }
  }

  const fetchRebalancingAnalysis = async () => {
    try {
      const response = await fetch('http://localhost:5000/api/rebalance', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          portfolio: portfolio.map(stock => ({
            ticker: stock.ticker.toUpperCase(),
            weight: parseFloat(stock.weight) / 100
          })),
          startDate,
          transactionCost
        })
      });
      
      const data = await response.json();
      if (data.success) {
        setRebalancingResults(data.rebalancing_results);
      }
    } catch (err) {
      setNotification({
        open: true,
        message: 'Failed to fetch rebalancing analysis',
        severity: 'error',
        duration: 5000
      });
    }
  };

  const fetchCorrelationData = async () => {
    try {
      const response = await fetch('http://localhost:5000/api/correlation', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          portfolio: portfolio.map(stock => ({
            ticker: stock.ticker.toUpperCase(),
            weight: parseFloat(stock.weight) / 100
          })),
          startDate
        })
      })
      
      const data = await response.json()
      if (data.success) {
        setCorrelationData(data.correlations)
      }
    } catch (err) {
      setNotification({
        open: true,
        message: 'Failed to fetch correlation data',
        severity: 'error',
        duration: 5000
      })
    }
  }

  const validatePortfolio = () => {
    // Check if any ticker is empty or contains only whitespace
    const hasEmptyTicker = portfolio.some(stock => !stock.ticker.trim());
    if (hasEmptyTicker) {
      setNotification({
        open: true,
        message: 'Please enter valid tickers for all stocks',
        severity: 'error',
        duration: 4000
      });
      return false;
    }

    // Check if weights sum to 100%
    if (!validateWeights()) {
      setNotification({
        open: true,
        message: `Portfolio weights must sum to 100% (current: ${totalWeight}%)`,
        severity: 'error',
        duration: 4000
      });
      return false;
    }

    return true;
  };

  // Clean up the handleBacktest function
  const handleBacktest = async () => {
    if (!validatePortfolio()) return;
    if (comparisonMode === 'portfolio' && !validateWeightsB()) {
      setNotification({
        open: true,
        message: 'Please ensure both portfolios have valid weights',
        severity: 'error',
        duration: 4000
      });
      return;
    }

    setLoading(true);
    setError(null);

    try {
      if (comparisonMode === 'portfolio') {
        // Compare two portfolios directly
        const response = await fetch('http://localhost:5000/api/compare', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            portfolios: [
              {
                name: 'Portfolio A',
                portfolio: portfolio.map(stock => ({
                  ticker: stock.ticker.trim().toUpperCase(),
                  weight: parseFloat(stock.weight)
                }))
              },
              {
                name: 'Portfolio B',
                portfolio: portfolioB.map(stock => ({
                  ticker: stock.ticker.trim().toUpperCase(),
                  weight: parseFloat(stock.weight)
                }))
              }
            ],
            startDate
          })
        });

        const data = await response.json();
        if (data.success) {
          // Clear other results first
          setResults(null);
          setAttribution(null);
          setRebalancingResults(null);
          setCorrelationData(null);
          
          // Set comparison results and force tab switch
          setComparisonResults(data);
          setSelectedTab(5);  // Switch to comparison tab
          
          setNotification({
            open: true,
            message: 'Portfolio comparison completed successfully',
            severity: 'success',
            duration: 3000
          });
        } else {
          throw new Error(data.error || 'Failed to compare portfolios');
        }
      } else {
        // Regular benchmark comparison
        const validPortfolio = portfolio.filter(stock => stock.ticker.trim());
        const requestBody = {
          portfolio: validPortfolio.map(stock => ({
            ticker: stock.ticker.trim().toUpperCase(),
            weight: parseFloat(stock.weight)
          })),
          benchmark: comparisonMode === 'portfolio' ? null : benchmark,
          startDate
        };

        // Make all API calls concurrently
        const [backtestData, attributionData, rebalancingData, correlationData] = 
          await Promise.all([
            fetch('http://localhost:5000/api/backtest', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(requestBody)
            }).then(res => res.json()),
            fetch('http://localhost:5000/api/attribution', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(requestBody)
            }).then(res => res.json()),
            fetch('http://localhost:5000/api/rebalance', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(requestBody)
            }).then(res => res.json()),
            fetch('http://localhost:5000/api/correlation', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(requestBody)
            }).then(res => res.json())
          ]);

        // Check for errors
        if (!backtestData.success) throw new Error(backtestData.error);
        if (!attributionData.success) throw new Error(attributionData.error);
        if (!rebalancingData.success) throw new Error(rebalancingData.error);
        if (!correlationData.success) throw new Error(correlationData.error);

        // Update state
        setResults(backtestData);
        setAttribution(attributionData.attribution);
        setRebalancingResults(rebalancingData.rebalancing_results);
        setCorrelationData(correlationData.correlations);
        setSelectedTab(0);
      }

      setNotification({
        open: true,
        message: 'Analysis completed successfully',
        severity: 'success',
        duration: 3000
      });
    } catch (err) {
      setNotification({
        open: true,
        message: `Analysis failed: ${err.message}`,
        severity: 'error',
        duration: 5000
      });
      // Clear all results on error
      setResults(null);
      setAttribution(null);
      setRebalancingResults(null);
      setCorrelationData(null);
      setComparisonResults(null);
    } finally {
      setLoading(false);
    }
  };

  // Add this component for editing portfolio names
  const EditablePortfolioName = ({ initialName, onSave }) => {
    const [isEditing, setIsEditing] = useState(false);
    const [name, setName] = useState(initialName);
    const inputRef = useRef(null);

    useEffect(() => {
      if (isEditing && inputRef.current) {
        inputRef.current.focus();
      }
    }, [isEditing]);

    const handleSave = () => {
      onSave(name.trim());
      setIsEditing(false);
    };

    const handleKeyPress = (e) => {
      if (e.key === 'Enter') {
        handleSave();
      } else if (e.key === 'Escape') {
        setName(initialName);
        setIsEditing(false);
      }
    };

    return isEditing ? (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <TextField
          ref={inputRef}
          size="small"
          value={name}
          onChange={(e) => setName(e.target.value)}
          onKeyDown={handleKeyPress}
          onBlur={handleSave}
          autoFocus
          placeholder="Enter portfolio name"
          sx={{ minWidth: 200 }}
        />
        <IconButton size="small" onClick={handleSave} color="primary">
          <CheckIcon />
        </IconButton>
        <IconButton 
          size="small" 
          onClick={() => {
            setName(initialName);
            setIsEditing(false);
          }}
          color="error"
        >
          <CloseIcon />
        </IconButton>
      </Box>
    ) : (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Typography variant="subtitle1">{name || 'Untitled Portfolio'}</Typography>
        <IconButton size="small" onClick={() => setIsEditing(true)}>
          <EditIcon />
        </IconButton>
      </Box>
    );
  };

  // Update the save portfolio function to include name
  const handleSavePortfolio = async () => {
    try {
      if (!validatePortfolio()) {
        return;
      }

      setNotification({
        open: true,
        message: 'Saving portfolio...',
        severity: 'info',
        duration: null
      });

      const portfolioData = {
        portfolio,
        benchmark,
        startDate,
        name: `Portfolio ${new Date().toLocaleString()}`
      };

      const response = await fetch('http://localhost:5000/api/portfolio/save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(portfolioData)
      });
      
      const data = await response.json();
      if (data.success) {
        setNotification({
          open: true,
          message: 'Portfolio saved successfully!',
          severity: 'success',
          duration: 3000
        });
        // Refresh the list of saved portfolios
        await loadSavedPortfolios();
      } else {
        throw new Error(data.error || 'Failed to save portfolio');
      }
    } catch (err) {
      setNotification({
        open: true,
        message: `Error: ${err.message}`,
        severity: 'error',
        duration: 5000
      });
    }
  };

  // Add function to update portfolio name
  const handleUpdatePortfolioName = async (filename, newName) => {
    try {
      const response = await fetch('http://localhost:5000/api/portfolio/update-name', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ filename, name: newName })
      });
      
      const data = await response.json();
      if (data.success) {
        setSavedPortfolios(data.portfolios);
        setNotification({
          open: true,
          message: 'Portfolio name updated successfully',
          severity: 'success',
          duration: 3000
        });
      } else {
        throw new Error(data.error || 'Failed to update portfolio name');
      }
    } catch (err) {
      setNotification({
        open: true,
        message: `Error updating portfolio name: ${err.message}`,
        severity: 'error',
        duration: 5000
      });
    }
  };

  // Update the loadSavedPortfolios function
  const loadSavedPortfolios = async () => {
    try {
      // Show loading notification
      setNotification({
        open: true,
        message: 'Loading portfolios...',
        severity: 'info',
        duration: null
      });

      const response = await fetch('http://localhost:5000/api/portfolio/load');
      const data = await response.json();
      
      // Clear loading notification regardless of outcome
      setNotification({
        open: false,
        message: '',
        severity: 'info',
        duration: null
      });

      if (data.success) {
        setSavedPortfolios(data.portfolios);
        setLoadDialogOpen(true);
        // Show success notification only after dialog is open
        setTimeout(() => {
          setNotification({
            open: true,
            message: 'Portfolios loaded successfully',
            severity: 'success',
            duration: 2000
          });
        }, 100);
      } else {
        throw new Error(data.error || 'Failed to load portfolios');
      }
    } catch (err) {
      // Clear loading and show error
      setNotification({
        open: true,
        message: `Failed to load portfolios: ${err.message}`,
        severity: 'error',
        duration: 5000
      });
      // Close dialog if open
      setLoadDialogOpen(false);
    }
  };

  // Update the handleLoadPortfolio function
  const handleLoadPortfolio = (savedPortfolio) => {
    try {
      setNotification({
        open: true,
        message: 'Loading portfolio...',
        severity: 'info',
        duration: null
      });

      setPortfolio(savedPortfolio.portfolio);
      setBenchmark(savedPortfolio.benchmark);
      setStartDate(savedPortfolio.startDate);
      
      // Clear previous results
      setResults(null);
      setAttribution(null);
      setRebalancingResults(null);
      setCorrelationData(null);
      
      // Close dialog first
      setLoadDialogOpen(false);

      // Show success notification after a brief delay
      setTimeout(() => {
        setNotification({
          open: true,
          message: 'Portfolio loaded successfully',
          severity: 'success',
          duration: 2000
        });
      }, 100);
    } catch (err) {
      setNotification({
        open: true,
        message: `Error loading portfolio: ${err.message}`,
        severity: 'error',
        duration: 5000
      });
      setLoadDialogOpen(false);
    }
  };

  const handleExportResults = async () => {
    if (!results) return;

    try {
      const response = await fetch('http://localhost:5000/api/export/csv', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(results)
      });

      const data = await response.json();
      
      if (data.success) {
        // Create and download CSV file
        const blob = new Blob([data.csv_data], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `portfolio_results_${new Date().toISOString().split('T')[0]}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

        setNotification({
          open: true,
          message: 'Results exported successfully',
          severity: 'success',
          duration: 3000
        });
      } else {
        throw new Error(data.error || 'Failed to export results');
      }
    } catch (err) {
      setNotification({
        open: true,
        message: 'Failed to export results: ' + err.message,
        severity: 'error',
        duration: 5000
      });
    }
  };

  const renderAttribution = () => {
    if (!attribution) return null;

    return (
      <>
        {/* Sector Attribution */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Sector Attribution Analysis
          </Typography>
          <Grid container spacing={3}>
            {/* Sector Table */}
            <Grid item xs={12} md={7}>
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell>Sector</TableCell>
                      <TableCell align="right">Weight</TableCell>
                      <TableCell align="right">Return</TableCell>
                      <TableCell align="right">Contribution</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {Object.entries(attribution.sector).map(([sector, data]) => (
                      <TableRow key={sector}>
                        <TableCell>{sector}</TableCell>
                        <TableCell align="right" sx={{ color: 'info.main' }}>
                          {(data.weight * 100).toFixed(2)}%
                        </TableCell>
                        <TableCell align="right" sx={{ 
                          color: data.return >= 0 ? 'success.main' : 'error.main',
                          fontWeight: 'medium'
                        }}>
                          {(data.return * 100).toFixed(2)}%
                        </TableCell>
                        <TableCell align="right" sx={{ 
                          color: data.contribution >= 0 ? 'success.main' : 'error.main',
                          fontWeight: 'bold'
                        }}>
                          {(data.contribution * 100).toFixed(2)}%
                        </TableCell>
                      </TableRow>
                    ))}
                    <TableRow sx={{ bgcolor: 'action.hover' }}>
                      <TableCell sx={{ fontWeight: 'bold' }}>Total</TableCell>
                      <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                        100.00%
                      </TableCell>
                      <TableCell align="right" sx={{ fontWeight: 'bold' }}>-</TableCell>
                      <TableCell align="right" sx={{ 
                        fontWeight: 'bold',
                        color: attribution.total_return >= 0 ? 'success.main' : 'error.main'
                      }}>
                        {(attribution.total_return * 100).toFixed(2)}%
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </TableContainer>
            </Grid>

            {/* Sector Contribution Pie Chart */}
            <Grid item xs={12} md={5}>
              <Box sx={{ height: 300 }}>
                <ResponsiveContainer>
                  <PieChart>
                    <Pie
                      data={Object.entries(attribution.sector).map(([sector, data]) => ({
                        name: sector,
                        value: (data.contribution / attribution.total_return) * 100  // Fix percentage calculation
                      }))}
                      dataKey="value"
                      nameKey="name"
                      cx="50%"
                      cy="50%"
                      outerRadius={80}
                      label={({ name, percent }) => `${name} (${percent.toFixed(1)}%)`}
                    >
                      {Object.entries(attribution.sector).map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(value) => `${(value * 100).toFixed(2)}%`} />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              </Box>
            </Grid>
          </Grid>
        </Paper>

        {/* Factor Attribution */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Factor Attribution Analysis
          </Typography>
          <Grid container spacing={3}>
            {/* Factor Metrics */}
            <Grid item xs={12} md={6}>
              <Box sx={{ p: 2, bgcolor: 'background.default', borderRadius: 1 }}>
                <Grid container spacing={2}>
                  <Grid item xs={6}>
                    <Paper elevation={3} sx={{ p: 2 }}>
                      <Typography variant="subtitle2" color="textSecondary">Market Beta</Typography>
                      <Typography variant="h4">
                        {attribution.factor.market_beta.toFixed(2)}
                      </Typography>
                      <Typography variant="caption" color="textSecondary">
                        {attribution.factor.market_beta > 1 ? 'More volatile than market' : 'Less volatile than market'}
                      </Typography>
                    </Paper>
                  </Grid>
                  <Grid item xs={6}>
                    <Paper elevation={3} sx={{ p: 2 }}>
                      <Typography variant="subtitle2" color="textSecondary">Alpha (annualized)</Typography>
                      <Typography variant="h4" color={attribution.factor.alpha >= 0 ? 'success.main' : 'error.main'}>
                        {(attribution.factor.alpha * 100).toFixed(2)}%
                      </Typography>
                      <Typography variant="caption" color="textSecondary">
                        {attribution.factor.alpha >= 0 ? 'Outperforming' : 'Underperforming'}
                      </Typography>
                    </Paper>
                  </Grid>
                  <Grid item xs={12}>
                    <Paper elevation={3} sx={{ p: 2 }}>
                      <Typography variant="subtitle2" color="textSecondary">R-squared</Typography>
                      <Typography variant="h4">
                        {(attribution.factor.r_squared * 100).toFixed(2)}%
                      </Typography>
                      <Typography variant="caption" color="textSecondary">
                        Percentage of variance explained by the market
                      </Typography>
                    </Paper>
                  </Grid>
                </Grid>
              </Box>
            </Grid>

            {/* Performance Comparison */}
            <Grid item xs={12} md={6}>
              <Box sx={{ p: 2, bgcolor: 'background.default', borderRadius: 1 }}>
                <Typography variant="subtitle1" gutterBottom>Performance Comparison</Typography>
                <Box sx={{ mb: 2 }}>
                  <Typography variant="subtitle2" color="textSecondary">Portfolio Return</Typography>
                  <Typography variant="h5" color={attribution.factor.portfolio_return >= 0 ? 'success.main' : 'error.main'}>
                    {(attribution.factor.portfolio_return * 100).toFixed(2)}%
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="subtitle2" color="textSecondary">Benchmark Return</Typography>
                  <Typography variant="h5" color={attribution.factor.benchmark_return >= 0 ? 'success.main' : 'error.main'}>
                    {(attribution.factor.benchmark_return * 100).toFixed(2)}%
                  </Typography>
                </Box>
                <Box sx={{ mt: 2, pt: 2, borderTop: 1, borderColor: 'divider' }}>
                  <Typography variant="subtitle2" color="textSecondary">Excess Return</Typography>
                  <Typography variant="h5" color={(attribution.factor.portfolio_return - attribution.factor.benchmark_return) >= 0 ? 'success.main' : 'error.main'}>
                    {((attribution.factor.portfolio_return - attribution.factor.benchmark_return) * 100).toFixed(2)}%
                  </Typography>
                </Box>
              </Box>
            </Grid>
          </Grid>
        </Paper>

        {/* Sector Contribution Chart */}
        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" color="primary" gutterBottom>Sector Contribution Analysis</Typography>
          <Box sx={{ height: 400 }}>
            <ResponsiveContainer>
              <BarChart
                data={Object.entries(attribution.sector).map(([sector, data]) => ({
                  sector,
                  contribution: data.contribution * 100,
                  return: data.return * 100,
                  weight: data.weight * 100
                }))}
                margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="sector" />
                <YAxis label={{ value: 'Percentage (%)', angle: -90, position: 'insideLeft' }} />
                <Tooltip formatter={(value) => `${value.toFixed(2)}%`} />
                <Legend />
                <Bar dataKey="contribution" name="Contribution" fill="#8884d8" />
                <Bar dataKey="return" name="Return" fill="#82ca9d" />
                <Bar dataKey="weight" name="Weight" fill="#ffc658" />
              </BarChart>
            </ResponsiveContainer>
          </Box>
          <Typography variant="caption" sx={{ mt: 2, display: 'block' }}>
            Comparison of sector weights, returns, and contributions to portfolio performance
          </Typography>
        </Paper>
      </>
    );
  };

  const renderRebalancingAnalysis = () => {
    if (!rebalancingResults || !results) return null;

    const strategies = {
      'null': 'Buy and Hold',
      'M': 'Monthly Rebalancing',
      'Q': 'Quarterly Rebalancing',
      'Y': 'Yearly Rebalancing'
    };

    // Get initial investment from results
    const initial_investment = results.historical_performance.initial_investment;

    // Prepare data for annual returns bar chart
    const annualReturnsData = Object.entries(rebalancingResults).map(([strategy, data]) => ({
      strategy: strategies[strategy],
      return: data.annualized_return * 100
    }));

    return (
      <>
        {/* Rebalancing Metrics Table */}
        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="h6" gutterBottom>Rebalancing Strategy Comparison</Typography>
          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Strategy</TableCell>
                  <TableCell align="right">Final Value</TableCell>
                  <TableCell align="right">Annual Return</TableCell>
                  <TableCell align="right">Volatility</TableCell>
                  <TableCell align="right">Total Cost</TableCell>
                  <TableCell align="right">Cost %</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {Object.entries(rebalancingResults).map(([freq, data]) => (
                  <TableRow key={freq}>
                    <TableCell>{strategies[freq]}</TableCell>
                    <TableCell align="right">
                      ${data.final_value.toLocaleString(undefined, { 
                        minimumFractionDigits: 2, 
                        maximumFractionDigits: 2 
                      })}
                    </TableCell>
                    <TableCell align="right">
                      {(data.annualized_return * 100).toFixed(2)}%
                    </TableCell>
                    <TableCell align="right">
                      {(data.volatility * 100).toFixed(2)}%
                    </TableCell>
                    <TableCell align="right">
                      ${data.total_cost.toLocaleString(undefined, { 
                        minimumFractionDigits: 2, 
                        maximumFractionDigits: 2 
                      })}
                    </TableCell>
                    <TableCell align="right">
                      {data.cost_percentage.toFixed(3)}%
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>

        {/* Annual Returns Bar Chart */}
        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="h6" gutterBottom>Annual Returns Comparison</Typography>
          <Box sx={{ height: 300, width: '100%' }}>
            <ResponsiveContainer>
              <BarChart
                data={annualReturnsData}
                margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="strategy"
                  label={{ value: 'Strategy', position: 'bottom', offset: 0 }}
                />
                <YAxis 
                  label={{ value: 'Annual Return (%)', angle: -90, position: 'insideLeft' }}
                  tickFormatter={(value) => `${value.toFixed(1)}%`}
                  domain={['dataMin - 5', 'dataMax + 5']}  // Add padding
                />
                <Tooltip 
                  formatter={(value) => [`${value.toFixed(2)}%`, 'Annual Return']}
                />
                <Bar 
                  dataKey="return" 
                  fill="#8884d8"
                  name="Annual Return"
                >
                  {annualReturnsData.map((entry, index) => (
                    <Cell 
                      key={`cell-${index}`}
                      fill={entry.return > 0 ? COLORS[index % COLORS.length] : '#ff7373'}
                    />
                  ))}
                </Bar>
                <ReferenceLine 
                  y={initial_investment} 
                  stroke="gray" 
                  strokeDasharray="3 3"
                  label="Initial Investment"
                />
              </BarChart>
            </ResponsiveContainer>
          </Box>
          <Typography variant="caption" sx={{ mt: 2, display: 'block' }}>
            Comparison of annualized returns across different rebalancing strategies. 
            Green bars indicate positive returns, red bars indicate negative returns.
          </Typography>
        </Paper>

        {/* Strategy Performance Chart */}
        <Paper sx={{ p: 2 }}>
          <Typography variant="h6" gutterBottom>Strategy Performance Comparison</Typography>
          <Box sx={{ height: 400, width: '100%' }}>
            <ResponsiveContainer>
              <LineChart
                data={results.historical_performance.dates.map((date, i) => ({
                  date,
                  'Buy and Hold': rebalancingResults['null']?.values[i],
                  'Monthly': rebalancingResults['M']?.values[i],
                  'Quarterly': rebalancingResults['Q']?.values[i],
                  'Yearly': rebalancingResults['Y']?.values[i]
                }))}
                margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date"
                  label={{ value: 'Date', position: 'bottom', offset: 0 }}
                />
                <YAxis 
                  label={{ value: 'Portfolio Value ($)', angle: -90, position: 'insideLeft' }}
                  tickFormatter={(value) => `$${value.toLocaleString()}`}
                  domain={[
                    dataMin => Math.floor(dataMin * 0.9),  // Add 10% padding below
                    dataMax => Math.ceil(dataMax * 1.1)    // Add 10% padding above
                  ]}
                />
                <Tooltip 
                  formatter={(value) => [`$${value.toLocaleString()}`, 'Value']}
                  labelFormatter={(label) => `Date: ${label}`}
                />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="Buy and Hold" 
                  stroke={COLORS[0]} 
                  strokeWidth={2}
                  dot={false}
                  isAnimationActive={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="Monthly" 
                  stroke={COLORS[1]} 
                  strokeWidth={2}
                  dot={false}
                  isAnimationActive={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="Quarterly" 
                  stroke={COLORS[2]} 
                  strokeWidth={2}
                  dot={false}
                  isAnimationActive={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="Yearly" 
                  stroke={COLORS[3]} 
                  strokeWidth={2}
                  dot={false}
                  isAnimationActive={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </Box>
          <Typography variant="caption" sx={{ mt: 2, display: 'block' }}>
            Comparison of different rebalancing strategies starting with the same initial investment. 
            Transaction costs are included in the performance calculations.
          </Typography>
        </Paper>
      </>
    );
  };

  const handleComparePortfolios = async (selectedPortfolios) => {
    try {
      setNotification({
        open: true,
        message: 'Comparing portfolios...',
        severity: 'info',
        duration: null
      });

      const response = await fetch('http://localhost:5000/api/compare', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          portfolios: selectedPortfolios.map(p => ({
            name: p.portfolio.name || `Portfolio ${p.filename}`,
            portfolio: p.portfolio.portfolio,
            benchmark: p.portfolio.benchmark,
            startDate: p.portfolio.startDate
          })),
          startDate
        })
      });

      const data = await response.json();
      if (data.success) {
        setComparisonResults(data);
        // Force tab switch to comparison tab
        const comparisonTabIndex = 5;  // Index of comparison tab
        setSelectedTab(comparisonTabIndex);
        setComparisonDialogOpen(false);  // Close the comparison dialog
        setNotification({
          open: true,
          message: 'Portfolio comparison completed successfully',
          severity: 'success',
          duration: 3000
        });
      } else {
        throw new Error(data.error || 'Failed to compare portfolios');
      }
    } catch (err) {
      console.error('Comparison error:', err);
      setNotification({
        open: true,
        message: 'Failed to compare portfolios: ' + err.message,
        severity: 'error',
        duration: 5000
      });
    }
  };

  // Add a new component for portfolio composition display
  const PortfolioCompositionCard = ({ portfolio, title }) => {
    const totalValue = portfolio.reduce((sum, stock) => sum + parseFloat(stock.weight), 0);
    
    return (
      <Paper sx={{ p: 2, height: '100%' }}>
        <Typography variant="h6" gutterBottom color="primary">
          {title}
        </Typography>
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Ticker</TableCell>
                <TableCell align="right">Weight</TableCell>
                <TableCell align="right">Allocation</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {portfolio.map((stock, index) => (
                <TableRow key={index}>
                  <TableCell>{stock.ticker}</TableCell>
                  <TableCell align="right">{stock.weight}%</TableCell>
                  <TableCell align="right">
                    <Box sx={{ width: '100%', mr: 1 }}>
                      <LinearProgress
                        variant="determinate"
                        value={(stock.weight / totalValue) * 100}
                        sx={{
                          height: 8,
                          borderRadius: 4,
                          bgcolor: 'background.paper',
                          '& .MuiLinearProgress-bar': {
                            bgcolor: COLORS[index % COLORS.length],
                            borderRadius: 4,
                          },
                        }}
                      />
                    </Box>
                  </TableCell>
                </TableRow>
              ))}
              <TableRow>
                <TableCell sx={{ fontWeight: 'bold' }}>Total</TableCell>
                <TableCell align="right" sx={{ fontWeight: 'bold' }}>{totalValue}%</TableCell>
                <TableCell />
              </TableRow>
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>
    );
  };

  // Update the renderComparison function to make it consistent with benchmark analysis
  const renderComparison = () => {
    if (!comparisonResults) return null;

    const { comparison_results, dates } = comparisonResults;
    const portfolioNames = Object.keys(comparison_results);

    // Calculate drawdown series for each portfolio
    const drawdownSeries = dates.map((date, i) => {
      const data = { date };
      portfolioNames.forEach(name => {
        const returns = comparison_results[name].cumulative_returns;
        const maxValue = Math.max(...returns.slice(0, i + 1));
        const currentValue = returns[i];
        data[`${name} Drawdown`] = ((currentValue / maxValue) - 1) * 100;
      });
      return data;
    });

    return (
      <>
        {/* Performance Summary */}
        <Paper sx={{ p: 3, mb: 2 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Performance Comparison
          </Typography>
          <Grid container spacing={3}>
            {portfolioNames.map(name => (
              <Grid item xs={12} md={6} key={name}>
                <Paper elevation={3} sx={{ p: 2 }}>
                  <Typography variant="h6" gutterBottom>{name}</Typography>
                  <TableContainer>
                    <Table size="small">
                      <TableBody>
                        <TableRow>
                          <TableCell>Total Return</TableCell>
                          <TableCell align="right" sx={{ 
                            color: comparison_results[name].metrics.cagr >= 0 ? 'success.main' : 'error.main',
                            fontWeight: 'bold'
                          }}>
                            {(comparison_results[name].metrics.cagr * 100).toFixed(2)}%
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell>Volatility</TableCell>
                          <TableCell align="right">
                            {(comparison_results[name].metrics.annual_volatility * 100).toFixed(2)}%
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell>Maximum Drawdown</TableCell>
                          <TableCell align="right" sx={{ color: 'error.main' }}>
                            {(comparison_results[name].metrics.max_drawdown * 100).toFixed(2)}%
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell>Final Value</TableCell>
                          <TableCell align="right">
                            ${comparison_results[name].metrics.end_balance.toLocaleString(undefined, { 
                              minimumFractionDigits: 0, 
                              maximumFractionDigits: 0 
                            })}
                          </TableCell>
                        </TableRow>
                      </TableBody>
                    </Table>
                  </TableContainer>
                </Paper>
              </Grid>
            ))}
          </Grid>
        </Paper>

        {/* Cumulative Performance Chart */}
        <Paper sx={{ p: 3, mb: 2 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Cumulative Performance
          </Typography>
          <Box sx={{ height: 400 }}>
            <ResponsiveContainer>
              <LineChart data={dates.map((date, i) => ({
                date,
                ...Object.fromEntries(
                  portfolioNames.map(name => [
                    name,
                    comparison_results[name].metrics.start_balance * 
                    comparison_results[name].cumulative_returns[i]
                  ])
                )
              }))}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date"
                  tickFormatter={(date) => new Date(date).toLocaleDateString()}
                />
                <YAxis 
                  tickFormatter={(value) => `$${value.toLocaleString()}`}
                  label={{ value: 'Portfolio Value ($)', angle: -90, position: 'insideLeft' }}
                />
                <Tooltip 
                  formatter={(value) => [`$${value.toLocaleString()}`, 'Value']}
                  labelFormatter={(label) => new Date(label).toLocaleDateString()}
                />
                <Legend />
                {portfolioNames.map((name, index) => (
                  <Line
                    key={name}
                    type="monotone"
                    dataKey={name}
                    stroke={COLORS[index % COLORS.length]}
                    strokeWidth={2}
                    dot={false}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </Box>
        </Paper>

        {/* Drawdown Analysis */}
        <Paper sx={{ p: 3, mb: 2 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Drawdown Analysis
          </Typography>
          <Box sx={{ height: 400, mb: 3 }}>
            <ResponsiveContainer>
              <LineChart data={drawdownSeries}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date"
                  tickFormatter={(date) => new Date(date).toLocaleDateString()}
                />
                <YAxis 
                  label={{ value: 'Drawdown (%)', angle: -90, position: 'insideLeft' }}
                  tickFormatter={(value) => `${value.toFixed(1)}%`}
                />
                <Tooltip 
                  formatter={(value) => [`${value.toFixed(2)}%`, 'Drawdown']}
                  labelFormatter={(label) => new Date(label).toLocaleDateString()}
                />
                <Legend />
                {portfolioNames.map((name, index) => (
                  <Line
                    key={name}
                    type="monotone"
                    dataKey={`${name} Drawdown`}
                    stroke={COLORS[index % COLORS.length]}
                    strokeWidth={2}
                    dot={false}
                  />
                ))}
                <ReferenceLine y={0} stroke="gray" strokeDasharray="3 3" />
              </LineChart>
            </ResponsiveContainer>
          </Box>

          {/* Drawdown Statistics */}
          <Grid container spacing={3}>
            {portfolioNames.map((name, index) => (
              <Grid item xs={12} md={6} key={name}>
                <Paper 
                  elevation={3} 
                  sx={{ 
                    p: 2,
                    bgcolor: alpha(COLORS[index % COLORS.length], 0.05)
                  }}
                >
                  <Typography variant="subtitle1" gutterBottom color="primary">
                    {name} - Drawdown Statistics
                  </Typography>
                  <TableContainer>
                    <Table size="small">
                      <TableBody>
                        <TableRow>
                          <TableCell>Maximum Drawdown</TableCell>
                          <TableCell align="right" sx={{ color: 'error.main' }}>
                            {(comparison_results[name].metrics.max_drawdown * 100).toFixed(2)}%
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell>Average Drawdown</TableCell>
                          <TableCell align="right">
                            {(comparison_results[name].metrics.avg_drawdown * 100).toFixed(2)}%
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell>Average Recovery Time</TableCell>
                          <TableCell align="right">
                            {Math.round(comparison_results[name].metrics.avg_recovery_time)} days
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell>Drawdown Distribution</TableCell>
                          <TableCell align="right">
                            <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
                              <Chip 
                                size="small" 
                                label={`Severe: ${comparison_results[name].metrics.drawdown_categories.severe}`}
                                color="error"
                              />
                              <Chip 
                                size="small" 
                                label={`Moderate: ${comparison_results[name].metrics.drawdown_categories.moderate}`}
                                color="warning"
                              />
                              <Chip 
                                size="small" 
                                label={`Mild: ${comparison_results[name].metrics.drawdown_categories.mild}`}
                                color="success"
                              />
                            </Box>
                          </TableCell>
                        </TableRow>
                      </TableBody>
                    </Table>
                  </TableContainer>
                </Paper>
              </Grid>
            ))}
          </Grid>
        </Paper>
      </>
    );
  };

  const renderCorrelationMatrix = () => {
    if (!correlationData) return null;
    const theme = useTheme();
    const isDarkMode = theme.palette.mode === 'dark';

    const matrix = correlationData[correlationType].matrix;
    const tickers = Object.keys(matrix);
    const minCorr = correlationData[correlationType].min;
    const maxCorr = correlationData[correlationType].max;

    return (
      <Box>
        {/* Correlation Type Selection */}
        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Correlation Analysis
          </Typography>
          <Box sx={{ mb: 2 }}>
            <ButtonGroup>
              <Button 
                variant={correlationType === 'pearson' ? 'contained' : 'outlined'}
                onClick={() => setCorrelationType('pearson')}
              >
                Pearson
              </Button>
              <Button 
                variant={correlationType === 'spearman' ? 'contained' : 'outlined'}
                onClick={() => setCorrelationType('spearman')}
              >
                Spearman
              </Button>
            </ButtonGroup>
          </Box>

          {/* Correlation Summary */}
          <Grid container spacing={2} sx={{ mb: 3 }}>
            <Grid item xs={12} md={4}>
              <Paper elevation={3} sx={{ p: 2, bgcolor: 'background.default' }}>
                <Typography variant="subtitle2" color="textSecondary">
                  Minimum Correlation
                </Typography>
                <Typography variant="h4" color={minCorr >= 0 ? 'success.main' : 'error.main'}>
                  {minCorr.toFixed(2)}
                </Typography>
              </Paper>
            </Grid>
            <Grid item xs={12} md={4}>
              <Paper elevation={3} sx={{ p: 2, bgcolor: 'background.default' }}>
                <Typography variant="subtitle2" color="textSecondary">
                  Maximum Correlation
                </Typography>
                <Typography variant="h4" color={maxCorr >= 0 ? 'success.main' : 'error.main'}>
                  {maxCorr.toFixed(2)}
                </Typography>
              </Paper>
            </Grid>
            <Grid item xs={12} md={4}>
              <Paper elevation={3} sx={{ p: 2, bgcolor: 'background.default' }}>
                <Typography variant="subtitle2" color="textSecondary">
                  Average Correlation
                </Typography>
                <Typography variant="h4" color={correlationData[correlationType].mean >= 0 ? 'success.main' : 'error.main'}>
                  {correlationData[correlationType].mean.toFixed(2)}
                </Typography>
              </Paper>
            </Grid>
          </Grid>

          {/* Correlation Matrix */}
          <Typography variant="h6" gutterBottom>Correlation Matrix</Typography>
          <Box sx={{ 
            overflowX: 'auto',
            '& td, & th': { 
              minWidth: '80px',
              transition: 'background-color 0.2s'
            },
            '& td:hover, & th:hover': { 
              bgcolor: 'action.hover' 
            }
          }}>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell />
                  {tickers.map(ticker => (
                    <TableCell 
                      key={ticker}
                      sx={{ 
                        fontWeight: 'bold',
                        position: 'sticky',
                        top: 0,
                        bgcolor: 'background.paper',
                        zIndex: 1
                      }}
                    >
                      {ticker}
                    </TableCell>
                  ))}
                </TableRow>
              </TableHead>
              <TableBody>
                {tickers.map(ticker1 => (
                  <TableRow key={ticker1}>
                    <TableCell 
                      component="th" 
                      scope="row"
                      sx={{ 
                        fontWeight: 'bold',
                        position: 'sticky',
                        left: 0,
                        bgcolor: 'background.paper',
                        zIndex: 1
                      }}
                    >
                      {ticker1}
                    </TableCell>
                    {tickers.map(ticker2 => (
                      <TableCell 
                        key={`${ticker1}-${ticker2}`}
                        sx={{
                          cursor: 'help',
                          bgcolor: getCorrelationColor(matrix[ticker1][ticker2], isDarkMode),
                          '&:hover': { opacity: 0.8 }
                        }}
                        onClick={() => {
                          setNotification({
                            open: true,
                            message: `Correlation between ${ticker1} and ${ticker2}: ${matrix[ticker1][ticker2].toFixed(3)}`,
                            severity: 'info',
                            duration: 3000
                          });
                        }}
                      >
                        {matrix[ticker1][ticker2].toFixed(2)}
                      </TableCell>
                    ))}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Box>

          {/* Correlation Legend */}
          <Box sx={{ mt: 2, p: 2, bgcolor: 'background.paper', borderRadius: 1 }}>
            <Typography variant="subtitle2" gutterBottom>
              Correlation Guide:
            </Typography>
            <Grid container spacing={2}>
              <Grid item xs={12} md={4}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Box sx={{ width: 20, height: 20, bgcolor: getCorrelationColor(-1, isDarkMode), mr: 1 }} />
                  <Typography variant="body2">
                    Strong Negative (-1.0 to -0.7)
                  </Typography>
                </Box>
              </Grid>
              <Grid item xs={12} md={4}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Box sx={{ width: 20, height: 20, bgcolor: getCorrelationColor(0, isDarkMode), mr: 1 }} />
                  <Typography variant="body2">
                    No Correlation (-0.3 to 0.3)
                  </Typography>
                </Box>
              </Grid>
              <Grid item xs={12} md={4}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Box sx={{ width: 20, height: 20, bgcolor: getCorrelationColor(1, isDarkMode), mr: 1 }} />
                  <Typography variant="body2">
                    Strong Positive (0.7 to 1.0)
                  </Typography>
                </Box>
              </Grid>
            </Grid>
          </Box>

          <Typography variant="caption" sx={{ mt: 2, display: 'block' }}>
            Click on any correlation value for more details. Darker colors indicate stronger correlations.
            {correlationType === 'pearson' 
              ? " Pearson correlation measures linear relationships between variables."
              : " Spearman correlation measures monotonic relationships, including non-linear patterns."}
          </Typography>
        </Paper>
      </Box>
    );
  };

  const helpTexts = {
    portfolio: 'Enter stock tickers and their weights. Weights must sum to 100%.',
    dateRange: 'Select the time period for backtesting. Longer periods provide better historical context.',
    benchmark: 'Choose a market index or stock to compare your portfolio against.',
    rebalancing: 'See how different rebalancing strategies affect your portfolio\'s performance.',
    attribution: 'Understand how different sectors and factors contribute to your portfolio\'s performance.',
    transactionCost: 'Cost per trade as a percentage of the trade value.'
  };

  // Update the PortfolioComparisonDialog component
  const PortfolioComparisonDialog = ({ open, onClose, portfolios, onCompare }) => {
    const [selected, setSelected] = useState([]);
    const [isComparing, setIsComparing] = useState(false);

    // Reset selection when dialog opens
    useEffect(() => {
      if (open) {
        setSelected([]);
        setIsComparing(false);
      }
    }, [open]);

    const handleTogglePortfolio = (portfolio) => {
      const currentIndex = selected.findIndex(p => p.filename === portfolio.filename);
      const newSelected = [...selected];

      if (currentIndex === -1) {
        newSelected.push(portfolio);
      } else {
        newSelected.splice(currentIndex, 1);
      }

      setSelected(newSelected);
    };

    const handleCompare = async () => {
      try {
        if (selected.length < 2) {
          setNotification({
            open: true,
            message: 'Please select at least 2 portfolios to compare',
            severity: 'warning',
            duration: 3000
          });
          return;
        }

        setIsComparing(true);
        setNotification({
          open: true,
          message: 'Comparing portfolios...',
          severity: 'info',
          duration: null
        });

        await onCompare(selected);
        
        // Only close after successful comparison
        setIsComparing(false);
        onClose();

      } catch (err) {
        setIsComparing(false);
        setNotification({
          open: true,
          message: `Error comparing portfolios: ${err.message}`,
          severity: 'error',
          duration: 5000
        });
      }
    };

    return (
      <Dialog
        open={open}
        onClose={!isComparing ? onClose : undefined}  // Prevent closing while comparing
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          Compare Portfolios
          {!isComparing && (
            <IconButton
              aria-label="close"
              onClick={onClose}
              sx={{ position: 'absolute', right: 8, top: 8 }}
            >
              <CloseIcon />
            </IconButton>
          )}
        </DialogTitle>
        <DialogContent>
          <Typography variant="body2" gutterBottom color="text.secondary" sx={{ mb: 2 }}>
            Select portfolios to compare (2-5 portfolios recommended)
          </Typography>
          <List>
            {portfolios.map((portfolio) => (
              <ListItem
                key={portfolio.filename}
                button
                onClick={() => !isComparing && handleTogglePortfolio(portfolio)}
                selected={selected.some(p => p.filename === portfolio.filename)}
                disabled={isComparing}
                sx={{ 
                  cursor: isComparing ? 'default' : 'pointer',
                  '&.Mui-selected': {
                    bgcolor: 'primary.light',
                    '&:hover': {
                      bgcolor: 'primary.light',
                    },
                  },
                }}
              >
                <ListItemText
                  primary={portfolio.portfolio.name || `Portfolio ${portfolio.filename}`}
                  secondary={`Saved on: ${portfolio.filename.split('_')[1].split('.')[0]}`}
                />
                {selected.some(p => p.filename === portfolio.filename) && (
                  <Chip
                    label="Selected"
                    color="primary"
                    size="small"
                    sx={{ ml: 1 }}
                  />
                )}
              </ListItem>
            ))}
          </List>
          {portfolios.length === 0 && (
            <Typography variant="body2" sx={{ textAlign: 'center', color: 'text.secondary', py: 2 }}>
              No saved portfolios found
            </Typography>
          )}
        </DialogContent>
        <DialogActions>
          <Button 
            onClick={onClose} 
            disabled={isComparing}
          >
            Cancel
          </Button>
          <Button
            onClick={handleCompare}
            disabled={selected.length < 2 || isComparing}
            variant="contained"
            startIcon={!isComparing && <CompareIcon />}
          >
            {isComparing ? (
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <CircularProgress size={20} />
                <span>Comparing...</span>
              </Box>
            ) : (
              `Compare (${selected.length})`
            )}
          </Button>
        </DialogActions>
      </Dialog>
    );
  };

  const renderHighlights = () => {
    if (!results && !comparisonResults) return null;

    if (comparisonResults) {
      const { comparison_results } = comparisonResults;
      const portfolioNames = Object.keys(comparison_results);

      return (
        <Paper sx={{ p: 3, mb: 2 }}>
          <Typography variant="h5" gutterBottom color="primary" fontWeight="500">
            Portfolio Comparison Highlights
          </Typography>

          {/* Portfolio Composition Cards */}
          <Grid container spacing={3} sx={{ mb: 4 }}>
            {portfolioNames.map((name, index) => (
              <Grid item xs={12} md={6} key={name}>
                <PortfolioCompositionCard 
                  portfolio={comparison_results[name].portfolio}
                  title={name}
                />
              </Grid>
            ))}
          </Grid>

          {/* Key Metrics Comparison */}
          <Grid container spacing={3}>
            {portfolioNames.map((name, index) => (
              <Grid item xs={12} md={6} key={name}>
                <Paper 
                  elevation={3} 
                  sx={{ 
                    p: 2, 
                    background: `linear-gradient(45deg, ${COLORS[index % COLORS.length]}22, ${COLORS[(index + 1) % COLORS.length]}22)`,
                  }}
                >
                  <Typography variant="h6" gutterBottom>
                    {name} Performance
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={6}>
                      <Paper sx={{ p: 2, bgcolor: 'background.paper' }}>
                        <Typography variant="subtitle2" color="textSecondary">
                          Total Return
                        </Typography>
                        <Typography 
                          variant="h4"
                          color={comparison_results[name].metrics.cagr >= 0 ? 'success.main' : 'error.main'}
                        >
                          {(comparison_results[name].metrics.cagr * 100).toFixed(1)}%
                        </Typography>
                      </Paper>
                    </Grid>
                    <Grid item xs={6}>
                      <Paper sx={{ p: 2, bgcolor: 'background.paper' }}>
                        <Typography variant="subtitle2" color="textSecondary">
                          Risk Level
                        </Typography>
                        <Typography 
                          variant="h4"
                          color={comparison_results[name].metrics.annual_volatility > 0.2 ? 'error.main' : 
                                comparison_results[name].metrics.annual_volatility > 0.15 ? 'warning.main' : 'success.main'}
                        >
                          {comparison_results[name].metrics.annual_volatility > 0.2 ? 'High' : 
                           comparison_results[name].metrics.annual_volatility > 0.15 ? 'Medium' : 'Low'}
                        </Typography>
                      </Paper>
                    </Grid>
                    <Grid item xs={12}>
                      <Paper sx={{ p: 2, bgcolor: 'background.paper' }}>
                        <Typography variant="subtitle2" gutterBottom color="textSecondary">
                          Key Statistics
                        </Typography>
                        <Grid container spacing={2}>
                          <Grid item xs={6}>
                            <Typography variant="body2" color="textSecondary">Max Drawdown</Typography>
                            <Typography variant="h6" color="error.main">
                              {(comparison_results[name].metrics.max_drawdown * 100).toFixed(1)}%
                            </Typography>
                          </Grid>
                          <Grid item xs={6}>
                            <Typography variant="body2" color="textSecondary">Final Value</Typography>
                            <Typography variant="h6">
                              ${comparison_results[name].metrics.end_balance.toLocaleString()}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Paper>
                    </Grid>
                  </Grid>
                </Paper>
              </Grid>
            ))}
          </Grid>

          {/* Relative Performance Summary */}
          <Paper sx={{ p: 2, mt: 3 }}>
            <Typography variant="h6" gutterBottom>
              Relative Performance Analysis
            </Typography>
            <Grid container spacing={2}>
              {portfolioNames.map((name, index) => {
                const metrics = comparison_results[name].metrics;
                const otherPortfolios = portfolioNames.filter(p => p !== name);
                const comparisons = otherPortfolios.map(other => ({
                  name: other,
                  return_diff: metrics.cagr - comparison_results[other].metrics.cagr,
                  risk_diff: metrics.annual_volatility - comparison_results[other].metrics.annual_volatility
                }));

                return (
                  <Grid item xs={12} key={name}>
                    <Paper sx={{ p: 2, bgcolor: 'background.default' }}>
                      <Typography variant="subtitle1" gutterBottom>
                        {name} vs Others
                      </Typography>
                      {comparisons.map(comp => (
                        <Box key={comp.name} sx={{ mb: 1 }}>
                          <Typography variant="body2" color="textSecondary">
                            vs {comp.name}:
                          </Typography>
                          <Box sx={{ display: 'flex', gap: 2, ml: 2 }}>
                            <Typography variant="body2">
                              Return: <Box component="span" sx={{ 
                                color: comp.return_diff > 0 ? 'success.main' : 'error.main',
                                fontWeight: 'bold'
                              }}>
                                {comp.return_diff > 0 ? '+' : ''}{(comp.return_diff * 100).toFixed(2)}%
                              </Box>
                            </Typography>
                            <Typography variant="body2">
                              Risk: <Box component="span" sx={{ 
                                color: comp.risk_diff < 0 ? 'success.main' : 'error.main',
                                fontWeight: 'bold'
                              }}>
                                {comp.risk_diff > 0 ? '+' : ''}{(comp.risk_diff * 100).toFixed(2)}%
                              </Box>
                            </Typography>
                          </Box>
                        </Box>
                      ))}
                    </Paper>
                  </Grid>
                );
              })}
            </Grid>
          </Paper>
        </Paper>
      );
    }

    // Original highlights for single portfolio
    return renderOriginalHighlights();
  };

  const renderOriginalHighlights = () => {
    if (!results) return null;

    const metrics = results.portfolio_metrics;
    const benchmarkMetrics = results.benchmark_metrics;
    
    // Calculate additional metrics
    const positiveMonths = results.historical_performance.portfolio_values.filter((v, i) => 
      i > 0 && v > results.historical_performance.portfolio_values[i-1]
    ).length;
    const totalMonths = results.historical_performance.portfolio_values.length;
    const positiveMonthsPercentage = (positiveMonths / totalMonths * 100).toFixed(2);

    const benchmarkPositiveMonths = results.historical_performance.benchmark_values.filter((v, i) => 
      i > 0 && v > results.historical_performance.benchmark_values[i-1]
    ).length;
    const benchmarkPositivePercentage = (benchmarkPositiveMonths / totalMonths * 100).toFixed(2);

    const startDate = new Date(results.historical_performance.dates[0]);
    const endDate = new Date(results.historical_performance.dates[results.historical_performance.dates.length - 1]);
    
    const portfolioCumulativeReturn = ((metrics.end_balance / metrics.start_balance - 1) * 100).toFixed(2);
    const benchmarkCumulativeReturn = ((benchmarkMetrics.end_balance / benchmarkMetrics.start_balance - 1) * 100).toFixed(2);

    return (
      <Paper sx={{ p: 3, mb: 2 }}>
        <Typography variant="h5" gutterBottom color="primary" fontWeight="500">
          Performance Highlights
        </Typography>
        
        {/* Key Metrics Grid */}
        <Grid container spacing={3} sx={{ mb: 4 }}>
          {/* Return Section */}
          <Grid item xs={12} md={6}>
            <Paper 
              elevation={3} 
              sx={{ 
                p: 2, 
                background: 'linear-gradient(45deg, #FF6B6B 30%, #FFD93D 90%)',  // Updated colors
                color: 'white'
              }}
            >
              <Typography variant="h6" gutterBottom sx={{ color: 'rgba(255,255,255,0.9)' }}>
                Return Metrics
              </Typography>
              <Grid container spacing={2}>
                <Grid item xs={6}>
                  <Typography variant="subtitle2" sx={{ color: 'rgba(255,255,255,0.7)' }}>
                    Annualized Return
                  </Typography>
                  <Typography variant="h4">
                    {(metrics.cagr * 100).toFixed(1)}%
                  </Typography>
                </Grid>
                <Grid item xs={6}>
                  <Typography variant="subtitle2" sx={{ color: 'rgba(255,255,255,0.7)' }}>
                    vs Benchmark
                  </Typography>
                  <Typography 
                    variant="h4"
                    sx={{ 
                      color: metrics.active_return > 0 ? '#4CAF50' : '#f44336',
                      textShadow: '1px 1px 1px rgba(0,0,0,0.2)'
                    }}
                  >
                    {(metrics.active_return * 100).toFixed(1)}%
                  </Typography>
                </Grid>
              </Grid>
            </Paper>
          </Grid>

          {/* Risk Section */}
          <Grid item xs={12} md={6}>
            <Paper 
              elevation={3} 
              sx={{ 
                p: 2, 
                background: 'linear-gradient(45deg, #4ECDC4 30%, #95A5A6 90%)',  // Updated colors
                color: 'white'
              }}
            >
              <Typography variant="h6" gutterBottom sx={{ color: 'rgba(255,255,255,0.9)' }}>
                Risk Metrics
              </Typography>
              <Grid container spacing={2}>
                <Grid item xs={6}>
                  <Typography variant="subtitle2" sx={{ color: 'rgba(255,255,255,0.7)' }}>
                    Volatility
                  </Typography>
                  <Typography variant="h4">
                    {(metrics.annual_volatility * 100).toFixed(1)}%
                  </Typography>
                </Grid>
                <Grid item xs={6}>
                  <Typography variant="subtitle2" sx={{ color: 'rgba(255,255,255,0.7)' }}>
                    Max Drawdown
                  </Typography>
                  <Typography variant="h4" color="error.light">
                    {(metrics.max_drawdown * 100).toFixed(1)}%
                  </Typography>
                </Grid>
              </Grid>
            </Paper>
          </Grid>
        </Grid>

        {/* Summary Cards */}
        <Grid container spacing={2}>
          {/* Investment Summary */}
          <Grid item xs={12}>
            <Paper elevation={2} sx={{ p: 2, bgcolor: 'background.paper' }}>
              <Typography variant="h6" color="primary" gutterBottom>
                Investment Summary
              </Typography>
              <Typography variant="body1" paragraph sx={{ color: 'text.primary' }}>
                ${metrics.start_balance.toLocaleString()} invested in {
                  startDate.toLocaleDateString('en-US', { 
                    month: 'long', 
                    year: 'numeric' 
                  })
                } would be worth <Box component="span" sx={{ color: 'success.main', fontWeight: 'bold' }}>
                  ${metrics.end_balance.toLocaleString()}
                </Box> as of {
                  endDate.toLocaleDateString('en-US', { 
                    month: 'long', 
                    year: 'numeric' 
                  })
                }, representing a cumulative return of <Box component="span" sx={{ color: 'success.main', fontWeight: 'bold' }}>
                  {portfolioCumulativeReturn.toLocaleString()}%
                </Box>. Over the same period, the benchmark would be worth ${
                  benchmarkMetrics.end_balance.toLocaleString()
                }, a return of {benchmarkCumulativeReturn}%.
              </Typography>
            </Paper>
          </Grid>

          {/* Return Details */}
          <Grid item xs={12} md={6}>
            <Paper elevation={2} sx={{ p: 2, bgcolor: 'background.paper', height: '100%' }}>
              <Typography variant="h6" color="primary" gutterBottom>
                Return Analysis
              </Typography>
              <Typography variant="body1" sx={{ color: 'text.primary' }}>
                The portfolio generated an annualized return of <Box component="span" fontWeight="bold">
                  {(metrics.cagr * 100).toFixed(2)}%
                </Box>, with {metrics.positive_days} out of {metrics.total_days} trading days positive ({(metrics.positive_days / metrics.total_days * 100).toFixed(2)}%. 
                The benchmark returned <Box component="span" fontWeight="bold">
                  {(benchmarkMetrics.cagr * 100).toFixed(2)}%
                </Box> annually, with {benchmarkMetrics.positive_days} positive days ({(benchmarkMetrics.positive_days / benchmarkMetrics.total_days * 100).toFixed(2)}%.
              </Typography>
            </Paper>
          </Grid>

          {/* Risk Details */}
          <Grid item xs={12} md={6}>
            <Paper elevation={2} sx={{ p: 2, bgcolor: 'background.paper', height: '100%' }}>
              <Typography variant="h6" color="primary" gutterBottom>
                Risk Analysis
              </Typography>
              <Typography variant="body1" sx={{ color: 'text.primary' }}>
                Maximum drawdown was <Box component="span" color="error.main" fontWeight="bold">
                  {(metrics.max_drawdown * 100).toFixed(2)}%
                </Box>. The portfolio achieved a Sharpe Ratio of {metrics.sharpe_ratio.toFixed(2)} compared to the benchmark's {benchmarkMetrics.sharpe_ratio.toFixed(2)}. 
                With a beta of {metrics.beta.toFixed(2)}, the portfolio shows {metrics.beta > 1 ? 'higher' : 'lower'} volatility than the market.
              </Typography>
            </Paper>
          </Grid>
        </Grid>
      </Paper>
    );
  };

  // Add this function before renderPerformanceSummary
  const calculateYearlyReturns = (returns, dates) => {
    if (!returns || !dates || returns.length === 0 || dates.length === 0) {
      return {
        bestYear: 0,
        worstYear: 0
      };
    }

    const yearlyReturns = {};
    let currentYear = null;
    let yearReturn = 1;

    returns.forEach((value, index) => {
      const date = new Date(dates[index]);
      const year = date.getFullYear();

      if (currentYear === null) {
        currentYear = year;
      }

      if (year === currentYear) {
        yearReturn *= (1 + value);
      } else {
        yearlyReturns[currentYear] = yearReturn - 1;
        currentYear = year;
        yearReturn = 1 + value;
      }
    });

    // Add the last year
    if (currentYear !== null) {
      yearlyReturns[currentYear] = yearReturn - 1;
    }

    const yearlyReturnValues = Object.values(yearlyReturns);
    
    return {
      bestYear: yearlyReturnValues.length > 0 ? Math.max(...yearlyReturnValues) : 0,
      worstYear: yearlyReturnValues.length > 0 ? Math.min(...yearlyReturnValues) : 0
    };
  };

  // Update the renderPerformanceSummary function to pass dates
  const renderPerformanceSummary = () => {
    if (!results) return null;

    // Calculate yearly returns for both portfolio and benchmark
    const portfolioYearlyMetrics = calculateYearlyReturns(
      results.historical_performance.portfolio_returns,
      results.historical_performance.dates
    );
    const benchmarkYearlyMetrics = calculateYearlyReturns(
      results.historical_performance.benchmark_returns,
      results.historical_performance.dates
    );

    // Add summary metrics with yearly returns
    const summaryMetrics = [
      { key: 'start_balance', label: 'Start Balance', format: 'currency' },
      { key: 'end_balance', label: 'End Balance', format: 'currency' },
      { key: 'cagr', label: 'Annualized Return (CAGR)', format: 'percent' },
      { key: 'annual_volatility', label: 'Standard Deviation', format: 'percent' },
      { 
        key: 'best_year', 
        label: 'Best Year', 
        format: 'percent',
        getValue: (metrics) => metrics === results.portfolio_metrics ? 
          portfolioYearlyMetrics.bestYear : benchmarkYearlyMetrics.bestYear
      },
      { 
        key: 'worst_year', 
        label: 'Worst Year', 
        format: 'percent',
        getValue: (metrics) => metrics === results.portfolio_metrics ? 
          portfolioYearlyMetrics.worstYear : benchmarkYearlyMetrics.worstYear
      },
      { key: 'max_drawdown', label: 'Maximum Drawdown', format: 'percent' },
      { key: 'sharpe_ratio', label: 'Sharpe Ratio', format: 'ratio' },
      { key: 'sortino_ratio', label: 'Sortino Ratio', format: 'ratio' },
      { key: 'benchmark_correlation', label: 'Benchmark Correlation', format: 'ratio' }
    ];

    return (
      <>
        {/* Performance Summary */}
        <Fade in timeout={300}>
          <Paper sx={{ p: 3, mb: 2 }}>
            <Typography variant="h6" color="primary" gutterBottom>
              Performance Summary
            </Typography>
            <Typography variant="subtitle2" color="textSecondary" gutterBottom>
              Portfolio performance statistics
            </Typography>
            <TableContainer>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>Metric</TableCell>
                    <TableCell>Portfolio</TableCell>
                    <TableCell>{benchmark.toUpperCase()}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {summaryMetrics.map(({ key, label, format, getValue }) => (
                    <TableRow key={key} hover>
                      <TableCell 
                        component="th" 
                        scope="row"
                        sx={{ fontWeight: 'medium' }}
                      >
                        {label}
                      </TableCell>
                      <TableCell sx={{
                        color: key === 'max_drawdown' ? 'error.main' : 
                               (key === 'cagr' || key === 'best_year') && 
                               (getValue ? getValue(results.portfolio_metrics) : results.portfolio_metrics[key]) > 0 ? 'success.main' : 
                               key === 'worst_year' && 
                               (getValue ? getValue(results.portfolio_metrics) : results.portfolio_metrics[key]) < 0 ? 'error.main' : 
                               'inherit'
                      }}>
                        {getValue ? 
                          formatValue(getValue(results.portfolio_metrics), format) :
                          formatValue(results.portfolio_metrics[key], format)}
                      </TableCell>
                      <TableCell sx={{
                        color: key === 'max_drawdown' ? 'error.main' : 
                               (key === 'cagr' || key === 'best_year') && 
                               (getValue ? getValue(results.benchmark_metrics) : results.benchmark_metrics[key]) > 0 ? 'success.main' : 
                               key === 'worst_year' && 
                               (getValue ? getValue(results.benchmark_metrics) : results.benchmark_metrics[key]) < 0 ? 'error.main' : 
                               'inherit'
                      }}>
                        {getValue ? 
                          formatValue(getValue(results.benchmark_metrics), format) :
                          formatValue(results.benchmark_metrics[key], format)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        </Fade>

        {/* Growth Chart */}
        <Paper sx={{ p: 3, mb: 2 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Portfolio Growth
          </Typography>
          <Box sx={{ height: 400 }}>
            <ResponsiveContainer>
              <LineChart data={results.historical_performance.dates.map((date, i) => ({
                date,
                Portfolio: results.historical_performance.portfolio_values[i],
                Benchmark: results.historical_performance.benchmark_values[i]
              }))}
              margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date"
                  tickFormatter={(date) => new Date(date).toLocaleDateString()}
                />
                <YAxis 
                  tickFormatter={(value) => `$${value.toLocaleString()}`}
                  label={{ value: 'Portfolio Value ($)', angle: -90, position: 'insideLeft' }}
                />
                <Tooltip 
                  formatter={(value) => [`$${value.toLocaleString()}`, 'Value']}
                  labelFormatter={(label) => new Date(label).toLocaleDateString()}
                />
                <Legend />
                <Line type="monotone" dataKey="Portfolio" stroke={COLORS[0]} dot={false} />
                <Line type="monotone" dataKey="Benchmark" stroke={COLORS[1]} dot={false} />
              </LineChart>
            </ResponsiveContainer>
          </Box>
        </Paper>

        {/* Drawdown Chart */}
        <Paper sx={{ p: 3, mb: 2 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Drawdown Analysis
          </Typography>
          <Box sx={{ height: 400 }}>
            <ResponsiveContainer>
              <LineChart data={results.historical_performance.dates.map((date, i) => {
                const portfolioValue = results.historical_performance.portfolio_values[i];
                const benchmarkValue = results.historical_performance.benchmark_values[i];
                const portfolioMax = Math.max(...results.historical_performance.portfolio_values.slice(0, i + 1));
                const benchmarkMax = Math.max(...results.historical_performance.benchmark_values.slice(0, i + 1));
                
                return {
                  date,
                  'Portfolio Drawdown': ((portfolioValue / portfolioMax - 1) * 100),
                  'Benchmark Drawdown': ((benchmarkValue / benchmarkMax - 1) * 100)
                };
              })}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date"
                  tickFormatter={(date) => new Date(date).toLocaleDateString()}
                />
                <YAxis 
                  tickFormatter={(value) => `${value.toFixed(1)}%`}
                  label={{ value: 'Drawdown (%)', angle: -90, position: 'insideLeft' }}
                />
                <Tooltip 
                  formatter={(value) => [`${value.toFixed(2)}%`, 'Drawdown']}
                  labelFormatter={(label) => new Date(label).toLocaleDateString()}
                />
                <Legend />
                <Line type="monotone" dataKey="Portfolio Drawdown" stroke={COLORS[0]} dot={false} />
                <Line type="monotone" dataKey="Benchmark Drawdown" stroke={COLORS[1]} dot={false} />
                <ReferenceLine y={0} stroke="gray" strokeDasharray="3 3" />
              </LineChart>
            </ResponsiveContainer>
          </Box>
        </Paper>

        {/* Risk and Return Metrics */}
        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" color="primary" gutterBottom>
            Risk and Return Metrics
          </Typography>
          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Metric</TableCell>
                  <TableCell>Portfolio</TableCell>
                  <TableCell>{results.benchmark_metrics ? benchmark.toUpperCase() : 'Benchmark'}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {detailedMetrics.map(({ key, label, format }) => (
                  <TableRow key={key}>
                    <TableCell>{label}</TableCell>
                    <TableCell>
                      {formatValue(results.portfolio_metrics[key], format)}
                    </TableCell>
                    <TableCell>
                      {results.benchmark_metrics && results.benchmark_metrics[key] 
                        ? formatValue(results.benchmark_metrics[key], format) 
                        : 'N/A'}
                    </TableCell>
                  </TableRow>
                ))}
                <TableRow>
                  <TableCell>Positive Periods</TableCell>
                  <TableCell>
                    {`${results.portfolio_metrics.positive_days} out of ${results.portfolio_metrics.total_days} (${(results.portfolio_metrics.positive_days / results.portfolio_metrics.total_days * 100).toFixed(2)}%)`}
                  </TableCell>
                  <TableCell>
                    {`${results.benchmark_metrics.positive_days} out of ${results.benchmark_metrics.total_days} (${(results.benchmark_metrics.positive_days / results.benchmark_metrics.total_days * 100).toFixed(2)}%)`}
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </TableContainer>
          <Typography variant="caption" sx={{ mt: 2, display: 'block' }}>
            * {benchmark.toUpperCase()} is used as the benchmark for calculations. 
            Value-at-risk metrics are monthly values.
          </Typography>
        </Paper>
      </>
    );
  };

  const renderRiskMetrics = () => {
    if (!results) return null;

    const riskMetrics = [
      { key: 'arithmetic_mean_monthly', label: 'Arithmetic Mean (monthly)', format: 'percent' },
      { key: 'arithmetic_mean_annual', label: 'Arithmetic Mean (annualized)', format: 'percent' },
      { key: 'geometric_mean_monthly', label: 'Geometric Mean (monthly)', format: 'percent' },
      { key: 'geometric_mean_annual', label: 'Geometric Mean (annualized)', format: 'percent' },
      { key: 'annual_volatility', label: 'Standard Deviation (annualized)', format: 'percent' },
      { key: 'downside_deviation', label: 'Downside Deviation (monthly)', format: 'percent' },
      { key: 'max_drawdown', label: 'Maximum Drawdown', format: 'percent' },
      { key: 'beta', label: 'Beta(*)', format: 'ratio' },
      { key: 'alpha', label: 'Alpha (annualized)', format: 'percent' },
      { key: 'r_squared', label: 'R2', format: 'percent' },
      { key: 'sharpe_ratio', label: 'Sharpe Ratio', format: 'ratio' },
      { key: 'sortino_ratio', label: 'Sortino Ratio', format: 'ratio' },
      { key: 'calmar_ratio', label: 'Calmar Ratio', format: 'ratio' },
      { key: 'var_historical', label: 'Historical Value-at-Risk (5%)', format: 'percent' },
      { key: 'cvar', label: 'Conditional Value-at-Risk (5%)', format: 'percent' },
      { key: 'active_return', label: 'Active Return', format: 'percent' },
      { key: 'tracking_error', label: 'Tracking Error', format: 'percent' },
      { key: 'information_ratio', label: 'Information Ratio', format: 'ratio' }
    ];

    return (
      <Paper sx={{ p: 2, mb: 2 }}>
        <Typography variant="h6" gutterBottom>Risk and Return Metrics</Typography>
        <Typography variant="subtitle2" gutterBottom color="textSecondary">
          Portfolio return and risk metrics
        </Typography>
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Metric</TableCell>
                <TableCell>Portfolio</TableCell>
                <TableCell>{results.benchmark_metrics ? benchmark.toUpperCase() : 'Benchmark'}</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {riskMetrics.map(({ key, label, format }) => (
                <TableRow key={key}>
                  <TableCell>{label}</TableCell>
                  <TableCell>{formatValue(results.portfolio_metrics[key], format)}</TableCell>
                  <TableCell>
                    {results.benchmark_metrics && results.benchmark_metrics[key] 
                      ? formatValue(results.benchmark_metrics[key], format) 
                      : 'N/A'}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
        <Typography variant="caption" sx={{ mt: 2, display: 'block' }}>
          * {benchmark.toUpperCase()} is used as the benchmark for calculations. 
          Value-at-risk metrics are monthly values.
        </Typography>
      </Paper>
    );
  };

  const renderDrawdownTable = (drawdowns, title) => {
    if (!drawdowns || drawdowns.length === 0) return null;

    return (
      <Box sx={{ mt: 3 }}>
        <Typography variant="h6" gutterBottom>{title}</Typography>
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Rank</TableCell>
                <TableCell>Start</TableCell>
                <TableCell>End</TableCell>
                <TableCell>Length</TableCell>
                <TableCell>Recovery By</TableCell>
                <TableCell>Recovery Time</TableCell>
                <TableCell>Underwater Period</TableCell>
                <TableCell align="right">Drawdown</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {drawdowns.map((drawdown, index) => (
                <TableRow key={index}>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>{drawdown.start}</TableCell>
                  <TableCell>{drawdown.end}</TableCell>
                  <TableCell>{drawdown.length}</TableCell>
                  <TableCell>{drawdown.recovery_date}</TableCell>
                  <TableCell>{drawdown.recovery_time}</TableCell>
                  <TableCell>{drawdown.underwater_period}</TableCell>
                  <TableCell align="right" sx={{ color: 'error.main' }}>
                    {(drawdown.drawdown * 100).toFixed(2)}%
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
        <Typography variant="caption" sx={{ mt: 1, display: 'block' }}>
          Worst 10 drawdowns included above
        </Typography>
      </Box>
    );
  };

  // Add this TabPanel component definition at the top level
  const TabPanel = ({ value, index, children }) => (
    <Box
      role="tabpanel"
      hidden={value !== index}
      sx={{
        minHeight: '400px',
        position: 'relative',
        width: '100%'
      }}
    >
      {value === index && (
        <Fade in={value === index} timeout={300}>
          <Box>{children}</Box>
        </Fade>
      )}
    </Box>
  );

  // Update the renderResults function
  const renderResults = () => {
    if (!results && !comparisonResults) return null;

    const tabs = [
      ...(results || comparisonResults ? [{ label: "Highlights", index: 0 }] : []),
      ...(results ? [
        { label: "Performance", index: 1 },
        { label: "Attribution Analysis", index: 2 },
        { label: "Rebalancing Analysis", index: 3 },
        { label: "Correlation Analysis", index: 4 }
      ] : []),
      ...(comparisonResults ? [{ label: "Portfolio Comparison", index: 5 }] : [])
    ];

    return (
      <Box sx={{ 
        minHeight: '600px', // Add minimum height to container
        position: 'relative'
      }}>
        <Paper sx={{ mb: 2, overflow: 'hidden' }}>
          <Tabs
            value={selectedTab}
            onChange={(_, newValue) => setSelectedTab(newValue)}
            variant="scrollable"
            scrollButtons="auto"
            sx={{
              borderBottom: 1,
              borderColor: 'divider',
              '& .MuiTab-root': {
                minWidth: 'auto',
                px: 3,
                transition: 'all 0.3s ease',
                '&:hover': {
                  bgcolor: 'action.hover',
                },
              },
              '& .Mui-selected': {
                fontWeight: 'bold',
                transform: 'scale(1.05)',
              },
            }}
          >
            {tabs.map((tab) => (
              <Tab 
                key={tab.index} 
                label={tab.label}
                sx={{
                  fontWeight: selectedTab === tab.index ? 'bold' : 'normal',
                  color: selectedTab === tab.index ? 'primary.main' : 'text.secondary'
                }}
              />
            ))}
          </Tabs>
        </Paper>

        <Box sx={{ 
          position: 'relative',
          minHeight: '400px' // Ensure consistent height
        }}>
          <TabPanel value={selectedTab} index={0}>
            {(results || comparisonResults) && renderHighlights()}
          </TabPanel>
          <TabPanel value={selectedTab} index={1}>
            {results && renderPerformanceSummary()}
          </TabPanel>
          <TabPanel value={selectedTab} index={2}>
            {results && renderAttribution()}
          </TabPanel>
          <TabPanel value={selectedTab} index={3}>
            {results && renderRebalancingAnalysis()}
          </TabPanel>
          <TabPanel value={selectedTab} index={4}>
            {results && renderCorrelationMatrix()}
          </TabPanel>
          <TabPanel value={selectedTab} index={5}>
            {comparisonResults && renderComparison()}
          </TabPanel>
        </Box>
      </Box>
    );
  };

  const handleCloseNotification = (event, reason) => {
    if (reason === 'clickaway') return;
    setNotification(prev => ({ ...prev, open: false }));
  };

  // Add delete function
  const handleDeletePortfolio = async (filename) => {
    try {
      setNotification({
        open: true,
        message: 'Deleting portfolio...',
        severity: 'info',
        duration: null
      });

      const response = await fetch('http://localhost:5000/api/portfolio/delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ filename })
      });
      
      const data = await response.json();
      if (data.success) {
        setSavedPortfolios(data.portfolios);
        setNotification({
          open: true,
          message: 'Portfolio deleted successfully',
          severity: 'success',
          duration: 3000
        });
      } else {
        throw new Error(data.error || 'Failed to delete portfolio');
      }
    } catch (err) {
      setNotification({
        open: true,
        message: `Error deleting portfolio: ${err.message}`,
        severity: 'error',
        duration: 5000
      });
    }
  };

  const renderPeriodPerformance = () => (
    <Grid container spacing={2}>
      <Grid item xs={12} md={3}>
        <Paper sx={{ p: 2 }}>
          <Typography variant="subtitle2">YTD Return</Typography>
          <Typography variant="h6" color={getMetricColor(ytdReturn, true)}>
            {formatValue(ytdReturn, 'percent')}
          </Typography>
        </Paper>
      </Grid>
      {/* Add similar items for 1Y, 3Y, 5Y returns */}
    </Grid>
  );

  // Add this function in the App component before the return statement
  const handleQuickAction = async (action) => {
    try {
      switch (action) {
        case 'loadExample':
          // Load example portfolio
          setPortfolio([
            { ticker: 'AAPL', weight: '20' },
            { ticker: 'MSFT', weight: '20' },
            { ticker: 'GOOGL', weight: '20' },
            { ticker: 'AMZN', weight: '20' },
            { ticker: 'VOO', weight: '20' }
          ]);
          setBenchmark('QQQ');
          setNotification({
            open: true,
            message: 'Example portfolio loaded',
            severity: 'success',
            duration: 3000
          });
          break;

        case 'clear':
          // Clear current portfolio
          setPortfolio([{ ticker: '', weight: '' }]);
          setResults(null);
          setAttribution(null);
          setRebalancingResults(null);
          setCorrelationData(null);
          setNotification({
            open: true,
            message: 'Portfolio cleared',
            severity: 'info',
            duration: 3000
          });
          break;

        case 'export':
          // Export current results
          if (!results) {
            setNotification({
              open: true,
              message: 'No results to export. Run backtest first.',
              severity: 'warning',
              duration: 3000
            });
            return;
          }
          await handleExportResults();
          break;

        case 'clearCache':
          // Clear data cache
          const response = await fetch('http://localhost:5000/api/cache/clear', {
            method: 'POST'
          });
          const data = await response.json();
          if (data.success) {
            setNotification({
              open: true,
              message: 'Cache cleared successfully',
              severity: 'success',
              duration: 3000
            });
          } else {
            throw new Error(data.error || 'Failed to clear cache');
          }
          break;

        default:
          console.warn(`Unknown action: ${action}`);
      }
    } catch (err) {
      setNotification({
        open: true,
        message: `Error: ${err.message}`,
        severity: 'error',
        duration: 5000
      });
    }
  };

  // Add this styled component at the top
  const StyledModeButton = styled(Button)(({ theme }) => ({
    height: '48px', // Fixed height
    flex: 1,
    position: 'relative',
    transition: 'all 0.2s ease-in-out',
    transform: 'scale(1)',
    '&:hover': {
      transform: 'scale(1.02)',
    },
  }));

  // Update the ComparisonModeToggle component
  const ComparisonModeToggle = ({ mode, onChange }) => {
    const theme = useTheme();
    
    return (
      <Paper 
        elevation={3}
        sx={{ 
          p: 2, 
          mb: 2,
          minHeight: '140px', // Fixed minimum height to prevent layout shifts
          background: `linear-gradient(45deg, ${alpha(theme.palette.primary.main, 0.05)}, ${alpha(theme.palette.secondary.main, 0.05)})`,
          backdropFilter: 'blur(8px)',
        }}
      >
        <Typography variant="subtitle1" gutterBottom>Analysis Mode</Typography>
        <Box sx={{ 
          display: 'flex', 
          gap: 2,
          mb: 2,
          height: '48px', // Fixed height container
        }}>
          <StyledModeButton
            variant={mode === 'benchmark' ? 'contained' : 'outlined'}
            onClick={() => onChange('benchmark')}
            startIcon={<ShowChartIcon />}
            sx={{
              opacity: mode === 'benchmark' ? 1 : 0.8,
              boxShadow: mode === 'benchmark' ? theme.shadows[4] : 'none',
            }}
          >
            Benchmark Analysis
          </StyledModeButton>

          <StyledModeButton
            variant={mode === 'portfolio' ? 'contained' : 'outlined'}
            onClick={() => onChange('portfolio')}
            startIcon={<CompareArrowsIcon />}
            sx={{
              opacity: mode === 'portfolio' ? 1 : 0.8,
              boxShadow: mode === 'portfolio' ? theme.shadows[4] : 'none',
            }}
          >
            Portfolio Comparison
          </StyledModeButton>
        </Box>

        <Box sx={{ 
          height: '24px', // Fixed height for description
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <Typography 
            variant="caption" 
            color="text.secondary"
            sx={{ 
              textAlign: 'center',
              fontStyle: 'italic',
              opacity: 0.8
            }}
          >
            {mode === 'benchmark' 
              ? "Compare your portfolio against a market benchmark"
              : "Compare multiple portfolios against each other"}
          </Typography>
        </Box>
      </Paper>
    );
  };

  // Update the ActionButtonsSection to use fixed heights
  const ActionButtonsSection = ({ 
    handleBacktest, 
    handleSavePortfolio, 
    loadSavedPortfolios,
    comparisonMode,
    setComparisonMode,
    loading,
    isMobile 
  }) => (
    <Box sx={{ mb: 2 }}>
      <Grid container spacing={2}>
        {/* Main Actions */}
        <Grid item xs={12}>
          <Box sx={{ 
            display: 'flex', 
            gap: 2, 
            flexWrap: 'wrap',
            height: '40px', // Fixed height for buttons
          }}>
            <Button
              variant="contained"
              color="primary"
              onClick={handleBacktest}
              disabled={loading}
              startIcon={loading ? <CircularProgress size={20} /> : null}
              sx={{ minWidth: '160px' }} // Fixed minimum width
            >
              {loading ? 'Running Backtest...' : 'Run Backtest'}
            </Button>

            <ButtonGroup 
              variant="outlined"
              sx={{ height: '100%' }} // Match parent height
            >
              <Button
                onClick={handleSavePortfolio}
                startIcon={<SaveIcon />}
                disabled={loading}
                sx={{ minWidth: '100px' }} // Fixed minimum width
              >
                Save
              </Button>
              <Button
                onClick={loadSavedPortfolios}
                startIcon={<LoadIcon />}
                disabled={loading}
                sx={{ minWidth: '100px' }} // Fixed minimum width
              >
                Load
              </Button>
            </ButtonGroup>
          </Box>
        </Grid>

        {/* Analysis Mode Toggle */}
        <Grid item xs={12}>
          <ComparisonModeToggle 
            mode={comparisonMode} 
            onChange={setComparisonMode}
          />
        </Grid>
      </Grid>
    </Box>
  );

  // Add error boundary component
  const ErrorFallback = ({ error, resetErrorBoundary }) => (
    <Paper 
      sx={{ 
        p: 3, 
        m: 2, 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center',
        gap: 2
      }}
    >
      <Typography variant="h6" color="error">
        Something went wrong
      </Typography>
      <Typography color="text.secondary">
        {error.message}
      </Typography>
      <Button 
        variant="contained" 
        onClick={resetErrorBoundary}
        startIcon={<RefreshIcon />}
      >
        Try Again
      </Button>
    </Paper>
  );

  // Add a LoadPortfolioButton component
  const LoadPortfolioButton = ({ onLoad, portfolioType, disabled }) => {
    const [anchorEl, setAnchorEl] = useState(null);
    const [savedPortfolios, setSavedPortfolios] = useState([]);
    const [loading, setLoading] = useState(false);

    const handleClick = async (event) => {
      setAnchorEl(event.currentTarget);
      setLoading(true);
      try {
        const response = await fetch('http://localhost:5000/api/portfolio/load');
        const data = await response.json();
        if (data.success) {
          setSavedPortfolios(data.portfolios);
        }
      } catch (err) {
        console.error('Failed to load portfolios:', err);
      }
      setLoading(false);
    };

    return (
      <>
        <Button
          variant="outlined"
          onClick={handleClick}
          startIcon={<LoadIcon />}
          disabled={disabled}
          sx={{ ml: 1 }}
        >
          Load {portfolioType}
        </Button>
        <Menu
          anchorEl={anchorEl}
          open={Boolean(anchorEl)}
          onClose={() => setAnchorEl(null)}
        >
          {loading ? (
            <MenuItem disabled>
              <CircularProgress size={20} sx={{ mr: 1 }} />
              Loading...
            </MenuItem>
          ) : savedPortfolios.length > 0 ? (
            savedPortfolios.map((savedPortfolio) => (
              <MenuItem
                key={savedPortfolio.filename}
                onClick={() => {
                  onLoad(savedPortfolio.portfolio);
                  setAnchorEl(null);
                }}
              >
                {savedPortfolio.portfolio.name || savedPortfolio.filename}
              </MenuItem>
            ))
          ) : (
            <MenuItem disabled>No saved portfolios</MenuItem>
          )}
        </Menu>
      </>
    );
  };

  // Update the PortfolioHealthScore component
  const PortfolioHealthScore = ({ portfolioA, portfolioB, totalWeightA, totalWeightB, comparisonMode }) => {
    // Only show health score if there's actual portfolio data
    const hasPortfolioData = portfolioA.some(stock => stock.ticker || stock.weight) ||
      (comparisonMode === 'portfolio' && portfolioB.some(stock => stock.ticker || stock.weight));
    
    if (!hasPortfolioData) return null;

    const calculatePortfolioScore = (portfolio, totalWeight) => {
      let score = 100;
      const validStocks = portfolio.filter(stock => stock.ticker && stock.weight);
      
      // Weight distribution check - more accurate
      const calculatedWeight = validStocks.reduce((sum, stock) => sum + parseFloat(stock.weight || 0), 0);
      if (Math.abs(calculatedWeight - 100) > 0.01) {
        const weightDiff = Math.abs(calculatedWeight - 100);
        score -= Math.min(20, weightDiff); // Cap penalty at 20 points
      }
      
      // Diversification check
      if (validStocks.length < 3) {
        score -= 15;
      } else if (validStocks.length < 5) {
        score -= 5; // Smaller penalty for moderate diversification
      }
      
      // Concentration check - more sophisticated
      const maxWeight = Math.max(...validStocks.map(stock => parseFloat(stock.weight) || 0));
      if (maxWeight > 50) {
        score -= 15;
      } else if (maxWeight > 30) {
        score -= 10;
      } else if (maxWeight > 20) {
        score -= 5;
      }
      
      return Math.max(0, score);
    };

    const scoreA = calculatePortfolioScore(portfolioA, totalWeightA);
    const scoreB = comparisonMode === 'portfolio' ? 
      calculatePortfolioScore(portfolioB, totalWeightB) : 100;

    // Calculate combined score
    const finalScore = comparisonMode === 'portfolio' ? 
      Math.floor((scoreA + scoreB) / 2) : scoreA;

    const getScoreColor = (score) => {
      if (score >= 80) return 'success.main';
      if (score >= 60) return 'warning.main';
      return 'error.main';
    };

    const getScoreStatus = (score) => {
      if (score >= 80) return 'Excellent';
      if (score >= 60) return 'Good';
      return 'Needs Attention';
    };

    return (
      <Paper sx={{ p: 2, mb: 2 }}>
        <Typography variant="h6" gutterBottom>Portfolio Health</Typography>
        <Grid container spacing={2}>
          <Grid item xs={12} md={4}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Box sx={{ position: 'relative', display: 'inline-flex' }}>
                <CircularProgress
                  variant="determinate"
                  value={finalScore}
                  size={80}
                  thickness={4}
                  sx={{ color: getScoreColor(finalScore) }}
                />
                <Box
                  sx={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    bottom: 0,
                    right: 0,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Typography variant="h6" component="div" color={getScoreColor(finalScore)}>
                    {finalScore}%
                  </Typography>
                </Box>
              </Box>
              <Typography variant="subtitle1">
                Overall Health: {getScoreStatus(finalScore)}
              </Typography>
            </Box>
          </Grid>

          {/* Portfolio A Health */}
          <Grid item xs={12} md={4}>
            <Paper elevation={3} sx={{ p: 2 }}>
              <Typography variant="subtitle2" gutterBottom>Portfolio A Health</Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                {portfolioA.length > 0 && (
                  <>
                    {portfolioA.filter(stock => stock.ticker && stock.weight).length < 5 && (
                      <Chip 
                        size="small" 
                        label={portfolioA.filter(stock => stock.ticker && stock.weight).length < 3 ? 
                          "Low Diversification" : "Moderate Diversification"} 
                        color={portfolioA.filter(stock => stock.ticker && stock.weight).length < 3 ? 
                          "warning" : "info"} 
                      />
                    )}
                    {Math.max(...portfolioA.filter(stock => stock.ticker).map(stock => parseFloat(stock.weight) || 0)) > 20 && (
                      <Chip 
                        size="small" 
                        label="High Concentration" 
                        color={Math.max(...portfolioA.filter(stock => stock.ticker).map(stock => parseFloat(stock.weight) || 0)) > 50 ? 
                          "error" : "warning"} 
                      />
                    )}
                    <Chip 
                      size="small" 
                      label={`Score: ${scoreA}%`} 
                      color={scoreA >= 80 ? 'success' : scoreA >= 60 ? 'warning' : 'error'}
                    />
                  </>
                )}
              </Box>
            </Paper>
          </Grid>

          {/* Portfolio B Health (only in comparison mode) */}
          {comparisonMode === 'portfolio' && (
            <Grid item xs={12} md={4}>
              <Paper elevation={3} sx={{ p: 2 }}>
                <Typography variant="subtitle2" gutterBottom>Portfolio B Health</Typography>
                <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                  {portfolioB.length > 0 && (
                    <>
                      {portfolioB.filter(stock => stock.ticker && stock.weight).length < 5 && (
                        <Chip 
                          size="small" 
                          label={portfolioB.filter(stock => stock.ticker && stock.weight).length < 3 ? 
                            "Low Diversification" : "Moderate Diversification"} 
                          color={portfolioB.filter(stock => stock.ticker && stock.weight).length < 3 ? 
                            "warning" : "info"} 
                        />
                      )}
                      {Math.max(...portfolioB.filter(stock => stock.ticker).map(stock => parseFloat(stock.weight) || 0)) > 20 && (
                        <Chip 
                          size="small" 
                          label="High Concentration" 
                          color={Math.max(...portfolioB.filter(stock => stock.ticker).map(stock => parseFloat(stock.weight) || 0)) > 50 ? 
                          "error" : "warning"} 
                        />
                      )}
                      <Chip 
                        size="small" 
                        label={`Score: ${scoreB}%`} 
                        color={scoreB >= 80 ? 'success' : scoreB >= 60 ? 'warning' : 'error'}
                      />
                    </>
                  )}
                </Box>
              </Paper>
            </Grid>
          )}
        </Grid>
      </Paper>
    );
  };

  const PortfolioSuggestions = ({ portfolio, results }) => {
    if (!results) return null;

    const generateSuggestions = () => {
      const suggestions = [];
      const metrics = results.portfolio_metrics;

      if (metrics.annual_volatility > 0.25) {
        suggestions.push({
          type: 'warning',
          message: 'High portfolio volatility detected. Consider adding more defensive stocks.',
          action: 'Reduce Risk'
        });
      }

      if (metrics.max_drawdown < -0.2) {
        suggestions.push({
          type: 'warning',
          message: 'Large maximum drawdown. Consider improving downside protection.',
          action: 'Improve Protection'
        });
      }

      if (metrics.sharpe_ratio < 1) {
        suggestions.push({
          type: 'info',
          message: 'Low risk-adjusted returns. Consider optimizing your asset allocation.',
          action: 'Optimize Returns'
        });
      }

      if (portfolio.length < 5) {
        suggestions.push({
          type: 'info',
          message: 'Limited diversification. Consider adding more assets to reduce risk.',
          action: 'Diversify'
        });
      }

      return suggestions;
    };

    const suggestions = generateSuggestions();

    return suggestions.length > 0 ? (
      <Paper sx={{ p: 2, mb: 2 }}>
        <Typography variant="h6" gutterBottom>
          Portfolio Suggestions
          <Tooltip title="Automated suggestions based on portfolio analysis">
            <InfoIcon fontSize="small" sx={{ ml: 1, color: 'action.active' }} />
          </Tooltip>
        </Typography>
        <List dense>
          {suggestions.map((suggestion, index) => (
            <ListItem
              key={index}
              sx={{
                bgcolor: `${suggestion.type}.light`,
                borderRadius: 1,
                mb: 1
              }}
            >
              <ListItemIcon>
                {suggestion.type === 'warning' ? (
                  <WarningIcon color="warning" />
                ) : (
                  <InfoIcon color="info" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={suggestion.message}
                secondary={suggestion.action}
              />
            </ListItem>
          ))}
        </List>
      </Paper>
    ) : null;
  };

  // Add this constant at the top level, after other constants
  const detailedMetrics = [
    { key: 'arithmetic_mean_monthly', label: 'Arithmetic Mean (monthly)', format: 'percent' },
    { key: 'arithmetic_mean_annual', label: 'Arithmetic Mean (annualized)', format: 'percent' },
    { key: 'geometric_mean_monthly', label: 'Geometric Mean (monthly)', format: 'percent' },
    { key: 'geometric_mean_annual', label: 'Geometric Mean (annualized)', format: 'percent' },
    { key: 'annual_volatility', label: 'Standard Deviation (annualized)', format: 'percent' },
    { key: 'downside_deviation', label: 'Downside Deviation (monthly)', format: 'percent' },
    { key: 'max_drawdown', label: 'Maximum Drawdown', format: 'percent' },
    { key: 'beta', label: 'Beta(*)', format: 'ratio' },
    { key: 'alpha', label: 'Alpha (annualized)', format: 'percent' },
    { key: 'r_squared', label: 'R2', format: 'percent' },
    { key: 'sharpe_ratio', label: 'Sharpe Ratio', format: 'ratio' },
    { key: 'sortino_ratio', label: 'Sortino Ratio', format: 'ratio' },
    { key: 'calmar_ratio', label: 'Calmar Ratio', format: 'ratio' },
    { key: 'var_historical', label: 'Historical Value-at-Risk (5%)', format: 'percent' },
    { key: 'cvar', label: 'Conditional Value-at-Risk (5%)', format: 'percent' },
    { key: 'active_return', label: 'Active Return', format: 'percent' },
    { key: 'tracking_error', label: 'Tracking Error', format: 'percent' },
    { key: 'information_ratio', label: 'Information Ratio', format: 'ratio' }
  ];

  // The return statement should be inside the App function
  return (
    <ErrorBoundary>
      <ThemeProvider theme={themeMemo}>
        <CssBaseline />
        <Container maxWidth="lg" sx={{ 
          bgcolor: 'background.default', 
          minHeight: '100vh',
          px: { xs: 1, sm: 2, md: 3 },  // Responsive padding
          py: 3,
          display: 'flex',
          flexDirection: 'column',
          gap: 2
        }}>
          {/* Header Section */}
          <Paper 
            elevation={2} 
            sx={{ 
              p: 2, 
              display: 'flex', 
              justifyContent: 'space-between', 
              alignItems: 'center',
              position: 'sticky',
              top: 0,
              zIndex: 1100,
              backdropFilter: 'blur(8px)',
              bgcolor: 'background.default'
            }}
          >
            <Typography variant={isMobile ? "h5" : "h4"} component="h1">
              Stock Portfolio Backtester
            </Typography>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <IconButton 
                onClick={() => setTutorialOpen(true)} 
                color="inherit"
                title="Help"
              >
                <HelpIcon />
              </IconButton>
              <IconButton 
                onClick={() => setDarkMode(!darkMode)} 
                color="inherit"
                title={darkMode ? "Light Mode" : "Dark Mode"}
              >
                {darkMode ? <LightModeIcon /> : <DarkModeIcon />}
              </IconButton>
            </Box>
          </Paper>

          {/* Main Content Section */}
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <PortfolioHealthScore 
              portfolioA={portfolio}
              portfolioB={portfolioB}
              totalWeightA={totalWeight}
              totalWeightB={totalWeightB}
              comparisonMode={comparisonMode}
            />
            
            {results && (
              <PortfolioSuggestions 
                portfolio={portfolio}
                results={results}
              />
            )}
            
            {/* Input Section */}
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {comparisonMode === 'portfolio' ? (
                // Portfolio Comparison Mode
                <Grid container spacing={2}>
                  <Grid item xs={12} md={6}>
                    <Paper sx={{ p: 2, mb: 2 }}>
                      <Box sx={{ 
                        display: 'flex', 
                        justifyContent: 'space-between', 
                        alignItems: 'center', 
                        mb: 2 
                      }}>
                        <Typography variant="h6">Portfolio A</Typography>
                        <Box>
                          <LoadPortfolioButton
                            onLoad={(loadedPortfolio) => {
                              setPortfolio(loadedPortfolio.portfolio);
                              validateWeights();
                            }}
                            portfolioType="Portfolio A"
                            disabled={loading}
                          />
                        </Box>
                      </Box>
                      <PortfolioSection 
                        portfolio={portfolio}
                        handleInputChange={handleInputChange}
                        handleRemoveStock={handleRemoveStock}
                        handleAddStock={handleAddStock}
                        isMobile={isMobile}
                        helpTexts={helpTexts}
                        title="Portfolio A Composition"
                      />
                    </Paper>
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Paper sx={{ p: 2, mb: 2 }}>
                      <Box sx={{ 
                        display: 'flex', 
                        justifyContent: 'space-between', 
                        alignItems: 'center', 
                        mb: 2 
                      }}>
                        <Typography variant="h6">Portfolio B</Typography>
                        <Box>
                          <LoadPortfolioButton
                            onLoad={(loadedPortfolio) => {
                              setPortfolioB(loadedPortfolio.portfolio);
                              validateWeightsB();
                            }}
                            portfolioType="Portfolio B"
                            disabled={loading}
                          />
                        </Box>
                      </Box>
                      <PortfolioSection 
                        portfolio={portfolioB}
                        handleInputChange={(index, field, value) => {
                          const newPortfolio = [...portfolioB];
                          newPortfolio[index][field] = value;
                          setPortfolioB(newPortfolio);
                          if (field === 'weight') validateWeightsB();
                        }}
                        handleRemoveStock={(index) => {
                          const newPortfolio = portfolioB.filter((_, i) => i !== index);
                          setPortfolioB(newPortfolio);
                        }}
                        handleAddStock={() => setPortfolioB([...portfolioB, { ticker: '', weight: '' }])}
                        isMobile={isMobile}
                        helpTexts={helpTexts}
                        isPortfolioB={true}
                        title="Portfolio B Composition"
                      />
                    </Paper>
                  </Grid>
                </Grid>
              ) : (
                // Benchmark Mode
                <PortfolioSection 
                  portfolio={portfolio}
                  handleInputChange={handleInputChange}
                  handleRemoveStock={handleRemoveStock}
                  handleAddStock={handleAddStock}
                  isMobile={isMobile}
                  helpTexts={helpTexts}
                />
              )}
              
              <BacktestParametersSection 
                benchmark={benchmark}
                startDate={startDate}
                transactionCost={transactionCost}
                setBenchmark={setBenchmark}
                setStartDate={setStartDate}
                setTransactionCost={setTransactionCost}
                handleDatePreset={handleDatePreset}
                datePresets={datePresets}
                isMobile={isMobile}
                helpTexts={helpTexts}
                showBenchmark={backtestParameters.showBenchmark}
              />

              <ActionButtonsSection 
                handleBacktest={handleBacktest}
                handleSavePortfolio={handleSavePortfolio}
                loadSavedPortfolios={loadSavedPortfolios}
                comparisonMode={comparisonMode}
                setComparisonMode={setComparisonMode}
                loading={loading}
                isMobile={isMobile}
              />
            </Box>

            {/* Results Section */}
            {loading && <LoadingState message="Processing..." />}
            {error && (
              <Alert 
                severity="error" 
                sx={{ mb: 2 }}
                action={
                  <IconButton
                    aria-label="close"
                    color="inherit"
                    size="small"
                    onClick={() => setError(null)}
                  >
                    <CloseIcon fontSize="inherit" />
                  </IconButton>
                }
              >
                {error}
              </Alert>
            )}
            <ResultsSection>
              <Box sx={{ 
                display: 'flex', 
                flexDirection: 'column', 
                gap: 2,
                opacity: loading ? 0.5 : 1,
                transition: 'opacity 0.3s'
              }}>
                {renderResults()}
              </Box>
            </ResultsSection>
          </Box>

          {/* Notifications */}
          <Snackbar
            open={notification.open}
            autoHideDuration={notification.duration}
            onClose={handleCloseNotification}
            anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            sx={{ bottom: { xs: 16, sm: 24 } }}
          >
            <Alert 
              onClose={handleCloseNotification} 
              severity={notification.severity}
              variant="filled"
              sx={{ width: '100%' }}
            >
              {notification.message}
              {notification.duration === null && (
                <CircularProgress 
                  size={16} 
                  sx={{ ml: 1, color: 'inherit' }} 
                />
              )}
            </Alert>
          </Snackbar>

          {/* Dialogs */}
          <Tutorial
            open={tutorialOpen}
            onClose={() => setTutorialOpen(false)}
          />
          
          <PortfolioComparisonDialog
            open={comparisonDialogOpen}
            onClose={() => setComparisonDialogOpen(false)}
            portfolios={savedPortfolios}
            onCompare={handleComparePortfolios}
          />
          
          <Dialog
            open={loadDialogOpen}
            onClose={() => setLoadDialogOpen(false)}
            maxWidth="sm"
            fullWidth
            fullScreen={isMobile}
          >
            <DialogTitle>
              Load Portfolio
              <IconButton
                aria-label="close"
                onClick={() => setLoadDialogOpen(false)}
                sx={{ position: 'absolute', right: 8, top: 8 }}
              >
                <CloseIcon />
              </IconButton>
            </DialogTitle>
            <DialogContent dividers>
              {savedPortfolios.length > 0 ? (
                <List>
                  {savedPortfolios.map((savedPortfolio, index) => (
                    <React.Fragment key={savedPortfolio.filename}>
                      <ListItem
                        sx={{ 
                          display: 'flex',
                          flexDirection: 'column',
                          alignItems: 'stretch',
                          p: 2
                        }}
                      >
                        <Box sx={{ 
                          display: 'flex', 
                          justifyContent: 'space-between',
                          alignItems: 'center',
                          width: '100%',
                          mb: 1
                        }}>
                          <EditablePortfolioName
                            initialName={savedPortfolio.portfolio.name || `Portfolio ${index + 1}`}
                            onSave={(newName) => handleUpdatePortfolioName(savedPortfolio.filename, newName)}
                          />
                          <Box>
                            <IconButton
                              onClick={() => handleLoadPortfolio(savedPortfolio.portfolio)}
                              color="primary"
                              title="Load Portfolio"
                            >
                              <LoadIcon />
                            </IconButton>
                            <IconButton 
                              color="error"
                              onClick={() => handleDeletePortfolio(savedPortfolio.filename)}
                              title="Delete Portfolio"
                            >
                              <DeleteIcon />
                            </IconButton>
                          </Box>
                        </Box>
                        <Typography variant="caption" color="text.secondary">
                          Saved on: {new Date(savedPortfolio.filename.split('_')[1].split('.')[0]).toLocaleString()}
                        </Typography>
                        <Box sx={{ mt: 1, display: 'flex', gap: 1 }}>
                          <Chip 
                            size="small" 
                            label={`${savedPortfolio.portfolio.portfolio.length} stocks`}
                            color="primary"
                            variant="outlined"
                          />
                          <Chip 
                            size="small" 
                            label={`Benchmark: ${savedPortfolio.portfolio.benchmark}`}
                            color="secondary"
                            variant="outlined"
                          />
                        </Box>
                      </ListItem>
                      {index < savedPortfolios.length - 1 && <Divider />}
                    </React.Fragment>
                  ))}
                </List>
              ) : (
                <Box sx={{ 
                  p: 4, 
                  textAlign: 'center', 
                  color: 'text.secondary',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 2
                }}>
                  <SaveIcon sx={{ fontSize: 48, opacity: 0.5 }} />
                  <Typography>No saved portfolios found</Typography>
                  <Typography variant="body2">
                    Save a portfolio to see it here
                  </Typography>
                </Box>
              )}
            </DialogContent>
          </Dialog>
        </Container>
      </ThemeProvider>
    </ErrorBoundary>
  );
} // End of App function

export default App;


// Remove these unused components/functions:
1. renderRiskMetrics - duplicate of detailed metrics in renderPerformanceSummary
2. renderPeriodPerformance - unused YTD performance component
3. renderDrawdownTable - functionality moved to comparison view
4. StyledPaper - unused styled component
5. AnimatedGrid - unused styled component
6. MetricCard - unused component
7. LoadingState - functionality covered by LoadingOverlay
8. LoadPortfolioButton - functionality moved to dialog
9. ErrorFallback - unused error component
10. formatValue function at the top (duplicate)

// Remove these unused imports:
import {
  Stability as StabilityIcon,  // Not used
  Shield as ShieldIcon,        // Not used
} from '@mui/icons-material'

// Remove unused state:
const [loadDialogOpen, setLoadDialogOpen] = useState(false); // Duplicate state
const [ytdReturn, setYtdReturn] = useState(null);           // Unused state

// Remove unused effects:
useEffect(() => {
  // Remove duplicate dark mode effect
}, []);

// Remove unused constants:
const getCorrelationColor = (value, isDarkMode) => { ... }  // Moved to component
const metricDescriptions = { ... }  // Duplicate object

// Remove unused helper functions:
const validateTicker = async (ticker) => { ... }  // Functionality moved to backend
const formatMetricValue = (value, format) => { ... }  // Duplicate function
const getMetricDescription = (key) => { ... }  // Unused function