<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSV Preview</title>
    <script src="{{ url_for('static', filename='edited_csv.js') }}"></script>
</head>
<body>
    {% include 'header.html' %}
    <h1>CSV Preview</h1>

    <!-- Display error messages -->
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            <details>
                <summary>Errors found during submission (click to expand):</summary>
                <ul>
                    {% for category, message in messages %}
                        <li><strong>{{ category }}:</strong> {{ message }}</li>
                    {% endfor %}
                </ul>
            </details>
        {% endif %}
    {% endwith %}

    <!-- Render tables for new, existing, and invalid entries -->
    {% for table_name, entries, editable, tableclass in [
        ('New Entries', new_entries, true, 'table-valid-entries'),
        ('Existing Entries', existing_entries, true, 'table-valid-entries'),
        ('Invalid Entries', invalid_entries, false, 'table-invalid-entries')
    ] %}
        {% if entries %}
            <h2>{{ table_name }}</h2>
            {% if table_name == 'Invalid Entries' %}
                {% if mode == 'import' %}
                <p>These entries already exist:</p>
                {% elif mode == 'edit' %}
                <p>These entries do not exist:</p>
                {% endif %}
            {% endif %}
            <table border="1" class="{{ tableclass }}">
                <thead>
                    <tr>
                        {% for attrib in item_attributes %}
                            <th data-attrib="{{ attrib.attrib_name }}">{{ attrib.display_name }}</th>
                        {% endfor %}
                    </tr>
                </thead>
                <tbody>
                    {% for entry in entries %}
                        <tr>
                            {% for attrib in item_attributes %}
                                <td {% if editable %}contenteditable="true"{% endif %}>
                                    {{ entry[attrib.attrib_name] }}
                                </td>
                            {% endfor %}
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        {% endif %}
    {% endfor %}

    <!-- Form button to confirm and save data -->
    {% if new_entries or existing_entries %}
    <form action="/confirm_save" method="POST" onsubmit="return collectEditedData(event)">
        <button type="submit">Confirm and Save to Database</button>
    </form>
    {% endif %}

    <!-- Cancel button that redirects to the home page -->
    <button type="button" onclick="window.location.href='/'">Cancel</button>
</body>
</html>