from __future__ import annotations
import os
import re
import base64
from typing import List, Dict, Any, Optional
from markdown_it import MarkdownIt


def _process_image_paths(md_content: str, out_dir: str) -> str:
    """
    Process image paths in markdown content to ensure they work in HTML.
    Converts relative paths to base64 embedded images for better portability.
    
    :param md_content: The markdown content with image references
    :param out_dir: The output directory where images are stored
    :return: Processed markdown content with embedded images
    """
    def replace_image(match):
        caption = match.group(1)
        img_path = match.group(2)
        
        if not os.path.isabs(img_path):
            abs_img_path = os.path.join(out_dir, img_path)
        else:
            abs_img_path = img_path
        
        if os.path.exists(abs_img_path):
            try:
                with open(abs_img_path, 'rb') as f:
                    img_data = f.read()
                    img_ext = os.path.splitext(abs_img_path)[1].lower()
                    
                    if img_ext in ['.jpg', '.jpeg']:
                        mime_type = 'image/jpeg'
                    elif img_ext == '.png':
                        mime_type = 'image/png'
                    elif img_ext == '.gif':
                        mime_type = 'image/gif'
                    elif img_ext == '.webp':
                        mime_type = 'image/webp'
                    else:
                        mime_type = 'image/jpeg'
                    
                    b64_data = base64.b64encode(img_data).decode('ascii')
                    
                    return f'<img src="data:{mime_type};base64,{b64_data}" alt="{caption}" />'
            except Exception as e:
                print(f"Warning: Could not process image {abs_img_path}: {e}")
                return f'<div class="image-error">Image not found: {caption}</div>'
        else:
            print(f"Warning: Image file not found: {abs_img_path}")
            return f'<div class="image-error">Image not found: {caption}</div>'
    
    pattern = r'!\[([^\]]*)\]\(([^)]+)\)'
    processed_content = re.sub(pattern, replace_image, md_content)
    
    return processed_content


def write_html_from_lines(html_lines: List[str], out_dir: str, filename: str = "result.html") -> str:
    """
    Convert HTML lines directly into a single HTML file and save it.
    
    This function is used when VLM is enabled to ensure proper HTML table formatting
    instead of markdown-to-HTML conversion.

    :param html_lines: List of HTML strings to join into a single file
    :param out_dir: Directory where the HTML file will be saved
    :param filename: Name of the HTML file (default: "result.html")
    :return: The absolute path of the written HTML file
    """
    os.makedirs(out_dir, exist_ok=True)

    html_content = "\n".join(html_lines).strip() + "\n"
    html_content = re.sub(r"\n{3,}", "\n\n", html_content)

    html_content = _process_image_paths(html_content, out_dir)
    
    html_content = _add_table_styling(html_content)
    
    html_document = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Analysis Results</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        {_get_css_styles()}
    </style>
</head>
<body>
    <button class="theme-toggle" onclick="toggleTheme()" title="Toggle dark mode"></button>
    <div class="container">
        <header class="header">
            <div class="header-content">
                <div class="header-text">
                    <h1>Document Analysis Results</h1>
                    <p class="subtitle">Intelligent Document Processing & Analysis</p>
                </div>
                <div class="header-badge">
                    Generated by Doctra
                </div>
            </div>
        </header>
        <main class="content">
            {html_content}
        </main>
        <footer class="footer">
            <div class="footer-content">
                <div class="footer-brand">Doctra</div>
                <div class="footer-info">
                    <span>Intelligent Document Processing</span>
                    <a href="https://github.com/AdemBoukhris457/Doctra" target="_blank">GitHub</a>
                </div>
            </div>
        </footer>
    </div>
    <script>
        // Theme toggle functionality
        function toggleTheme() {{
            const body = document.body;
            const currentTheme = body.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            
            body.setAttribute('data-theme', newTheme);
            localStorage.setItem('doctra-theme', newTheme);
            
            // Add smooth transition
            body.style.transition = 'all 0.3s ease';
            setTimeout(() => {{
                body.style.transition = '';
            }}, 300);
        }}

        // Load saved theme on page load
        document.addEventListener('DOMContentLoaded', function() {{
            const savedTheme = localStorage.getItem('doctra-theme') || 'light';
            document.body.setAttribute('data-theme', savedTheme);
        }});

        // Add smooth scroll behavior
        document.documentElement.style.scrollBehavior = 'smooth';

        // Add loading animation
        window.addEventListener('load', function() {{
            document.body.style.opacity = '0';
            document.body.style.transition = 'opacity 0.5s ease';
            setTimeout(() => {{
                document.body.style.opacity = '1';
            }}, 100);
        }});
    </script>
