document.addEventListener('DOMContentLoaded', function() {
    // Initialize all tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Handle document upload interactions
    const documentUploads = document.querySelectorAll('.document-upload');
    documentUploads.forEach(upload => {
        const input = upload.querySelector('input[type="file"]');
        
        upload.addEventListener('click', () => {
            input.click();
        });
        
        input.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                upload.style.borderColor = 'var(--success)';
                upload.style.backgroundColor = '#f8fff8';
                upload.querySelector('i').className = 'fas fa-check-circle';
                upload.querySelector('i').style.color = 'var(--success)';
                
                // If this is a CV upload, parse the file
                if (upload.closest('#upload-cv')) {
                    parseCV(e.target.files[0]);
                }
            }
        });
    });

    // Form validation for profile creation
    const profileForm = document.getElementById('profile-form');
    if (profileForm) {
        profileForm.addEventListener('submit', function(e) {
            let valid = true;
            
            // Validate required fields
            const requiredFields = profileForm.querySelectorAll('[required]');
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.style.borderColor = 'var(--danger)';
                    valid = false;
                } else {
                    field.style.borderColor = '';
                }
            });
            
            if (!valid) {
                e.preventDefault();
                alert('Please fill in all required fields.');
            } else {
                // Form is valid, show success message
                alert('Profile submitted successfully!');
            }
        });
    }

    // Admin dashboard functionality
    if (document.querySelector('#admin-dashboard')) {
        // Initialize map (placeholder for actual map implementation)
        initMap();
        
        // Filter functionality
        const filterRegion = document.getElementById('filter-region');
        const filterSkill = document.getElementById('filter-skill');
        
        [filterRegion, filterSkill].forEach(filter => {
            filter.addEventListener('change', updateDashboardFilters);
        });
        
        // Quick action buttons
        document.querySelectorAll('.quick-action').forEach(button => {
            button.addEventListener('click', function() {
                const action = this.dataset.action;
                handleQuickAction(action);
            });
        });
    }

    // Check-in system functionality
    if (document.querySelector('#checkin')) {
        const checkInBtn = document.getElementById('checkin-btn');
        const checkOutBtn = document.getElementById('checkout-btn');
        
        checkInBtn.addEventListener('click', handleCheckIn);
        checkOutBtn.addEventListener('click', handleCheckOut);
    }
});

// Helper functions
function parseCV(file) {
    console.log('Parsing CV file:', file.name);
    // In a real implementation, this would call a CV parsing API
    // For demo, we'll simulate parsing after a delay
    setTimeout(() => {
        document.getElementById('full-name').value = 'John Doe';
        document.getElementById('phone').value = '072 123 4567';
        document.getElementById('email').value = 'john.doe@example.com';
        document.getElementById('address').value = '123 Main Street, Bloemfontein';
        document.getElementById('skills').value = 'Electrician with 5 years experience. Certified solar panel installer.';
        document.getElementById('experience').value = 'ABC Electrical (2018-2023) - Senior Electrician\nXYZ Solar (2016-2018) - Installation Technician';
        
        alert('CV information extracted successfully. Please review and complete any missing fields.');
    }, 1500);
}

function initMap() {
    console.log('Initializing map...');
    // This would initialize a real map (Google Maps, Leaflet, etc.)
    // For demo purposes, we just log to console
}

function updateDashboardFilters() {
    const region = document.getElementById('filter-region').value;
    const skill = document.getElementById('filter-skill').value;
    
    console.log('Updating dashboard filters:', { region, skill });
    // In a real implementation, this would filter the displayed data
}

function handleQuickAction(action) {
    console.log('Handling quick action:', action);
    switch(action) {
        case 'email':
            window.location.href = 'mailto:?subject=Workforce%20Staffing';
            break;
        case 'whatsapp':
            window.open('https://wa.me/?text=Hello%20from%20Workforce%20Staffing');
            break;
        case 'sms':
            // SMS functionality would depend on device capabilities
            alert('SMS functionality would open device messaging app');
            break;
        case 'export':
            exportData();
            break;
    }
}

function exportData() {
    console.log('Exporting data...');
    // In a real implementation, this would generate a CSV/Excel file
    alert('Data export would download a file with current filtered data');
}

function handleCheckIn() {
    console.log('Handling check-in...');
    // In a real implementation, this would interface with biometric device
    alert('Biometric check-in would be processed here');
}

function handleCheckOut() {
    console.log('Handling check-out...');
    // In a real implementation, this would interface with biometric device
    alert('Biometric check-out would be processed here');
}

// Utility function to format dates
function formatDate(date) {
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return new Date(date).toLocaleDateString('en-ZA', options);
}

// Initialize any charts on the page
function initCharts() {
    // This would initialize Chart.js or similar charting library
    console.log('Initializing charts...');
}

// Call initCharts when the page loads if there are charts
if (document.querySelector('.attendance-chart') || document.querySelector('.progress-chart')) {
    initCharts();
}