{% comment %} Partial: renders the users <ul> for group detail pages {% endcomment %}
<div class="d-flex align-items-center mb-2">
    <div class="me-auto"></div>
    <div>
        <button type="button" class="btn btn-sm btn-outline-secondary show-group-table-btn">Show table</button>
    </div>
</div>

<ul id="group-users-list" class="list-group list-group-flush">
    {% for user in users %}
        <li class="list-group-item bg-transparent border-0 py-2"
            data-username="{% if group_type == 'cid' %}{{ user.cid|default:''|escape }}{% else %}{{ user.username|default:''|escape }}{% endif %}"
            data-name="{% if group_type == 'cid' %}{{ user.name|default:''|escape }}{% else %}{{ user.get_full_name|default:user.username|escape }}{% endif %}"
            data-email="{{ user.email|default:''|escape }}"
            {% if group_type == 'cid' %}data-cid="{{ user.cid|default:''|escape }}" data-passcode="{{ user.passcode|default:''|escape }}"{% endif %}>
            {% if group_type == "cid" %}
                <div class="d-flex align-items-start">
                    <div>
                        <div class="fw-bold">{{ user.name }}</div>
                        <div class="small text-muted">{{ user.email }}</div>
                        {% if user.notes %}
                            <div class="small text-muted mt-1">Notes: {{ user.notes|truncatechars:120 }}</div>
                        {% endif %}
                    </div>
                    <div class="ms-auto text-end small text-muted">
                        <div>CID: {{ user.cid }}</div>
                        <div>Passcode: {{ user.passcode }}</div>
                        <div class="mt-1">
                            {% if user.login_email_sent %}
                                <span class="badge bg-success ms-1 login-email-status">Email sent</span>
                            {% else %}
                                <span class="badge bg-secondary ms-1 login-email-status">Not sent</span>
                            {% endif %}
                            {% if user.email %}
                                <button type="button" class="btn btn-sm btn-outline-primary ms-2 send-login-email-btn" data-cid="{{ user.cid }}" data-url="{% url 'generic:candidate_email_details' user.cid %}">Send Login Email</button>
                                <a class="btn btn-sm btn-outline-secondary ms-2" href="{{ user.get_email_details_url }}?preview=1" target="_blank">View Login Email</a>
                                <a class="btn btn-sm btn-outline-secondary ms-2" href="{% url 'generic:update_cid' pk=user.pk %}">Edit Cid User</a>
                            {% else %}
                                <span class="small text-muted ms-2">No email</span>
                            {% endif %}
                        </div>
                    </div>
                </div>
            {% else %}
                <div class="d-flex align-items-center">
                    <div class="fw-bold">{{ user.username }}</div>
                    <div class="ms-2 small text-muted">{{ user.email }}</div>
                </div>
            {% endif %}
        </li>
    {% endfor %}
</ul>

    <!-- Modal: Group users table / CSV export -->
<div class="modal fade" id="groupUsersModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Group users</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-sm" id="group-users-table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Username / CID</th>
                                <th>Passcode</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm btn-outline-primary" id="download-group-csv-btn">Download CSV</button>
                <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function(){
        const showBtn = document.querySelector('.show-group-table-btn');
        const modalEl = document.getElementById('groupUsersModal');
        if(!showBtn || !modalEl) return;
        const bsModal = new bootstrap.Modal(modalEl);

        function buildTable(){
            const tbody = modalEl.querySelector('#group-users-table tbody');
            tbody.innerHTML = '';
            const items = document.querySelectorAll('#group-users-list > li');
            items.forEach(function(li){
                const name = li.dataset.name || '';
                const email = li.dataset.email || '';
                const username = li.dataset.username || '';
                const cid = li.dataset.cid || '';
                const passcode = li.dataset.passcode || '';
                const userCell = cid ? cid : username;
                const tr = document.createElement('tr');
                tr.innerHTML = `<td>${escapeHtml(name)}</td><td>${escapeHtml(email)}</td><td>${escapeHtml(userCell)}</td><td>${escapeHtml(passcode)}</td>`;
                tbody.appendChild(tr);
            });
        }

        function escapeHtml(s){
            if(!s) return '';
            return s.toString().replace(/&/g, '&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
        }

        showBtn.addEventListener('click', function(){
            buildTable();
            bsModal.show();
        });

        document.getElementById('download-group-csv-btn').addEventListener('click', function(){
            const rows = [];
            const header = ['Name','Email','Username/CID','Passcode'];
            rows.push(header);
            document.querySelectorAll('#group-users-table tbody tr').forEach(function(tr){
                const cols = Array.from(tr.children).map(td => td.textContent || '');
                rows.push(cols);
            });
            const csv = rows.map(r => r.map(cell => `"${(cell||'').toString().replace(/"/g,'""')}"`).join(',')).join('\n');
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            const ts = new Date().toISOString().replace(/[:.]/g,'-');
            a.download = `group-users-${ts}.csv`;
            document.body.appendChild(a);
            a.click();
            a.remove();
            URL.revokeObjectURL(url);
        });
    });
</script>
