{% extends "base.html" %}

{% block title %}{{ count_session.session_name }} - ScanLook{% endblock %}

{% block content %}
<div class="session-detail-container">
    <div class="session-detail-header">
        <div>
            <a href="{{ url_for('admin_dashboard') }}{% if count_session.status == 'archived' %}?show_archived=1{% endif %}" class="breadcrumb">← Back to Dashboard</a>
            <h1 class="page-title">
                {{ count_session.session_name }}
                {% if count_session.status == 'archived' %}<span class="archived-badge">ARCHIVED</span>{% endif %}
            </h1>
            <span class="session-type-badge session-type-{{ count_session.session_type }}">
                {{ 'Full Physical' if count_session.session_type == 'full_physical' else 'Cycle Count' }}
            </span>
        </div>
        <div class="session-actions-header">
            {% if count_session.status == 'archived' %}
                <button class="btn btn-success" onclick="activateSession()">✓ Activate Session</button>
            {% else %}
                <button class="btn btn-secondary" onclick="archiveSession()">📦 Archive Session</button>
            {% endif %}
        </div>
    </div>

    <!-- Baseline Upload Section -->
    <div class="section-card">
        <h2 class="section-title">Baseline Data</h2>
        
        <div class="baseline-grid">
            <div class="baseline-item">
                <div class="baseline-label">MASTER Baseline</div>
                <div class="baseline-status">
                    {% if count_session.master_baseline_timestamp %}
                        <span class="status-badge status-success">✓ Uploaded</span>
                        <small class="baseline-time">{{ count_session.master_baseline_timestamp[:16] }}</small>
                    {% else %}
                        <span class="status-badge status-warning">⚠ Not Uploaded</span>
                    {% endif %}
                </div>
                {% if not count_session.master_baseline_timestamp %}
                <!-- Note: Using data_imports blueprint URL -->
                <form method="POST" action="{{ url_for('invcount.upload_master', session_id=count_session.session_id) }}" enctype="multipart/form-data" class="upload-form">
                    <input type="file" name="csv_file" accept=".csv" required class="file-input">
                    <button type="submit" class="btn btn-primary btn-sm">Upload MASTER</button>
                </form>
                {% endif %}
            </div>

            <div class="baseline-item">
                <div class="baseline-label">CURRENT Baseline (Optional)</div>
                <div class="baseline-status">
                    {% if count_session.current_baseline_timestamp %}
                        <span class="status-badge status-success">✓ Uploaded</span>
                        <small class="baseline-time">{{ count_session.current_baseline_timestamp[:16] }}</small>
                    {% else %}
                        <span class="status-badge status-neutral">Not Uploaded</span>
                    {% endif %}
                </div>
                {% if count_session.master_baseline_timestamp %}
                <form method="POST" action="{{ url_for('invcount.upload_current', session_id=count_session.session_id) }}" enctype="multipart/form-data" class="upload-form">
                    <input type="hidden" name="baseline_type" value="current">
                    <input type="file" name="csv_file" accept=".csv" required class="file-input">
                    <button type="submit" class="btn btn-secondary btn-sm">
                        {{ 'Refresh CURRENT' if count_session.current_baseline_timestamp else 'Upload CURRENT' }}
                    </button>
                </form>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Statistics Section -->
<div class="section-card">
    <h2 class="section-title">Real-Time Statistics</h2>
    
    <div class="stats-grid">
        <div class="stat-card stat-match" onclick="showStatusDetails('match')">
            <div class="stat-number" id="count-matched">{{ stats.matched or 0 }}</div>
            <div class="stat-label">✓ Matched</div>
        </div>
        <div class="stat-card stat-duplicate" onclick="showStatusDetails('duplicates')">
            <div class="stat-number" id="count-duplicates">{{ stats.duplicates or 0 }}</div>
            <div class="stat-label">🔵 Duplicates</div>
        </div>
        <div class="stat-card stat-weight-disc" onclick="showStatusDetails('weight_discrepancy')">
            <div class="stat-number" id="count-discrepancy">{{ stats.weight_discrepancy or 0 }}</div>
            <div class="stat-label">⚖️ Weight Discrepancy</div>
        </div>
        <div class="stat-card stat-wrong" onclick="showStatusDetails('wrong_location')">
            <div class="stat-number" id="count-wrong">{{ stats.wrong_location or 0 }}</div>
            <div class="stat-label">⚠ Wrong Location</div>
        </div>
        <div class="stat-card stat-ghost" onclick="showStatusDetails('ghost_lot')">
            <div class="stat-number" id="count-ghost">{{ stats.ghost_lots or 0 }}</div>
            <div class="stat-label">🟣 Ghost Lots</div>
        </div>
        <div class="stat-card stat-missing" onclick="showStatusDetails('missing')">
            <div class="stat-number" id="count-missing">{{ stats.missing_lots or 0 }}</div>
            <div class="stat-label">🔴 Missing</div>
        </div>
    </div>
