/**
 * ScanLook - Main JavaScript
 * Client-side utilities and enhancements
 */

// Auto-dismiss flash messages after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    const flashMessages = document.querySelectorAll('.flash');
    
    flashMessages.forEach(function(flash) {
        setTimeout(function() {
            flash.style.animation = 'slideOut 0.3s ease';
            setTimeout(function() {
                flash.remove();
            }, 300);
        }, 5000);
    });
});

// Animation for slide out
const style = document.createElement('style');
style.textContent = `
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(120%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// Utility: Format timestamp
function formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleString();
}

// Utility: Format number with commas
function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// Auto-focus on scan inputs when page loads
window.addEventListener('load', function() {
    const scanInput = document.querySelector('.scan-input');
    if (scanInput) {
        scanInput.focus();
    }
});

// Prevent accidental page navigation
window.addEventListener('beforeunload', function(e) {
    const isCountingPage = document.querySelector('.count-location-container');
    if (isCountingPage) {
        const scans = document.querySelectorAll('.scan-item').length;
        if (scans > 0) {
            e.preventDefault();
            e.returnValue = '';
        }
    }
});

// Auto-uppercase inputs with specific classes
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('scan-input')) {
        e.target.value = e.target.value.toUpperCase();
    }
});

// Settings dropdown toggle
function toggleSettings() {
    const menu = document.getElementById('settingsMenu');
    if (menu) {
        menu.classList.toggle('show');
    }
}

// Close settings dropdown when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.matches('.btn-settings') && !e.target.closest('.settings-dropdown')) {
        const menu = document.getElementById('settingsMenu');
        if (menu && menu.classList.contains('show')) {
            menu.classList.remove('show');
        }
    }
});
