{% extends "base.html" %}

{% block title %}Matched Images{% endblock %}
{% block page_id %}matched-images{% endblock %}
{% block page_title %}Matched Images{% endblock %}
{% block eyebrow %}Operations{% endblock %}

{% block head %}
<style>
    /* ── Controls ───────────────────────────────────────────────────────── */
    .mi-controls {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        flex-wrap: wrap;
        margin-bottom: 20px;
    }
    .mi-total { font-size: 14px; font-weight: 600; color: #475569; }
    .mi-show  { display: flex; align-items: center; gap: 8px; font-size: 14px; color: #475569; font-weight: 600; }
    .mi-show select {
        padding: 8px 12px;
        border: 1.5px solid #cbd5e1;
        border-radius: 10px;
        background: #ffffff;
        color: #0f172a;
        font-size: 14px;
        cursor: pointer;
    }

    /* ── Table wrapper ──────────────────────────────────────────────────── */
    .mi-table-wrapper {
        overflow-x: auto;
        border-radius: 14px;
        border: 1px solid #e2e8f0;
        background: #ffffff;
    }
    .mi-table {
        width: 100%;
        border-collapse: collapse;
        min-width: 700px;
    }
    .mi-table thead tr {
        background: #f8fafc;
        border-bottom: 2px solid #e2e8f0;
    }
    .mi-table th {
        padding: 14px 18px;
        text-align: left;
        font-size: 12px;
        font-weight: 700;
        color: #334155;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        white-space: nowrap;
    }
    .mi-table td {
        padding: 14px 18px;
        border-bottom: 1px solid #f1f5f9;
        vertical-align: middle;
    }
    .mi-table tbody tr:last-child td { border-bottom: none; }
    .mi-table tbody tr:hover td { background: #f8fafc; }

    /* Sl No */
    .mi-slno { font-size: 13px; font-weight: 700; color: #94a3b8; }

    /* User cell */
    .mi-user-cell {
        display: flex;
        align-items: center;
        gap: 12px;
        min-width: 160px;
    }
    .mi-avatar {
        width: 44px; height: 44px;
        border-radius: 50%;
        overflow: hidden;
        flex-shrink: 0;
        border: 2px solid #e2e8f0;
        cursor: pointer;
        transition: border-color 0.2s, transform 0.2s;
    }
    .mi-avatar:hover { border-color: #2c7da0; transform: scale(1.08); }
    .mi-avatar img { width: 100%; height: 100%; object-fit: cover; display: block; }

    .mi-user-name  { font-size: 14px; font-weight: 700; color: #0f172a; }
    .mi-user-email { font-size: 12px; color: #64748b; margin-top: 2px; }

    /* Event images strip */
    .mi-images-strip {
        display: flex;
        gap: 8px;
        align-items: center;
        overflow-x: auto;
        padding-bottom: 4px;
        scrollbar-width: thin;
    }
    .mi-images-strip::-webkit-scrollbar { height: 4px; }
    .mi-images-strip::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 2px; }

    .mi-event-img {
        width: 52px; height: 52px;
        border-radius: 8px;
        object-fit: cover;
        flex-shrink: 0;
        cursor: pointer;
        border: 2px solid #e2e8f0;
        transition: border-color 0.2s, transform 0.2s;
    }
    .mi-event-img:hover { border-color: #2c7da0; transform: scale(1.08); }

    .mi-img-count {
        font-size: 12px; font-weight: 700;
        color: #64748b;
        white-space: nowrap;
        flex-shrink: 0;
        background: #f1f5f9;
        padding: 4px 10px;
        border-radius: 20px;
    }

    .mi-no-images { font-size: 13px; color: #cbd5e1; font-style: italic; }

    /* Pagination */
    .mi-pagination { display: flex; gap: 8px; justify-content: center; margin-top: 24px; flex-wrap: wrap; }
    .mi-page-link {
        padding: 9px 16px;
        border: 1.5px solid #cbd5e1;
        border-radius: 10px;
        background: #fff;
        color: #334155;
        text-decoration: none;
        font-size: 14px;
        font-weight: 600;
        transition: all 0.2s;
    }
    .mi-page-link:hover { background: #f8fafc; border-color: #2c7da0; }
    .mi-page-link.active { background: #0f2b3d; border-color: #0f2b3d; color: #fff; }

    .mi-footer { text-align: center; padding: 14px 0 4px; font-size: 13px; color: #64748b; }

    .mi-show-more-btn {
        flex-shrink: 0;
        padding: 6px 12px;
        background: #f1f5f9;
        border: 1.5px solid #cbd5e1;
        border-radius: 8px;
        font-size: 12px;
        font-weight: 700;
        color: #2c7da0;
        cursor: pointer;
        transition: all 0.2s;
        white-space: nowrap;
    }
    .mi-show-more-btn:hover {
        background: #dbeafe;
        border-color: #7dd3fc;
    }

    /* ── Lightbox Modal ─────────────────────────────────────────────────── */
    .mi-lightbox {
        display: none;
        position: fixed; inset: 0;
        background: rgba(0,0,0,0.88);
        z-index: 2000;
        align-items: center;
        justify-content: center;
        padding: 16px;
    }
    .mi-lightbox.active { display: flex; }

    .mi-lightbox-inner {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 16px;
        max-width: 90vw;
        max-height: 90vh;
    }

    /* Side arrow buttons */
    .mi-lightbox-arrow {
        position: fixed;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(255,255,255,0.12);
        border: 2px solid rgba(255,255,255,0.25);
        color: #ffffff;
        font-size: 28px;
        font-weight: 300;
        width: 52px; height: 52px;
        border-radius: 50%;
        cursor: pointer;
        display: flex; align-items: center; justify-content: center;
        transition: all 0.2s;
        z-index: 2002;
        line-height: 1;
        user-select: none;
    }
    .mi-lightbox-arrow:hover { background: rgba(255,255,255,0.28); border-color: rgba(255,255,255,0.6); }
    .mi-lightbox-arrow:disabled { opacity: 0.2; cursor: not-allowed; }
    .mi-arrow-left  { left: 20px; }
    .mi-arrow-right { right: 20px; }

    .mi-lightbox-img {
        max-width: 80vw;
        max-height: 75vh;
        object-fit: contain;
        border-radius: 12px;
        box-shadow: 0 20px 60px rgba(0,0,0,0.5);
    }

    .mi-lightbox-close {
        position: fixed; top: 20px; right: 20px;
        background: rgba(255,255,255,0.15);
        border: 1.5px solid rgba(255,255,255,0.3);
        color: #ffffff; font-size: 22px;
        width: 42px; height: 42px;
        border-radius: 50%;
        cursor: pointer;
        display: flex; align-items: center; justify-content: center;
        transition: background 0.2s;
        z-index: 2003;
    }
    .mi-lightbox-close:hover { background: rgba(255,255,255,0.3); }

    .mi-lightbox-counter {
        font-size: 13px; font-weight: 600;
        color: rgba(255,255,255,0.7);
        text-align: center;
    }
    .mi-lightbox-caption {
        font-size: 13px; color: rgba(255,255,255,0.55);
        text-align: center;
    }
    .mi-lightbox-nav {
        display: flex;
        gap: 12px;
        align-items: center;
        justify-content: center;
    }
    .mi-lightbox-btn {
        padding: 10px 28px;
        background: rgba(255,255,255,0.15);
        border: 1.5px solid rgba(255,255,255,0.3);
        color: #ffffff;
        font-size: 14px;
        font-weight: 700;
        border-radius: 10px;
        cursor: pointer;
        transition: all 0.2s;
    }
    .mi-lightbox-btn:hover { background: rgba(255,255,255,0.28); }
    .mi-lightbox-btn:disabled { opacity: 0.3; cursor: not-allowed; }

    /* Mobile responsive */
    @media (max-width: 640px) {
        .mi-table { min-width: 100%; }
        .mi-event-img { width: 44px; height: 44px; }
        .mi-avatar { width: 38px; height: 38px; }
        .mi-lightbox-img { max-width: 95vw; max-height: 60vh; }
        .mi-arrow-left  { left: 6px; width: 40px; height: 40px; font-size: 22px; }
        .mi-arrow-right { right: 6px; width: 40px; height: 40px; font-size: 22px; }
    }
</style>
{% endblock %}

{% block content %}
<section class="panel-stack">
    <article class="glass-card panel-card">
        <div class="panel-header">
            <div>
                <p class="eyebrow">Debug</p>
                <h3>Matched Images</h3>
            </div>
            <span class="pill">{{ total }} users</span>
        </div>

        <div class="panel-body">
            <!-- Controls -->
            <div class="mi-controls">
                <span class="mi-total">Showing {{ rows|length }} of {{ total }} users with matched images</span>
                <form method="GET" action="{{ url_for('admin.matched_images_page') }}" class="mi-show">
                    <label>Show</label>
                    <select name="limit" onchange="this.form.submit()">
                        <option value="10"  {% if limit == 10  %}selected{% endif %}>10</option>
                        <option value="25"  {% if limit == 25  %}selected{% endif %}>25</option>
                        <option value="50"  {% if limit == 50  %}selected{% endif %}>50</option>
                    </select>
                    <input type="hidden" name="page" value="1">
                </form>
            </div>

            {% if rows %}
            <div class="mi-table-wrapper">
                <table class="mi-table">
                    <thead>
                        <tr>
                            <th>Sl No</th>
                            <th>Visitor</th>
                            <th>Email</th>
                            <th>Matched Images</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for row in rows %}
                        <tr>
                            <!-- Sl No -->
                            <td class="mi-slno">{{ loop.index + ((page - 1) * limit) }}</td>

                            <!-- User: round photo + name -->
                            <td>
                                <div class="mi-user-cell">
                                    <div class="mi-avatar" data-name="{{ row.name | e }}" title="Click to view photo">
                                        <img
                                            src="{{ row.user_photo or '/admin/static/no photo.png' }}"
                                            alt="{{ row.name }}"
                                            onerror="this.src='/admin/static/no photo.png'">
                                    </div>
                                    <div>
                                        <div class="mi-user-name">{{ row.name }}</div>
                                        <div class="mi-user-email">ID: {{ row.user_id }}</div>
                                    </div>
                                </div>
                            </td>

                            <!-- Email -->
                            <td style="font-size:13px;color:#475569;">{{ row.email or '—' }}</td>

                            <!-- Event images -->
                            <td>
                                {% if row.images %}
                                <div class="mi-images-strip">
                                    <span class="mi-img-count">{{ row.images|length }} img</span>
                                    {% for img in row.images %}
                                    {% if loop.index0 < 5 %}
                                    <img
                                        class="mi-event-img"
                                        src="{{ img.original_url }}"
                                        alt="Event {{ img.id }}"
                                        onerror="this.src='/admin/static/no photo.png'"
                                        data-row="{{ loop.index0 + ((page-1)*limit) }}_{{ row.user_id }}"
                                        data-imgidx="{{ loop.index0 }}"
                                        title="Click to view">
                                    {% endif %}
                                    {% endfor %}
                                    {% if row.images|length > 5 %}
                                    <button
                                        class="mi-show-more-btn"
                                        data-row="0_{{ row.user_id }}"
                                        data-imgidx="5"
                                        title="Show all {{ row.images|length }} images">
                                        +{{ row.images|length - 5 }} more
                                    </button>
                                    {% endif %}
                                </div>
                                {% else %}
                                <span class="mi-no-images">No images yet</span>
                                {% endif %}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            {% if total_pages > 1 %}
            <div class="mi-pagination">
                {% if page > 1 %}
                    <a href="{{ url_for('admin.matched_images_page', page=page-1, limit=limit) }}" class="mi-page-link">&laquo; Prev</a>
                {% endif %}
                {% for p in range(1, total_pages + 1) %}
                    {% if p == page %}
                        <span class="mi-page-link active">{{ p }}</span>
                    {% elif p <= 2 or p > total_pages - 2 or (p >= page - 1 and p <= page + 1) %}
                        <a href="{{ url_for('admin.matched_images_page', page=p, limit=limit) }}" class="mi-page-link">{{ p }}</a>
                    {% endif %}
                {% endfor %}
                {% if page < total_pages %}
                    <a href="{{ url_for('admin.matched_images_page', page=page+1, limit=limit) }}" class="mi-page-link">Next &raquo;</a>
                {% endif %}
            </div>
            {% endif %}

            <div class="mi-footer">Showing page {{ page }} of {{ total_pages }} ({{ total }} total users)</div>

            {% else %}
            <div style="text-align:center;padding:60px 20px;color:#94a3b8;">
                <p style="font-size:18px;margin-bottom:8px;">No matched images found</p>
                <p style="font-size:14px;">Face matching hasn't run yet, or no matches exist.</p>
            </div>
            {% endif %}
        </div>
    </article>
</section>

<!-- LIGHTBOX MODAL -->
<div id="miLightbox" class="mi-lightbox">
    <button class="mi-lightbox-close" onclick="closeLightbox()">&times;</button>

    <!-- Left arrow -->
    <button class="mi-lightbox-arrow mi-arrow-left" id="miPrevBtn" onclick="navigateImage(-1)">&#8249;</button>

    <div class="mi-lightbox-inner">
        <img id="miLightboxImg" class="mi-lightbox-img" src="" alt="">
        <div id="miLightboxCounter" class="mi-lightbox-counter"></div>
        <div id="miLightboxCaption" class="mi-lightbox-caption"></div>
        <!-- Prev / Next buttons below image -->
        <div class="mi-lightbox-nav">
            <button class="mi-lightbox-btn" id="miPrevBtnBottom" onclick="navigateImage(-1)">&laquo; Prev</button>
            <button class="mi-lightbox-btn" id="miNextBtnBottom" onclick="navigateImage(1)">Next &raquo;</button>
        </div>
    </div>

    <!-- Right arrow -->
    <button class="mi-lightbox-arrow mi-arrow-right" id="miNextBtn" onclick="navigateImage(1)">&#8250;</button>
</div>
{% endblock %}

{% block scripts %}
<script>
    // Store image data server-side into JS
    const _imageMap = {};
    {% for row in rows %}
    {% if row.images %}
    _imageMap["{{ row.user_id }}"] = {
        name: {{ row.name | tojson }},
        urls: {{ row.images | map(attribute='original_url') | list | tojson }}
    };
    {% endif %}
    {% endfor %}

    let _currentImages = [];
    let _currentIndex  = 0;
    let _currentUser   = '';

    // Delegate click on event images via data attributes
    document.addEventListener('click', function(e) {
        // Event image click
        if (e.target.classList.contains('mi-event-img')) {
            const el    = e.target;
            const parts = el.dataset.row.split('_');
            const uid   = parts[parts.length - 1];
            const idx   = parseInt(el.dataset.imgidx, 10);
            const entry = _imageMap[uid];
            if (entry) openEventImages(idx, entry.urls, entry.name);
            return;
        }
        // Show more button click — open at index 5
        if (e.target.classList.contains('mi-show-more-btn')) {
            const parts = e.target.dataset.row.split('_');
            const uid   = parts[parts.length - 1];
            const entry = _imageMap[uid];
            if (entry) openEventImages(0, entry.urls, entry.name);
            return;
        }
        // User avatar click
        const avatar = e.target.closest('.mi-avatar');
        if (avatar) {
            const img  = avatar.querySelector('img');
            const name = avatar.dataset.name;
            openUserPhoto(img ? img.src : '', name);
        }
    });

    // ── Open user photo (single image, no nav) ────────────────────────────
    function openUserPhoto(url, name) {
        if (!url) url = '/admin/static/no photo.png';
        _currentImages = [url];
        _currentIndex  = 0;
        _currentUser   = name;
        document.getElementById('miLightboxImg').src = url;
        document.getElementById('miLightboxCaption').textContent = name;
        document.getElementById('miLightboxNav').style.display = 'none';
        document.getElementById('miLightbox').classList.add('active');
    }

    // ── Open event images (with Next / Prev nav) ──────────────────────────
    function openEventImages(startIdx, urls, userName) {
        _currentImages = urls.filter(u => u);
        _currentIndex  = startIdx;
        _currentUser   = userName;
        if (!_currentImages.length) return;
        if (_currentIndex >= _currentImages.length) _currentIndex = 0;
        renderLightbox();
        document.getElementById('miLightbox').classList.add('active');
    }

    function renderLightbox() {
        const img = document.getElementById('miLightboxImg');
        img.src   = _currentImages[_currentIndex];
        document.getElementById('miLightboxCaption').textContent = _currentUser;
        document.getElementById('miLightboxCounter').textContent =
            `${_currentIndex + 1} / ${_currentImages.length}`;

        const atFirst = _currentIndex === 0;
        const atLast  = _currentIndex === _currentImages.length - 1;
        const showNav = _currentImages.length > 1;

        // Side arrows
        document.getElementById('miPrevBtn').disabled = atFirst;
        document.getElementById('miNextBtn').disabled = atLast;
        document.getElementById('miPrevBtn').style.display = showNav ? 'flex' : 'none';
        document.getElementById('miNextBtn').style.display = showNav ? 'flex' : 'none';

        // Bottom buttons
        document.getElementById('miPrevBtnBottom').disabled = atFirst;
        document.getElementById('miNextBtnBottom').disabled = atLast;
        document.getElementById('miPrevBtnBottom').parentElement.style.display = showNav ? 'flex' : 'none';
    }

    function navigateImage(dir) {
        const next = _currentIndex + dir;
        if (next < 0 || next >= _currentImages.length) return;
        _currentIndex = next;
        renderLightbox();
    }

    function closeLightbox() {
        document.getElementById('miLightbox').classList.remove('active');
        document.getElementById('miLightboxImg').src = '';
    }

    // Close on backdrop click
    document.getElementById('miLightbox').addEventListener('click', function(e) {
        if (e.target === this) closeLightbox();
    });

    // Keyboard navigation
    document.addEventListener('keydown', e => {
        if (!document.getElementById('miLightbox').classList.contains('active')) return;
        if (e.key === 'Escape') closeLightbox();
        if (e.key === 'ArrowRight') navigateImage(1);
        if (e.key === 'ArrowLeft')  navigateImage(-1);
    });
</script>
{% endblock %}