{% block content %}
    <div class="container py-3">
        <div class="row mb-3">
            <div class="col-12 d-flex justify-content-between align-items-center">
                <h3 class="mb-0">Candidates for {{ exam.get_exam_name }}</h3>
                <div>
                    <a class="btn btn-sm btn-outline-light" href="{% url exam.app_name|add:':exam_cids_edit' exam.pk %}">Edit Exam CIDs</a>
                    <a class="btn btn-sm btn-outline-light ms-2" href="{% url exam.app_name|add:':exam_users_edit' exam.pk %}">Edit Exam Users</a>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-6 mb-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title">CID candidates <small class="text-muted">({{ cid_user_count }})</small></h5>
                        <div class="mb-2 input-group input-group-sm">
                            <input id="cid-filter" class="form-control form-control-sm" placeholder="Filter CID candidates by CID, name, email or passcode">
                            <button type="button" id="cid-filter-clear" class="btn btn-outline-secondary d-none" title="Clear filter">×</button>
                            <span id="cid-filter-indicator" class="input-group-text d-none">Filtered</span>
                        </div>
                        <div id="htmx-info"></div>
                        <div id="cid-list" hx-get="{% url exam.app_name|add:':exam_cids_cid_list' exam.id %}" hx-trigger="load" hx-swap="innerHTML">
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item">
                                    <div class="d-flex align-items-center placeholder-glow">
                                        <span class="placeholder col-2 me-2"></span>
                                        <span class="placeholder col-4 me-2"></span>
                                        <span class="placeholder col-3"></span>
                                    </div>
                                </li>
                                <li class="list-group-item">
                                    <div class="d-flex align-items-center placeholder-glow">
                                        <span class="placeholder col-2 me-2"></span>
                                        <span class="placeholder col-4 me-2"></span>
                                        <span class="placeholder col-3"></span>
                                    </div>
                                </li>
                                <li class="list-group-item">
                                    <div class="d-flex align-items-center placeholder-glow">
                                        <span class="placeholder col-2 me-2"></span>
                                        <span class="placeholder col-4 me-2"></span>
                                        <span class="placeholder col-3"></span>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-6 mb-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title">User candidates <small class="text-muted">({{ user_user_count }})</small></h5>
                        <div class="mb-2 input-group input-group-sm">
                            <input id="user-filter" class="form-control form-control-sm" placeholder="Filter User candidates by username or email">
                            <button type="button" id="user-filter-clear" class="btn btn-outline-secondary d-none" title="Clear filter">×</button>
                            <span id="user-filter-indicator" class="input-group-text d-none">Filtered</span>
                        </div>
                        <div id="user-list" hx-get="{% url exam.app_name|add:':exam_cids_user_list' exam.id %}" hx-trigger="load" hx-swap="innerHTML">
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item">
                                    <div class="d-flex align-items-center placeholder-glow">
                                        <span class="placeholder col-3 me-2"></span>
                                        <span class="placeholder col-4"></span>
                                    </div>
                                </li>
                                <li class="list-group-item">
                                    <div class="d-flex align-items-center placeholder-glow">
                                        <span class="placeholder col-3 me-2"></span>
                                        <span class="placeholder col-4"></span>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {% if has_submissions %}
            <div id="submitted-list" hx-get="{% url exam.app_name|add:':exam_cids_submitted_list' exam.id %}" hx-trigger="load" hx-swap="innerHTML">
                <div class="card">
                    <div class="card-body">
                        <div class="placeholder-glow">
                            <h5 class="card-title placeholder col-4"></h5>
                            <p class="placeholder col-8"></p>
                            <ul class="list-unstyled small">
                                <li class="placeholder col-6 mb-2"></li>
                                <li class="placeholder col-6 mb-2"></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        {% endif %}

        <div class="row mt-3">
            <div class="col-12">
                <button class="btn btn-sm btn-outline-secondary" title="View all user exam history" hx-get="{% url exam.app_name|add:':exam_user_status' exam.id %}" hx-target=".modal-content" data-bs-toggle="modal" data-bs-target="#history-modal">Exam history <i class="bi bi-clock-history"></i></button>
            </div>
        </div>

        <!-- HTMX modal for history / partials -->
        <div id="history-modal" class="modal fade" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Exam user history: <span id="history-user"></span></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body"></div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}


