"""
HTML Report Generator for Intervariable Imperfection Analysis

This module contains all the HTML generation logic for creating comprehensive reports with collapsible sections and interactive elements.
"""

from datetime import datetime
from pathlib import Path

import polars as pl

from imperfekt.analysis.utils.html_reporting_helpers import (
    fig_to_html,
    get_apple_style_css,
    get_javascript,
)


class IntervariableHTMLReportGenerator:
    """Generates HTML reports for intervariable imperfection analysis results."""

    def __init__(self, analysis_instance):
        """
        Initialize the report generator.

        Args:
            analysis_instance: The IntervariableImperfection instance containing results
        """
        self.analysis = analysis_instance

    def generate_report(
        self, report_path: str = "intervariable_report.html", title: str = None
    ) -> Path:
        """
        Generates an HTML report from the analysis results.

        Args:
            report_path: The filename for the HTML report

        Returns:
            Path to the generated report file
        """
        # Get full report path
        full_report_path = self.analysis.save_path / report_path

        # Generate HTML content
        html_content = self._generate_html_content(title=title)

        # Write to file
        with open(full_report_path, "w", encoding="utf-8") as f:
            f.write(html_content)

        return full_report_path

    # Update the _generate_html_content method to include all sections
    def _generate_html_content(self, title: str = None) -> str:
        """Generates the complete HTML content for the report."""
        # Get current timestamp
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # Start building HTML
        html = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Intervariable Imperfection Analysis Report</title>
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
        <style>
            {get_apple_style_css()}
        </style>
    </head>
    <body>
        <div class="container">
            <header class="header">
                <div class="header-content">
                    <h1>📊 Intervariable Imperfection Analysis Report{f" - {title}" if title else ""}</h1>
                    <div class="metadata">
                        <span class="badge">Generated: {timestamp}</span>
                        <span class="badge">Analyzed Imperfection: {self.analysis.imperfection}</span>
                        <span class="badge">Columns: {len(self.analysis.cols)}</span>
                        <span class="badge">α = {self.analysis.alpha}</span>
                        <span class="badge">Total Observations: {self.analysis.df.height}, Unique Encounters: {self.analysis.df.select(pl.col(self.analysis.id_col).n_unique()).item()}</span>
                    </div>
                </div>
            </header>

            <main class="main-content">
                {self._generate_row_statistics_section()}
                {self._generate_mcar_test_section()}
                {self._generate_mar_mnar_test_section()}
                {self._generate_symmetric_correlation_section()}
                {self._generate_asymmetric_correlation_section()}
            </main>

            <footer class="footer">
                <p>Report generated by Imperfekt Analysis Framework</p>
            </footer>
        </div>
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
        <script>
            {get_javascript()}
        </script>
    </body>
    </html>
    """
        return html

    def _generate_row_statistics_section(self) -> str:
        """Generates the row statistics section."""
        if self.analysis.results.rs_overall_statistics is None:
            return self._generate_empty_section("📊 Row Statistics", "No row statistics available")

        # Overall row statistics table
        try:
            overall_table_html = (
                self.analysis.results.rs_overall_statistics.to_pandas()
                .describe()
                .to_html(
                    index=True,
                    table_id=None,
                    classes="table",
                    escape=False,
                    float_format="%.4g",
                )
            )
        except Exception:
            overall_table_html = "<p>Unable to display overall row statistics table</p>"

        # Case-level row statistics table
        try:
            case_level_table_html = (
                self.analysis.results.rs_case_level_statistics.to_pandas()
                .describe()
                .to_html(
                    index=True,
                    table_id=None,
                    classes="table",
                    escape=False,
                    float_format="%.4g",
                )
            )
        except Exception:
            case_level_table_html = "<p>Unable to display case-level row statistics table</p>"

        # Empty statistics if available
        empty_stats_content = ""
        if self.analysis.results.rs_empty_statistics:
            try:
                empty_count, empty_pct = self.analysis.results.rs_empty_statistics
                empty_stats_content = f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>🔍 All-Null Rows Statistics</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            <div class="grid">
                                <div class="card">
                                    <div class="metric">
                                        <div class="metric-value">{empty_count}</div>
                                        <div class="metric-label">Total All-Null Rows</div>
                                    </div>
                                </div>
                                <div class="card">
                                    <div class="metric">
                                        <div class="metric-value">{empty_pct:.2f}%</div>
                                        <div class="metric-label">Percentage of All-Null Rows</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                """
            except Exception:
                empty_stats_content = ""

        # Add case-level statistics plots
        plots_html = ""
        if (
            self.analysis.results.plots.rs_case_level_histogram
            and self.analysis.results.plots.rs_case_level_boxplot
        ):
            try:
                histogram_html = fig_to_html(self.analysis.results.plots.rs_case_level_histogram)
                boxplot_html = fig_to_html(self.analysis.results.plots.rs_case_level_boxplot)

                plots_html = f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>📈 Row Statistics Visualizations</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            <div class="plot-section">
                                <div class="plot-header" onclick="togglePlot(this)">
                                    <h4>Average Imperfect Variables Distribution</h4>
                                    <span class="plot-chevron">▼</span>
                                </div>
                                <div class="plot-container collapsible-plot">
                                    {histogram_html}
                                    {boxplot_html}
                                </div>
                            </div>
                        </div>
                    </div>
                """
            except Exception as e:
                plots_html = f"<p>Error loading row statistics plots: {str(e)}</p>"

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">📊 Row Statistics</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="info">
                    <strong>What this shows:</strong>
                    <p><em>This section describes how complete each row (timestamp) is across all columns.</em></p>
                    <ul>
                        <li><em>Overall Row Completeness:</em> Descriptive statistics summarize the proportion of complete values per row across the dataset.</li>
                        <li><em>Case-Level Completeness:</em> Distribution of average row completeness per case, showing how data quality varies across individuals.</li>
                    </ul>
                    <p><em>Histograms and boxplots visualize how completeness is distributed across cases.</em></p>
                </div>
                {empty_stats_content}
                <div class="subsection">
                    <div class="subsection-header">
                        <h3>📋 Overall Row Completeness Statistics</h3>
                        <span class="subsection-chevron">▼</span>
                    </div>
                    <div class="subsection-content">
                        <div class="table-container">
                            {overall_table_html}
                        </div>
                    </div>
                </div>

                <div class="subsection">
                    <div class="subsection-header">
                        <h3>📋 Case-Level Row Completeness Statistics</h3>
                        <span class="subsection-chevron">▼</span>
                    </div>
                    <div class="subsection-content">
                        <div class="table-container">
                            {case_level_table_html}
                        </div>
                    </div>
                </div>

                {plots_html}
            </div>
        </section>
        """

    def _generate_mcar_test_section(self) -> str:
        """Generates the MCAR test section."""
        if self.analysis.results.mcar_results is None:
            return self._generate_empty_section("🎯 MCAR Test", "No MCAR test results available")

        # MCAR test results
        mcar_content = ""
        try:
            little_test = self.analysis.results.mcar_results.get(
                "little_mcar_test", "No test results"
            )
            # Format the Little's MCAR test results as a table
            if isinstance(little_test, dict):
                test_statistic = little_test.get("test_statistic", "N/A")
                degrees_of_freedom = little_test.get("degrees_of_freedom", "N/A")
                p_value = little_test.get("p_value", "N/A")
                significant = little_test.get("significant", "N/A")
                phi = little_test.get("phi", "N/A")
                cramers_v = little_test.get("cramers_v", "N/A")
                complete_cases = little_test.get("complete_cases", "N/A")

                # Determine significance interpretation
                significance_text = "Yes (Reject MCAR)" if significant else "No (Accept MCAR)"
                significance_class = "warning" if significant else "info"

                # Safe formatting function for numpy types
                def safe_format(value, decimals=4):
                    try:
                        if hasattr(value, "item"):  # numpy scalar
                            value = value.item()
                        if isinstance(value, (int, float)):
                            return f"{value:.{decimals}f}"
                        else:
                            return str(value)
                    except Exception:
                        return str(value)

                # Format p-value specially
                def format_p_value(p_val):
                    try:
                        if hasattr(p_val, "item"):  # numpy scalar
                            p_val = p_val.item()
                        if isinstance(p_val, (int, float)):
                            if p_val == 0.0 or p_val < 0.000001:
                                return "< 0.000001"
                            else:
                                return f"{p_val:.6f}"
                        else:
                            return str(p_val)
                    except Exception:
                        return str(p_val)

                little_test_table = f"""
                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Statistic</th>
                                    <th>Value</th>
                                    <th>Interpretation</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Test Statistic (χ²)</td>
                                    <td>{safe_format(test_statistic)}</td>
                                    <td>Chi-squared test statistic</td>
                                </tr>
                                <tr>
                                    <td>Degrees of Freedom</td>
                                    <td>{degrees_of_freedom}</td>
                                    <td>Number of degrees of freedom</td>
                                </tr>
                                <tr>
                                    <td>P-value</td>
                                    <td>{format_p_value(p_value)}</td>
                                    <td>Probability of observing this result under MCAR</td>
                                </tr>
                                <tr>
                                    <td>Significant (α = {self.analysis.alpha})</td>
                                    <td>{significance_text}</td>
                                    <td>Statistical significance at α = {self.analysis.alpha}</td>
                                </tr>
                                <tr>
                                    <td>Phi Coefficient</td>
                                    <td>{safe_format(phi)}</td>
                                    <td>Effect size measure (0 = no association, 1 = perfect association)</td>
                                </tr>
                                <tr>
                                    <td>Cramér's V</td>
                                    <td>{safe_format(cramers_v)}</td>
                                    <td>Normalized effect size (0 = no association, 1 = perfect association)</td>
                                </tr>
                                <tr>
                                    <td>Complete Cases</td>
                                    <td>{complete_cases}</td>
                                    <td>Number of observations with no missing values</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                """
                mcar_content = """
                <div class="info">
                    <strong>What this shows:</strong>
                    <p><em>This test evaluates whether data are “Missing Completely At Random” (MCAR).</em></p>
                    <ul>
                        <li>A significant result (p &lt; α) suggests that missingness is NOT completely at random.</li>
                        <li>Pattern table and upset plot show how imperfection patterns are distributed across variables.</li>
                    </ul>
                </div>
                """
                mcar_content += f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>🧪 Little's MCAR Test Results</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            <div class="{significance_class}">
                                <p><strong>Result:</strong> {significance_text}</p>
                            </div>
                            {little_test_table}
                        </div>
                    </div>
                """
            else:
                # Fallback for non-dict results
                mcar_content = f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>🧪 Little's MCAR Test Results</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            <div class="info">
                                <p><strong>Test Result:</strong> {str(little_test)}</p>
                                <p><em>This test checks if missing data is Missing Completely At Random (MCAR) across all variables.</em></p>
                            </div>
                        </div>
                    </div>
                """

            # Add missing data patterns table
            if "patterns" in self.analysis.results.mcar_results:
                patterns_table_html = (
                    self.analysis.results.mcar_results["patterns"]
                    .to_pandas()
                    .to_html(index=False, table_id=None, classes="table", escape=False)
                )

                mcar_content += f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>📊 Missing Data Patterns</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            <div class="table-container">
                                {patterns_table_html}
                            </div>
                        </div>
                    </div>
                """

        except Exception as e:
            mcar_content = f"<p>Error displaying MCAR results: {str(e)}</p>"

        # UpSet plot
        upset_plot_html = ""
        if self.analysis.results.plots.mcar_upset_plot:
            try:
                upset_html = fig_to_html(self.analysis.results.plots.mcar_upset_plot)
                upset_plot_html = f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>📈 Co-Imperfection UpSet Plot</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            <div class="plot-container">
                                {upset_html}
                            </div>
                        </div>
                    </div>
                """
            except Exception as e:
                upset_plot_html = f"<p>Error loading UpSet plot: {str(e)}</p>"

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">🎯 MCAR Test</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                {mcar_content}
                {upset_plot_html}
            </div>
        </section>
        """

    def _generate_mar_mnar_test_section(self) -> str:
        """Generates the MAR/MNAR test section."""
        if self.analysis.results.mar_mnar_results is None:
            return self._generate_empty_section(
                "🔬 MAR/MNAR Test", "No MAR/MNAR test results available"
            )

        try:
            table_html = self.analysis.results.mar_mnar_results.to_pandas().to_html(
                index=False,
                table_id=None,
                classes="table",
                escape=False,
                float_format="%.4g",
            )
        except Exception:
            table_html = "<p>Unable to display MAR/MNAR test results</p>"

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">🔬 MAR/MNAR Test</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="info">
                    <strong>What this shows:</strong>
                    <p><em>This analysis distinguishes between “Missing At Random” (MAR) and “Missing Not At Random” (MNAR).</em></p>
                    <ul>
                        <li><em>MAR model:</em> Uses predictors from other variables and severity indicators.</li>
                        <li><em>MNAR model:</em> Adds the lagged value of the same variable to detect systematic missingness tied to its own past values.</li>
                        <li>A Likelihood Ratio Test compares the two models to evaluate whether missingness follows MAR or MNAR patterns.</li>
                    </ul>
                </div>

                <div class="subsection">
                    <div class="subsection-header">
                        <h3>📋 Temporal MAR/MNAR Test Results</h3>
                        <span class="subsection-chevron">▼</span>
                    </div>
                    <div class="subsection-content">
                        <div class="table-container">
                            {table_html}
                        </div>
                    </div>
                </div>
            </div>
        </section>
        """

    def _generate_symmetric_correlation_section(self) -> str:
        """Generates the symmetric correlation section."""
        content_parts = []
        content_parts.append(f"""
            <div class="info">
                <strong>What this shows:</strong>
                <p><em>This section quantifies associations between imperfection patterns of different variables.</em></p>
                <p>Symmetric correlation asks whether missingness in variable A is associated with missingness in variable B, treating both sides equally.</p>
                <ol>
                    <li>A Pearson correlation test assesses the strength and direction of relationships between imperfections of variables, visualized in a heatmap.</li>
                    <li>Chi-squared tests check for independence between missingness in pairs of variables.</li>
                    <ul><li>Cramér’s V measures association strength:
                    <ul>
                        <li>0.00: Negligible</li>
                        <li>0.10: Weak</li>
                        <li>0.30: Moderate</li>
                        <li>0.50: Strong</li>
                        <li>1.00: Perfect</li>
                    </ul>
                    </li></ul>
                    <li>Scatter plots show lagged (lag={self.analysis.sc_max_lag}) symmetric correlations, identifying clusters or periodic patterns of missingness.</li>
                    <ul>
                    <li>Example:
                        If col_x leads col_y by 2 time points, the cross-correlation at lag -2 will be positive.
                        Meaning that if col_x is missing, col_y is likely to be missing 2 time points later.
                        Or: At a positive lag, the cross-correlation indicates how likely col_y is to be missing after col_x is missing.
                    </li>
                    </ul>
                </ol>
            </div>
        """)

        # Correlation matrix results
        if self.analysis.results.sc_symmetric_correlation is not None:
            try:
                corr_heatmap = self.analysis.results.plots.sc_correlation_heatmap

                # Check if the heatmap object exists before processing it
                if corr_heatmap:
                    fig_html = fig_to_html(corr_heatmap)
                    content_parts.append(f"""
                        <div class="subsection">
                            <div class="subsection-header">
                                <h3>📊 Imperfection Correlation Matrix</h3>
                                <span class="subsection-chevron">▼</span>
                            </div>
                            <div class="subsection-content">
                                <div class="plot-section">
                                    <div class="plot-header" onclick="togglePlot(this)">
                                        <h4>Heatmap</h4>
                                        <span class="plot-chevron">▼</span>
                                    </div>
                                    <div class="plot-container collapsible-plot">
                                        {fig_html}
                                    </div>
                                </div>
                            </div>
                        </div>
                    """)
            except Exception as e:
                content_parts.append(f"<p>Error displaying correlation matrix: {str(e)}</p>")

        # Chi-squared test results
        if self.analysis.results.sc_chi2_intervariable_matrix is not None:
            try:
                chi2_table_html = (
                    self.analysis.results.sc_chi2_intervariable_matrix.to_pandas().to_html(
                        index=False,
                        table_id=None,
                        classes="table",
                        escape=False,
                        float_format="%.4g",
                    )
                )
                content_parts.append(f"""

                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>🧮 Chi-squared Test Results</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            <div class="table-container">
                                {chi2_table_html}
                            </div>
                        </div>
                    </div>
                """)
            except Exception as e:
                content_parts.append(f"<p>Error displaying chi-squared results: {str(e)}</p>")

        # Cross-correlation plots
        if self.analysis.results.plots.sc_lag_scatter_plot:
            plots_html = ""
            for (
                pair_key,
                plot_fig,
            ) in self.analysis.results.plots.sc_lag_scatter_plot.items():
                try:
                    fig_html = fig_to_html(plot_fig)
                    plots_html += f"""
                        <div class="plot-section">
                            <div class="plot-header" onclick="togglePlot(this)">
                                <h4>{pair_key.replace("_vs_", " vs ").title()}</h4>
                                <span class="plot-chevron">▼</span>
                            </div>
                            <div class="plot-container collapsible-plot">
                                {fig_html}
                            </div>
                        </div>
                    """
                except Exception as e:
                    plots_html += f"<p>Error loading plot for {pair_key}: {str(e)}</p>"

            if plots_html:
                content_parts.append(f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>📈 Symmetric Cross-Correlation Plots</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            {plots_html}
                        </div>
                    </div>
                """)

        if not content_parts:
            return self._generate_empty_section(
                "🔄 Symmetric Correlation",
                "No symmetric correlation analysis available",
            )

        content = "".join(content_parts)
        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">🔄 Symmetric Correlation</h2>
                <span class="chevron">▼</span>
            </div>

            <div class="section-content">
                {content}
            </div>
        </section>
        """

    def _generate_asymmetric_correlation_section(self) -> str:
        """Generates the asymmetric correlation section."""
        content_parts = []

        # Statistical comparison results
        if self.analysis.results.ac_asymmetric_statistical_results:
            stats_content = ""
            for (
                pair_key,
                stats_result,
            ) in self.analysis.results.ac_asymmetric_statistical_results.items():
                try:
                    if isinstance(stats_result, dict):
                        correlation = stats_result.get("correlation", "N/A")
                        mannwhitney_p = stats_result.get("mann_whitney_u", {}).get("p_val", "N/A")
                        missing_mean = stats_result.get("stats_when_missing", {}).get("mean", "N/A")
                        observed_mean = stats_result.get("stats_when_present", {}).get(
                            "mean", "N/A"
                        )

                        # Safe formatting function for asymmetric stats
                        def safe_format_value(value, decimals=3):
                            try:
                                if value is None:
                                    return "N/A"
                                if hasattr(value, "item"):  # numpy scalar
                                    value = value.item()
                                if isinstance(value, (int, float)) and not (
                                    value != value
                                ):  # Check for NaN
                                    return f"{value:.{decimals}f}"
                                else:
                                    return str(value) if value is not None else "N/A"
                            except Exception:
                                return "N/A"

                        stats_content += f"""
                            <div class="card">
                                <h4>{pair_key.replace("_", " ").title()}</h4>
                                <div class="metric">
                                    <div class="metric-value">{safe_format_value(correlation, 4)}</div>
                                    <div class="metric-label">Correlation (lag=0)</div>
                                </div>
                                <div class="metric">
                                    <div class="metric-value">{safe_format_value(mannwhitney_p, 4)}</div>
                                    <div class="metric-label">Mann-Whitney p-value</div>
                                </div>
                                <div class="metric">
                                    <div class="metric-value">{safe_format_value(missing_mean, 3)}</div>
                                    <div class="metric-label">Mean (Missing)</div>
                                </div>
                                <div class="metric">
                                    <div class="metric-value">{safe_format_value(observed_mean, 3)}</div>
                                    <div class="metric-label">Mean (Observed)</div>
                                </div>
                            </div>
                        """
                except Exception as e:
                    stats_content += f"<p>Error displaying stats for {pair_key}: {str(e)}</p>"

            if len(stats_content) > 0:
                content_parts.append(f"""
                    <div class="info">
                        <strong>What this shows:</strong>
                        <p>Asymmetric correlation asks whether the observed values of variable A change depending on whether variable B is imperfect. Here the relationship is not symmetric because A and B play different roles.</p>
                        <ul>
                            <li>Mann–Whitney U tests compare observed values when the other variable is missing versus when it is observed.</li>
                            <li>Histograms and boxplots illustrate differences between the two groups.</li>
                            <li>Scatter plots show lagged (lag={self.analysis.ac_max_lag}) asymmetric correlations, capturing how observed values shift around imperfect timestamps.
                             <ul>
                                <li> Negative lags indicate that missingness in indicated_col leads changes in observation_col values.</li>
                                <li>Positive lags indicate that observation_col values precede missingness in indicated_col.</li>
                             </ul>
                            </li>
                        </ul>
                    </div>
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>📊 Asymmetric Statistical Comparison</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            <div class="grid">
                                {stats_content}
                            </div>
                        </div>
                    </div>
                """)

        # Distribution plots (histograms and boxplots)
        if (
            self.analysis.results.plots.ac_multi_histogram
            or self.analysis.results.plots.ac_multi_boxplot
        ):
            plots_html = ""
            all_pairs = set()
            if self.analysis.results.plots.ac_multi_histogram:
                all_pairs.update(self.analysis.results.plots.ac_multi_histogram.keys())
            if self.analysis.results.plots.ac_multi_boxplot:
                all_pairs.update(self.analysis.results.plots.ac_multi_boxplot.keys())

            for pair_key in all_pairs:
                pair_plots = []

                if pair_key in self.analysis.results.plots.ac_multi_histogram:
                    try:
                        fig_html = fig_to_html(
                            self.analysis.results.plots.ac_multi_histogram[pair_key]
                        )
                        pair_plots.append(fig_html)
                    except Exception as e:
                        pair_plots.append(f"<p>Error loading histogram: {str(e)}</p>")

                if pair_key in self.analysis.results.plots.ac_multi_boxplot:
                    try:
                        fig_html = fig_to_html(
                            self.analysis.results.plots.ac_multi_boxplot[pair_key]
                        )
                        pair_plots.append(fig_html)
                    except Exception as e:
                        pair_plots.append(f"<p>Error loading boxplot: {str(e)}</p>")

                if pair_plots:
                    plots_content = "".join(pair_plots)
                    plots_html += f"""
                        <div class="plot-section">
                            <div class="plot-header" onclick="togglePlot(this)">
                                <h4>Distribution Analysis: {pair_key.replace("_", " ").title()}</h4>
                                <span class="plot-chevron">▼</span>
                            </div>
                            <div class="plot-container collapsible-plot">
                                {plots_content}
                            </div>
                        </div>
                    """

            if plots_html:
                content_parts.append(f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>📈 Distribution Comparison Plots</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            {plots_html}
                        </div>
                    </div>
                """)

        # Lagged cross-correlation plots
        if self.analysis.results.plots.ac_lag_scatter_plot:
            plots_html = ""
            for (
                pair_key,
                plot_fig,
            ) in self.analysis.results.plots.ac_lag_scatter_plot.items():
                try:
                    fig_html = fig_to_html(plot_fig)
                    plots_html += f"""
                        <div class="plot-section">
                            <div class="plot-header" onclick="togglePlot(this)">
                                <h4>Lagged Correlation: {pair_key.replace("_", " ").title()}</h4>
                                <span class="plot-chevron">▼</span>
                            </div>
                            <div class="plot-container collapsible-plot">
                                {fig_html}
                            </div>
                        </div>
                    """
                except Exception as e:
                    plots_html += (
                        f"<p>Error loading lagged correlation plot for {pair_key}: {str(e)}</p>"
                    )

            if plots_html:
                content_parts.append(f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>📈 Asymmetric Lagged Cross-Correlation</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            {plots_html}
                        </div>
                    </div>
                """)

        if not content_parts:
            return self._generate_empty_section(
                "⚖️ Asymmetric Correlation",
                "No asymmetric correlation analysis available",
            )

        content = "".join(content_parts)
        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">⚖️ Asymmetric Correlation</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                {content}
            </div>
        </section>
        """

    def _generate_empty_section(self, title: str, message: str) -> str:
        """Generates an empty section with a warning message."""
        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">{title}</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="warning">
                    <p>{message}</p>
                </div>
            </div>
        </section>
        """
