{% extends "base.html" %}

{% block title %}Scanning - {{ session.process_name }} - ScanLook{% endblock %}

{% block content %}
<div class="count-location-container">
    <div class="location-header">
        <div class="location-info">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <a href="{{ url_for('conssheets.index') }}" class="breadcrumb">← Back to Sessions</a>
                <a href="{{ url_for('conssheets.edit_session_header', session_id=session.id) }}" 
                class="btn-edit-header" title="Edit header fields">
                    <i class="fa-solid fa-pencil"></i>
                </a>
            </div>
            <div class="location-label">{{ session.process_name }}</div>
            <div class="header-values">
                {% for hv in header_values %}
                <span class="header-pill"><strong>{{ hv.field_label }}:</strong> {{ hv.field_value }}</span>
                {% endfor %}
            </div>
            <div class="location-stats">
                <span class="stat-pill">Scanned: <span id="scanCount">{{ scans|length }}</span></span>
            </div>
        </div>
    </div>

    {% if not dup_key_field %}
    <div class="alert alert-warning" style="margin: var(--space-lg) 0; padding: var(--space-lg); background: rgba(255,170,0,0.2); border-radius: var(--radius-md);">
        <strong>⚠️ No duplicate key configured!</strong><br>
        Please configure a detail field with "Use for duplicate detection" checked in the admin panel.
    </div>
    {% endif %}

    <div class="scan-card" style="border: 2px solid var(--color-primary); margin-bottom: 20px;">
        <div class="scan-header" >
            <h2 class="scan-title" style="color: var(--color-primary);">🚀 Smart Router Scan</h2>
        </div>
        <div class="scan-form">
            <div class="scan-input-group">
                <input type="text" id="smartScanner" class="scan-input" 
                       placeholder="Scan Raw Barcode Here..." 
                       autocomplete="off" autofocus>
                <button type="button" id="btnSmartScan" class="btn btn-primary">Go</button>
            </div>
            <div id="routerFeedback" style="display:none; padding: 10px; margin-top: 10px; border-radius: 4px;">
                <pre id="routerOutput" style="margin: 0; font-family: monospace; white-space: pre-wrap;"></pre>
            </div>
        </div>
    </div>
    

    <div id="duplicateSameModal" class="modal">
        <div class="modal-content modal-duplicate">
            <div class="duplicate-lot-number" id="dupSameLotNumber"></div>
            <h3 class="duplicate-title" style="color: var(--color-duplicate);">Already Scanned</h3>
            <p class="duplicate-message">This was already scanned in this session.<br>Add it again?</p>
            <div class="modal-actions">
                <button type="button" class="btn btn-secondary btn-lg" onclick="cancelDuplicate()">No</button>
                <button type="button" class="btn btn-lg" style="background: var(--color-duplicate); color: white;" onclick="confirmDuplicate()">Yes, Add</button>
            </div>
        </div>
    </div>

    <div id="duplicateOtherModal" class="modal">
        <div class="modal-content modal-duplicate">
            <div class="duplicate-lot-number" id="dupOtherLotNumber"></div>
            <h3 class="duplicate-title" style="color: var(--color-warning);">⚠️ Previously Consumed</h3>
            <p class="duplicate-message" id="dupOtherInfo"></p>
            <p class="duplicate-message">Are you sure you want to add it?</p>
            <div class="modal-actions">
                <button type="button" class="btn btn-secondary btn-lg" onclick="cancelDuplicate()">No</button>
                <button type="button" class="btn btn-lg" style="background: var(--color-warning); color: var(--color-bg);" onclick="confirmDuplicate()">Yes, Add</button>
            </div>
        </div>
    </div>

    <div id="fieldsModal" class="modal">
        <div class="modal-content">
            <h3 class="modal-title">Enter Details</h3>
            <div class="modal-lot-info">
                <div id="modalDupKeyValue" class="modal-lot-number"></div>
            </div>
            <form id="fieldsForm" class="weight-form">
                {% for field in detail_fields %}
                {% if not field.is_duplicate_key %}
                <div class="form-group">
                    <label class="form-label">{{ field.field_label }}{% if field.is_required %}<span style="color: var(--color-danger);">*</span>{% endif %}</label>
                    {% if field.field_type == 'REAL' %}
                    <input type="number" id="field_{{ field.field_name }}" name="{{ field.field_name }}" class="form-input" step="0.01" inputmode="decimal" {% if field.is_required %}required{% endif %}>
                    {% elif field.field_type == 'INTEGER' %}
                    <input type="number" id="field_{{ field.field_name }}" name="{{ field.field_name }}" class="form-input" step="1" {% if field.is_required %}required{% endif %}>
                    {% elif field.field_type == 'DATE' %}
                    <input type="date" id="field_{{ field.field_name }}" name="{{ field.field_name }}" class="form-input" {% if field.is_required %}required{% endif %}>
                    {% else %}
                    <input type="text" id="field_{{ field.field_name }}" name="{{ field.field_name }}" class="form-input" {% if field.max_length %}maxlength="{{ field.max_length }}"{% endif %} {% if field.is_required %}required{% endif %}>
                    {% endif %}
                </div>
                {% endif %}
                {% endfor %}
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="cancelFields()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="saveSmartScanData()">Save</button>
                </div>
            </form>
        </div>
    </div>

    <div class="scans-section">
        <div class="scans-header">
            <h3 class="scans-title">Scanned Items (<span id="scanListCount">{{ scans|length }}</span>)</h3>
        </div>
        <div style="margin-top: 10px;">
            <button type="button" class="btn btn-secondary btn-sm" onclick="document.getElementById('importModal').style.display='flex'">
                <i class="fa-solid fa-file-import"></i> Bulk Import Excel
            </button>
        </div>
        <div class="scans-grid scan-header-row" style="--field-count: {{ detail_fields|length }};">
            {% for field in detail_fields %}
            <div class="cs-scan-row-cell scan-col-header">{{ field.field_label }}</div>
            {% endfor %}
            <div class="cs-scan-row-cell scan-col-header">Status</div>
        </div>
        <div id="scansList" class="scans-grid" style="--field-count: {{ detail_fields|length }};">
            {% for scan in scans %}
            <div class="cs-scan-row cs-scan-row-{{ scan.duplicate_status }}" 
                data-detail-id="{{ scan.id }}" 
                onclick="openScanDetail(this.dataset.detailId)">
                {% for field in detail_fields %}
                <div class="cs-scan-row-cell">{% if field.field_type == 'REAL' %}{{ '%.1f'|format(scan[field.field_name]|float) if scan[field.field_name] else '-' }}{% else %}{{ scan[field.field_name] or '-' }}{% endif %}</div>
                {% endfor %}
                <div class="cs-scan-row-status">
                    {% if scan.duplicate_status == 'dup_same_session' %}<span class="status-dot status-dot-blue"></span> Dup
                    {% elif scan.duplicate_status == 'dup_other_session' %}<span class="status-dot status-dot-orange"></span> Warn
                    {% else %}<span class="status-dot status-dot-green"></span> OK{% endif %}
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <div id="scanDetailModal" class="modal">
        <div class="modal-content modal-large">
            <div class="modal-header-bar">
                <h3 class="modal-title">Scan Details</h3>
                <button type="button" class="btn-close-modal" onclick="closeScanDetail()">✕</button>
            </div>
            <div id="scanDetailContent" class="scan-detail-content"></div>
        </div>
    </div>

    <div class="finish-section">
        <div class="action-buttons-row">
            <a href="{{ url_for('conssheets.index') }}" class="btn btn-secondary btn-block btn-lg">← Back to Sessions</a>
            <button class="btn btn-success btn-block btn-lg" onclick="exportToExcel()">📊 Export to Excel</button>
        </div>
    </div>