</div>

    <!-- Active Counters Section -->
    {% if active_counters %}
    <div class="section-card">
        <h2 class="section-title">Active Counters</h2>
        <div id="active-counters-container"> <div class="counter-list">
                {% for counter in active_counters %}
            <div class="counter-item">
                <div class="counter-avatar">{{ counter.full_name[0] }}</div>
                <div class="counter-info">
                    <div class="counter-name">{{ counter.full_name }}</div>
                    <div class="counter-location">📍 {{ counter.location_name }}</div>
                </div>
                <div class="counter-time">{{ counter.start_timestamp[11:16] }}</div>
            </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Location Progress Section -->
    {% if locations %}
    <div class="section-card">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: var(--space-md);">
        <h2 class="section-title" style="margin-bottom: 0;">Location Progress</h2>
        <button class="btn btn-danger btn-sm" onclick="showFinalizeAllConfirm()">
            ⚠️ Finalize All Bins
        </button>
    </div>
        <div class="location-table">
            <table>
                <thead>
                    <tr>
                        <th>Location</th>
                        <th>Status</th>
                        <th>Counter</th>
                        <th>Expected</th>
                        <th>Found</th>
                        <th>Missing</th>
                    </tr>
                </thead>
                <tbody>
                    {% for loc in locations %}
                    <!-- Refactored to use data attributes instead of direct Jinja injection in onclick -->
                    <tr class="location-row-clickable" 
                        data-id="{{ loc.location_count_id }}" 
                        data-name="{{ loc.location_name }}" 
                        data-status="{{ loc.status }}"
                        onclick="handleLocationClick(this)">
                        <td><strong>{{ loc.location_name }}</strong></td>
                        <td>
                            <span class="status-badge status-{{ loc.status }}">
                                {% if loc.status == 'completed' %}✓ Done
                                {% elif loc.status == 'in_progress' %}⏳ Counting
                                {% else %}○ Pending{% endif %}
                            </span>
                        </td>
                        <td>{{ loc.counter_name or '-' }}</td>
                        <td>{{ loc.expected_lots_master }}</td>
                        <td>{{ loc.lots_found }}</td>
                        <td>{{ loc.lots_missing_calc }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    {% endif %}
</div>

<!-- Status Details Modal -->
<div id="statusModal" class="modal">
    <div class="modal-content modal-xl">
        <div class="modal-header-bar">
            <h3 class="modal-title" id="statusModalTitle">Details</h3>
            <div class="modal-header-actions">
                <button class="btn btn-secondary btn-sm" onclick="exportStatusToCSV()">
                    📥 Export CSV
                </button>
                <button type="button" class="btn-close-modal" onclick="closeStatusModal()">✕</button>
            </div>
        </div>
        
        <div id="statusDetailContent" class="status-detail-content">
            <div class="loading-spinner">Loading...</div>
        </div>
    </div>
</div>

<!-- Location Detail Modal -->
<div id="locationModal" class="modal">
    <div class="modal-content modal-xl">
        <div class="modal-header-bar">
            <h3 class="modal-title" id="locationModalTitle">Location Details</h3>
            <div class="modal-header-actions">
                <button id="finalizeLocationBtn" class="btn btn-success btn-sm" style="display: none;" onclick="showFinalizeConfirm()">
                    ✓ Finalize Location
                </button>
                <button id="reopenLocationBtn" class="btn btn-warning btn-sm" style="display: none;" onclick="showReopenConfirm()">
                    🔓 Reopen Location
                </button>
                <button id="deleteLocationBtn" class="btn btn-danger btn-sm" style="display: none;" onclick="showDeleteBinConfirm()">
                    🗑️ Delete Bin
                </button>
                <button class="btn btn-secondary btn-sm" onclick="exportLocationToCSV()">
                    📥 Export CSV
                </button>
                <button type="button" class="btn-close-modal" onclick="closeLocationModal()">✕</button>
            </div>
        </div>
        
        <div id="locationDetailContent" class="status-detail-content">
            <div class="loading-spinner">Loading...</div>
        </div>
    </div>
</div>

<!-- Finalize Confirmation Modal -->
<div id="finalizeConfirmModal" class="modal">
    <div class="modal-content modal-small">
        <div class="modal-header-bar">
            <h3 class="modal-title">Finalize Location?</h3>
            <button type="button" class="btn-close-modal" onclick="closeFinalizeConfirm()">✕</button>
        </div>
        
        <div class="confirm-modal-content">
            <div class="confirm-icon">⚠️</div>
            <p class="confirm-text">
                Are you sure you want to finalize <strong id="finalizeBinName"></strong>?
            </p>
            <p class="confirm-subtext">
                This will mark the location as completed. The counter can no longer add scans to this location.
            </p>
        </div>
        
        <div class="modal-actions">
            <button class="btn btn-secondary" onclick="closeFinalizeConfirm()">Cancel</button>
            <button class="btn btn-success" onclick="confirmFinalize()">✓ Yes, Finalize</button>
        </div>
    </div>
</div>

<!-- Reopen Confirmation Modal -->
<div id="reopenConfirmModal" class="modal">
    <div class="modal-content modal-small">
        <div class="modal-header-bar">
            <h3 class="modal-title">Reopen Location?</h3>
            <button type="button" class="btn-close-modal" onclick="closeReopenConfirm()">✕</button>
        </div>
        
        <div class="confirm-modal-content">
            <div class="confirm-icon">🔓</div>
            <p class="confirm-text">
                Are you sure you want to reopen <strong id="reopenBinName"></strong>?
            </p>
            <p class="confirm-subtext">
                This will mark the location as in progress. The counter will be able to add more scans to this location.
            </p>
        </div>
        
        <div class="modal-actions">
            <button class="btn btn-secondary" onclick="closeReopenConfirm()">Cancel</button>
            <button class="btn btn-warning" onclick="confirmReopen()">🔓 Yes, Reopen</button>
        </div>
    </div>
</div>

<script>
// Store the Session ID globally to use in functions without passing it every time
const CURRENT_SESSION_ID = "{{ count_session.session_id }}";

function showStatusDetails(status) {
    document.getElementById('statusModal').style.display = 'flex';
    document.getElementById('statusDetailContent').innerHTML = '<div class="loading-spinner">Loading...</div>';
    
    // Set modal title
    const titles = {
        'match': '✓ Matched Lots',
        'duplicates': '🔵 Duplicate Lots',
        'weight_discrepancy': '⚖️ Weight Discrepancy',
        'wrong_location': '⚠ Wrong Location',
        'ghost_lot': '🟣 Ghost Lots',
        'missing': '🔴 Missing Lots'
    };
    document.getElementById('statusModalTitle').textContent = titles[status] || 'Details';
    
    // Fetch details using the blueprint URL structure
    fetch(`/invcount/session/${CURRENT_SESSION_ID}/status-details/${status}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentStatusData = data.items;
                currentStatusType = status;
                displayStatusDetails(data.items, status);
            } else {
                document.getElementById('statusDetailContent').innerHTML = 
                    `<div class="empty-state"><p>Error: ${data.message || 'Unknown error'}</p></div>`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('statusDetailContent').innerHTML = 
                `<div class="empty-state"><p>Network error: ${error.message}</p></div>`;
        });
}

function displayStatusDetails(items, status) {
    const content = document.getElementById('statusDetailContent');
    
    if (!items || items.length === 0) {
        content.innerHTML = '<div class="empty-state"><p>No items found</p></div>';
        return;
    }
    
    let html = '<div class="detail-table-container"><table class="detail-table"><thead><tr>';
    
    // Table headers based on status type
    if (status === 'missing') {
        html += `
            <th colspan="4" class="section-header section-counted">EXPECTED (MASTER)</th>
        </tr><tr>
            <th>LOT #</th>
            <th>SKU #</th>
            <th>E Bin</th>
            <th>E Weight</th>
        `;
    } else {
        html += `
            <th colspan="4" class="section-header section-counted">COUNTED</th>
            <th colspan="2" class="section-header section-expected">EXPECTED (MASTER)</th>
            <th colspan="2" class="section-header section-current">CURRENT</th>
            <th colspan="2" class="section-header section-counted">INFO</th>
        </tr><tr>
            <th class="col-counted">LOT #</th>
            <th class="col-counted">SKU #</th>
            <th class="col-counted">Counted Bin</th>
            <th class="col-counted">Weight</th>
            <th class="col-expected">E Bin</th>
            <th class="col-expected">E Weight</th>
            <th class="col-current">C Bin</th>
            <th class="col-current">C Weight</th>
            <th class="col-counted">Scanned By</th>
            <th class="col-counted">Scanned At</th>
        `;
    }
    
    html += '</tr></thead><tbody>';
    
    // Table rows
    items.forEach(item => {
        html += '<tr>';
        
        if (status === 'missing') {
            html += `
                <td><strong>${item.lot_number}</strong></td>
                <td>${item.item || '-'}</td>
                <td>${item.system_bin || '-'}</td>
                <td>${item.system_quantity || '-'} lbs</td>
            `;
        } else {
            html += `
                <td class="col-counted"><strong>${item.lot_number}</strong></td>
                <td class="col-counted">${item.item || '-'}</td>
                <td class="col-counted">${item.scanned_location || '-'}</td>
                <td class="col-counted">${item.actual_weight || '-'} lbs</td>
                <td class="col-expected">${item.master_expected_location || '-'}</td>
                <td class="col-expected">${item.master_expected_weight ? item.master_expected_weight + ' lbs' : '-'}</td>
                <td class="col-current">${item.current_system_location || '-'}</td>
                <td class="col-current">${item.current_system_weight ? item.current_system_weight + ' lbs' : '-'}</td>
                <td class="col-counted">${item.scanned_by_name || '-'}</td>
                <td class="col-counted">${item.scan_timestamp ? item.scan_timestamp.substring(0, 19) : '-'}</td>
            `;
        }
        
        html += '</tr>';
    });
    
    html += '</tbody></table></div>';
    content.innerHTML = html;
}

function closeStatusModal() {
    document.getElementById('statusModal').style.display = 'none';
}

let currentStatusData = null;
let currentStatusType = null;

function exportStatusToCSV() {
    if (!currentStatusData || currentStatusData.length === 0) {
        alert('No data to export');
        return;
    }
    
    // Build CSV content
    let csv = '';
    
    // Headers based on status type
    if (currentStatusType === 'missing') {
        csv = 'LOT #,SKU #,E Bin,E Weight\n';
        
        currentStatusData.forEach(item => {
            csv += `"${item.lot_number}",`;
            csv += `"${item.item || ''}",`;
            csv += `"${item.system_bin || ''}",`;
            csv += `"${item.system_quantity || ''} lbs"\n`;
        });
    } else {
        csv = 'LOT #,SKU #,Counted Bin,Weight,E Bin,E Weight,C Bin,C Weight,Scanned By,Scanned At\n';
        
        currentStatusData.forEach(item => {
            csv += `"${item.lot_number}",`;
            csv += `"${item.item || ''}",`;
            csv += `"${item.scanned_location || ''}",`;
            csv += `"${item.actual_weight || ''} lbs",`;
            csv += `"${item.master_expected_location || ''}",`;
            csv += `"${item.master_expected_weight ? item.master_expected_weight + ' lbs' : ''}",`;
            csv += `"${item.current_system_location || ''}",`;
            csv += `"${item.current_system_weight ? item.current_system_weight + ' lbs' : ''}",`;
            csv += `"${item.scanned_by_name || ''}",`;
            csv += `"${item.scan_timestamp ? item.scan_timestamp.substring(0, 19) : ''}"\n`;
        });
    }
    
    // Create download link
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    // Generate filename with status type and timestamp
    const timestamp = new Date().toISOString().slice(0, 19).replace(/[:.]/g, '-');
    const statusName = document.getElementById('statusModalTitle').textContent.replace(/[^a-z0-9]/gi, '_');
    link.setAttribute('href', url);
    link.setAttribute('download', `${statusName}_${timestamp}.csv`);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

let currentLocationId = null;
let currentLocationName = '';
let currentLocationStatus = '';
let currentLocationData = null;

// New helper function to handle click from data attributes
function handleLocationClick(row) {
    const id = row.getAttribute('data-id');
    const name = row.getAttribute('data-name');
    const status = row.getAttribute('data-status');
    showLocationDetails(id, name, status);
}

function showLocationDetails(locationCountId, locationName, status) {
    currentLocationId = locationCountId;
    currentLocationName = locationName;
    currentLocationStatus = status;
    
    document.getElementById('locationModal').style.display = 'flex';
    document.getElementById('locationModalTitle').textContent = `${locationName} - All Scans`;
    document.getElementById('locationDetailContent').innerHTML = '<div class="loading-spinner">Loading...</div>';
    
    // Show finalize or reopen button based on status
    const finalizeBtn = document.getElementById('finalizeLocationBtn');
    const reopenBtn = document.getElementById('reopenLocationBtn');
    const deleteBtn = document.getElementById('deleteLocationBtn'); // ADD THIS LINE

    deleteBtn.style.display = 'block';

    if (status === 'in_progress') {
        finalizeBtn.style.display = 'block';
        reopenBtn.style.display = 'none';
    } else if (status === 'completed') {
        finalizeBtn.style.display = 'none';
        reopenBtn.style.display = 'block';
    } else {
        finalizeBtn.style.display = 'none';
        reopenBtn.style.display = 'none';
    }
    
    // Fetch all scans for this location
    fetch(`/invcount/location/${locationCountId}/scans`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentLocationData = data.scans;
                displayLocationScans(data.scans);
            } else {
                document.getElementById('locationDetailContent').innerHTML = 
                    `<div class="empty-state"><p>Error: ${data.message || 'Unknown error'}</p></div>`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('locationDetailContent').innerHTML = 
                `<div class="empty-state"><p>Network error: ${error.message}</p></div>`;
        });
}

function displayLocationScans(scans) {
    const content = document.getElementById('locationDetailContent');
    
    if (!scans || scans.length === 0) {
        content.innerHTML = '<div class="empty-state"><p>No scans found for this location</p></div>';
        return;
    }
    
    let html = '<div class="detail-table-container"><table class="detail-table"><thead><tr>';
    html += `
        <th colspan="4" class="section-header section-counted">COUNTED</th>
        <th colspan="2" class="section-header section-expected">EXPECTED (MASTER)</th>
        <th colspan="2" class="section-header section-current">CURRENT</th>
        <th colspan="2" class="section-header section-counted">INFO</th>
    </tr><tr>
        <th class="col-counted">LOT #</th>
        <th class="col-counted">SKU #</th>
        <th class="col-counted">Counted Bin</th>
        <th class="col-counted">Weight</th>
        <th class="col-expected">E Bin</th>
        <th class="col-expected">E Weight</th>
        <th class="col-current">C Bin</th>
        <th class="col-current">C Weight</th>
        <th class="col-counted">Status</th>
        <th class="col-counted">Scanned At</th>
    `;
    
    html += '</tr></thead><tbody>';
    
    scans.forEach(scan => {
        // Determine status badge
        let statusBadge = '';
        if (scan.duplicate_status === '01' || scan.duplicate_status === '04') {
            statusBadge = '🔵 Duplicate';
        } else if (scan.duplicate_status === '03') {
            statusBadge = '🟠 Dup (Other)';
        } else if (scan.master_status === 'match' && Math.abs(scan.actual_weight - (scan.master_expected_weight || 0)) >= 0.01) {
            statusBadge = '⚖️ Weight Off';
        } else if (scan.master_status === 'match') {
            statusBadge = '✓ Match';
        } else if (scan.master_status === 'wrong_location') {
            statusBadge = '⚠ Wrong Loc';
        } else if (scan.master_status === 'ghost_lot') {
            statusBadge = '🟣 Ghost';
        }
        
        html += '<tr>';
        html += `
            <td class="col-counted"><strong>${scan.lot_number}</strong></td>
            <td class="col-counted">${scan.item || '-'}</td>
            <td class="col-counted">${scan.scanned_location || '-'}</td>
            <td class="col-counted">${scan.actual_weight || '-'} lbs</td>
            <td class="col-expected">${scan.master_expected_location || '-'}</td>
            <td class="col-expected">${scan.master_expected_weight ? scan.master_expected_weight + ' lbs' : '-'}</td>
            <td class="col-current">${scan.current_system_location || '-'}</td>
            <td class="col-current">${scan.current_system_weight ? scan.current_system_weight + ' lbs' : '-'}</td>
            <td class="col-counted">${statusBadge}</td>
            <td class="col-counted">${scan.scan_timestamp ? scan.scan_timestamp.substring(0, 19) : '-'}</td>
        `;
        html += '</tr>';
    });
    
    html += '</tbody></table></div>';
    content.innerHTML = html;
}

function closeLocationModal() {
    document.getElementById('locationModal').style.display = 'none';
    currentLocationId = null;
    currentLocationData = null;
}

function exportLocationToCSV() {
    if (!currentLocationData || currentLocationData.length === 0) {
        alert('No data to export');
        return;
    }
    
    let csv = 'LOT #,SKU #,Counted Bin,Weight,E Bin,E Weight,C Bin,C Weight,Status,Scanned At\n';
    
    currentLocationData.forEach(scan => {
        let status = '';
        if (scan.duplicate_status === '01' || scan.duplicate_status === '04') {
            status = 'Duplicate';
        } else if (scan.duplicate_status === '03') {
            status = 'Dup (Other)';
        } else if (scan.master_status === 'match' && Math.abs(scan.actual_weight - (scan.master_expected_weight || 0)) >= 0.01) {
            status = 'Weight Off';
        } else if (scan.master_status === 'match') {
            status = 'Match';
        } else if (scan.master_status === 'wrong_location') {
            status = 'Wrong Loc';
        } else if (scan.master_status === 'ghost_lot') {
            status = 'Ghost';
        }
        
        csv += `"${scan.lot_number}",`;
        csv += `"${scan.item || ''}",`;
        csv += `"${scan.scanned_location || ''}",`;
        csv += `"${scan.actual_weight || ''} lbs",`;
        csv += `"${scan.master_expected_location || ''}",`;
        csv += `"${scan.master_expected_weight ? scan.master_expected_weight + ' lbs' : ''}",`;
        csv += `"${scan.current_system_location || ''}",`;
        csv += `"${scan.current_system_weight ? scan.current_system_weight + ' lbs' : ''}",`;
        csv += `"${status}",`;
        csv += `"${scan.scan_timestamp ? scan.scan_timestamp.substring(0, 19) : ''}"\n`;
    });
    
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    const timestamp = new Date().toISOString().slice(0, 19).replace(/[:.]/g, '-');
    link.setAttribute('href', url);
    link.setAttribute('download', `${currentLocationName}_${timestamp}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function showFinalizeConfirm() {
    document.getElementById('finalizeBinName').textContent = currentLocationName;
    document.getElementById('finalizeConfirmModal').style.display = 'flex';
}

function closeFinalizeConfirm() {
    document.getElementById('finalizeConfirmModal').style.display = 'none';
}

function confirmFinalize() {
    // Correctly points to the /finish route to trigger Missing Lot calculations
    fetch(`/invcount/count/${CURRENT_SESSION_ID}/location/${currentLocationId}/finish`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeFinalizeConfirm();
            closeLocationModal();
            location.reload(); // Reload to show updated status and Missing counts
        } else {
            alert(data.message || 'Error finalizing location');
        }
    })
    .catch(error => {
        console.error('Finalize Error:', error);
        alert('Error: ' + error.message);
    });
}


function showReopenConfirm() {
    document.getElementById('reopenBinName').textContent = currentLocationName;
    document.getElementById('reopenConfirmModal').style.display = 'flex';
}

function closeReopenConfirm() {
    document.getElementById('reopenConfirmModal').style.display = 'none';
}

function confirmReopen() {
    // Note: The /reopen endpoint is handled by blueprints/admin_locations.py
    fetch(`/invcount/location/${currentLocationId}/reopen`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeReopenConfirm();
            closeLocationModal();
            location.reload(); // Reload to show updated status
        } else {
            alert(data.message || 'Error reopening location');
        }
    })
    .catch(error => {
        alert('Error: ' + error.message);
    });
}

