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

    // Initialize popovers
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });

    // Auto-dismiss alerts after 5 seconds
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }, 5000);
    });

    // Enable dropdowns on hover for desktop
    if (window.innerWidth > 992) {
        const dropdowns = document.querySelectorAll('.dropdown-hover');
        dropdowns.forEach(function(dropdown) {
            dropdown.addEventListener('mouseenter', function() {
                this.classList.add('show');
                this.querySelector('.dropdown-menu').classList.add('show');
            });
            dropdown.addEventListener('mouseleave', function() {
                this.classList.remove('show');
                this.querySelector('.dropdown-menu').classList.remove('show');
            });
        });
    }

    // Handle date/time pickers
    const dateInputs = document.querySelectorAll('.datepicker');
    dateInputs.forEach(function(input) {
        new Datepicker(input, {
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayHighlight: true
        });
    });

    // Handle time inputs
    const timeInputs = document.querySelectorAll('.timepicker');
    timeInputs.forEach(function(input) {
        new Timepicker(input, {
            showMeridian: false,
            minuteStep: 15
        });
    });

    // Handle form submissions with confirmation
    const confirmForms = document.querySelectorAll('form[data-confirm]');
    confirmForms.forEach(function(form) {
        form.addEventListener('submit', function(e) {
            if (!confirm(this.getAttribute('data-confirm'))) {
                e.preventDefault();
                return false;
            }
            return true;
        });
    });

    // Toggle password visibility
    const togglePasswordBtns = document.querySelectorAll('.toggle-password');
    togglePasswordBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const input = this.previousElementSibling;
            const icon = this.querySelector('i');
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    });

    // Handle task status changes
    const statusSelects = document.querySelectorAll('.status-select');
    statusSelects.forEach(function(select) {
        select.addEventListener('change', function() {
            const form = this.closest('form');
            if (form) {
                form.submit();
            }
        });
    });

    // Handle priority changes
    const prioritySelects = document.querySelectorAll('.priority-select');
    prioritySelects.forEach(function(select) {
        select.addEventListener('change', function() {
            const form = this.closest('form');
            if (form) {
                form.submit();
            }
        });
    });

    // Initialize any charts if present
    if (typeof Chart !== 'undefined') {
        initializeCharts();
    }
});

// Function to initialize charts
function initializeCharts() {
    // Example chart initialization
    const ctx = document.getElementById('taskStatusChart');
    if (ctx) {
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['To Do', 'In Progress', 'In Review', 'Done'],
                datasets: [{
                    data: JSON.parse(ctx.getAttribute('data-counts') || '[0, 0, 0, 0]'),
                    backgroundColor: [
                        '#6c757d',
                        '#0dcaf0',
                        '#6f42c1',
                        '#198754'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                    }
                }
            }
        });
    }
}

// Function to handle file upload previews
function handleFileUploadPreview(input, previewId) {
    const preview = document.getElementById(previewId);
    const file = input.files[0];
    const reader = new FileReader();

    reader.onloadend = function() {
        preview.src = reader.result;
        preview.style.display = 'block';
    }

    if (file) {
        reader.readAsDataURL(file);
    } else {
        preview.src = '';
        preview.style.display = 'none';
    }
}

// Function to format dates nicely
function formatDate(dateString) {
    const options = { 
        year: 'numeric', 
        month: 'short', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    };
    return new Date(dateString).toLocaleDateString(undefined, options);
}

// Function to update relative time (e.g., "2 hours ago")
function updateRelativeTimes() {
    const timeElements = document.querySelectorAll('.time-ago');
    timeElements.forEach(function(element) {
        const timestamp = new Date(element.getAttribute('datetime'));
        const seconds = Math.floor((new Date() - timestamp) / 1000);
        
        let interval = Math.floor(seconds / 31536000);
        if (interval > 1) {
            element.textContent = interval + ' years ago';
            return;
        }
        
        interval = Math.floor(seconds / 2592000);
        if (interval > 1) {
            element.textContent = interval + ' months ago';
            return;
        }
        
        interval = Math.floor(seconds / 86400);
        if (interval > 1) {
            element.textContent = interval + ' days ago';
            return;
        }
        
        interval = Math.floor(seconds / 3600);
        if (interval > 1) {
            element.textContent = interval + ' hours ago';
            return;
        }
        
        interval = Math.floor(seconds / 60);
        if (interval > 1) {
            element.textContent = interval + ' minutes ago';
            return;
        }
        
        element.textContent = 'Just now';
    });
}

// Update relative times on page load and then every minute
updateRelativeTimes();
setInterval(updateRelativeTimes, 60000);