</div>

<div id="importModal" class="modal">
    <div class="modal-content">
        <div class="modal-header-bar">
            <h3 class="modal-title">Bulk Import Data</h3>
            <button type="button" class="btn-close-modal" onclick="document.getElementById('importModal').style.display='none'">&times;</button>
        </div>
        
        <div class="modal-body" style="text-align: center;">
            <p style="color: var(--color-text-muted); margin-bottom: 20px;">
                Upload an Excel file (.xlsx) to automatically populate this session.
                <br><strong>Warning:</strong> This bypasses all validation checks.
            </p>
            
            <div style="margin-bottom: 30px; padding: 15px; background: var(--color-bg); border-radius: 8px;">
                <p style="font-size: 0.9rem; margin-bottom: 10px;">Step 1: Get the correct format</p>
                <a href="{{ url_for('conssheets.download_import_template', session_id=session['id']) }}" class="btn btn-secondary btn-sm">
                    <i class="fa-solid fa-download"></i> Download Template
                </a>
            </div>
            
            <form action="{{ url_for('conssheets.import_session_data', session_id=session['id']) }}" method="POST" enctype="multipart/form-data">
                <div style="margin-bottom: 20px;">
                    <input type="file" name="file" accept=".xlsx" class="file-input" required style="width: 100%;">
                </div>
                
                <button type="submit" class="btn btn-primary btn-block">
                    <i class="fa-solid fa-upload"></i> Upload & Process
                </button>
            </form>
        </div>
    </div>