// Close modal on escape
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeStatusModal();
        closeLocationModal();
        closeFinalizeConfirm();
        closeReopenConfirm();
    }
});
function archiveSession() {
    if (!confirm('Archive this session? It will be hidden from the main dashboard but can be reactivated later.')) return;
    
    fetch('{{ url_for("invcount.archive_session", session_id=count_session.session_id) }}', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'}
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            window.location.href = '{{ url_for("admin_dashboard") }}';
        } else {
            alert(data.message || 'Error archiving session');
        }
    });
}

function activateSession() {
    if (!confirm('Reactivate this session? It will appear on the main dashboard again.')) return;
    
    fetch('{{ url_for("invcount.activate_session", session_id=count_session.session_id) }}', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'}
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Error activating session');
        }
    });
}

function showFinalizeAllConfirm() {
    if (confirm("⚠️ WARNING: This will finalize ALL open bins in this session and calculate missing items. This cannot be undone. Are you sure?")) {
        fetch(`/invcount/session/${CURRENT_SESSION_ID}/finalize-all`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'}
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                location.reload();
            } else {
                alert("Error: " + data.message);
            }
        });
    }
}

function showDeleteBinConfirm() {
    if (confirm(`⚠️ DANGER: Are you sure you want to delete ALL data for ${currentLocationName}? This will hide the bin from staff and wipe any missing lot flags.`)) {
        fetch(`/invcount/location/${currentLocationId}/delete`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                closeLocationModal();
                location.reload(); 
            } else {
                alert(data.message || 'Error deleting bin');
            }
        })
        .catch(error => {
            alert('Error: ' + error.message);
        });
    }
}

