{% extends 'generic/cid_group_base.html' %}

{% block content %}
    <div class="card mb-3">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <h2 class="card-title mb-1">Group: {{ group.name }}</h2>
                    <div class="small text-muted">This page shows an overview of the candidates and exams associated with the group.</div>
                </div>
                <div class="text-end">
                    <div class="small text-muted">Users in group</div>
                    <div class="fw-bold">{{ users|length }}</div>
                </div>
            </div>

            <div class="mt-3">
                <details>
                    <summary class="small">Help</summary>
                    <div class="small text-muted mt-2">
                        Once a candidate has been added to a group and the group has been added to an exam individual candidates can be allocated to the exam. Adding a group to an exam does not automatically give group members access — they must be added.
                    </div>
                </details>
            </div>
        </div>
    </div>

    <div class="card mb-3">
        <div class="card-body">
            <h3 class="card-title mb-2">Users</h3>
            <div class="d-flex align-items-center mb-2">
                <div class="me-auto small text-muted">Sort by:</div>
                <div class="btn-group btn-group-sm user-sort-group" role="group" aria-label="Sort">
                    <button type="button" class="btn btn-sm btn-outline-secondary sort-btn" data-key="username">{% if group_type == 'cid' %}CID{% else %}Username{% endif %} <span class="sort-caret"></span></button>
                    <button type="button" class="btn btn-sm btn-outline-secondary sort-btn" data-key="name">Name <span class="sort-caret"></span></button>
                    <button type="button" class="btn btn-sm btn-outline-secondary sort-btn" data-key="email">Email <span class="sort-caret"></span></button>
                </div>
            </div>

            {% if group_type == 'cid' %}
                <div class="mb-2">
                    <form method="post" hx-post="{% url 'generic:cid_group_generate_preview' group.pk %}" hx-target="#cid-generate-preview" hx-swap="innerHTML">
                        {% csrf_token %}
                        <label class="small text-muted">Quick generate users (one per line: name,email)</label>
                        <textarea name="rows" class="form-control form-control-sm mb-2" rows="5" placeholder="John Smith,j.smith@example.org\nJane Doe,jane@example.org"></textarea>
                        <div>
                            <button type="submit" class="btn btn-sm btn-outline-primary">Preview</button>
                        </div>
                    </form>
                    <div id="cid-generate-preview"></div>
                </div>
            {% endif %}

            <div id="group-users-wrap">
                {% if users %}
                    {% include 'generic/partials/group_users_list.html' with users=users group_type=group_type %}
                {% else %}
                    <p class="small text-muted">This group has no users.
                        {% if group_type == "cid" %}
                            You can create or add users <a href="{% url 'generic:manage_cids' %}">here</a>.
                        {% endif %}
                    </p>
                {% endif %}
            </div>
        </div>
    </div>



    <div class="card mb-3">
        <div class="card-body">
            <h3 class="card-title mb-2">Exams</h3>
            <div class="small text-muted mb-2">The group is associated with these exams. Adding the group to an exam helps add members quickly but does not grant automatic access.</div>
            <div class="mb-2">
                {% if group_type == "cid" %}
                    Add more <a href='{% url "generic:cid_group_exams" group.pk %}'>here</a>.
                {% else %}
                    Add more <a href='{% url "generic:user_group_exams" group.pk %}'>here</a>.
                {% endif %}
            </div>

            {% with group.GetGroupExams as exam_map %}
                {% for key, value in exam_map.items %}
                    <h5 class="mt-3">{{ key }}</h5>
                    <div class="list-group list-group-flush">
                        {% for exam in value %}
                            <div class="list-group-item bg-transparent border-0 py-2 d-flex align-items-center">
                                <div>
                                    <a href="{{ exam.get_absolute_url }}" class="fw-bold">{{ exam }}</a>
                                    <div class="small text-muted">{{ exam }}</div>
                                </div>

                                <div class="ms-3">
                                    {% if group_type == "cid" %}
                                        <a href="{{ exam.get_cid_edit_url }}" class="edit-link small">Edit candidates</a>
                                    {% else %}
                                        <a href="{{ exam.get_user_edit_url }}" class="edit-link small">Edit candidates</a>
                                    {% endif %}
                                </div>

                                <div class="ms-auto">
                                    <div class="btn-group btn-group-sm" role="group">
                                        {% if group_type == "cid" %}
                                            <form class="m-0 d-inline">
                                                <input type="hidden" name="exam_id" value="{{ exam.pk }}">
                                                <input type="hidden" name="exam_type" value="{{ exam.app_name }}">
                                                <button class="btn btn-sm btn-outline-success hx-action-btn" hx-post="{% url 'generic:cid_group_add_candidates_to_exams' group.pk %}" name="action" value="add">Add</button>
                                                <button class="btn btn-sm btn-outline-danger hx-action-btn" hx-post="{% url 'generic:cid_group_add_candidates_to_exams' group.pk %}" name="action" value="remove">Remove</button>
                                            </form>
                                        {% else %}
                                            <form class="m-0 d-inline">
                                                <input type="hidden" name="exam_id" value="{{ exam.pk }}">
                                                <input type="hidden" name="exam_type" value="{{ exam.app_name }}">
                                                <button class="btn btn-sm btn-outline-success hx-action-btn" hx-post="{% url 'generic:user_group_add_candidates_to_exams' group.pk %}" name="action" value="add">Add</button>
                                                <button class="btn btn-sm btn-outline-danger hx-action-btn" hx-post="{% url 'generic:user_group_add_candidates_to_exams' group.pk %}" name="action" value="remove">Remove</button>
                                            </form>
                                        {% endif %}
                                    </div>
                                </div>

                                <div class="px-3 ms-2 small text-muted">
                                    {% if group_type == "cid" %}
                                        (Cid candidate count: {{ exam.valid_cid_users.count }})
                                    {% else %}
                                        (User candidate count: {{ exam.valid_user_users.count }})
                                    {% endif %}
                                </div>
                            </div>
                        {% endfor %}
                    </div>
                {% endfor %}
            {% endwith %}
        </div>
    </div>