</div>

<!-- Styles moved to static/css/style.css -->

<script id="session-data" type="application/json">
{
    "detailFields": {{ detail_fields|tojson|safe }},
    "dupKeyFieldName": {{ (dup_key_field.field_name if dup_key_field else '')|tojson|safe }},
    "sessionId": {{ session.id }}
}
</script>

<script>
// Read data from the JSON block above
const sessionData = JSON.parse(document.getElementById('session-data').textContent);
const detailFields = sessionData.detailFields;
const dupKeyFieldName = sessionData.dupKeyFieldName;
const sessionId = sessionData.sessionId;

// --- SMART SCANNER LOGIC ---
const smartInput = document.getElementById('smartScanner');
const feedbackArea = document.getElementById('routerFeedback');
const feedbackText = document.getElementById('routerOutput');

// Handle Enter Key
smartInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        processSmartScan(this.value);
    }
});

document.getElementById('btnSmartScan').addEventListener('click', function() {
    processSmartScan(smartInput.value);
});

function processSmartScan(barcode, confirm = false) {
    if (!barcode.trim()) return;

    // LOCK UI to prevent double-scans
    if(smartInput) smartInput.disabled = true;
    if (!confirm) feedbackArea.style.display = 'none';

    fetch(`/conssheets/session/${sessionId}/scan`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
            barcode: barcode,
            confirm_duplicate: confirm 
        }) 
    })
    .then(response => response.json())
    .then(data => {
        if(smartInput) smartInput.disabled = false;
        
        // --- 1. HANDLE DUPLICATE CONFIRMATION ---
        if (data.needs_confirmation) {
            playErrorBeep();
            isSmartScan = true; 
            currentDupKeyValue = barcode; 
            if (data.duplicate_status === 'dup_same_session') {
                // Try to fill display element, fallback to simple ID
                let el = document.getElementById('dupSameLotNumber');
                if(el) el.textContent = barcode;
                document.getElementById('duplicateSameModal').style.display = 'flex';
            } else {
                let el = document.getElementById('dupOtherLotNumber');
                if(el) el.textContent = barcode;
                if(document.getElementById('dupOtherInfo')) document.getElementById('dupOtherInfo').textContent = data.message;
                document.getElementById('duplicateOtherModal').style.display = 'flex';
            }
            // IMPORTANT: Refocus away from scanner to prevent phantom enters
            document.activeElement.blur();
            return; 
        }

        // --- 2. HANDLE "OPEN DETAILS FORM" ---
        if (data.needs_input) {
            // CRITICAL FIX: Save the barcode globally so the 'Save' button can use it
            currentDupKeyValue = barcode; 
            
            const parsedData = data.data;
            
            // Populate fields
            for (const [key, value] of Object.entries(parsedData)) {
                let el = document.getElementById(key);
                if (!el) el = document.querySelector(`[name="${key}"]`);
                
                if (el) {
                    if (['INPUT', 'SELECT', 'TEXTAREA'].includes(el.tagName)) {
                        el.value = value;
                    } else {
                        el.textContent = value;
                    }
                }
                
                let displayEl = document.getElementById(key + '_display') || document.getElementById('display_' + key);
                if (displayEl) displayEl.textContent = value;
            }

            showFieldsModal(); 
            
            smartInput.value = '';
            return;
        }

        // --- 3. STANDARD SUCCESS/FAIL ---
        if (data.success) {
            if (data.detail_id && data.data) {
                addScanToList(data.detail_id, data.data, data.data.duplicate_status);
            }
            feedbackArea.style.display = 'none';
            if(smartInput) {
                smartInput.value = '';
                smartInput.focus();
            }
        } else {
            playErrorBeep();
            feedbackArea.style.display = 'block';
            feedbackArea.style.background = 'rgba(220, 53, 69, 0.2)';
            feedbackArea.style.border = '1px solid #dc3545';
            feedbackText.style.color = '#dc3545';
            feedbackText.textContent = data.message;
            if(smartInput) {
                smartInput.value = '';
                smartInput.focus();
            }
        }
    })  
    .catch(err => {
        if(smartInput) smartInput.disabled = false;
        console.error(err); // Log it, don't popup alert to annoy user
    });
}