</body>
</html>"""

    html_path = os.path.join(out_dir, filename)
    with open(html_path, "w", encoding="utf-8") as f:
        f.write(html_document)

    return os.path.abspath(html_path)


def write_html(md_lines: List[str], out_dir: str, filename: str = "result.html") -> str:
    """
    Convert collected Markdown lines into a single HTML file and save it.
    
    Converts Markdown content to HTML with proper styling, table support,
    and code highlighting. Includes a modern, responsive design.

    :param md_lines: List of markdown strings to join into a single file
    :param out_dir: Directory where the HTML file will be saved
    :param filename: Name of the HTML file (default: "result.html")
    :return: The absolute path of the written HTML file
    """
    os.makedirs(out_dir, exist_ok=True)

    md_content = "\n".join(md_lines).strip() + "\n"
    md_content = re.sub(r"\n{3,}", "\n\n", md_content)

    md_content = _process_image_paths(md_content, out_dir)

    md = MarkdownIt("commonmark", {"breaks": True, "html": True})
    
    html_body = md.render(md_content)
    
    html_body = _add_table_styling(html_body)
    
    html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Analysis Results</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        {_get_css_styles()}
    </style>
</head>
<body>
    <button class="theme-toggle" onclick="toggleTheme()" title="Toggle dark mode"></button>
    <div class="container">
        <header class="header">
            <div class="header-content">
                <div class="header-text">
                    <h1>Document Analysis Results</h1>
                    <p class="subtitle">Intelligent Document Processing & Analysis</p>
                </div>
                <div class="header-badge">
                    Generated by Doctra
                </div>
            </div>
        </header>
        <main class="content">
            {html_body}
        </main>
        <footer class="footer">
            <div class="footer-content">
                <div class="footer-brand">Doctra</div>
                <div class="footer-info">
                    <span>Intelligent Document Processing</span>
                    <a href="https://github.com/AdemBoukhris457/Doctra" target="_blank">GitHub</a>
                </div>
            </div>
        </footer>
    </div>
    <script>
        // Theme toggle functionality
        function toggleTheme() {{
            const body = document.body;
            const currentTheme = body.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            
            body.setAttribute('data-theme', newTheme);
            localStorage.setItem('doctra-theme', newTheme);
            
            // Add smooth transition
            body.style.transition = 'all 0.3s ease';
            setTimeout(() => {{
                body.style.transition = '';
            }}, 300);
        }}

        // Load saved theme on page load
        document.addEventListener('DOMContentLoaded', function() {{
            const savedTheme = localStorage.getItem('doctra-theme') || 'light';
            document.body.setAttribute('data-theme', savedTheme);
        }});

        // Add smooth scroll behavior
        document.documentElement.style.scrollBehavior = 'smooth';

        // Add loading animation
        window.addEventListener('load', function() {{
            document.body.style.opacity = '0';
            document.body.style.transition = 'opacity 0.5s ease';
            setTimeout(() => {{
                document.body.style.opacity = '1';
            }}, 100);
        }});
    </script>
</body>
</html>"""

    html_path = os.path.join(out_dir, filename)
    with open(html_path, "w", encoding="utf-8") as f:
        f.write(html_content)

    return os.path.abspath(html_path)


