document.addEventListener('DOMContentLoaded', () => {
    // --- Chat Widget Logic ---
    const chatForm = document.getElementById('chat-form');
    const chatInput = document.getElementById('chat-input');
    const chatMessages = document.getElementById('chat-messages');

    if (chatForm && chatInput && chatMessages) {
        const appendMessage = (text, sender) => {
            const msgDiv = document.createElement('div');
            msgDiv.classList.add('message', sender);
            msgDiv.textContent = text;
            chatMessages.appendChild(msgDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        };

        chatForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const message = chatInput.value.trim();
            if (!message) return;

            appendMessage(message, 'visitor');
            chatInput.value = '';

            try {
                const response = await fetch('api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });
                const data = await response.json();
                
                // Artificial delay for realism
                setTimeout(() => {
                    appendMessage(data.reply, 'bot');
                }, 500);
            } catch (error) {
                console.error('Error:', error);
                appendMessage("Sorry, something went wrong. Please try again.", 'bot');
            }
        });
    }

    // --- Patient Form: Auto-calculate DOB from Age ---
    // Use jQuery for better compatibility with Inputmask and existing events
    function setupAgeToDob(ageId, dobId) {
        $(document).on('input', '#' + ageId, function() {
            var age = parseInt($(this).val());
            var $dob = $('#' + dobId);
            
            if (!isNaN(age) && age >= 0) {
                var currentYear = new Date().getFullYear();
                var birthYear = currentYear - age;
                // Default to Jan 1st of the birth year: YYYY-01-01
                var dob = birthYear + '-01-01'; 
                
                // Set value and trigger input/change for Inputmask and other listeners
                $dob.val(dob).trigger('input').trigger('change');
            } else {
                // Optional: Clear DOB if age is invalid/cleared? 
                // $dob.val('').trigger('input');
            }
        });
    }

    setupAgeToDob('add_patient_age', 'add_patient_dob');
    setupAgeToDob('edit_patient_age', 'edit_patient_dob');
});