// Function to handle the "Save" click from the Details Modal
function saveSmartScanData() {
    // 1. Validate we have the original barcode
    if (!currentDupKeyValue) {
        alert("Error: Original barcode lost. Please scan again.");
        return;
    }

    // 2. Collect inputs using NAME ONLY (Fixes the database error)
    const form = document.getElementById('fieldsForm');
    if (!form) return console.error("Form not found!");

    let formData = {};
    
    // Grab all inputs, but ONLY use the 'name' attribute
    form.querySelectorAll('input, select').forEach(el => {
        if (el.name) {
            formData[el.name] = el.value;
        }
    });

    // 3. Send the payload
    fetch(`/conssheets/session/${sessionId}/scan`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
            barcode: currentDupKeyValue,  // The original scan (TEST10)
            field_values: formData,       // The Clean Data (weight: 164)
            confirm_duplicate: true,      // Bypass duplicate check
            extra_data: formData          
        }) 
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('fieldsModal').style.display = 'none';
            if (data.detail_id && data.data) {
                addScanToList(data.detail_id, data.data, data.data.duplicate_status);
            }
            currentDupKeyValue = '';
            smartInput.value = '';
            smartInput.focus();
        } else if (data.needs_input) {
            alert("Error: Please fill in all required fields.");
        } else {
            alert("System Message: " + data.message);
        }
    })
    .catch(err => console.error(err));
}
function resetSmartScan() {
    document.getElementById('smartScanner').value = '';
    document.getElementById('smartScanner').focus();
    document.getElementById('routerFeedback').style.display = 'none';
}
// --- ERROR BEEP ---
function playErrorBeep() {
    try {
        const ctx = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = ctx.createOscillator();
        const gainNode = ctx.createGain();
        oscillator.connect(gainNode);
        gainNode.connect(ctx.destination);
        oscillator.type = 'square';
        oscillator.frequency.setValueAtTime(520, ctx.currentTime);
        gainNode.gain.setValueAtTime(0.3, ctx.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.4);
        oscillator.start(ctx.currentTime);
        oscillator.stop(ctx.currentTime + 0.4);
    } catch(e) {
        console.warn('Audio not available:', e);
    }
}

// Standard variables
let currentDupKeyValue = '';
let currentDuplicateStatus = '';
let isDuplicateConfirmed = false;
let isProcessing = false;
let isSmartScan = false;

document.getElementById('lotScanForm').addEventListener('submit', function(e) {
    e.preventDefault();
    if (isProcessing) return;
    const scannedValue = document.getElementById('dupKeyInput').value.trim();
    if (!scannedValue) return;
    isProcessing = true;
    currentDupKeyValue = scannedValue;
    document.getElementById('dupKeyInput').value = '';
    checkDuplicate();
});

function checkDuplicate() {
    const fieldValues = {};
    fieldValues[dupKeyFieldName] = currentDupKeyValue;
    fetch(`/conssheets/session/${sessionId}/scan`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ field_values: fieldValues, check_only: true })
    })
    .then(r => r.json())
    .then(data => {
        if (data.needs_confirmation) {
            currentDuplicateStatus = data.duplicate_status;
            if (data.duplicate_status === 'dup_same_session') {
                document.getElementById('dupSameLotNumber').textContent = currentDupKeyValue;
                document.getElementById('duplicateSameModal').style.display = 'flex';
            } else if (data.duplicate_status === 'dup_other_session') {
                document.getElementById('dupOtherLotNumber').textContent = currentDupKeyValue;
                document.getElementById('dupOtherInfo').textContent = data.duplicate_info;
                document.getElementById('duplicateOtherModal').style.display = 'flex';
            }
        } else {
            showFieldsModal();
        }
    })
    .catch(error => { console.error('Error:', error); showFieldsModal(); });
}

function confirmDuplicate() {
    isDuplicateConfirmed = true;
    document.getElementById('duplicateSameModal').style.display = 'none';
    document.getElementById('duplicateOtherModal').style.display = 'none';

    // NEW LOGIC: If this was a Smart Scan, re-run it with confirmation
    if (isSmartScan) {
        processSmartScan(currentDupKeyValue, true);
        isSmartScan = false; // Reset flag
    } else {
        // Old Logic (Manual Form)
        showFieldsModal();
    }
}