{% block js %}
    <script>
        (function(){
            // Utilities to run both on initial load and after HTMX swaps

            function normalizeText(s){ return (s||'').toString().toLowerCase(); }

            function filterList(inputElem, listSelector, indicatorId, clearBtnId){
                const q = normalizeText(inputElem.value.trim());
                document.querySelectorAll(listSelector).forEach(function(li){
                    const text = normalizeText(li.textContent || '');
                    if(!q || text.indexOf(q) !== -1){
                        try{ li.style.removeProperty('display'); }catch(e){}
                        li.classList.remove('d-none');
                    } else {
                        try{ li.style.setProperty('display','none','important'); }catch(e){ li.style.display = 'none'; }
                        li.classList.add('d-none');
                    }
                });

                // Toggle indicator & clear button
                try{
                    const ind = document.getElementById(indicatorId);
                    const clearBtn = document.getElementById(clearBtnId);
                    if(ind) ind.classList.toggle('d-none', !q);
                    if(clearBtn) clearBtn.classList.toggle('d-none', !q);
                }catch(e){}
            }

            function initTooltips(){
                document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function(el){
                    try{ new bootstrap.Tooltip(el); }catch(e){/* ignore if bootstrap not available */}
                });
            }

            // Exam-level state exposed to the script so we can show Reviewed badges
            const examResultsPublished = {{ exam.publish_results|yesno:'true,false' }};

            function highlightSubmitted(){
                // Find any submitted rows (table rows or list items) that include
                // data attributes for cid/user. Then insert a small badge on matching list items.
                // Collect submitted identifiers first to avoid duplicate processing
                const submittedEls = document.querySelectorAll('#submitted-candidates [data-cid], #submitted-candidates [data-user]');
                // Build maps of submitted identifiers -> their timestamps so we
                // can attach tooltip text to the badges we create below.
                const submittedCids = new Map();
                const submittedUsers = new Map();
                submittedEls.forEach(function(el){
                    try{
                        const cid = el.dataset && el.dataset.cid ? el.dataset.cid.toString() : null;
                        const user = el.dataset && el.dataset.user ? el.dataset.user.toString() : null;
                        const first = el.dataset && el.dataset.first ? el.dataset.first.toString() : '';
                        const last = el.dataset && el.dataset.last ? el.dataset.last.toString() : '';
                        if(cid && cid !== 'None') submittedCids.set(cid, {first:first, last:last});
                        if(user && user !== 'None') submittedUsers.set(user, {first:first, last:last});
                    }catch(e){ console.error('highlightSubmitted collect error', e); }
                });

                // Helper to ensure a single badge exists inside an li and update its tooltip
                function ensureBadge(li, selector, className, text, title){
                    // Prefer the explicit badge container if present
                    const container = li.querySelector('.badge-container') || li;
                    let b = container.querySelector(selector);
                    if(!b){
                        b = document.createElement('span');
                        b.className = className;
                        b.textContent = text;
                        container.appendChild(b);
                    }
                    if(title){
                        b.setAttribute('title', title);
                        b.setAttribute('data-bs-toggle', 'tooltip');
                    }
                    return b;
                }

                // Add/update badges for CID list items
                if(submittedCids.size){
                    document.querySelectorAll('#cid-list .list-group-item').forEach(function(li){
                        try{
                            const link = li.querySelector && li.querySelector('.cid-link');
                            const text = (link && link.textContent) ? link.textContent.trim() : (li.textContent||'').trim();
                            if(submittedCids.has(text)){
                                const info = submittedCids.get(text) || {first:'', last:''};
                                // add Started badge if start time exists
                                if(info.first){
                                    const t = `Started\nFirst: ${info.first}`;
                                    ensureBadge(li, '.started-badge', 'started-badge badge bg-info ms-2', 'Started', t);
                                }
                                // Only show a 'Completed' badge when the candidate has an end time
                                if(info.last){
                                    const tComp = `Completed\nFirst: ${info.first}\nLast: ${info.last}`;
                                    ensureBadge(li, '.completed-badge', 'completed-badge badge bg-primary ms-2', 'Completed', tComp);

                                    // If the exam results have been published (reviewed), show Reviewed/Submitted badge in green
                                    if(examResultsPublished){
                                        const t = `Reviewed\nFirst: ${info.first}\nLast: ${info.last}`;
                                        ensureBadge(li, '.submitted-badge', 'submitted-badge badge bg-success ms-2', 'Reviewed', t);
                                    }
                                }
                            }
                        }catch(e){ console.error('highlightSubmitted CID item error', e); }
                    });
                }

                // Add/update badges for User list items
                if(submittedUsers.size){
                    document.querySelectorAll('#user-list .list-group-item').forEach(function(li){
                        try{
                            const txt = (li.textContent||'').trim();
                            for(const user of submittedUsers.keys()){
                                if(txt.indexOf(user) !== -1){
                                    const info = submittedUsers.get(user) || {first:'', last:''};
                                    if(info.first){
                                        const t = `Started\nFirst: ${info.first}`;
                                        ensureBadge(li, '.started-badge', 'started-badge badge bg-info ms-2', 'Started', t);
                                    }
                                    if(info.last){
                                        const tComp = `Completed\nFirst: ${info.first}\nLast: ${info.last}`;
                                        ensureBadge(li, '.completed-badge', 'completed-badge badge bg-primary ms-2', 'Completed', tComp);
                                        if(examResultsPublished){
                                            const t = `Reviewed\nFirst: ${info.first}\nLast: ${info.last}`;
                                            ensureBadge(li, '.submitted-badge', 'submitted-badge badge bg-success ms-2', 'Reviewed', t);
                                        }
                                    }
                                    break;
                                }
                            }
                        }catch(e){ console.error('highlightSubmitted User item error', e); }
                    });
                }
            }

            // Wire filters
            document.addEventListener('DOMContentLoaded', function(){
                const cidFilter = document.getElementById('cid-filter');
                if(cidFilter && !cidFilter.dataset.bound){
                    cidFilter.addEventListener('input', function(){ filterList(cidFilter, '#cid-list .list-group-item', 'cid-filter-indicator', 'cid-filter-clear'); });
                    cidFilter.dataset.bound = '1';
                }

                const userFilter = document.getElementById('user-filter');
                if(userFilter && !userFilter.dataset.bound){
                    userFilter.addEventListener('input', function(){ filterList(userFilter, '#user-list .list-group-item', 'user-filter-indicator', 'user-filter-clear'); });
                    userFilter.dataset.bound = '1';
                }

                // Clear buttons
                const cidClear = document.getElementById('cid-filter-clear');
                if(cidClear && !cidClear.dataset.bound){
                    cidClear.addEventListener('click', function(){ const f=document.getElementById('cid-filter'); if(f){ f.value=''; filterList(f, '#cid-list .list-group-item', 'cid-filter-indicator', 'cid-filter-clear'); }});
                    cidClear.dataset.bound = '1';
                }

                const userClear = document.getElementById('user-filter-clear');
                if(userClear && !userClear.dataset.bound){
                    userClear.addEventListener('click', function(){ const f=document.getElementById('user-filter'); if(f){ f.value=''; filterList(f, '#user-list .list-group-item', 'user-filter-indicator', 'user-filter-clear'); }});
                    userClear.dataset.bound = '1';
                }

                // initial runs (may be no partials yet)
                initTooltips();
                highlightSubmitted();
            });

            // After HTMX swaps, re-run highlight and tooltips when our partials load
            document.body.addEventListener('htmx:afterSwap', function(evt){
                try{
                    const target = evt.detail && evt.detail.target ? evt.detail.target : null;
                    if(!target) return;

                    const id = target.id || (target.closest && target.closest('[id]') ? target.closest('[id]').id : null);
                    if(id === 'cid-list' || id === 'user-list' || id === 'submitted-list'){
                        initTooltips();
                        // submitted-list may have loaded now; re-run highlighting
                        highlightSubmitted();

                        // Re-run current filters for newly-loaded partials
                        try{
                            const cf = document.getElementById('cid-filter');
                            if(cf) filterList(cf, '#cid-list .list-group-item');
                            const uf = document.getElementById('user-filter');
                            if(uf) filterList(uf, '#user-list .list-group-item');
                        }catch(e){ /* ignore */ }
                    }
                }catch(e){ console.error(e); }
            });
        })();
    </script>
{% endblock %}


{% block css %}
    <style>
        .cid-name { margin-top: 0.25rem; }
        .cid-link { font-size: 1.05rem; }
        .submitted { color: green; }
        .cid-notes { font-style: italic; color: #6c757d; }
    </style>
{% endblock %}