/**
 * Custom JavaScript for Aplikasi Donasi Online
 */

document.addEventListener('DOMContentLoaded', function() {
    
    // Navbar Scroll Effect
    const navbar = document.querySelector('.navbar');
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                navbar.classList.add('shadow');
            } else {
                navbar.classList.remove('shadow');
            }
        });
    }
    
    // Auto-dismiss flash messages after 5 seconds
    const flashMessages = document.querySelectorAll('.alert:not(.alert-permanent)');
    flashMessages.forEach(function(flash) {
        setTimeout(function() {
            const bsAlert = bootstrap.Alert.getOrCreateInstance(flash);
            bsAlert.close();
        }, 5000);
    });
    
    // Form Validation for Donasi
    const donasiForm = document.getElementById('donasi-form');
    if (donasiForm) {
        donasiForm.addEventListener('submit', function(event) {
            const jumlahDonasi = document.getElementById('jumlah_donasi');
            
            // Reset error messages
            document.querySelectorAll('.invalid-feedback').forEach(function(el) {
                el.style.display = 'none';
            });
            document.querySelectorAll('.is-invalid').forEach(function(el) {
                el.classList.remove('is-invalid');
            });
            
            // Validate jumlah donasi
            if (jumlahDonasi && (isNaN(jumlahDonasi.value) || jumlahDonasi.value <= 0)) {
                event.preventDefault();
                jumlahDonasi.classList.add('is-invalid');
                const errorMsg = document.createElement('div');
                errorMsg.className = 'invalid-feedback';
                errorMsg.textContent = 'Jumlah donasi harus berupa angka dan lebih dari 0';
                jumlahDonasi.parentNode.appendChild(errorMsg);
            }
        });
    }
    
    // Preview image before upload
    const imageInputs = document.querySelectorAll('.image-upload');
    imageInputs.forEach(function(input) {
        input.addEventListener('change', function(event) {
            const preview = document.getElementById(this.dataset.preview);
            if (preview && this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    });
    
    // Konfirmasi delete
    const deleteButtons = document.querySelectorAll('.btn-delete');
    deleteButtons.forEach(function(button) {
        button.addEventListener('click', function(event) {
            if (!confirm('Apakah Anda yakin ingin menghapus data ini?')) {
                event.preventDefault();
            }
        });
    });
    
    // Format input rupiah
    const rupiahInputs = document.querySelectorAll('.rupiah-input');
    rupiahInputs.forEach(function(input) {
        input.addEventListener('keyup', function(e) {
            // Skip for arrow keys
            if(e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
                return;
            }
            
            // Remove all non-digit characters
            let value = this.value.replace(/\D/g, '');
            
            // Format the value
            if (value !== '') {
                value = parseInt(value, 10).toLocaleString('id-ID');
            }
            
            // Update the value
            this.value = value;
        });
        
        // On form submit, remove the formatting
        input.form.addEventListener('submit', function() {
            input.value = input.value.replace(/\D/g, '');
        });
    });
    
    // Donasi otomatis form toggle
    const otomatisCheckbox = document.getElementById('donasi_otomatis');
    const otomatisOptions = document.getElementById('opsi-donasi-otomatis');
    
    if (otomatisCheckbox && otomatisOptions) {
        otomatisCheckbox.addEventListener('change', function() {
            if (this.checked) {
                otomatisOptions.style.display = 'block';
            } else {
                otomatisOptions.style.display = 'none';
            }
        });
        
        // Initial state
        otomatisOptions.style.display = otomatisCheckbox.checked ? 'block' : 'none';
    }
    
    // Initialize tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Countdown for kampanye aktif
    const countdowns = document.querySelectorAll('.countdown');
    countdowns.forEach(function(countdown) {
        const endDate = new Date(countdown.dataset.end).getTime();
        
        // Update every second
        const timer = setInterval(function() {
            const now = new Date().getTime();
            const distance = endDate - now;
            
            // Calculate days, hours, minutes, seconds
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            
            // Display result
            countdown.innerHTML = `${days}h ${hours}j ${minutes}m ${seconds}d`;
            
            // Clear when finished
            if (distance < 0) {
                clearInterval(timer);
                countdown.innerHTML = "Berakhir";
            }
        }, 1000);
    });

});