function cancelDuplicate() {
    document.getElementById('duplicateSameModal').style.display = 'none';
    document.getElementById('duplicateOtherModal').style.display = 'none';
    
    // NEW LOGIC: Reset Smart Scanner if that's where we came from
    if (isSmartScan) {
        document.getElementById('smartScanner').value = '';
        document.getElementById('smartScanner').focus();
        document.getElementById('routerFeedback').style.display = 'none';
        isSmartScan = false;
    } else {
        // Old Logic (Manual Form)
        document.getElementById('dupKeyInput').focus();
    }
    
    isDuplicateConfirmed = false;
    isProcessing = false;
    currentDuplicateStatus = '';
}

function showFieldsModal() {
    document.getElementById('modalDupKeyValue').textContent = currentDupKeyValue;
    document.getElementById('fieldsModal').style.display = 'flex';
    const form = document.getElementById('fieldsForm');
    form.reset();
    // Focus on first required field, or first input if none required
    const firstRequired = form.querySelector('input[required]');
    const firstInput = form.querySelector('input:not([disabled])');
    if (firstRequired) firstRequired.focus();
    else if (firstInput) firstInput.focus();
}

function cancelFields() {
    document.getElementById('fieldsModal').style.display = 'none';
    document.getElementById('dupKeyInput').focus();
    isDuplicateConfirmed = false;
    isProcessing = false;
    currentDuplicateStatus = '';
}

document.getElementById('fieldsForm').addEventListener('submit', function(e) {
    e.preventDefault();
    submitScan();
});

function submitScan() {
    const fieldValues = {};
    fieldValues[dupKeyFieldName] = currentDupKeyValue;
    detailFields.forEach(field => {
        if (!field.is_duplicate_key) {
            const input = document.getElementById('field_' + field.field_name);
            if (input) fieldValues[field.field_name] = input.value;
        }
    });
    fetch(`/conssheets/session/${sessionId}/scan`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ field_values: fieldValues, confirm_duplicate: isDuplicateConfirmed })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            document.getElementById('fieldsModal').style.display = 'none';
            if (data.updated_entry_ids && data.updated_entry_ids.length > 0) {
                data.updated_entry_ids.forEach(id => {
                    const row = document.querySelector(`[data-detail-id="${id}"]`);
                    if (row) {
                        row.className = 'cs-scan-row cs-scan-row-dup_same_session';
                        row.querySelector('.cs-scan-row-status').innerHTML = '<span class="status-dot status-dot-blue"></span> Dup';
                    }
                });
            }
            addScanToList(data.detail_id, fieldValues, data.duplicate_status);
            currentDupKeyValue = '';
            isDuplicateConfirmed = false;
            isProcessing = false;
            currentDuplicateStatus = '';
            document.getElementById('dupKeyInput').focus();
        } else {
            alert(data.message || 'Error saving scan');
            isProcessing = false;
        }
    })
    .catch(error => { console.error('Error:', error); alert('Error saving scan'); isProcessing = false; });
}

function addScanToList(detailId, fieldValues, duplicateStatus) {
    const scansList = document.getElementById('scansList');
    let statusClass = duplicateStatus || 'normal';
    let statusDot = 'green', statusText = 'OK';
    if (duplicateStatus === 'dup_same_session') { statusDot = 'blue'; statusText = 'Dup'; }
    else if (duplicateStatus === 'dup_other_session') { statusDot = 'orange'; statusText = 'Warn'; }
    const scanRow = document.createElement('div');
    scanRow.className = 'cs-scan-row cs-scan-row-' + statusClass;
    scanRow.setAttribute('data-detail-id', detailId);
    scanRow.onclick = function() { openScanDetail(detailId); };
    let cellsHtml = '';
    detailFields.forEach(field => {
        let value = fieldValues[field.field_name] || '-';
        if (field.field_type === 'REAL' && value !== '-') value = parseFloat(value).toFixed(1);
        cellsHtml += `<div class="cs-scan-row-cell">${value}</div>`;
    });
    cellsHtml += `<div class="cs-scan-row-status"><span class="status-dot status-dot-${statusDot}"></span> ${statusText}</div>`;
    scanRow.innerHTML = cellsHtml;
    scansList.insertBefore(scanRow, scansList.firstChild);
    const countSpan = document.getElementById('scanListCount');
    const scanCountSpan = document.getElementById('scanCount');
    const newCount = scansList.children.length;
    if (countSpan) countSpan.textContent = newCount;
    if (scanCountSpan) scanCountSpan.textContent = newCount;
}

