<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manual Entry – {{ event_data.event_name if event_data else 'Registration' }}</title>
    <link href="https://fonts.googleapis.com/css2?family=Syne:wght@600;700;800&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            min-height: 100vh; font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #f0f2fa 0%, #e8ecf8 100%);
            display: flex; flex-direction: column; align-items: center;
            padding: 24px 12px 40px; -webkit-font-smoothing: antialiased;
        }

        .page { width: 100%; max-width: 600px; }

        .site-banner {
            width: 100%; border-radius: 20px; overflow: hidden;
            margin-bottom: 20px; box-shadow: 0 4px 24px rgba(35,82,240,0.12);
        }
        .site-banner img { width: 100%; display: block; }

        .card {
            background: #fff; border-radius: 28px;
            box-shadow: 0 12px 48px rgba(35,82,240,0.1), 0 2px 8px rgba(0,0,0,0.06);
            overflow: hidden; margin-bottom: 20px;
        }

        /* Header */
        .card-header {
            display: flex; align-items: center; gap: 14px;
            padding: 22px 28px; border-bottom: 1px solid #e4e7f0;
            background: #fafbff;
        }
        .back-btn {
            width: 38px; height: 38px; border-radius: 50%;
            border: 1.5px solid #e4e7f0; background: #fff;
            cursor: pointer; display: flex; align-items: center; justify-content: center;
            font-size: 18px; color: #0d1117; transition: all 0.2s ease;
            text-decoration: none; flex-shrink: 0;
        }
        .back-btn:hover { border-color: #2352f0; background: #eef1ff; }

        .header-info { flex: 1; }
        .header-title {
            font-family: 'Plus Jakarta Sans', sans-serif;
            font-size: 17px; font-weight: 800; color: #0d1117; letter-spacing: -0.01em;
        }
        .header-sub { font-size: 12px; color: #6b7280; margin-top: 2px; }

        /* Body */
        .card-body { padding: 28px; }

        .input-group { margin-bottom: 16px; position: relative; }
        .input-group label {
            display: flex; align-items: center; gap: 5px;
            font-size: 10px; text-transform: uppercase;
            letter-spacing: 0.12em; font-weight: 700;
            color: #6b7280; margin-bottom: 8px;
        }
        .req { color: #2352f0; font-weight: 800; }

        .input-group input {
            width: 100%; height: 54px;
            border: 1.5px solid #e4e7f0; border-radius: 14px;
            background: #fafbff; padding: 14px 16px;
            font-family: 'Inter', sans-serif; font-size: 15px;
            color: #0d1117; transition: all 0.2s ease;
        }
        .input-group input::placeholder { color: #b0b8cc; }
        .input-group input:focus {
            outline: none; border-color: #2352f0;
            background: #fff; box-shadow: 0 0 0 4px rgba(35,82,240,0.08);
        }

        /* Predictive dropdown */
        #suggestions {
            position: absolute; top: 100%; left: 0; right: 0;
            background: #fff; border: 1.5px solid #e4e7f0;
            border-top: none; border-radius: 0 0 14px 14px;
            box-shadow: 0 12px 32px rgba(0,0,0,0.1);
            z-index: 500; max-height: 260px; overflow-y: auto; display: none;
        }
        #suggestions.open { display: block; }
        .suggestion-item {
            padding: 12px 16px; cursor: pointer;
            border-bottom: 1px solid #f3f4f6; transition: background 0.12s;
        }
        .suggestion-item:last-child { border-bottom: none; }
        .suggestion-item:hover { background: #f0f4ff; }
        .sug-name { font-size: 14px; font-weight: 700; color: #0d1117; }
        .sug-meta { font-size: 12px; color: #6b7280; margin-top: 2px; }

        .search-btn {
            width: 100%; height: 54px; border: none; border-radius: 14px;
            font-family: 'Syne', sans-serif; font-size: 15px; font-weight: 700;
            cursor: pointer; transition: all 0.22s ease;
            background: linear-gradient(135deg, #4f73f5, #1a3cc4);
            color: #fff; box-shadow: 0 6px 20px rgba(35,82,240,0.28);
        }
        .search-btn:hover { transform: translateY(-2px); box-shadow: 0 10px 28px rgba(35,82,240,0.38); }

        .helper { font-size: 12px; color: #9ca3af; margin-top: 10px; line-height: 1.6; }

        /* Camera section — shown after visitor confirmed */
        #cameraSection { display: none; margin-top: 24px; }
        #cameraSection.active { display: block; }

        .visitor-strip {
            display: flex; align-items: center; gap: 14px;
            padding: 13px 18px; background: #f0f4ff;
            border: 1.5px solid #c7d2fe; border-radius: 14px; margin-bottom: 16px;
        }
        .v-avatar {
            width: 38px; height: 38px; border-radius: 50%;
            background: linear-gradient(135deg, #4f73f5, #1a3cc4);
            display: flex; align-items: center; justify-content: center;
            font-size: 16px; color: #fff; flex-shrink: 0;
        }
        .v-name  { font-size: 14px; font-weight: 700; color: #0d1117; }
        .v-email { font-size: 12px; color: #6b7280; margin-top: 1px; }

        .camera-frame {
            position: relative; width: 100%; height: 340px;
            border-radius: 18px; overflow: hidden;
            background: #f1f5f9; border: 2px dashed #e4e7f0;
            cursor: pointer; transition: all 0.25s ease; margin-bottom: 10px;
        }
        .camera-frame.has-feed { border-style: solid; border-color: #2352f0; box-shadow: 0 0 0 4px rgba(35,82,240,0.08); }
        .camera-frame video, .camera-frame img { width: 100%; height: 100%; object-fit: cover; display: block; }
        #cameraCanvas { display: none; }

        .cam-placeholder {
            position: absolute; inset: 0;
            display: grid; place-items: center; text-align: center; padding: 20px;
        }
        .cam-placeholder strong { display: block; font-size: 14px; font-weight: 700; color: #0d1117; margin-bottom: 6px; }
        .cam-placeholder span   { font-size: 12px; color: #6b7280; line-height: 1.6; }

        .tap-hint { text-align: center; font-size: 12px; color: #9ca3af; margin-bottom: 14px; }

        .cam-controls { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px; }

        .register-btn {
            width: 100%; height: 52px; border: none; border-radius: 14px;
            font-family: 'Syne', sans-serif; font-size: 15px; font-weight: 700;
            cursor: pointer; transition: all 0.22s ease;
            background: linear-gradient(135deg, #4f73f5, #1a3cc4);
            color: #fff; box-shadow: 0 6px 20px rgba(35,82,240,0.28);
        }
        .register-btn:hover { transform: translateY(-2px); box-shadow: 0 10px 28px rgba(35,82,240,0.38); }
        .register-btn:disabled { opacity: 0.5; transform: none; cursor: not-allowed; }

        .retake-btn {
            width: 100%; height: 52px; border-radius: 14px;
            border: 1.5px solid #e4e7f0; background: #f5f7ff;
            color: #0d1117; font-family: 'Syne', sans-serif;
            font-size: 15px; font-weight: 600; cursor: pointer; transition: all 0.2s ease;
        }
        .retake-btn:hover { border-color: #2352f0; background: #eef1ff; }
        .retake-btn:disabled { opacity: 0.4; cursor: not-allowed; }

        .cam-status {
            border-radius: 12px; background: #f9fafb;
            border: 1.5px solid #e4e7f0;
            padding: 12px 14px; font-size: 12px; color: #6b7280; font-weight: 500;
        }
        .cam-status.ready { color: #10b981; border-color: #86efac; background: #f0fdf4; }

        .response-box {
            margin-top: 12px; background: #f9fafb; border: 1px solid #e4e7f0;
            border-radius: 12px; padding: 14px;
            font-family: 'Fira Code', 'Consolas', monospace;
            font-size: 11px; color: #6b7280;
            white-space: pre-wrap; word-break: break-word; line-height: 1.6;
            max-height: 120px; overflow-y: auto; display: none;
        }

        /* Modals */
        .modal-overlay {
            position: fixed; inset: 0; background: rgba(0,0,0,0.45);
            backdrop-filter: blur(6px);
            display: flex; align-items: center; justify-content: center;
            z-index: 1000; opacity: 0; visibility: hidden;
            transition: opacity 0.25s ease, visibility 0.25s ease; padding: 16px;
        }
        .modal-overlay.show { opacity: 1; visibility: visible; }
        .modal {
            background: #fff; border-radius: 24px; padding: 32px;
            width: 100%; max-width: 420px;
            box-shadow: 0 32px 80px rgba(0,0,0,0.18);
            transform: scale(0.92) translateY(12px);
            transition: transform 0.3s cubic-bezier(0.34,1.56,0.64,1);
        }
        .modal-overlay.show .modal { transform: scale(1) translateY(0); }
        .modal-title { font-family: 'Syne', sans-serif; font-size: 19px; font-weight: 800; color: #0d1117; margin-bottom: 20px; letter-spacing: -0.02em; }
        .modal-row { display: flex; justify-content: space-between; align-items: center; padding: 11px 0; border-bottom: 1px solid #f3f4f6; }
        .modal-row:last-child { border-bottom: none; }
        .modal-lbl { font-size: 12px; font-weight: 600; color: #6b7280; }
        .modal-val { font-size: 13px; color: #0d1117; font-weight: 600; text-align: right; max-width: 60%; word-break: break-word; }
        .modal-foot { display: flex; gap: 10px; margin-top: 24px; }
        .modal-foot button {
            flex: 1; height: 48px; border-radius: 14px;
            font-family: 'Syne', sans-serif; font-size: 14px; font-weight: 700;
            cursor: pointer; border: none; transition: all 0.2s ease;
        }
        .btn-cancel  { background: #f3f4f6; color: #0d1117; border: 1.5px solid #e4e7f0 !important; }
        .btn-confirm { background: linear-gradient(135deg, #4f73f5, #1a3cc4); color: #fff; box-shadow: 0 4px 14px rgba(35,82,240,0.28); }
        .btn-ok      { background: linear-gradient(135deg, #4f73f5, #1a3cc4); color: #fff; }

        /* Already registered */
        .already-photo { text-align: center; margin-bottom: 16px; }
        .already-photo img { width: 108px; height: 108px; border-radius: 50%; object-fit: cover; border: 3px solid #c7d2fe; box-shadow: 0 0 0 6px rgba(35,82,240,0.08); }
        .already-badge { display: inline-block; background: #eff6ff; border: 1px solid #bfdbfe; color: #2352f0; border-radius: 999px; padding: 5px 14px; font-size: 11px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; margin-bottom: 14px; }

        /* Not found */
        .not-found { text-align: center; padding: 8px 0 4px; }
        .nf-icon  { font-size: 44px; margin-bottom: 12px; }
        .nf-title { font-family: 'Syne', sans-serif; font-size: 17px; font-weight: 800; color: #0d1117; margin-bottom: 7px; }
        .nf-sub   { font-size: 13px; color: #6b7280; line-height: 1.7; }

        /* Multiple picker */
        .pick-item {
            display: flex; justify-content: space-between; align-items: center;
            padding: 12px; border-bottom: 1px solid #f3f4f6;
            cursor: pointer; transition: background 0.12s; border-radius: 10px;
        }
        .pick-item:last-child { border-bottom: none; }
        .pick-item:hover { background: #f0f4ff; }
        .pick-name { font-size: 14px; font-weight: 700; color: #0d1117; }
        .pick-meta { font-size: 12px; color: #6b7280; margin-top: 2px; }

        /* Result */
        .result-icon { width: 64px; height: 64px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 28px; font-weight: 700; margin: 0 auto 16px; }
        .result-msg  { font-size: 14px; font-weight: 600; color: #0d1117; text-align: center; line-height: 1.6; }

        /* Loader */
        #loader {
            display: none; position: fixed; inset: 0;
            background: rgba(240,242,250,0.92); backdrop-filter: blur(8px);
            z-index: 9999; flex-direction: column; align-items: center; justify-content: center; gap: 20px;
        }
        #loader.active { display: flex; }
        .spinner { width: 52px; height: 52px; border: 4px solid #e0e4f5; border-top-color: #2352f0; border-radius: 50%; animation: spin 0.75s linear infinite; }
        @keyframes spin { to { transform: rotate(360deg); } }
        .loader-text { font-family: 'Syne', sans-serif; font-size: 17px; font-weight: 800; color: #0d1117; }
        .loader-sub  { font-size: 13px; color: #6b7280; margin-top: -12px; }

        .footer-note { text-align: center; color: #b0b8cc; font-size: 12px; letter-spacing: 0.04em; margin-top: 20px; }
        .hidden { display: none !important; }

        @media (max-width: 480px) {
            .card-body { padding: 20px; }
            .cam-controls { grid-template-columns: 1fr; }
            .camera-frame { height: 260px; }
        }
    </style>
</head>
<body>
<div class="page">

    {% if header_image %}
    <div class="site-banner">
        {% if header_image.startswith('http') or header_image.startswith('data:') %}
            <img src="{{ header_image }}" alt="Event banner">
        {% else %}
            <img src="{{ url_for('static', filename=header_image) }}" alt="Event banner">
        {% endif %}
    </div>
    {% endif %}

    <div class="card">
        <div class="card-header">
            <a href="/register" class="back-btn">←</a>
            <div class="header-info">
                <div class="header-title">Manual Entry</div>
                <div class="header-sub">Search by name, email or mobile</div>
            </div>
        </div>

        <div class="card-body">

            <!-- Search section -->
            <div id="searchSection">
                <div class="input-group">
                    <label><span>Name / Email / Mobile</span> <span class="req">*</span></label>
                    <input type="text" id="identifierInput"
                           placeholder="Start typing your name, email or mobile…"
                           autocomplete="off">
                    <div id="suggestions"></div>
                </div>
                <button type="button" class="search-btn" id="lookupButton">Search Visitor</button>
                <p class="helper">Searches by name, email or mobile number.</p>
            </div>

            <!-- Camera section — shown after visitor confirmed -->
            <div id="cameraSection">
                <div class="visitor-strip" id="visitorStrip">
                    <div class="v-avatar">👤</div>
                    <div>
                        <div class="v-name" id="stripName">-</div>
                        <div class="v-email" id="stripEmail">-</div>
                    </div>
                </div>

                <div class="camera-frame" id="cameraFrame">
                    <video id="cameraVideo" autoplay playsinline muted class="hidden"></video>
                    <canvas id="cameraCanvas"></canvas>
                    <img id="capturedPreview" alt="Captured" class="hidden">
                    <div id="camPlaceholder" class="cam-placeholder">
                        <div>
                            <strong>Tap to capture</strong>
                            <span>Position the visitor's face clearly in frame</span>
                        </div>
                    </div>
                </div>

                <p class="tap-hint">Tap anywhere inside the frame to capture</p>

                <div class="cam-controls">
                    <button id="retakeBtn" class="retake-btn hidden" disabled>Retake Photo</button>
                    <button id="registerBtn" class="register-btn hidden" disabled>Register Visitor</button>
                </div>

                <div id="camStatus" class="cam-status">Camera starting…</div>
                <div id="responseBox" class="response-box"></div>
            </div>

        </div>
    </div>

    <!-- Visitor modal -->
    <div id="visitorModal" class="modal-overlay">
        <div class="modal">
            <h3 class="modal-title" id="modalTitle">Visitor Details</h3>
            <div id="modalPhotoWrap" class="already-photo" style="display:none;"><img id="modalPhoto" src="" alt="Photo"></div>
            <div id="modalBadge" style="display:none;text-align:center;margin-bottom:14px;"><span class="already-badge">✓ Already Registered</span></div>
            <div id="modalBody">
                <div class="modal-row"><span class="modal-lbl">Name</span><span class="modal-val" id="mName">-</span></div>
                <div class="modal-row"><span class="modal-lbl">Email</span><span class="modal-val" id="mEmail">-</span></div>
                <div class="modal-row"><span class="modal-lbl">Phone</span><span class="modal-val" id="mPhone">-</span></div>
            </div>
            <div id="notFoundBody" class="not-found" style="display:none;">
                <div class="nf-icon">🚫</div>
                <div class="nf-title">Visitor Not Found</div>
                <div class="nf-sub">This identifier is not registered.<br>Please contact the admin.</div>
            </div>
            <div class="modal-foot" id="modalFoot">
                <button class="btn-cancel" onclick="closeModal()">Cancel</button>
                <button class="btn-confirm" onclick="onContinue()">Continue</button>
            </div>
        </div>
    </div>

    <!-- Multiple picker modal -->
    <div id="multipleModal" class="modal-overlay">
        <div class="modal">
            <h3 class="modal-title">Multiple Visitors Found</h3>
            <p style="font-size:13px;color:#6b7280;margin-bottom:16px;">Select the correct visitor to continue.</p>
            <div id="multiplePicker" style="max-height:300px;overflow-y:auto;"></div>
            <div class="modal-foot">
                <button class="btn-cancel" onclick="document.getElementById('multipleModal').classList.remove('show')">Cancel</button>
            </div>
        </div>
    </div>

    <!-- Missing input modal -->
    <div id="missingModal" class="modal-overlay">
        <div class="modal">
            <h3 class="modal-title">Missing Input</h3>
            <p style="font-size:14px;color:#6b7280;margin-bottom:24px;">Please enter a name, email or mobile number.</p>
            <div class="modal-foot"><button class="btn-ok" onclick="document.getElementById('missingModal').classList.remove('show')">OK</button></div>
        </div>
    </div>

    <!-- Result modal -->
    <div id="resultModal" class="modal-overlay">
        <div class="modal" style="text-align:center;">
            <div id="resultIcon" class="result-icon"></div>
            <p id="resultMsg" class="result-msg"></p>
            <div class="modal-foot" style="margin-top:24px;">
                <button class="btn-ok" id="resultOkBtn" onclick="handleResultOk()">OK</button>
            </div>
        </div>
    </div>

    <div id="loader">
        <div class="spinner"></div>
        <p class="loader-text">Registering Visitor…</p>
        <p class="loader-sub">Please wait, do not close this page</p>
    </div>

    <div class="footer-note">&copy; 2026 IMTMA Event AI &nbsp;|&nbsp; All Rights Reserved</div>
</div>

<script>
let matchedVisitor    = null;
let cameraStream      = null;
let capturedImageBlob = null;

// ── Predictive search ──────────────────────────────────────────
const input        = document.getElementById('identifierInput');
const suggBox      = document.getElementById('suggestions');
let   searchTimer  = null;

input.addEventListener('input', () => {
    clearTimeout(searchTimer);
    const q = input.value.trim();
    if (q.length < 1) { hideSugg(); return; }
    searchTimer = setTimeout(() => fetchSugg(q), 220);
});

input.addEventListener('keydown', e => {
    if (e.key === 'Enter') { e.preventDefault(); hideSugg(); doLookup(input.value.trim()); }
    if (e.key === 'Escape') hideSugg();
});

document.addEventListener('click', e => { if (!e.target.closest('.input-group')) hideSugg(); });

async function fetchSugg(q) {
    try {
        const res  = await fetch(`/api/visitor-search?q=${encodeURIComponent(q)}`);
        const text = await res.text();
        let list;
        try { list = JSON.parse(text); } catch(_) { hideSugg(); return; }
        renderSugg(Array.isArray(list) ? list : []);
    } catch (_) { hideSugg(); }
}

function renderSugg(list) {
    if (!list.length) { hideSugg(); return; }
    suggBox.innerHTML = list.map(v => `
        <div class="suggestion-item" onmousedown="selectSugg(${v.id},'${esc(v.name)}','${esc(v.email)}','${esc(v.phone)}')">
            <div class="sug-name">${esc(v.name)}</div>
            <div class="sug-meta">${esc(v.email)} | ${esc(v.phone)}</div>
        </div>`).join('');
    suggBox.classList.add('open');
}

function hideSugg() { suggBox.classList.remove('open'); suggBox.innerHTML = ''; }

function selectSugg(id, name, email, phone) {
    input.value = name;
    hideSugg();
    resolveVisitor({ id, name, email, phone });
}

function esc(s) {
    return (s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}

// ── Lookup ─────────────────────────────────────────────────────
document.getElementById('lookupButton').addEventListener('click', () => {
    const q = input.value.trim();
    if (!q) { document.getElementById('missingModal').classList.add('show'); return; }
    hideSugg(); doLookup(q);
});

async function doLookup(identifier) {
    try {
        const res  = await fetch(`/api/visitor-lookup?identifier=${encodeURIComponent(identifier)}`);
        const data = await res.json();
        if (!data.found) { showNotFound(); return; }
        if (data.multiple) { showMultiplePicker(data.visitors); return; }
        resolveVisitor(data.visitor, data.already_registered, data.image_url);
    } catch (e) { showResult(false, e.message); }
}

// ── Visitor modal ──────────────────────────────────────────────
function resolveVisitor(visitor, alreadyRegistered, imageUrl) {
    matchedVisitor = visitor;
    if (alreadyRegistered === undefined) {
        const id = (visitor.email || visitor.phone || '').trim();
        if (!id) { showVisitorModal(visitor, false, ''); return; }
        fetch(`/api/visitor-lookup?identifier=${encodeURIComponent(id)}`)
            .then(r => r.ok ? r.json() : {})
            .then(d => showVisitorModal(visitor, d.already_registered||false, d.image_url||''))
            .catch(() => showVisitorModal(visitor, false, ''));
        return;
    }
    showVisitorModal(visitor, alreadyRegistered, imageUrl);
}

function showVisitorModal(visitor, alreadyReg, imageUrl) {
    document.getElementById('mName').textContent  = visitor.name  || '-';
    document.getElementById('mEmail').textContent = visitor.email || '-';
    document.getElementById('mPhone').textContent = visitor.phone || '-';

    const photoWrap = document.getElementById('modalPhotoWrap');
    const badge     = document.getElementById('modalBadge');
    const body      = document.getElementById('modalBody');
    const nf        = document.getElementById('notFoundBody');
    const foot      = document.getElementById('modalFoot');

    body.style.display = ''; nf.style.display = 'none';

    if (alreadyReg) {
        document.getElementById('modalTitle').textContent = 'Already Registered';
        badge.style.display = 'block';
        if (imageUrl) { document.getElementById('modalPhoto').src = imageUrl; photoWrap.style.display = 'block'; }
        else photoWrap.style.display = 'none';
        foot.innerHTML = `<button class="btn-ok" style="flex:1;height:48px;border-radius:14px;font-family:inherit;font-size:14px;font-weight:700;cursor:pointer;background:linear-gradient(135deg,#4f73f5,#1a3cc4);color:#fff;border:none;" onclick="closeModal()">Close</button>`;
    } else {
        document.getElementById('modalTitle').textContent = 'Visitor Details';
        badge.style.display = 'none'; photoWrap.style.display = 'none';
        foot.innerHTML = `
            <button class="btn-cancel" style="flex:1;height:48px;border-radius:14px;font-family:inherit;font-size:14px;font-weight:700;cursor:pointer;background:#f3f4f6;color:#0d1117;border:1.5px solid #e4e7f0;" onclick="closeModal()">Cancel</button>
            <button class="btn-confirm" style="flex:1;height:48px;border-radius:14px;font-family:inherit;font-size:14px;font-weight:700;cursor:pointer;background:linear-gradient(135deg,#4f73f5,#1a3cc4);color:#fff;border:none;" onclick="onContinue()">Continue</button>`;
    }
    document.getElementById('visitorModal').classList.add('show');
}

function showNotFound() {
    document.getElementById('modalTitle').textContent = 'Visitor Not Found';
    document.getElementById('modalBody').style.display    = 'none';
    document.getElementById('modalPhotoWrap').style.display = 'none';
    document.getElementById('modalBadge').style.display   = 'none';
    document.getElementById('notFoundBody').style.display = 'block';
    document.getElementById('modalFoot').innerHTML = `<button class="btn-ok" style="flex:1;height:48px;border-radius:14px;font-family:inherit;font-size:14px;font-weight:700;cursor:pointer;background:linear-gradient(135deg,#4f73f5,#1a3cc4);color:#fff;border:none;" onclick="closeModal()">OK</button>`;
    matchedVisitor = null;
    document.getElementById('visitorModal').classList.add('show');
}

function closeModal() {
    document.getElementById('visitorModal').classList.remove('show');
    document.getElementById('modalBody').style.display    = '';
    document.getElementById('notFoundBody').style.display = 'none';
}

function showMultiplePicker(visitors) {
    document.getElementById('multiplePicker').innerHTML = visitors.map(v => `
        <div class="pick-item" onclick="pickOne(${JSON.stringify(v).replace(/"/g,'&quot;')})">
            <div><div class="pick-name">${esc(v.name)}</div><div class="pick-meta">${esc(v.email)} | ${esc(v.phone)}</div></div>
            <span style="color:#2352f0;font-size:18px;">›</span>
        </div>`).join('');
    document.getElementById('multipleModal').classList.add('show');
}

function pickOne(visitor) {
    document.getElementById('multipleModal').classList.remove('show');
    resolveVisitor(visitor);
}

function onContinue() {
    closeModal();
    // Show camera section, hide search
    document.getElementById('searchSection').style.display = 'none';
    document.getElementById('cameraSection').classList.add('active');
    document.getElementById('stripName').textContent  = matchedVisitor.name  || '-';
    document.getElementById('stripEmail').textContent = matchedVisitor.email || matchedVisitor.phone || '-';
    startCamera();
}

// ── Camera ─────────────────────────────────────────────────────
async function startCamera() {
    try {
        if (cameraStream) cameraStream.getTracks().forEach(t => t.stop());
        cameraStream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 960 } }, audio: false
        });
        const vid = document.getElementById('cameraVideo');
        vid.srcObject = cameraStream;
        vid.classList.remove('hidden');
        document.getElementById('camPlaceholder').classList.add('hidden');
        document.getElementById('capturedPreview').classList.add('hidden');
        document.getElementById('cameraFrame').classList.add('has-feed');
        setCamStatus('Camera ready. Tap the frame to capture.', true);
    } catch (e) {
        setCamStatus('Unable to access camera. Check permissions.', false);
    }
}

document.getElementById('cameraFrame').addEventListener('click', capturePhoto);

async function capturePhoto() {
    if (!cameraStream) return;
    const vid    = document.getElementById('cameraVideo');
    const canvas = document.getElementById('cameraCanvas');
    canvas.width  = vid.videoWidth  || 1280;
    canvas.height = vid.videoHeight || 960;
    canvas.getContext('2d').drawImage(vid, 0, 0, canvas.width, canvas.height);

    capturedImageBlob = await new Promise(res => canvas.toBlob(res, 'image/jpeg', 0.92));
    if (!capturedImageBlob) return;

    const prev = document.getElementById('capturedPreview');
    prev.src = URL.createObjectURL(capturedImageBlob);
    prev.classList.remove('hidden');
    document.getElementById('cameraVideo').classList.add('hidden');

    const retake = document.getElementById('retakeBtn');
    const reg    = document.getElementById('registerBtn');
    retake.classList.remove('hidden'); retake.disabled = false;
    reg.classList.remove('hidden');    reg.disabled = !matchedVisitor;
    setCamStatus('Photo captured. Ready to register.', true);
}

document.getElementById('retakeBtn').addEventListener('click', () => {
    capturedImageBlob = null;
    document.getElementById('capturedPreview').classList.add('hidden');
    document.getElementById('cameraVideo').classList.remove('hidden');
    const retake = document.getElementById('retakeBtn');
    const reg    = document.getElementById('registerBtn');
    retake.classList.add('hidden'); retake.disabled = true;
    reg.classList.add('hidden');    reg.disabled = true;
    setCamStatus('Camera ready. Tap the frame to capture.', true);
});

function setCamStatus(msg, ready) {
    const el = document.getElementById('camStatus');
    el.textContent = msg;
    el.className = 'cam-status' + (ready ? ' ready' : '');
}

// ── Registration ───────────────────────────────────────────────
document.getElementById('registerBtn').addEventListener('click', submitRegistration);

async function submitRegistration() {
    if (!matchedVisitor)    { showResult(false, 'No visitor selected.'); return; }
    if (!capturedImageBlob) { showResult(false, 'Please capture a photo first.'); return; }

    const identifier = matchedVisitor.email || matchedVisitor.phone;
    if (!identifier) { showResult(false, 'Visitor has no email or phone on record.'); return; }

    const loader = document.getElementById('loader');
    const retake = document.getElementById('retakeBtn');
    const reg    = document.getElementById('registerBtn');

    loader.classList.add('active');
    reg.disabled = retake.disabled = true;

    const formData = new FormData();
    formData.append('identifier', identifier);
    formData.append('image', capturedImageBlob, 'onsite-camera.jpg');

    try {
        const res  = await fetch('/api/register', { method: 'POST', body: formData });
        const text = await res.text();
        let data;
        try { data = JSON.parse(text); } catch(_) { data = { error: text || 'Non-JSON response' }; }

        const box = document.getElementById('responseBox');
        box.style.display = 'block';
        box.innerText = JSON.stringify(data, null, 2);

        if (data.success) showResult(true, `✓ ${data.name || matchedVisitor.name} registered successfully!`);
        else              showResult(false, data.error || 'Registration failed.');
    } catch (e) {
        showResult(false, e.message);
    } finally {
        loader.classList.remove('active');
        reg.disabled = retake.disabled = false;
    }
}

function handleResultOk() {
    const icon = document.getElementById('resultIcon');
    // If registration was successful, go back to home
    if (icon.textContent === '✓') {
        window.location.href = '/register';
    } else {
        document.getElementById('resultModal').classList.remove('show');
    }
}

function showResult(success, message) {
    const icon = document.getElementById('resultIcon');
    icon.textContent      = success ? '✓' : '✕';
    icon.style.background = success ? '#dcfce7' : '#fee2e2';
    icon.style.color      = success ? '#16a34a' : '#dc2626';
    document.getElementById('resultMsg').textContent = message;
    document.getElementById('resultModal').classList.add('show');
}
</script>
</body>
</html>