function refreshDashboardStats() {
    const sessionId = CURRENT_SESSION_ID;
    
    fetch(`/invcount/session/${sessionId}/get_stats`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const s = data.stats;
                // These IDs must match your HTML and the keys must match sessions.py
                if (document.getElementById('count-matched')) document.getElementById('count-matched').innerText = s.matched;
                if (document.getElementById('count-duplicates')) document.getElementById('count-duplicates').innerText = s.duplicates;
                if (document.getElementById('count-discrepancy')) document.getElementById('count-discrepancy').innerText = s.discrepancy;
                if (document.getElementById('count-wrong')) document.getElementById('count-wrong').innerText = s.wrong_location; // Fixed
                if (document.getElementById('count-ghost')) document.getElementById('count-ghost').innerText = s.ghost_lots;     // Fixed
                if (document.getElementById('count-missing')) document.getElementById('count-missing').innerText = s.missing;
            }
        })
        .catch(err => console.error('Error refreshing stats:', err));

    fetch(`/invcount/session/${sessionId}/active-counters-fragment`)
        .then(response => response.text())
        .then(html => {
            const container = document.getElementById('active-counters-container');
            if (container) container.innerHTML = html;
        })
        .catch(err => console.error('Error refreshing counters:', err));
}

// This tells the browser: "Run the refresh function every 30 seconds"
setInterval(refreshDashboardStats, 30000);

// This runs it IMMEDIATELY once so you don't wait 30 seconds for the first update
refreshDashboardStats();
</script>
{% endblock %}