def display_backtest_results(results, comparison_type, portfolio1_name, portfolio2_name=None):
        # Do not pre-format metrics here
        if comparison_type == "Portfolio vs Benchmark":
            display_portfolio_vs_benchmark(results, portfolio1_name)
        elif comparison_type == "Portfolio vs Portfolio":
            display_portfolio_vs_portfolio(results, portfolio1_name, portfolio2_name)
    
    def display_portfolio_vs_benchmark(results, portfolio_name):
        # Extract data from results
        returns = results['returns']
        cum_returns = results['cum_returns']
        weights = results['weights']
        price_data = results['price_data']
        available_selected = results['available_selected']
        metrics = results['metrics']
        benchmark_metrics = results.get('benchmark_metrics', {})
        benchmark_returns = results.get('benchmark_returns', pd.Series(dtype=float))
        benchmark_cum_returns = results.get('benchmark_cum_returns', pd.Series(dtype=float))
    
        # Define a consistent theme for all plots
        THEMES = {
            'plotly_dark': 'plotly_dark',
            'plotly_light': 'plotly_white'
        }
        selected_theme = THEMES.get('plotly_dark')  # Change as needed
    
        # Create tabs for better organization
        main_tab, metrics_tab, risk_tab, analysis_tab, insights_tab = st.tabs([
            "📈 Main Charts", "📊 Performance Metrics", "🎯 Risk Analysis", "🔍 Deep Analysis", "🧠 Metric-Based Insights"
        ])
    
        with main_tab:
            st.header("🔹 Portfolio vs Benchmark Overview")
            col1, col2 = st.columns([2, 1])
            with col1:
                st.subheader("Portfolio Composition")
                fig_composition = px.pie(
                    values=weights,
                    names=price_data.columns,
                    title="Current Portfolio Allocation",
                    template=selected_theme,
                    hole=0.4
                )
                fig_composition.update_traces(textinfo='percent+label')
                st.plotly_chart(fig_composition, use_container_width=True)
    
            with col2:
                st.subheader("Key Performance Indicators")
                # Format metrics here, ensuring numerical operations are valid
                annualized_cagr = metrics.get('Annualized Return (CAGR)', None)
                if isinstance(annualized_cagr, (int, float)) and not np.isnan(annualized_cagr):
                    annualized_return = f"{annualized_cagr:.2f}%"
                else:
                    annualized_return = "N/A"
    
                # Similarly format other metrics
                total_return = f"{(cum_returns.iloc[-1] - 1) * 100:.2f}%" if not cum_returns.empty else "N/A"
                sharpe_ratio = f"{metrics.get('Sharpe Ratio', 'N/A'):.2f}" if 'Sharpe Ratio' in metrics and not np.isnan(metrics.get('Sharpe Ratio', np.nan)) else "N/A"
                max_drawdown = f"{metrics.get('Maximum Drawdown', 0):.2f}%" if 'Maximum Drawdown' in metrics and not np.isnan(metrics.get('Maximum Drawdown', np.nan)) else "N/A"
    
                metrics_display = {
                    "Total Return": total_return,
                    "Annualized Return": annualized_return,
                    "Sharpe Ratio": sharpe_ratio,
                    "Max Drawdown": max_drawdown
                }
                for metric, value in metrics_display.items():
                    st.metric(metric, value)
    
        # Performance Metrics Tab
        with metrics_tab:
            st.header("📊 Key Performance Metrics")
            st.subheader("Performance Comparison Table")
    
            # Define metrics separately
            common_metrics = [
                'Annualized Return (CAGR)',
                'Maximum Drawdown',
                'Sharpe Ratio',
                'Sortino Ratio',
                'Standard Deviation (Annualized)',
                'Beta',
                'Alpha (annualized)',
                'R2',
                'Calmar Ratio',
                'Information Ratio',
                'Tracking Error',
                'Upside Capture Ratio',
                'Downside Capture Ratio',
                'Best Year',
                'Worst Year'
            ]
    
            # Filter metrics
            filtered_portfolio_metrics = {k: v for k, v in metrics.items() if k in common_metrics}
            filtered_benchmark_metrics = {k: v for k, v in benchmark_metrics.items() if k in common_metrics}
    
            # Create DataFrame for Portfolio vs Benchmark Metrics
            performance_comparison_df = create_performance_stats_df_portfolio_vs_benchmark(
                metrics_portfolio=filtered_portfolio_metrics,
                metrics_benchmark=filtered_benchmark_metrics,
                portfolio_name=portfolio_name
            )
    
            # Define which metrics are percentage-based
            percentage_metrics = [
                'Annualized Return (CAGR)',
                'Maximum Drawdown',
                'Standard Deviation (Annualized)',
                'Alpha (annualized)',
                'Tracking Error',
                'Upside Capture Ratio',
                'Downside Capture Ratio',
                'Best Year',
                'Worst Year'
            ]
    
            # Style the metrics table
            def highlight_better(row):
                styles = [''] * len(row)
                portfolio_val = row["Portfolio"]
                benchmark_val = row["Benchmark"]
    
                # Skip if Portfolio or Benchmark is 'N/A'
                if portfolio_val == "N/A" or benchmark_val == "N/A":
                    return styles
    
                try:
                    # Convert string values to float if possible
                    portfolio_num = float(str(portfolio_val).strip('%').strip('$').replace(',', ''))
                    benchmark_num = float(str(benchmark_val).strip('%').strip('$').replace(',', ''))
    
                    # Determine if higher is better or lower is better based on metric name
                    metric_name = row.name
                    lower_is_better = any(keyword in metric_name for keyword in [
                        'Drawdown', 'Deviation', 'Tracking Error', 'Downside Capture Ratio'
                    ])
                    if lower_is_better:
                        better = portfolio_num < benchmark_num
                    else:
                        better = portfolio_num > benchmark_num
    
                    # Apply styling
                    if better:
                        styles[0] = 'background-color: #d4f7d4'  # Portfolio Green
                        styles[1] = 'background-color: #f7d4d4'  # Benchmark Red
                    else:
                        styles[0] = 'background-color: #f7d4d4'  # Portfolio Red
                        styles[1] = 'background-color: #d4f7d4'  # Benchmark Green
                except (ValueError, TypeError):
                    pass  # Skip if conversion fails
    
                return styles
    
            def custom_formatter(x, metric):
                try:
                    # Attempt to convert to float after stripping possible symbols
                    if x == "N/A":
                        return "N/A"
                    value = float(str(x).strip('%').strip('$').replace(',', ''))
                    if metric in percentage_metrics:
                        return f"{value:.2f}%"
                    else:
                        return f"{value:.2f}"
                except (ValueError, TypeError):
                    return "N/A"  # Return 'N/A' if conversion fails
    
            # Apply formatter row-wise to access metric name
            def row_formatter(row):
                metric = row.name
                formatted = {}
                for col in ['Portfolio', 'Benchmark']:
                    formatted[col] = custom_formatter(row[col], metric)
                return pd.Series(formatted)
    
            # Ensure 'Portfolio' and 'Benchmark' columns exist
            required_columns = ['Portfolio', 'Benchmark']
            for col in required_columns:
                if col not in performance_comparison_df.columns:
                    performance_comparison_df[col] = "N/A"
    
            # Assuming performance_comparison_df is already created and correctly named
            formatted_metrics = performance_comparison_df.apply(row_formatter, axis=1)
            performance_comparison_df[['Portfolio', 'Benchmark']] = formatted_metrics[['Portfolio', 'Benchmark']]
    
            # Apply the highlight function to style the rows
            styled_metrics = performance_comparison_df.style.apply(
                highlight_better,
                axis=1
            ).format({
                'Portfolio': lambda x: x,
                'Benchmark': lambda x: x
            })
    
            # Add metric explanations
            metric_explanations = {
                'Annualized Return (CAGR)': 'Compound Annual Growth Rate - The geometric mean of portfolio returns, representing the mean annual growth rate over a specified time period.',
                'Maximum Drawdown': 'Largest peak-to-trough decline in the portfolio’s value, indicating the maximum potential loss.',
                'Sharpe Ratio': 'Measures the performance of the portfolio compared to a risk-free asset, after adjusting for its risk. Higher values indicate better risk-adjusted returns.',
                'Sortino Ratio': 'Similar to the Sharpe Ratio but only penalizes downside volatility, providing a better assessment of negative risk.',
                'Standard Deviation (Annualized)': 'Represents the portfolio’s volatility, measuring the dispersion of returns around the mean. Higher values indicate higher risk.',
                'Beta': 'Indicates the portfolio’s sensitivity to market movements. A beta greater than 1 means the portfolio is more volatile than the market.',
                'Alpha (annualized)': 'Represents the portfolio’s excess return over the expected return based on its beta. Positive alpha indicates outperformance.',
                'R2': 'Determines how well the portfolio’s returns are explained by the benchmark’s returns. Values close to 1 indicate strong correlation.',
                'Calmar Ratio': 'Calculates the portfolio’s return relative to its maximum drawdown. Higher values indicate better performance considering risk.',
                'Information Ratio': 'Measures the portfolio’s excess return over a benchmark relative to the volatility of that excess return.',
                'Tracking Error': 'Represents the standard deviation of the difference between the portfolio and benchmark returns, indicating consistency in outperforming the benchmark.',
                'Upside Capture Ratio': 'Shows how well the portfolio captures gains when the benchmark is up. Values above 100% indicate outperformance in up markets.',
                'Downside Capture Ratio': 'Shows how well the portfolio captures losses when the benchmark is down. Values below 100% indicate outperformance in down markets.',
                'Best Year': 'The highest annual return achieved by the portfolio within the assessment period.',
                'Worst Year': 'The lowest annual return experienced by the portfolio within the assessment period.'
            }
    
            # Display the metrics table
            col1, col2 = st.columns(2)
            with col1:
                st.dataframe(styled_metrics, use_container_width=True)
    
            with col2:
                with st.expander("📖 Metric Definitions", expanded=True):
                    for metric, explanation in metric_explanations.items():
                        st.markdown(f"**{metric}**")
                        st.markdown(f"_ {explanation}_")
                        st.markdown("---")
    
            # Interactive Summary Recommendations
            create_summary_recommendations('comparison', metrics=metrics)
    
    def display_portfolio_vs_portfolio(results, portfolio1_name, portfolio2_name):
        """Displays comparison between two portfolios with enhanced UI/UX."""
        # Extract data from results
        returns_a = results.get('returns_a', pd.Series(dtype=float))
        returns_b = results.get('returns_b', pd.Series(dtype=float))
        cum_returns_a = results.get('cum_returns_a', pd.Series(dtype=float))
        cum_returns_b = results.get('cum_returns_b', pd.Series(dtype=float))
        weights_a = results.get('weights_a', [])
        weights_b = results.get('weights_b', [])
        price_data_a = results.get('price_data_a', pd.DataFrame())
        price_data_b = results.get('price_data_b', pd.DataFrame())
        metrics_a = results.get('metrics_a', {})
        metrics_b = results.get('metrics_b', {})
    
        # Define available_a and available_b based on price data columns
        available_a = list(price_data_a.columns)
        available_b = list(price_data_b.columns)
    
        # Ensure that available_a and available_b are not empty
        if not available_a:
            st.error(f"No available data for Portfolio '{portfolio1}'.")
            return
        if not available_b:
            st.error(f"No available data for Portfolio '{portfolio2}'.")
            return
    
        # Define a consistent theme for all plots
        THEMES = {
            'plotly_dark': 'plotly_dark',
            'plotly_light': 'plotly_white'
        }
        selected_theme = THEMES.get('plotly_light')  # Change as needed
    
        # Create tabs for better organization
        overview_tab, comparison_tab, risk_tab, analysis_tab = st.tabs([
            "📊 Overview", "🔄 Comparison", "🎯 Risk Analysis", "🔍 Deep Analysis"
        ])
    
        with overview_tab:
            st.header("🔹 Portfolio Overview")
            col1, col2 = st.columns([1,1])
            
            with col1:
                st.subheader(f"{portfolio1} Composition")
                fig_comp_a = px.pie(
                    values=weights_a,
                    names=price_data_a.columns,
                    title=f"{portfolio1} Allocation",
                    template=selected_theme,
                    hole=0.4,
                    color_discrete_sequence=px.colors.sequential.Blues
                )
                fig_comp_a.update_traces(textinfo='percent+label')
                st.plotly_chart(fig_comp_a, use_container_width=True)
    
                # Key metrics for portfolio 1
                metrics_display_a = {
                    "Total Return": f"{(cum_returns_a.iloc[-1] - 1) * 100:.2f}%",
                    "Annualized Return": metrics_a.get('Annualized Return (CAGR)', 'N/A'),
                    "Sharpe Ratio": metrics_a.get('Sharpe Ratio', 'N/A'),
                    "Max Drawdown": metrics_a.get('Maximum Drawdown', 'N/A')
                }
                st.subheader(f"{portfolio1} Key Metrics")
                for metric, value in metrics_display_a.items():
                    st.metric(f"{metric}", value)
    
            with col2:
                st.subheader(f"{portfolio2} Composition")
                fig_comp_b = px.pie(
                    values=weights_b,
                    names=price_data_b.columns,
                    title=f"{portfolio2} Allocation",
                    template=selected_theme,
                    hole=0.4,
                    color_discrete_sequence=px.colors.sequential.Oranges
                )
                fig_comp_b.update_traces(textinfo='percent+label')
                st.plotly_chart(fig_comp_b, use_container_width=True)
    
                # Key metrics for portfolio 2
                metrics_display_b = {
                    "Total Return": f"{(cum_returns_b.iloc[-1] - 1) * 100:.2f}%",
                    "Annualized Return": metrics_b.get('Annualized Return (CAGR)', 'N/A'),
                    "Sharpe Ratio": metrics_b.get('Sharpe Ratio', 'N/A'),
                    "Max Drawdown": metrics_b.get('Maximum Drawdown', 'N/A')
                }
                st.subheader(f"{portfolio2} Key Metrics")
                for metric, value in metrics_display_b.items():
                    st.metric(f"{metric}", value)
    
            # Cumulative Returns Comparison with Interactive Features
            st.subheader("Cumulative Returns Comparison")
            fig_returns = go.Figure()
            fig_returns.add_trace(go.Scatter(
                x=cum_returns_a.index,
                y=cum_returns_a,
                name=portfolio1,
                line=dict(color='cyan', width=2),
                hovertemplate='%{y:.2f}'
            ))
            fig_returns.add_trace(go.Scatter(
                x=cum_returns_b.index,
                y=cum_returns_b,
                name=portfolio2,
                line=dict(color='orange', width=2, dash='dash'),
                hovertemplate='%{y:.2f}'
            ))
            fig_returns.update_layout(
                template=selected_theme,
                hovermode='x unified',
                height=500,
                xaxis_title='Date',
                yaxis_title='Cumulative Returns',
                legend=dict(x=0.01, y=0.99)
            )
            st.plotly_chart(fig_returns, use_container_width=True)
    
            metrics_a = results.get('metrics_a', {})
            metrics_b = results.get('metrics_b', {})
    
            create_portfolio_comparison_summary(
                portfolio1_name=portfolio1_name,
                portfolio2_name=portfolio2_name,
                metrics_a=metrics_a,
                metrics_b=metrics_b
            )
    
        with comparison_tab:
            st.header("🔄 Performance Metrics Comparison")
            st.subheader("Detailed Performance Metrics")
    
            detailed_metrics = [
                'Annualized Return (CAGR)',
                'Sharpe Ratio',
                'Sortino Ratio',
                'Maximum Drawdown',
                'Beta',
                'Alpha (annualized)',
                'Information Ratio',
                'Modigliani–Modigliani Measure',
                'Tracking Error',
                'Calmar Ratio'
            ]
    
            metrics_comparison = pd.DataFrame({
                'Metric': detailed_metrics,
                portfolio1_name: [metrics_a.get(metric, "N/A") for metric in detailed_metrics],
                portfolio2_name: [metrics_b.get(metric, "N/A") for metric in detailed_metrics]
            })
    
            # Apply styling
            styled_comparison = metrics_comparison.style.apply(
                highlight_better_performance(portfolio1_name, portfolio2_name),
                axis=1
            )
    
            # Display the styled dataframe
            st.dataframe(styled_comparison, height=400)
    
            # Rolling Performance Difference with Interactive Slider
            st.subheader("Rolling Performance Difference (30-Day MA)")
            window_size = st.slider("Select Rolling Window (Days)", min_value=10, max_value=60, value=30)
            rolling_diff = (returns_a - returns_b).rolling(window=window_size).mean() * 252
    
            fig_diff = px.line(
                rolling_diff,
                title=f"{window_size}-Day Rolling Return Difference",
                labels={"index": "Date", "value": "Return Difference"},
                template=selected_theme
            )
            fig_diff.update_traces(line=dict(color='magenta'))
            fig_diff.update_layout(
                hovermode='x unified',
                height=500,
                xaxis_title='Date',
                yaxis_title='Return Difference'
            )
            st.plotly_chart(fig_diff, use_container_width=True)
    
        with risk_tab:
            st.header("🎯 Risk Analysis")
            col1, col2 = st.columns([1,1])
            
            with col1:
                    # Rolling Volatility Plot
                    st.subheader("📉 Rolling Volatility (30-Day)")
                    rolling_vol = returns_a.rolling(window=30).std() * np.sqrt(252)
                    rolling_vol_bench = returns_b.rolling(window=30).std() * np.sqrt(252)
                    
                    fig_vol = go.Figure()
                    fig_vol.add_trace(go.Scatter(
                        x=rolling_vol.index,
                        y=rolling_vol,
                        name=f"{portfolio1_name} Volatility",
                        line=dict(color='cyan', width=2)
                    ))
                    fig_vol.add_trace(go.Scatter(
                        x=rolling_vol_bench.index,
                        y=rolling_vol_bench,
                        name=f"{portfolio2_name} Volatility",
                        line=dict(color='orange', width=2, dash='dash')
                    ))
                    fig_vol.update_layout(
                        template=selected_theme,
                        hovermode='x unified',
                        height=400,
                        xaxis_title='Date',
                        yaxis_title='Annualized Volatility (%)',
                        legend=dict(x=0.01, y=0.99)
                    )
                    st.plotly_chart(fig_vol, use_container_width=True)
                    
                    # Drawdowns Comparison
                    st.subheader("📉 Top 10 Drawdowns Comparison")
                    drawdowns_portfolio = get_drawdown_details(cum_returns_a)
                    drawdowns_benchmark = get_drawdown_details(cum_returns_b)
    
                    if drawdowns_portfolio and drawdowns_benchmark:
                        drawdowns_portfolio_df = pd.DataFrame(drawdowns_portfolio).sort_values(by='Drawdown', ascending=True).head(10)
                        drawdowns_benchmark_df = pd.DataFrame(drawdowns_benchmark).sort_values(by='Drawdown', ascending=True).head(10)
    
                        combined_drawdowns = pd.DataFrame({
                            f"📅 {portfolio1_name} Start Date": drawdowns_portfolio_df['Start'],
                            f"📅 {portfolio1_name} End Date": drawdowns_portfolio_df['End'],
                            f"📉 {portfolio1_name} Drawdown (%)": drawdowns_portfolio_df['Drawdown'],
                            f"📅 {portfolio2_name} Start Date": drawdowns_benchmark_df['Start'],
                            f"📅 {portfolio2_name} End Date": drawdowns_benchmark_df['End'],
                            f"📉 {portfolio2_name} Drawdown (%)": drawdowns_benchmark_df['Drawdown']
                        })
    
                        st.table(combined_drawdowns)
    
                        fig_drawdown_comparison = go.Figure(data=[
                            go.Bar(
                                name=portfolio1_name,
                                x=drawdowns_portfolio_df['Start'],
                                y=drawdowns_portfolio_df['Drawdown'],
                                marker_color='cyan',
                                hovertemplate='%{y:.2f}% on %{x}<extra></extra>'
                            ),
                            go.Bar(
                                name=portfolio2_name,
                                x=drawdowns_benchmark_df['Start'],
                                y=drawdowns_benchmark_df['Drawdown'],
                                marker_color='orange',
                                hovertemplate='%{y:.2f}% on %{x}<extra></extra>'
                            )
                        ])
                        fig_drawdown_comparison.update_layout(
                            barmode='group',
                            title=f"📊 Top 10 Drawdowns Comparison: {portfolio1_name} vs {portfolio2_name}",
                            xaxis_title='Start Date',
                            yaxis_title='Drawdown (%)',
                            template=selected_theme,
                            legend=dict(x=0.01, y=0.99),
                            height=600
                        )
                        st.plotly_chart(fig_drawdown_comparison, use_container_width=True)
                    else:
                        st.write("⚠️ Insufficient drawdown data for comparison.")
                    
            with col2:
                st.subheader("🛡️ Risk Contribution Analysis")
                col3, col4 = st.columns([1,1])
                
                with col3:
                    # Risk Contribution for Portfolio A
                    risk_contrib_a = calculate_risk_contribution(
                        returns_a.pct_change().dropna(),
                        weights_a
                    )
                    
                    # Risk Contribution for Portfolio B
                    risk_contrib_b = calculate_risk_contribution(
                        returns_b.pct_change().dropna(),
                        weights_b
                    )
                    
                    # Create DataFrame for plotting
                    risk_contrib_df_a = pd.DataFrame({
                        'Asset': available_a,
                        'Risk Contribution (%)': risk_contrib_a
                    }).sort_values(by='Risk Contribution (%)', ascending=False)
                    
                    risk_contrib_df_b = pd.DataFrame({
                        'Asset': available_b,
                        'Risk Contribution (%)': risk_contrib_b
                    }).sort_values(by='Risk Contribution (%)', ascending=False)
                    
                    # Plot Risk Contribution for Portfolio A
                    fig_risk_a = px.bar(
                        risk_contrib_df_a,
                        x='Asset',
                        y='Risk Contribution (%)',
                        title=f"🔍 {portfolio1_name} Risk Contribution",
                        labels={'Risk Contribution (%)': 'Risk Contribution (%)'},
                        template=selected_theme,
                        color='Risk Contribution (%)',
                        color_continuous_scale='Blues',
                        hover_data=['Risk Contribution (%)']
                    )
                    fig_risk_a.update_layout(
                        xaxis_title='Asset',
                        yaxis_title='Risk Contribution (%)',
                        height=500
                    )
                    st.plotly_chart(fig_risk_a, use_container_width=True)
            
                with col4:
                    # Plot Risk Contribution for Portfolio B
                    fig_risk_b = px.bar(
                        risk_contrib_df_b,
                        x='Asset',
                        y='Risk Contribution (%)',
                        title=f"🔍 {portfolio2_name} Risk Contribution",
                        labels={'Risk Contribution (%)': 'Risk Contribution (%)'},
                        template=selected_theme,
                        color='Risk Contribution (%)',
                        color_continuous_scale='Oranges',
                        hover_data=['Risk Contribution (%)']
                    )
                    fig_risk_b.update_layout(
                        xaxis_title='Asset',
                        yaxis_title='Risk Contribution (%)',
                        height=500
                    )
                    st.plotly_chart(fig_risk_b, use_container_width=True)
    
        elif current_step == "Optimize Portfolio":
            # Relevant code for Optimize Portfolio tab
            pass  # Not included as it's outside the performance metrics and risk analysis tabs
    
    def plot_drawdown_comparison(cum_returns_portfolio: pd.Series, cum_returns_benchmark: pd.Series, portfolio_name='Portfolio', benchmark_name='Benchmark') -> None:
        """Plots an enhanced drawdown comparison between portfolio and benchmark with improved visuals."""
        
        # Calculate drawdowns for portfolio
        portfolio_drawdown = (cum_returns_portfolio / cum_returns_portfolio.expanding().max() - 1) * 100
        
        # Calculate drawdowns for benchmark
        benchmark_drawdown = (cum_returns_benchmark / cum_returns_benchmark.expanding().max() - 1) * 100
        
        fig_drawdown = go.Figure()
        
        # Add portfolio drawdown
        fig_drawdown.add_trace(go.Scatter(
            x=portfolio_drawdown.index,
            y=portfolio_drawdown,
            mode='lines',
            name=portfolio_name,
            line=dict(color='red', width=2)
        ))
        
        # Add benchmark drawdown if available
        if not cum_returns_benchmark.empty:
            fig_drawdown.add_trace(go.Scatter(
                x=benchmark_drawdown.index,
                y=benchmark_drawdown,
                mode='lines',
                name=benchmark_name,
                line=dict(color='blue', width=2, dash='dash')
            ))
        
        # Update layout with better formatting
        fig_drawdown.update_layout(
            title=f'📉 Drawdown Comparison: {portfolio_name} vs {benchmark_name}',
            hovermode='x unified',
            yaxis=dict(
                showgrid=True,
                zeroline=True,
                title='Drawdown (%)',
                tickformat='.1f'
            ),
            xaxis=dict(
                showgrid=True,
                title='Date'
            ),
            legend=dict(
                x=0.01,
                y=0.99,
                bgcolor='rgba(255, 255, 255, 0.8)'
            ),
            height=500,
            template='plotly_white'
        )
        
        st.plotly_chart(fig_drawdown, use_container_width=True)
    
    def plot_growth_comparison(cum_returns, benchmark_cum_returns, portfolio_name='Portfolio', benchmark_name='Benchmark'):
        """Plots an enhanced growth comparison between portfolio and benchmark with improved interactivity."""
        fig_growth = px.line(
            title='📈 Growth Comparison',
            labels={'value': 'Cumulative Returns', 'index': 'Date'},
            template=THEME
        )
        
        fig_growth.add_scatter(
            x=cum_returns.index,
            y=cum_returns,
            mode='lines',
            name=portfolio_name,
            line=dict(color='cyan', width=2)
        )
        fig_growth.add_scatter(
            x=benchmark_cum_returns.index,
            y=benchmark_cum_returns,
            mode='lines',
            name=benchmark_name,
            line=dict(color='orange', width=2, dash='dash')
        )
        
        fig_growth.update_layout(
            hovermode='x unified',
            xaxis=dict(showgrid=True),
            yaxis=dict(showgrid=True),
            legend=dict(title="Legend", x=0.01, y=0.99),
            height=600  # Added height parameter
        )
        
        st.plotly_chart(fig_growth, use_container_width=True, height=600, config={'responsive': True})
    
    with metrics_tab:
        st.header("📊 Key Performance Metrics")
        st.subheader("Performance Comparison Table")
        
        # Existing performance comparison table code...
        
        # Add Growth Comparison Graph
        st.subheader("📈 Growth Comparison")
        if 'cum_returns' in results and 'benchmark_cum_returns' in results:
            plot_growth_comparison(
                cum_returns=results['cum_returns'],
                benchmark_cum_returns=results['benchmark_cum_returns'],
                portfolio_name=portfolio_name,
                benchmark_name='Benchmark'
            )
        else:
            st.warning("📉 Cumulative returns data is unavailable for growth comparison.")
    
    with risk_tab:
        st.header("🎯 Risk Analysis")
        col1, col2 = st.columns([1,1])
        
        with col1:
            # Rolling Volatility Plot
            st.subheader("📉 Rolling Volatility (30-Day)")
            rolling_vol = returns_a.rolling(window=30).std() * np.sqrt(252)
            rolling_vol_bench = returns_b.rolling(window=30).std() * np.sqrt(252)
            
            fig_vol = go.Figure()
            fig_vol.add_trace(go.Scatter(
                x=rolling_vol.index,
                y=rolling_vol,
                name=f"{portfolio1_name} Volatility",
                line=dict(color='cyan', width=2)
            ))
            fig_vol.add_trace(go.Scatter(
                x=rolling_vol_bench.index,
                y=rolling_vol_bench,
                name=f"{benchmark_name} Volatility",
                line=dict(color='orange', width=2, dash='dash')
            ))
            fig_vol.update_layout(
                template=selected_theme,
                hovermode='x unified',
                height=400,
                xaxis_title='Date',
                yaxis_title='Annualized Volatility (%)',
                legend=dict(x=0.01, y=0.99)
            )
            st.plotly_chart(fig_vol, use_container_width=True)
            
            # Drawdowns Comparison using Line Chart Instead of Bar Chart
            st.subheader("📉 Top 10 Drawdowns Comparison")
            drawdowns_portfolio = get_drawdown_details(cum_returns_a)
            drawdowns_benchmark = get_drawdown_details(cum_returns_b)
    
            if drawdowns_portfolio and drawdowns_benchmark:
                drawdowns_portfolio_df = pd.DataFrame(drawdowns_portfolio).sort_values(by='Drawdown', ascending=True).head(10)
                drawdowns_benchmark_df = pd.DataFrame(drawdowns_benchmark).sort_values(by='Drawdown', ascending=True).head(10)
    
                combined_drawdowns = pd.DataFrame({
                    f"📅 {portfolio1_name} Start Date": drawdowns_portfolio_df['Start'],
                    f"📅 {portfolio1_name} End Date": drawdowns_portfolio_df['End'],
                    f"📉 {portfolio1_name} Drawdown (%)": drawdowns_portfolio_df['Drawdown'],
                    f"📅 {benchmark_name} Start Date": drawdowns_benchmark_df['Start'],
                    f"📅 {benchmark_name} End Date": drawdowns_benchmark_df['End'],
                    f"📉 {benchmark_name} Drawdown (%)": drawdowns_benchmark_df['Drawdown']
                })
    
                st.table(combined_drawdowns)
    
                # Replace Bar Chart with Line Chart for Drawdown Comparison
                fig_drawdown_comparison = go.Figure()
                fig_drawdown_comparison.add_trace(go.Scatter(
                    x=drawdowns_portfolio_df['Start'],
                    y=drawdowns_portfolio_df['Drawdown'],
                    mode='lines+markers',
                    name=portfolio1_name,
                    line=dict(color='cyan', width=2)
                ))
                fig_drawdown_comparison.add_trace(go.Scatter(
                    x=drawdowns_benchmark_df['Start'],
                    y=drawdowns_benchmark_df['Drawdown'],
                    mode='lines+markers',
                    name=benchmark_name,
                    line=dict(color='orange', width=2, dash='dash')
                ))
                fig_drawdown_comparison.update_layout(
                    title=f"📊 Top 10 Drawdowns Comparison: {portfolio1_name} vs {benchmark_name}",
                    xaxis_title='Start Date',
                    yaxis_title='Drawdown (%)',
                    template=selected_theme,
                    legend=dict(x=0.01, y=0.99),
                    height=600
                )
                st.plotly_chart(fig_drawdown_comparison, use_container_width=True)
            else:
                st.write("⚠️ Insufficient drawdown data for comparison.")

problem: improve the 📊 Performance Metrics and 🎯 Risk Analysis tab user interface, reorganize as its a bit too messy right now, also dont use bar chart for drawdown comparison, use sth better, and add growth comparison graph in 📊 Performance Metrics
if the segments code need update, please return the full updated segments code, no need import or other stuff, only the full version of the updated segment, also brief explanation of changes on each part