def write_structured_html(html_path: str, items: List[Dict[str, Any]]) -> str | None:
    """
    Write a list of structured data items into an HTML file with tables.

    Each item becomes a separate section with styled tables. The function
    handles data normalization and creates a responsive HTML layout.

    :param html_path: Path where the HTML file will be saved
    :param items: List of dictionaries, each containing:
                 - 'title': Section title (optional)
                 - 'headers': List of column headers (optional)
                 - 'rows': List of data rows (optional)
    :return: Path to the written HTML file if successful, None if no items provided
    """
    if not items:
        return None

    valid_items = []
    for item in items:
        headers = item.get("headers") or []
        rows = item.get("rows") or []
        if headers or (rows and any(
                row for row in rows if any(cell for cell in row if cell is not None and str(cell).strip()))):
            valid_items.append(item)

    if not valid_items:
        print("Warning: No valid items to write to HTML")
        return None

    os.makedirs(os.path.dirname(html_path) or ".", exist_ok=True)

    html_sections = []
    for item in valid_items:
        try:
            title = item.get("title") or "Untitled"
            headers = item.get("headers") or []
            rows = item.get("rows") or []

            normalized_headers, normalized_rows = _normalize_data(headers, rows)

            if not normalized_rows and not normalized_headers:
                print(f"Skipping empty item: {title}")
                continue

            table_html = _create_html_table(normalized_headers, normalized_rows)
            section_html = f"""
            <section class="data-section">
                <h2 class="section-title">{_escape_html(title)}</h2>
                {table_html}
            </section>
            """
            html_sections.append(section_html)

        except Exception as e:
            print(f"Error processing item '{item.get('title', 'Unknown')}': {e}")
            continue

    if not html_sections:
        print("Warning: No valid sections to write to HTML")
        return None

    html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Structured Data Export</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        {_get_css_styles()}
        {_get_table_css_styles()}
    </style>
</head>
<body>
    <button class="theme-toggle" onclick="toggleTheme()" title="Toggle dark mode"></button>
    <div class="container">
        <header class="header">
            <div class="header-content">
                <div class="header-text">
                    <h1>Structured Data Export</h1>
                    <p class="subtitle">Intelligent Document Processing & Analysis</p>
                </div>
                <div class="header-badge">
                    Generated by Doctra
                </div>
            </div>
        </header>
        <main class="content">
            {''.join(html_sections)}
        </main>
        <footer class="footer">
            <div class="footer-content">
                <div class="footer-brand">Doctra</div>
                <div class="footer-info">
                    <span>Intelligent Document Processing</span>
                    <a href="https://github.com/AdemBoukhris457/Doctra" target="_blank">GitHub</a>
                </div>
            </div>
        </footer>
    </div>
    <script>
        // Theme toggle functionality
        function toggleTheme() {{
            const body = document.body;
            const currentTheme = body.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            
            body.setAttribute('data-theme', newTheme);
            localStorage.setItem('doctra-theme', newTheme);
            
            // Add smooth transition
            body.style.transition = 'all 0.3s ease';
            setTimeout(() => {{
                body.style.transition = '';
            }}, 300);
        }}

        // Load saved theme on page load
        document.addEventListener('DOMContentLoaded', function() {{
            const savedTheme = localStorage.getItem('doctra-theme') || 'light';
            document.body.setAttribute('data-theme', savedTheme);
        }});

        // Add smooth scroll behavior
        document.documentElement.style.scrollBehavior = 'smooth';

        // Add loading animation
        window.addEventListener('load', function() {{
            document.body.style.opacity = '0';
            document.body.style.transition = 'opacity 0.5s ease';
            setTimeout(() => {{
                document.body.style.opacity = '1';
            }}, 100);
        }});

        // Add table interaction enhancements
        document.addEventListener('DOMContentLoaded', function() {{
            const tables = document.querySelectorAll('.data-table');
            tables.forEach(table => {{
                table.addEventListener('mouseenter', function() {{
                    this.style.transform = 'scale(1.01)';
                }});
                table.addEventListener('mouseleave', function() {{
                    this.style.transform = 'scale(1)';
                }});
            }});
        }});
    </script>
