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_name}'.")
            return
        if not available_b:
            st.error(f"No available data for Portfolio '{portfolio2_name}'.")
            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, deep_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_name} Composition")
                fig_comp_a = px.pie(
                    values=weights_a,
                    names=price_data_a.columns,
                    title=f"{portfolio1_name} 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_name} Key Metrics")
                for metric, value in metrics_display_a.items():
                    st.metric(f"{metric}", value)
    
            with col2:
                st.subheader(f"{portfolio2_name} Composition")
                fig_comp_b = px.pie(
                    values=weights_b,
                    names=price_data_b.columns,
                    title=f"{portfolio2_name} 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_name} 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_name,
                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_name,
                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 Comparison with Interactive Layers
                 st.subheader("📉 Rolling Volatility Comparison (30-Day)")
                 rolling_vol_a = returns_a.rolling(window=30).std() * np.sqrt(252)
                 rolling_vol_b = returns_b.rolling(window=30).std() * np.sqrt(252)
                 
                 fig_vol = go.Figure()
                 fig_vol.add_trace(go.Scatter(
                     x=rolling_vol_a.index,
                     y=rolling_vol_a,
                     name=f"{portfolio1_name} Volatility",
                     line=dict(color='cyan', width=2)
                 ))
                 fig_vol.add_trace(go.Scatter(
                     x=rolling_vol_b.index,
                     y=rolling_vol_b,
                     name=f"{portfolio2_name} Volatility",
                     line=dict(color='orange', width=2, dash='dash')
                 ))
                 fig_vol.update_layout(
                     template=selected_theme,
                     hovermode='x unified',
                     height=500,
                     xaxis_title='Date',
                     yaxis_title='Annualized Volatility (%)',
                     legend=dict(x=0.01, y=0.99)
                 )
                 st.plotly_chart(fig_vol, use_container_width=True)
    
            with col2:
                 # Rolling Correlation Comparison with Interactive Features
                 st.subheader("🔄 Rolling Correlation (30-Day) Between Portfolios")
                 rolling_corr = returns_a.rolling(window=30).corr(returns_b)
                 
                 fig_corr = px.line(
                     rolling_corr,
                     title="📈 30-Day Rolling Correlation",
                     labels={"index": "Date", "value": "Correlation"},
                     template=selected_theme
                 )
                 fig_corr.update_traces(line=dict(color='purple'))
                 fig_corr.update_layout(
                     hovermode='x unified',
                     height=500,
                     xaxis_title='Date',
                     yaxis_title='Correlation'
                 )
                 st.plotly_chart(fig_corr, use_container_width=True)
    
            st.subheader("📉 Top 10 Drawdowns Comparison Between Portfolios")
            col3, col4 = st.columns([1,1])
            
            with col3:
                 # Get drawdown details
                 drawdowns_a = get_drawdown_details(cum_returns_a)
                 drawdowns_b = get_drawdown_details(cum_returns_b)
     
                 # Check if drawdown data is available
                 if drawdowns_a and drawdowns_b:
                     # Convert to DataFrame and sort
                     drawdowns_a_df = pd.DataFrame(drawdowns_a).sort_values(by='Drawdown', ascending=True).head(10)
                     drawdowns_b_df = pd.DataFrame(drawdowns_b).sort_values(by='Drawdown', ascending=True).head(10)
     
                     # Combine for comparison
                     combined_drawdowns = pd.DataFrame({
                         f"{portfolio1_name} Date": drawdowns_a_df['Start'],
                         f"{portfolio1_name} Drawdown (%)": drawdowns_a_df['Drawdown'],
                         f"{portfolio2_name} Date": drawdowns_b_df['Start'],
                         f"{portfolio2_name} Drawdown (%)": drawdowns_b_df['Drawdown']
                     })
     
                     # Display the comparison table
                     st.table(combined_drawdowns)
     
                     # Enhanced Comparative Line Chart
                     fig_drawdown_comparison = go.Figure()
                     fig_drawdown_comparison.add_trace(go.Scatter(
                         x=drawdowns_a_df['Start'],
                         y=drawdowns_a_df['Drawdown'],
                         mode='lines+markers',
                         name=f"{portfolio1_name} Drawdown",
                         line=dict(color='cyan', width=2)
                     ))
                     fig_drawdown_comparison.add_trace(go.Scatter(
                         x=drawdowns_b_df['Start'],
                         y=drawdowns_b_df['Drawdown'],
                         mode='lines+markers',
                         name=f"{portfolio2_name} Drawdown",
                         line=dict(color='orange', width=2, dash='dash')
                     ))
                     fig_drawdown_comparison.update_layout(
                         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 deep_analysis_tab:
            st.header("🔍 Deep Analysis")
            col1, col2 = st.columns([1,1])
            
            with col1:
                # Monthly Returns Heatmap for Portfolio1
                st.subheader(f"{portfolio1_name} Monthly Returns Heatmap")
                monthly_returns_a = returns_a.resample('M').agg(lambda x: (1 + x).prod() - 1)
                monthly_matrix_a = monthly_returns_a.groupby([monthly_returns_a.index.year, monthly_returns_a.index.month]).first().unstack()
                
                fig_heat_a = px.imshow(
                    monthly_matrix_a,
                    labels=dict(x="Month", y="Year", color="Returns"),
                    color_continuous_scale="RdYlGn",
                    title=f"{portfolio1_name} Monthly Returns Heatmap",
                    template=selected_theme
                )
                fig_heat_a.update_layout(
                    xaxis_title='Month',
                    yaxis_title='Year',
                    height=500
                )
                st.plotly_chart(fig_heat_a, use_container_width=True)
    
            with col2:
                # Monthly Returns Heatmap for Portfolio2
                st.subheader(f"{portfolio2_name} Monthly Returns Heatmap")
                monthly_returns_b = returns_b.resample('M').agg(lambda x: (1 + x).prod() - 1)
                monthly_matrix_b = monthly_returns_b.groupby([monthly_returns_b.index.year, monthly_returns_b.index.month]).first().unstack()
                
                fig_heat_b = px.imshow(
                    monthly_matrix_b,
                    labels=dict(x="Month", y="Year", color="Returns"),
                    color_continuous_scale="RdYlGn",
                    title=f"{portfolio2_name} Monthly Returns Heatmap",
                    template=selected_theme
                )
                fig_heat_b.update_layout(
                    xaxis_title='Month',
                    yaxis_title='Year',
                    height=500
                )
                st.plotly_chart(fig_heat_b, use_container_width=True)
    
            # Risk-Return Scatter Plot with Interactive Annotations
            st.subheader("🔥 Risk vs Return Scatter Plot")
            fig_risk_return = go.Figure()
            fig_risk_return.add_trace(go.Scatter(
                x=[returns_a.std() * np.sqrt(252)],
                y=[returns_a.mean() * 252],
                mode='markers+text',
                marker=dict(
                    size=20,
                    color='cyan',
                    line=dict(width=2, color='DarkSlateGrey')
                ),
                text=[portfolio1_name],
                textposition="top center",
                name=portfolio1_name
            ))
            fig_risk_return.add_trace(go.Scatter(
                x=[returns_b.std() * np.sqrt(252)],
                y=[returns_b.mean() * 252],
                mode='markers+text',
                marker=dict(
                    size=20,
                    color='orange',
                    line=dict(width=2, color='DarkSlateGrey')
                ),
                text=[portfolio2_name],
                textposition="top center",
                name=portfolio2_name
            ))
            fig_risk_return.update_layout(
                title='🔥 Risk vs Return Scatter Plot',
                xaxis_title='Annualized Volatility (Std Dev)',
                yaxis_title='Annualized Return',
                template=selected_theme,
                xaxis=dict(range=[0, max(returns_a.std(), returns_b.std()) * np.sqrt(252) * 1.2]),
                yaxis=dict(range=[0, max(returns_a.mean(), returns_b.mean()) * 252 * 1.2]),
                height=600
            )
            st.plotly_chart(fig_risk_return, use_container_width=True)
    
        def create_portfolio_comparison_summary(portfolio1_name: str, portfolio2_name: str, metrics_a: dict, metrics_b: dict):
            """
            Creates a single, comprehensive summary for portfolio comparison with actionable insights.
            """
            st.markdown("---")  # Visual separator
            
            with st.expander("📋 Portfolio Comparison Insights", expanded=True):
                # Performance Comparison
                st.markdown("### 📊 Key Performance Comparison")
                
                # Create two columns for side-by-side comparison
                col1, col2 = st.columns(2)
                
                metrics_to_compare = {
                    'Returns': 'Annualized Return (CAGR)',
                    'Risk': 'Standard Deviation (Annualized)',
                    'Risk-Adjusted': 'Sharpe Ratio',
                    'Maximum Loss': 'Maximum Drawdown'
                }
                
                with col1:
                    st.markdown(f"**{portfolio1_name}**")
                    for label, metric in metrics_to_compare.items():
                        value = metrics_a.get(metric, "N/A")
                        st.metric(label, value)
                        
                with col2:
                    st.markdown(f"**{portfolio2_name}**")
                    for label, metric in metrics_to_compare.items():
                        value = metrics_b.get(metric, "N/A")
                        st.metric(label, value)
                
                # Key Insights
                st.markdown("### 🔍 Key Insights")
                
                # Safely extract and compare metrics
                def safe_extract(metric_dict, metric_name):
                    value = metric_dict.get(metric_name, 0)
                    if isinstance(value, str):
                        try:
                            return float(value.strip('%'))
                        except (ValueError, AttributeError):
                            return float(value)
                        except ValueError:
                            st.warning(f"⚠️ Unable to convert metric '{metric_name}' to float. Using 0.")
                            return 0.0
                    elif isinstance(value, (float, np.float64, int)):
                        return float(value)
                    else:
                        st.warning(f"⚠️ Unexpected type for metric '{metric_name}'. Using 0.")
                        return 0.0
                
                returns_a = safe_extract(metrics_a, 'Annualized Return (CAGR)')
                returns_b = safe_extract(metrics_b, 'Annualized Return (CAGR)')
                better_returns = portfolio1_name if returns_a > returns_b else portfolio2_name
                
                vol_a = safe_extract(metrics_a, 'Standard Deviation (Annualized)')
                vol_b = safe_extract(metrics_b, 'Standard Deviation (Annualized)')
                lower_risk = portfolio1_name if vol_a < vol_b else portfolio2_name
                
                sharpe_a = safe_extract(metrics_a, 'Sharpe Ratio')
                sharpe_b = safe_extract(metrics_b, 'Sharpe Ratio')
                better_sharpe = portfolio1_name if sharpe_a > sharpe_b else portfolio2_name
                
                # Develop insights based on metric comparisons
                insights = [
                    f"📈 **Returns:** {better_returns} shows stronger performance ({returns_a:.1%} vs {returns_b:.1%})",
                    f"🛡️ **Risk Profile:** {lower_risk} demonstrates lower volatility ({vol_a:.1%} vs {vol_b:.1%})",
                    f"⚖️ **Sharpe Ratio:** {better_sharpe} has better risk-adjusted returns ({sharpe_a:.2f} vs {sharpe_b:.2f})",
                    "📊 **Diversification Analysis:** Consider increasing diversification if one portfolio is heavily concentrated in few assets."
                ]
                
                for insight in insights:
                    st.markdown(insight)
                
                # Action Items
                st.markdown("### ⚡ Recommended Actions")
                actions = [
                    "🔄 Consider rebalancing to optimize returns and manage risk.",
                    "📈 Review asset allocation to ensure diversification.",
                    "🛡️ Implement risk management strategies to mitigate potential losses.",
                    "🔍 Monitor benchmark performance to maintain alignment with investment goals."
                ]
                
                for action in actions:
                    st.markdown(action)
    
    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})
    
    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 create_portfolio_comparison_summary(portfolio1_name: str, portfolio2_name: str, metrics_a: dict, metrics_b: dict):
        """
        Creates a single, comprehensive summary for portfolio comparison with actionable insights.
        """
        st.markdown("---")  # Visual separator
        
        with st.expander("📋 Portfolio Comparison Insights", expanded=True):
            # Performance Comparison
            st.markdown("### 📊 Key Performance Comparison")
            
            # Create two columns for side-by-side comparison
            col1, col2 = st.columns(2)
            
            metrics_to_compare = {
                'Returns': 'Annualized Return (CAGR)',
                'Risk': 'Standard Deviation (Annualized)',
                'Risk-Adjusted': 'Sharpe Ratio',
                'Maximum Loss': 'Maximum Drawdown'
            }
            
            with col1:
                st.markdown(f"**{portfolio1_name}**")
                for label, metric in metrics_to_compare.items():
                    value = metrics_a.get(metric, "N/A")
                    st.metric(label, value)
                    
            with col2:
                st.markdown(f"**{portfolio2_name}**")
                for label, metric in metrics_to_compare.items():
                    value = metrics_b.get(metric, "N/A")
                    st.metric(label, value)
            
            # Key Insights
            st.markdown("### 🔍 Key Insights")
            
            # Safely extract and compare metrics
            def safe_extract(metric_dict, metric_name):
                value = metric_dict.get(metric_name, 0)
                if isinstance(value, str):
                    try:
                        return float(value.strip('%'))
                    except (ValueError, AttributeError):
                        return float(value)
                    except ValueError:
                        st.warning(f"⚠️ Unable to convert metric '{metric_name}' to float. Using 0.")
                        return 0.0
                elif isinstance(value, (float, np.float64, int)):
                    return float(value)
                else:
                    st.warning(f"⚠️ Unexpected type for metric '{metric_name}'. Using 0.")
                    return 0.0
            
            returns_a = safe_extract(metrics_a, 'Annualized Return (CAGR)')
            returns_b = safe_extract(metrics_b, 'Annualized Return (CAGR)')
            better_returns = portfolio1_name if returns_a > returns_b else portfolio2_name
            
            vol_a = safe_extract(metrics_a, 'Standard Deviation (Annualized)')
            vol_b = safe_extract(metrics_b, 'Standard Deviation (Annualized)')
            lower_risk = portfolio1_name if vol_a < vol_b else portfolio2_name
            
            sharpe_a = safe_extract(metrics_a, 'Sharpe Ratio')
            sharpe_b = safe_extract(metrics_b, 'Sharpe Ratio')
            better_sharpe = portfolio1_name if sharpe_a > sharpe_b else portfolio2_name
            
            # Develop insights based on metric comparisons
            insights = [
                f"📈 **Returns:** {better_returns} shows stronger performance ({returns_a:.1%} vs {returns_b:.1%})",
                f"🛡️ **Risk Profile:** {lower_risk} demonstrates lower volatility ({vol_a:.1%} vs {vol_b:.1%})",
                f"⚖️ **Sharpe Ratio:** {better_sharpe} has better risk-adjusted returns ({sharpe_a:.2f} vs {sharpe_b:.2f})",
                "📊 **Diversification Analysis:** Consider increasing diversification if one portfolio is heavily concentrated in few assets."
            ]
            
            for insight in insights:
                st.markdown(insight)
            
            # Action Items
            st.markdown("### ⚡ Recommended Actions")
            actions = [
                "🔄 Consider rebalancing to optimize returns and manage risk.",
                "📈 Review asset allocation to ensure diversification.",
                "🛡️ Implement risk management strategies to mitigate potential losses.",
                "🔍 Monitor benchmark performance to maintain alignment with investment goals."
            ]
            
            for action in actions:
                st.markdown(action)
    
    def generate_portfolio_comparison_recommendations(portfolio1_name: str, portfolio2_name: str, metrics_a: dict, metrics_b: dict) -> list:
        """
        Generate recommendations based on portfolio comparison analysis.
        
        Parameters:
        - portfolio1_name (str): Name of first portfolio
        - portfolio2_name (str): Name of second portfolio
        - metrics_a (dict): Performance metrics for first portfolio
        - metrics_b (dict): Performance metrics for second portfolio
        
        Returns:
        - list: List of recommendation strings
        """
        recommendations = []
        
        # Helper function to parse percentage strings
        def parse_percentage(value):
            if isinstance(value, str):
                try:
                    return float(value.strip('%')) / 100
                except (ValueError, AttributeError):
                    return 0.0
            return float(value)
        
        try:
            # Get full portfolio objects from session state
            portfolio1 = next(p for p in st.session_state.portfolios if p['name'] == portfolio1_name)
            portfolio2 = next(p for p in st.session_state.portfolios if p['name'] == portfolio2_name)
            
            # Compare returns
            returns_a = parse_percentage(metrics_a.get('Annualized Return (CAGR)', 0))
            returns_b = parse_percentage(metrics_b.get('Annualized Return (CAGR)', 0))
            
            if returns_a > returns_b:
                recommendations.append(f"📈 {portfolio1_name} shows higher returns ({returns_a:.1%} vs {returns_b:.1%})")
            else:
                recommendations.append(f"📈 {portfolio2_name} shows higher returns ({returns_b:.1%} vs {returns_a:.1%})")
            
            # Compare risk metrics
            vol_a = parse_percentage(metrics_a.get('Standard Deviation (Annualized)', 0))
            vol_b = parse_percentage(metrics_b.get('Standard Deviation (Annualized)', 0))
            
            if vol_a < vol_b:
                recommendations.append(f"📊 {portfolio1_name} has lower volatility ({vol_a:.1%} vs {vol_b:.1%})")
            else:
                recommendations.append(f"📊 {portfolio2_name} has lower volatility ({vol_b:.1%} vs {vol_a:.1%})")
            
            # Compare Sharpe ratios
            sharpe_a = float(metrics_a.get('Sharpe Ratio', 0))
            sharpe_b = float(metrics_b.get('Sharpe Ratio', 0))
            
            if sharpe_a > sharpe_b:
                recommendations.append(f"⚖️ {portfolio1_name} has better risk-adjusted returns (Sharpe: {sharpe_a:.2f} vs {sharpe_b:.2f})")
            else:
                recommendations.append(f"⚖️ {portfolio2_name} has better risk-adjusted returns (Sharpe: {sharpe_b:.2f} vs {sharpe_a:.2f})")
            
            # Compare maximum drawdowns
            dd_a = parse_percentage(metrics_a.get('Maximum Drawdown', 0))
            dd_b = parse_percentage(metrics_b.get('Maximum Drawdown', 0))
            
            if dd_a < dd_b:
                recommendations.append(f"🔻 {portfolio1_name} has smaller maximum drawdown ({dd_a:.1%} vs {dd_b:.1%})")
            else:
                recommendations.append(f"🔻 {portfolio2_name} has smaller maximum drawdown ({dd_b:.1%} vs {dd_a:.1%})")
            
            # Diversification comparison
            div_rec = f"📊 Diversification: {portfolio1_name} has {len(portfolio1['selected'])} assets vs " \
                      f"{portfolio2_name}'s {len(portfolio2['selected'])} assets"
            recommendations.append(div_rec)
            
            # Rebalancing frequency comparison
            freq_1 = rebalance_freq_inverse_mapping.get(portfolio1['rebalance_freq'], portfolio1['rebalance_freq'])
            freq_2 = rebalance_freq_inverse_mapping.get(portfolio2['rebalance_freq'], portfolio2['rebalance_freq'])
            recommendations.append(f"🔄 Rebalancing: {portfolio1_name} ({freq_1}) vs {portfolio2_name} ({freq_2})")
            
        except Exception as e:
            recommendations.append(f"⚠️ Some metrics could not be compared: {str(e)}")
        
        return recommendations

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