function openScanDetail(detailId) {
    fetch(`/conssheets/session/${sessionId}/detail/${detailId}`)
    .then(r => r.json())
    .then(data => {
        if (data.success) displayScanDetail(data.detail);
        else alert('Error loading details');
    });
}

function displayScanDetail(detail) {
    const content = document.getElementById('scanDetailContent');
    let statusBadge = '<span class="badge badge-success">✓ OK</span>';
    if (detail.duplicate_status === 'dup_same_session') statusBadge = '<span class="badge badge-duplicate">🔵 Duplicate</span>';
    else if (detail.duplicate_status === 'dup_other_session') statusBadge = '<span class="badge badge-warning">🟠 Previously Consumed</span>';
    let detailRows = '';
    detailFields.forEach(field => {
        let value = detail[field.field_name] || 'N/A';
        if (field.field_type === 'REAL' && value !== 'N/A') value = parseFloat(value).toFixed(2);
        detailRows += `<div class="detail-row"><span class="detail-label">${field.field_label}:</span><span class="detail-value">${value}</span></div>`;
    });
    let editFields = '';
    detailFields.forEach(field => {
        let inputType = 'text', extraAttrs = '';
        if (field.field_type === 'REAL') { inputType = 'number'; extraAttrs = 'step="0.01"'; }
        else if (field.field_type === 'INTEGER') { inputType = 'number'; extraAttrs = 'step="1"'; }
        else if (field.field_type === 'DATE') { inputType = 'date'; }
        let value = detail[field.field_name] || '';
        editFields += `<div class="form-group"><label class="form-label">${field.field_label}</label><input type="${inputType}" id="edit_${field.field_name}" class="form-input" value="${value}" ${extraAttrs}></div>`;
    });
    content.innerHTML = `
        <div class="detail-section">${detailRows}
            <div class="detail-row"><span class="detail-label">Status:</span><span class="detail-value">${statusBadge}</span></div>
            ${detail.duplicate_info ? `<div class="detail-row"><span class="detail-label">Info:</span><span class="detail-value">${detail.duplicate_info}</span></div>` : ''}
            <div class="detail-row"><span class="detail-label">Scanned:</span><span class="detail-value">${detail.scanned_at} by ${detail.scanned_by_name}</span></div>
        </div>
        <div class="detail-section"><h4 class="detail-section-title">Edit Scan</h4><div class="detail-form">${editFields}
            <div class="form-group"><label class="form-label">Comment</label><textarea id="editComment" class="form-textarea" rows="3">${detail.comment || ''}</textarea></div>
        </div></div>
        <div class="detail-actions">
            <button class="btn btn-secondary" onclick="closeScanDetail()">Cancel</button>
            <button class="btn btn-danger" onclick="deleteDetail(${detail.id})">Delete</button>
            <button class="btn btn-primary" onclick="saveDetail(${detail.id})">Save Changes</button>
        </div>`;
    document.getElementById('scanDetailModal').style.display = 'flex';
}

function closeScanDetail() { document.getElementById('scanDetailModal').style.display = 'none'; }

function saveDetail(detailId) {
    const fieldValues = {};
    detailFields.forEach(field => {
        const input = document.getElementById('edit_' + field.field_name);
        if (input) fieldValues[field.field_name] = input.value;
    });
    const comment = document.getElementById('editComment').value;
    fetch(`/conssheets/session/${sessionId}/detail/${detailId}/update`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ field_values: fieldValues, comment: comment })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { closeScanDetail(); location.reload(); }
        else alert(data.message || 'Error updating');
    });
}

function deleteDetail(detailId) {
    if (!confirm('Delete this scan?')) return;
    fetch(`/conssheets/session/${sessionId}/detail/${detailId}/delete`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'}
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { closeScanDetail(); location.reload(); }
        else alert(data.message || 'Error deleting');
    });
}

function exportToExcel() { 
    window.location.href = `/conssheets/session/${sessionId}/export?format=xlsx`;
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.getElementById('fieldsModal').style.display = 'none';
        document.getElementById('duplicateSameModal').style.display = 'none';
        document.getElementById('duplicateOtherModal').style.display = 'none';
        document.getElementById('scanDetailModal').style.display = 'none';
        document.getElementById('dupKeyInput').focus();
    }
});
</script>
{% endblock %}