import pandas as pd
import re

def format_number(x):
    return f"{x:,.2f}" if pd.notnull(x) else ""

def clean_table(html):
    """Remove the outer <table> tag generated by pandas."""
    html = re.sub(r"<table[^>]*>", "", html)
    html = html.replace("</table>", "")
    return html

def render_table_block(title, html_rows):
    """Render a table block with consistent HTML structure."""
    return f"""
    <div class="lines-block">
        <h2 class="lines-title">{title}</h2>
        <div class="table-container">
            <table class="table-custom">
                {html_rows}
            </table>
        </div>
    </div>
    """

def lines(df, theme="light"):
    df_copy = df.copy()

    # Format numeric columns ONLY for display
    for col in df_copy.select_dtypes(include=['float64', 'int64']).columns:
        df_copy[col] = df_copy[col].apply(format_number)

    # First and last 10 rows
    first_lines = df_copy.head(5)
    last_lines = df_copy.tail(5)

    # Convert to HTML (remove outer table)
    first_html = clean_table(first_lines.to_html(index=False, border=0))
    last_html = clean_table(last_lines.to_html(index=False, border=0))

    # Build blocks
    first_block = render_table_block("First lines data", first_html)
    last_block = render_table_block("Last lines data", last_html)

    return first_block + last_block