</body>
</html>"""

    with open(html_path, "w", encoding="utf-8") as f:
        f.write(html_content)

    return html_path


def _normalize_data(headers: List[str], rows: List[List]) -> tuple[List[str], List[List]]:
    """
    Normalize headers and rows to ensure consistent dimensions.

    :param headers: List of column headers
    :param rows: List of data rows
    :return: Tuple of (normalized_headers, normalized_rows)
    """
    if not rows:
        return headers, []

    max_cols = max(len(row) for row in rows) if rows else 0

    if headers:
        target_cols = max(len(headers), max_cols)
    else:
        target_cols = max_cols
        headers = [f"Column_{i + 1}" for i in range(target_cols)]

    normalized_headers = list(headers)
    while len(normalized_headers) < target_cols:
        normalized_headers.append(f"Column_{len(normalized_headers) + 1}")
    normalized_headers = normalized_headers[:target_cols]

    normalized_rows = []
    for row in rows:
        normalized_row = list(row)
        while len(normalized_row) < target_cols:
            normalized_row.append(None)
        normalized_rows.append(normalized_row[:target_cols])

    return normalized_headers, normalized_rows


def _create_html_table(headers: List[str], rows: List[List]) -> str:
    """
    Create an HTML table from headers and rows.

    :param headers: List of column headers
    :param rows: List of data rows
    :return: HTML table string
    """
    if not headers and not rows:
        return "<p class='no-data'>No data available</p>"

    header_html = ""
    if headers:
        header_cells = "".join(f"<th>{_escape_html(str(header))}</th>" for header in headers)
        header_html = f"<thead><tr>{header_cells}</tr></thead>"

    body_rows = []
    for row in rows:
        cells = "".join(f"<td>{_escape_html(str(cell) if cell is not None else '')}</td>" for cell in row)
        body_rows.append(f"<tr>{cells}</tr>")
    
    body_html = f"<tbody>{''.join(body_rows)}</tbody>" if body_rows else ""

    return f"""
    <div class="table-container">
        <table class="data-table">
            {header_html}
            {body_html}
        </table>
    </div>
    """


def render_html_table(
    headers: List[str] | None,
    rows: List[List[str]] | None,
    title: Optional[str] = None,
) -> str:
    """
    Render an HTML table from headers, rows, and optional title.
    
    Creates a properly formatted HTML table with headers, data rows,
    and optional title. This is used for VLM-extracted tables to ensure
    they display as proper HTML tables instead of markdown.

    :param headers: List of column headers (optional, will be auto-generated if None)
    :param rows: List of data rows, where each row is a list of cell values
    :param title: Optional title to display above the table
    :return: Formatted HTML table string
    """
    headers = headers or []
    rows = rows or []

    if not headers and not rows:
        return "<p class='no-data'>No data available</p>"

    width = len(headers) if headers else (max((len(r) for r in rows), default=1))

    if not headers:
        headers = [f"Column {i+1}" for i in range(width)]

    normalized_headers, normalized_rows = _normalize_data(headers, rows)

    table_html = _create_html_table(normalized_headers, normalized_rows)
    
    if title:
        return f"""
        <div class="table-section">
            <h3 class="table-title">{_escape_html(title)}</h3>
            {table_html}
        </div>
        """
    else:
        return table_html


def _add_table_styling(html_content: str) -> str:
    """
    Add table styling wrapper to HTML content.
    
    :param html_content: HTML content that may contain tables
    :return: HTML content with table styling
    """
    html_content = re.sub(
        r'<table(?:\s+[^>]*)?>',
        '<div class="table-container"><table class="markdown-table">',
        html_content
    )
    html_content = re.sub(
        r'</table>',
        '</table></div>',
        html_content
    )
    return html_content


def _escape_html(text: str) -> str:
    """
    Escape HTML special characters.

    :param text: Text to escape
    :return: Escaped text
    """
    if not text:
        return ""
    
    text = str(text)
    text = text.replace("&", "&amp;")
    text = text.replace("<", "&lt;")
    text = text.replace(">", "&gt;")
    text = text.replace('"', "&quot;")
    text = text.replace("'", "&#x27;")
    return text


def _get_css_styles() -> str:
    """Get CSS styles for the HTML document."""
    return """
        :root {
            --primary-color: #1e40af;
            --secondary-color: #1e3a8a;
            --accent-color: #3b82f6;
            --success-color: #059669;
            --warning-color: #d97706;
            --error-color: #dc2626;
            --text-color: #111827;
            --text-light: #6b7280;
            --text-muted: #9ca3af;
            --bg-color: #f9fafb;
            --card-bg: #ffffff;
            --border-color: #e5e7eb;
            --border-light: #f3f4f6;
            --shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
            --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);
            --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);
            --shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.1), 0 10px 10px rgba(0, 0, 0, 0.04);
            --border-radius: 8px;
            --border-radius-lg: 12px;
            --transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            --font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            --font-mono: 'JetBrains Mono', 'Fira Code', 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, monospace;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            font-family: var(--font-family);
            line-height: 1.6;
            color: var(--text-color);
            background: var(--bg-color);
            min-height: 100vh;
            font-size: 16px;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0;
            background: var(--card-bg);
            min-height: 100vh;
            box-shadow: var(--shadow-xl);
        }

        .header {
            background: var(--primary-color);
            color: white;
            padding: 2rem 3rem;
            border-bottom: 4px solid var(--accent-color);
            position: relative;
        }

        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
            pointer-events: none;
        }

        .header-content {
            position: relative;
            z-index: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .header-text {
            flex: 1;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
            font-weight: 700;
            letter-spacing: -0.025em;
        }

        .subtitle {
            font-size: 1.1rem;
            opacity: 0.9;
            font-weight: 400;
            color: rgba(255, 255, 255, 0.8);
        }

        .header-badge {
            background: rgba(255, 255, 255, 0.2);
            padding: 0.5rem 1rem;
            border-radius: var(--border-radius);
            font-size: 0.9rem;
            font-weight: 500;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .content {
            padding: 3rem;
            background: var(--card-bg);
        }

        .content h1, .content h2, .content h3, .content h4, .content h5, .content h6 {
            color: var(--text-color);
            margin-top: 2rem;
            margin-bottom: 1rem;
            font-weight: 600;
            line-height: 1.3;
        }

        .content h1 { 
            font-size: 2.25rem; 
            font-weight: 700;
            color: var(--primary-color);
            border-bottom: 3px solid var(--accent-color);
            padding-bottom: 0.5rem;
            margin-bottom: 1.5rem;
        }
        .content h2 { 
            font-size: 1.875rem; 
            font-weight: 600;
            color: var(--text-color);
            margin-top: 2.5rem;
            margin-bottom: 1rem;
            position: relative;
        }
        .content h2::before {
            content: '';
            position: absolute;
            left: -1rem;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 1.5rem;
            background: var(--accent-color);
            border-radius: 2px;
        }
        .content h3 { 
            font-size: 1.5rem; 
            font-weight: 600;
            color: var(--text-color);
            margin-top: 2rem;
        }
        .content h4 { 
            font-size: 1.25rem; 
            font-weight: 600;
            color: var(--text-light);
            margin-top: 1.5rem;
        }

        .content p {
            margin-bottom: 1.25rem;
            font-size: 1rem;
            line-height: 1.7;
            color: var(--text-color);
        }

        .content img {
            max-width: 100%;
            height: auto;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow-md);
            margin: 1.5rem 0;
            transition: var(--transition);
            border: 1px solid var(--border-color);
        }

        .content img:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .image-error {
            background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
            border: 2px dashed #f44336;
            border-radius: var(--border-radius);
            padding: 1rem;
            margin: 1rem 0;
            text-align: center;
            color: #d32f2f;
            font-style: italic;
            font-weight: 500;
        }

        .content pre {
            background: #f8fafc;
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
            padding: 1.5rem;
            overflow-x: auto;
            margin: 1.5rem 0;
            box-shadow: var(--shadow);
            position: relative;
            font-family: var(--font-mono);
        }

        .content pre::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: var(--accent-color);
            border-radius: var(--border-radius) var(--border-radius) 0 0;
        }

        .content code {
            background: #f1f5f9;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-family: var(--font-mono);
            font-size: 0.875em;
            font-weight: 500;
            color: var(--primary-color);
            border: 1px solid var(--border-light);
        }

        .content pre code {
            background: none;
            padding: 0;
            border: none;
            color: var(--text-color);
        }

        .content blockquote {
            border-left: 4px solid var(--accent-color);
            margin: 1.5rem 0;
            padding: 1rem 1.5rem;
            color: var(--text-light);
            font-style: italic;
            background: #f8fafc;
            border-radius: 0 var(--border-radius) var(--border-radius) 0;
            position: relative;
        }

        .content blockquote::before {
            content: '"';
            font-size: 2rem;
            color: var(--accent-color);
            position: absolute;
            top: -0.25rem;
            left: 0.75rem;
            opacity: 0.5;
            font-family: serif;
        }

        .content ul, .content ol {
            margin: 1rem 0;
            padding-left: 1.5rem;
        }

        .content li {
            margin-bottom: 0.5rem;
            font-size: 1rem;
            line-height: 1.6;
        }

        .content ul li {
            position: relative;
            list-style: none;
        }

        .content ul li::before {
            content: '•';
            color: var(--accent-color);
            font-weight: bold;
            position: absolute;
            left: -1rem;
        }

        .footer {
            background: #f8fafc;
            border-top: 1px solid var(--border-color);
            padding: 2rem 3rem;
            color: var(--text-light);
            font-size: 0.9rem;
        }

        .footer-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
        }

        .footer a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: var(--transition);
        }

        .footer a:hover {
            color: var(--accent-color);
            text-decoration: underline;
        }

        .footer-info {
            display: flex;
            gap: 2rem;
            align-items: center;
        }

        .footer-brand {
            font-weight: 600;
            color: var(--text-color);
        }

        /* Professional table styling */
        .markdown-table, table {
            width: 100%;
            border-collapse: collapse;
            margin: 1.5rem 0;
            background: var(--card-bg);
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: var(--shadow-md);
            border: 1px solid var(--border-color);
        }

        .markdown-table th, .markdown-table td,
        table th, table td {
            padding: 0.75rem 1rem;
            text-align: left;
            border-bottom: 1px solid var(--border-light);
        }

        .markdown-table th, table th {
            background: #f8fafc;
            color: var(--text-color);
            font-weight: 600;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border-bottom: 2px solid var(--accent-color);
        }

        .markdown-table tr:nth-child(even), table tr:nth-child(even) {
            background: #f8fafc;
        }

        .markdown-table tr:hover, table tr:hover {
            background: #f1f5f9;
            transition: var(--transition);
        }

        .markdown-table tr:last-child td, table tr:last-child td {
            border-bottom: none;
        }

        /* Ensure all tables are wrapped in containers */
        .table-container {
            margin: 1.5rem 0;
            overflow-x: auto;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow-md);
        }

        .table-container table {
            margin: 0;
            box-shadow: none;
        }

        /* Professional dark mode toggle */
        .theme-toggle {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
            width: 44px;
            height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: var(--shadow-md);
            transition: var(--transition);
            z-index: 1000;
        }

        .theme-toggle:hover {
            background: var(--accent-color);
            color: white;
            box-shadow: var(--shadow-lg);
        }

        .theme-toggle::before {
            content: '🌙';
            font-size: 1rem;
        }

        /* Dark mode styles */
        [data-theme="dark"] {
            --text-color: #f9fafb;
            --text-light: #d1d5db;
            --text-muted: #9ca3af;
            --bg-color: #111827;
            --card-bg: #1f2937;
            --border-color: #374151;
            --border-light: #4b5563;
        }

        [data-theme="dark"] body {
            background: var(--bg-color);
        }

        [data-theme="dark"] .theme-toggle::before {
            content: '☀️';
        }

        /* Dark mode table styles */
        [data-theme="dark"] .markdown-table,
        [data-theme="dark"] table {
            background: var(--card-bg);
            border-color: var(--border-color);
        }

        [data-theme="dark"] .markdown-table th,
        [data-theme="dark"] table th {
            background: #374151;
            color: #f9fafb;
            border-bottom-color: var(--accent-color);
        }

        [data-theme="dark"] .markdown-table td,
        [data-theme="dark"] table td {
            color: #f9fafb;
            border-bottom-color: var(--border-color);
        }

        [data-theme="dark"] .markdown-table tr:nth-child(even),
        [data-theme="dark"] table tr:nth-child(even) {
            background: #374151;
        }

        [data-theme="dark"] .markdown-table tr:hover,
        [data-theme="dark"] table tr:hover {
            background: #4b5563;
        }

        /* Dark mode footer styles to match header */
        [data-theme="dark"] .footer {
            background: var(--primary-color);
            color: white;
            border-top-color: var(--accent-color);
        }

        [data-theme="dark"] .footer-brand {
            color: white;
        }

        [data-theme="dark"] .footer a {
            color: rgba(255, 255, 255, 0.8);
        }

        [data-theme="dark"] .footer a:hover {
            color: white;
        }

        /* Professional scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--border-light);
        }

        ::-webkit-scrollbar-thumb {
            background: var(--accent-color);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--primary-color);
        }

        /* Professional selection styling */
        ::selection {
            background: var(--accent-color);
            color: white;
        }

        ::-moz-selection {
            background: var(--accent-color);
            color: white;
        }

        /* Enhanced focus states for accessibility */
        .theme-toggle:focus {
            outline: 2px solid var(--accent-color);
            outline-offset: 2px;
        }

        .footer a:focus {
            outline: 2px solid var(--accent-color);
            outline-offset: 2px;
            border-radius: 4px;
        }

        /* Print styles */
        @media print {
            body {
                background: white !important;
                color: black !important;
            }
            
            .header {
                background: #f8f9fa !important;
                color: black !important;
                box-shadow: none !important;
            }
            
            .content {
                box-shadow: none !important;
            }
            
            .theme-toggle {
                display: none !important;
            }

            .footer {
                background: #f8f9fa !important;
                border-top: 1px solid #ddd !important;
            }
        }

        @media (max-width: 768px) {
            .header {
                padding: 1.5rem 2rem;
            }
            
            .header-content {
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .content {
                padding: 2rem;
            }
            
            .markdown-table {
                font-size: 0.875rem;
            }
            
            .markdown-table th,
            .markdown-table td {
                padding: 0.5rem;
            }
            
            .theme-toggle {
                top: 1rem;
                right: 1rem;
                width: 40px;
                height: 40px;
            }

            .footer {
                padding: 1.5rem 2rem;
            }

            .footer-content {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
        }

        @media (max-width: 480px) {
            .header {
                padding: 1rem;
            }
            
            .header h1 {
                font-size: 1.75rem;
            }
            
            .content {
                padding: 1.5rem;
            }
            
            .markdown-table {
                font-size: 0.8rem;
            }
            
            .markdown-table th,
            .markdown-table td {
                padding: 0.375rem;
            }
        }
    """


def _get_table_css_styles() -> str:
    """Get additional CSS styles for tables."""
    return """
        .data-section {
            margin-bottom: 4rem;
            position: relative;
        }

        .data-section::before {
            content: '';
            position: absolute;
            top: -1rem;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color), var(--accent-color));
            border-radius: 1px;
        }

        .section-title {
            color: var(--text-color);
            font-size: 1.8rem;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 3px solid var(--primary-color);
            position: relative;
            font-weight: 700;
        }

        .section-title::after {
            content: '';
            position: absolute;
            bottom: -3px;
            left: 0;
            width: 50px;
            height: 3px;
            background: var(--accent-color);
        }

        .table-container {
            overflow-x: auto;
            margin: 2rem 0;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow-lg);
            position: relative;
            background: var(--card-bg);
        }

        .table-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color), var(--accent-color));
            border-radius: var(--border-radius) var(--border-radius) 0 0;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: var(--card-bg);
            font-size: 1rem;
            position: relative;
        }

        .data-table th {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 1.5rem 1.5rem;
            text-align: left;
            font-weight: 700;
            font-size: 0.95rem;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            position: relative;
        }

        .data-table th::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, transparent, white, transparent);
        }

        .data-table th:first-child {
            border-top-left-radius: var(--border-radius);
        }

        .data-table th:last-child {
            border-top-right-radius: var(--border-radius);
        }

        .data-table td {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid var(--border-color);
            vertical-align: top;
            font-size: 1rem;
            line-height: 1.6;
        }

        .data-table tr:nth-child(even) {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        }

        .data-table tr:hover {
            background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
            transform: scale(1.005);
            transition: var(--transition);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .data-table tr:last-child td:first-child {
            border-bottom-left-radius: var(--border-radius);
        }

        .data-table tr:last-child td:last-child {
            border-bottom-right-radius: var(--border-radius);
        }

        .data-table tr:last-child td {
            border-bottom: none;
        }

        .no-data {
            text-align: center;
            color: var(--text-light);
            font-style: italic;
            padding: 3rem;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: var(--border-radius);
            font-size: 1.1rem;
            position: relative;
        }

        .no-data::before {
            content: '📊';
            font-size: 2rem;
            display: block;
            margin-bottom: 1rem;
            opacity: 0.5;
        }

        /* Enhanced table animations */
        .data-table tr {
            transition: var(--transition);
        }

        .data-table td {
            transition: var(--transition);
        }

        .data-table tr:hover td {
            color: var(--text-color);
            font-weight: 500;
        }

        /* Table scrollbar styling */
        .table-container::-webkit-scrollbar {
            height: 8px;
        }

        .table-container::-webkit-scrollbar-track {
            background: var(--border-color);
            border-radius: 4px;
        }

        .table-container::-webkit-scrollbar-thumb {
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
            border-radius: 4px;
        }

        .table-container::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(90deg, var(--secondary-color), var(--accent-color));
        }

        @media (max-width: 768px) {
            .data-table {
                font-size: 0.9rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 1rem;
            }
            
            .section-title {
                font-size: 1.5rem;
            }
        }

        @media (max-width: 480px) {
            .data-table {
                font-size: 0.8rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.75rem;
            }
            
            .section-title {
                font-size: 1.3rem;
            }
        }
    """