{% endblock %}

{% block js %}
    <style>
        .edit-link { font-size: 0.85rem; opacity: 0.7; }
        .list-group-item .fw-bold { font-size: 0.95rem; }
        .card-title { font-size: 1rem; }
        /* keep existing small visual tweaks */
        .sort-caret { font-weight: 600; }
    </style>

    <script>
        document.addEventListener('DOMContentLoaded', function(){
            (function(){
                const sortGroup = document.querySelector('.user-sort-group');
                if(!sortGroup) return;
                let sortState = { key: 'username', dir: 'asc' };
                function updateCarets(){
                    sortGroup.querySelectorAll('.sort-btn').forEach(function(b){
                        const key = b.dataset.key;
                        const caret = b.querySelector('.sort-caret');
                        if(!caret) return;
                        caret.textContent = (sortState.key === key) ? (sortState.dir === 'asc' ? ' ▲' : ' ▼') : '';
                    });
                }
                function getVal(li, key){
                    if(!li) return '';
                    return (li.dataset[key] || '').toString().toLowerCase();
                }
                function sortList(key){
                    const ul = document.getElementById('group-users-list'); if(!ul) return;
                    const items = Array.from(ul.children);
                    const dir = (sortState.key === key && sortState.dir === 'asc') ? 'desc' : 'asc';
                    items.sort(function(a,b){ const va = getVal(a,key); const vb = getVal(b,key); if(va < vb) return dir === 'asc' ? -1 : 1; if(va > vb) return dir === 'asc' ? 1 : -1; return 0; });
                    items.forEach(function(it){ ul.appendChild(it); });
                    sortState = { key: key, dir: dir };
                    updateCarets();
                }
                sortGroup.querySelectorAll('.sort-btn').forEach(function(b){ b.addEventListener('click', function(){ sortList(b.dataset.key); }); });
                updateCarets();
            })();
        });
    </script>
    <script>
        // Send/resend login email handlers for CID users
        document.addEventListener('DOMContentLoaded', function(){
            document.body.addEventListener('click', function(e){
                const btn = e.target.closest && e.target.closest('.send-login-email-btn');
                if(!btn) return;
                e.preventDefault();
                const url = btn.dataset.url + '?resend=1';
                const cid = btn.dataset.cid;
                // show spinner on button
                btn.disabled = true;
                const spinner = document.createElement('span'); spinner.className = 'spinner-border spinner-border-sm ms-2'; spinner.setAttribute('role','status'); spinner.setAttribute('aria-hidden','true'); btn.appendChild(spinner);
                fetch(url, { method: 'GET', credentials: 'same-origin' })
                    .then(r => r.json())
                    .then(data => {
                        const li = btn.closest('li');
                        if(!li) return;
                        const status = li.querySelector('.login-email-status');
                        if(data.sent){
                            if(status){ status.textContent = 'Email sent'; status.className = 'badge bg-success ms-1 login-email-status'; }
                        } else {
                            if(status){ status.textContent = 'Not sent'; status.className = 'badge bg-secondary ms-1 login-email-status'; }
                            if(data.comment){ console.error('Email send comment:', data.comment); }
                        }
                    }).catch(err => { console.error('Failed to send login email', err); })
                    .finally(()=>{ if(btn){ const s = btn.querySelector('.spinner-border'); if(s) s.remove(); btn.disabled = false; } });
            });
        });

        // Visual indicators for HTMX add/remove actions
        document.addEventListener('DOMContentLoaded', function(){
            document.body.addEventListener('htmx:beforeRequest', function(evt){
                try{
                    const elt = evt.detail.elt;
                    if(!elt) return;
                    const btn = elt.closest && elt.closest('.hx-action-btn') ? elt.closest('.hx-action-btn') : (elt.classList && elt.classList.contains('hx-action-btn') ? elt : null);
                    if(!btn) return;
                    // stash original HTML for restore
                    btn.dataset._origHtml = btn.innerHTML;
                    btn.disabled = true;
                    const spinner = document.createElement('span');
                    spinner.className = 'spinner-border spinner-border-sm ms-2';
                    spinner.setAttribute('role','status'); spinner.setAttribute('aria-hidden','true');
                    spinner.dataset._hx_spinner = '1';
                    btn.appendChild(spinner);
                }catch(e){ console.error(e); }
            });

            document.body.addEventListener('htmx:afterRequest', function(evt){
                try{
                    const elt = evt.detail.elt;
                    if(!elt) return;
                    const btn = elt.closest && elt.closest('.hx-action-btn') ? elt.closest('.hx-action-btn') : (elt.classList && elt.classList.contains('hx-action-btn') ? elt : null);
                    if(!btn) return;
                    // remove spinner(s)
                    const sp = btn.querySelectorAll('span[data-_hx_spinner]');
                    sp.forEach(s => s.remove());
                    // show transient status
                    const status = document.createElement('span');
                    status.className = 'badge bg-success ms-2 hx-action-status';
                    status.textContent = 'Done';
                    btn.appendChild(status);
                    // restore after short delay
                    setTimeout(function(){
                        if(btn.dataset._origHtml){ btn.innerHTML = btn.dataset._origHtml; delete btn.dataset._origHtml; }
                        btn.disabled = false;
                    }, 1500);
                }catch(e){ console.error(e); }
            });
        });
    </script>
{% endblock %}