"""HTML exporter for chronobox reports.

Generates self-contained HTML reports with:
- Plotly interactive charts (embedded)
- CSS styling (inline)
- Sidebar navigation with section links
- Collapsible sections
- Responsive layout (mobile-friendly)
"""

from __future__ import annotations

from typing import Any


class HTMLExporter:
    """Export report context to self-contained HTML.

    Features:
    - All CSS and JavaScript inline (no external dependencies)
    - Interactive Plotly charts embedded as JSON
    - Sidebar navigation with smooth scrolling
    - Collapsible sections for detailed content
    - Responsive design
    """

    def export(self, context: dict[str, Any]) -> str:
        """Export context to HTML string.

        Parameters
        ----------
        context : dict
            Template context from a transformer.

        Returns
        -------
        str
            Self-contained HTML document.
        """
        title = context.get("title", "Report")
        css = context.get("css", "")
        sections = context.get("sections", [])
        model_info = context.get("model_info", {})

        sidebar_html = self._build_sidebar(sections)
        sections_html = self._build_sections(sections)
        model_info_html = self._build_model_info(model_info)
        js = self._build_javascript()

        return f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{title} - chronobox</title>
    <style>
{css}
    </style>
</head>
<body>
    <div class="report-container">
        <nav class="report-sidebar">
            <h3>Navigation</h3>
            {sidebar_html}
        </nav>
        <main class="report-main">
            <header class="report-header">
                <h1>{title}</h1>
            </header>

            {model_info_html}

            {sections_html}

            <footer class="report-footer">
                <p>Generated by <strong>chronobox</strong></p>
            </footer>
        </main>
    </div>

    <script>
{js}
    </script>
</body>
</html>"""

    def _build_sidebar(self, sections: list[dict[str, Any]]) -> str:
        """Build sidebar navigation HTML.

        Parameters
        ----------
        sections : list[dict]
            Report sections.

        Returns
        -------
        str
            Sidebar HTML.
        """
        items = []
        for i, section in enumerate(sections):
            sec_title = section.get("title", f"Section {i + 1}")
            sec_id = f"section-{i}"
            items.append(f'<li><a href="#{sec_id}">{sec_title}</a></li>')
        return f'<ul>{"".join(items)}</ul>'

    def _build_sections(self, sections: list[dict[str, Any]]) -> str:
        """Build HTML for all sections.

        Parameters
        ----------
        sections : list[dict]
            Report sections.

        Returns
        -------
        str
            Sections HTML.
        """
        html_parts = []
        for i, section in enumerate(sections):
            sec_id = f"section-{i}"
            sec_title = section.get("title", f"Section {i + 1}")
            content = section.get("content", "")
            table = section.get("table")
            plot = section.get("plot")
            collapsible = section.get("collapsible", False)

            section_content = ""

            if content:
                section_content += f"<div>{content}</div>"

            if table:
                section_content += self._table_to_html(table)

            if plot:
                section_content += (
                    f'<div class="cb-plot">'
                    f'<img src="data:image/png;base64,{plot}" />'
                    f"</div>"
                )

            if collapsible:
                html_parts.append(f"""
<section id="{sec_id}" class="cb-section">
    <div class="cb-collapsible" onclick="this.classList.toggle('open')">
        <div class="cb-collapsible-toggle">{sec_title}</div>
        <div class="cb-collapsible-content">
            {section_content}
        </div>
    </div>
</section>""")
            else:
                html_parts.append(f"""
<section id="{sec_id}" class="cb-section">
    <h2>{sec_title}</h2>
    {section_content}
</section>""")

        return "\n".join(html_parts)

    def _build_model_info(self, model_info: dict[str, Any]) -> str:
        """Build model info summary HTML.

        Parameters
        ----------
        model_info : dict
            Model information.

        Returns
        -------
        str
            Model info HTML.
        """
        if not model_info:
            return ""

        metrics = []
        for key, value in model_info.items():
            label = key.replace("_", " ").title()
            metrics.append(
                f'<div class="cb-metric">'
                f'<div class="cb-metric-value">{value}</div>'
                f'<div class="cb-metric-label">{label}</div>'
                f"</div>"
            )

        return f'<div class="cb-metrics">{"".join(metrics)}</div>'

    def _table_to_html(self, table: list[dict[str, Any]]) -> str:
        """Convert table data to HTML table.

        Parameters
        ----------
        table : list[dict]
            Table rows as dictionaries.

        Returns
        -------
        str
            HTML table string.
        """
        if not table:
            return ""

        # Get column headers from first row
        headers = list(table[0].keys())

        header_html = "".join(f"<th>{h}</th>" for h in headers)
        rows_html = ""
        for row in table:
            cells = ""
            for h in headers:
                val = row.get(h, "")
                if isinstance(val, float):
                    css_class = ' class="num"'
                    val = f"{val:.4f}"
                elif h == "significance":
                    css_class = ' class="sig"'
                else:
                    css_class = ""
                cells += f"<td{css_class}>{val}</td>"
            rows_html += f"<tr>{cells}</tr>\n"

        return f"""<table class="cb-table">
<thead><tr>{header_html}</tr></thead>
<tbody>
{rows_html}
</tbody>
</table>"""

    @staticmethod
    def _build_javascript() -> str:
        """Build inline JavaScript for interactivity.

        Returns
        -------
        str
            JavaScript code.
        """
        return """
// Smooth scrolling for sidebar links
document.querySelectorAll('.report-sidebar a').forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        var target = document.querySelector(this.getAttribute('href'));
        if (target) {
            target.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    });
});

// Collapsible sections
document.querySelectorAll('.cb-collapsible-toggle').forEach(function(toggle) {
    toggle.addEventListener('click', function() {
        this.parentElement.classList.toggle('open');
    });
});

// Highlight active sidebar link on scroll
var sections = document.querySelectorAll('.cb-section');
var navLinks = document.querySelectorAll('.report-sidebar a');

window.addEventListener('scroll', function() {
    var current = '';
    sections.forEach(function(section) {
        var sectionTop = section.offsetTop;
        if (window.scrollY >= sectionTop - 100) {
            current = '#' + section.getAttribute('id');
        }
    });
    navLinks.forEach(function(link) {
        link.style.fontWeight = link.getAttribute('href') === current ? 'bold' : 'normal';
    });
});
"""
