(function() {
    document.addEventListener('DOMContentLoaded', function() {
        createAccountModal();
        
        const accountSettingsBtn = document.getElementById('accountSettingsBtn');
        if (accountSettingsBtn) {
            accountSettingsBtn.addEventListener('click', openAccountModal);
        }
    });
    
    function createAccountModal() {
        const modalHtml = `
            <div id="accountStandaloneModal" class="fixed inset-0 bg-black bg-opacity-40 flex items-end justify-center sm:items-center" style="z-index: 100; display: none;">
                <div class="absolute inset-0" id="accountModalOverlay"></div>
                <div class="bg-white rounded-t-2xl sm:rounded-2xl w-full max-w-md mx-4 shadow-xl" style="transform: translateY(0); transition: transform 0.3s ease; animation: fadeIn 0.3s;">
                    <div class="w-full flex justify-center pt-2 pb-1 sm:hidden">
                        <div class="w-40 h-5 bg-gray-200 rounded-full mx-auto"></div>
                    </div>
                    <div class="p-5 border-b flex justify-between items-center">
                        <h2 class="text-lg font-semibold">Account Settings</h2>
                        <button id="closeAccountModal" class="text-gray-500 hover:text-gray-700 p-1">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <div id="accountGuestView" class="p-5 space-y-6" style="display: none;">
                        <div class="bg-gray-100 p-4 rounded-xl text-center">
                            <div class="w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center mx-auto mb-3">
                                <i class="fas fa-user text-gray-400 text-2xl"></i>
                            </div>
                            <h3 class="font-semibold text-lg">Guest Mode</h3>
                            <p class="text-sm text-gray-500 mt-2">You're currently using TrafficLight as a guest. Create an account to save your traffic lights and routes.</p>
                        </div>
                        
                        <div class="flex flex-col gap-3">
                            <button id="accountSignInBtn" class="bg-blue-500 hover:bg-blue-600 text-white font-medium px-4 py-2.5 rounded-lg transition-colors flex items-center justify-center gap-2">
                                <i class="fas fa-sign-in-alt"></i> Sign In
                            </button>
                            <button id="accountCreateBtn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium px-4 py-2.5 rounded-lg transition-colors flex items-center justify-center gap-2">
                                <i class="fas fa-user-plus"></i> Create Account
                            </button>
                        </div>
                    </div>
                    
                    <div id="accountUserView" class="p-5 space-y-6" style="display: none;">
                        <div class="bg-gray-100 p-4 rounded-xl">
                            <div class="flex items-center mb-2">
                                <div class="w-14 h-14 bg-blue-500 rounded-full flex items-center justify-center text-white mr-3">
                                    <i class="fas fa-user text-xl"></i>
                                </div>
                                <div>
                                    <h3 class="font-semibold text-lg" id="standaloneAccountUserName"></h3>
                                    <p class="text-sm text-gray-500" id="standaloneAccountUserEmail"></p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="space-y-5">
                            <div>
                                <h4 class="font-medium text-gray-700 mb-3">Profile Information</h4>
                                <div class="space-y-3">
                                    <div>
                                        <label class="block text-sm font-medium mb-1.5">Full Name</label>
                                        <input type="text" id="standaloneAccountFullName" class="w-full px-3.5 py-2.5 bg-gray-100 border-0 rounded-lg focus:ring-2 focus:ring-blue-500 focus:bg-white">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium mb-1.5">Email</label>
                                        <input type="email" id="standaloneAccountEmail" class="w-full px-3.5 py-2.5 bg-gray-100 border-0 rounded-lg focus:ring-2 focus:ring-blue-500 focus:bg-white" readonly>
                                    </div>
                                </div>
                            </div>
                            
                            <div>
                                <h4 class="font-medium text-gray-700 mb-3">Change Password</h4>
                                <div class="space-y-3">
                                    <div>
                                        <label class="block text-sm font-medium mb-1.5">Current Password</label>
                                        <input type="password" id="standaloneAccountCurrentPassword" class="w-full px-3.5 py-2.5 bg-gray-100 border-0 rounded-lg focus:ring-2 focus:ring-blue-500 focus:bg-white">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium mb-1.5">New Password</label>
                                        <input type="password" id="standaloneAccountNewPassword" class="w-full px-3.5 py-2.5 bg-gray-100 border-0 rounded-lg focus:ring-2 focus:ring-blue-500 focus:bg-white">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium mb-1.5">Confirm New Password</label>
                                        <input type="password" id="standaloneAccountConfirmPassword" class="w-full px-3.5 py-2.5 bg-gray-100 border-0 rounded-lg focus:ring-2 focus:ring-blue-500 focus:bg-white">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="border-t pt-5">
                                <div class="flex gap-3">
                                    <button id="standaloneAccountSaveBtn" class="bg-blue-500 hover:bg-blue-600 text-white font-medium px-4 py-2.5 rounded-lg transition-colors flex-1 flex items-center justify-center gap-2">
                                        <i class="fas fa-save"></i> Save Changes
                                    </button>
                                    <button id="standaloneAccountLogoutBtn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium px-4 py-2.5 rounded-lg transition-colors flex items-center justify-center gap-2 w-12">
                                        <i class="fas fa-sign-out-alt"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = modalHtml;
        document.body.appendChild(tempDiv.firstElementChild);
        
        document.getElementById('closeAccountModal').addEventListener('click', closeAccountModal);
        document.getElementById('accountModalOverlay').addEventListener('click', closeAccountModal);
        document.getElementById('accountSignInBtn').addEventListener('click', refreshPage);
        document.getElementById('accountCreateBtn').addEventListener('click', refreshPage);
        document.getElementById('standaloneAccountSaveBtn').addEventListener('click', saveAccountChanges);
        document.getElementById('standaloneAccountLogoutBtn').addEventListener('click', logoutUser);
    }
    
    function openAccountModal() {
        const modal = document.getElementById('accountStandaloneModal');
        const userInfo = localStorage.getItem('trafficLightUser');
        const token = localStorage.getItem('trafficLightToken');
        
        if (!userInfo || !token) {
            document.getElementById('accountGuestView').style.display = 'block';
            document.getElementById('accountUserView').style.display = 'none';
        } else {
            try {
                const user = JSON.parse(userInfo);
                document.getElementById('accountGuestView').style.display = 'none';
                document.getElementById('accountUserView').style.display = 'block';
                
                document.getElementById('standaloneAccountUserName').textContent = user.username || '';
                document.getElementById('standaloneAccountUserEmail').textContent = user.email || '';
                document.getElementById('standaloneAccountFullName').value = user.username || '';
                document.getElementById('standaloneAccountEmail').value = user.email || '';
                
                document.getElementById('standaloneAccountCurrentPassword').value = '';
                document.getElementById('standaloneAccountNewPassword').value = '';
                document.getElementById('standaloneAccountConfirmPassword').value = '';
            } catch (e) {
                document.getElementById('accountGuestView').style.display = 'block';
                document.getElementById('accountUserView').style.display = 'none';
            }
        }
        
        // Hide any dropdown that might be open
        const dropdowns = document.querySelectorAll('.show');
        dropdowns.forEach(dropdown => {
            dropdown.classList.remove('show');
        });
        
        modal.style.display = 'flex';
    }
    
    function closeAccountModal() {
        const modal = document.getElementById('accountStandaloneModal');
        const modalBody = modal.querySelector('div:nth-child(2)');
        
        modalBody.style.transform = 'translateY(100%)';
        
        setTimeout(() => {
            modal.style.display = 'none';
            modalBody.style.transform = 'translateY(0)';
        }, 300);
    }
    
    function refreshPage() {
        closeAccountModal();
        window.location.reload();
    }
    
    function saveAccountChanges() {
        const fullName = document.getElementById('standaloneAccountFullName').value.trim();
        const currentPassword = document.getElementById('standaloneAccountCurrentPassword').value;
        const newPassword = document.getElementById('standaloneAccountNewPassword').value;
        const confirmPassword = document.getElementById('standaloneAccountConfirmPassword').value;
        
        if (!fullName) {
            showAccountNotification('Please enter your full name', 'error');
            return;
        }
        
        if (currentPassword || newPassword || confirmPassword) {
            if (!currentPassword) {
                showAccountNotification('Please enter your current password', 'error');
                return;
            }
            
            if (!newPassword) {
                showAccountNotification('Please enter your new password', 'error');
                return;
            }
            
            if (newPassword !== confirmPassword) {
                showAccountNotification('New passwords do not match', 'error');
                return;
            }
            
            if (newPassword.length < 6) {
                showAccountNotification('New password must be at least 6 characters', 'error');
                return;
            }
        }
        
        const saveBtn = document.getElementById('standaloneAccountSaveBtn');
        const originalText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div> Updating...';
        saveBtn.disabled = true;
        
        const userInfo = JSON.parse(localStorage.getItem('trafficLightUser'));
        
        const data = {
            user_id: userInfo.id,
            full_name: fullName,
            current_password: currentPassword,
            new_password: newPassword
        };
        
        fetch('db.php?action=updateAccount', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                userInfo.username = fullName;
                localStorage.setItem('trafficLightUser', JSON.stringify(userInfo));
                
                // Update username in UI if possible
                const mainUserNameEl = document.getElementById('userName');
                if (mainUserNameEl) {
                    mainUserNameEl.textContent = fullName;
                }
                
                showAccountNotification('Account updated successfully', 'success');
                
                document.getElementById('standaloneAccountCurrentPassword').value = '';
                document.getElementById('standaloneAccountNewPassword').value = '';
                document.getElementById('standaloneAccountConfirmPassword').value = '';
                
                setTimeout(() => {
                    closeAccountModal();
                }, 1000);
            } else {
                showAccountNotification(data.message || 'Update failed', 'error');
            }
            
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;
        })
        .catch(error => {
            showAccountNotification('Connection error', 'error');
            
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;
        });
    }
    
    function logoutUser() {
        closeAccountModal();
        
        fetch('db.php?action=logout', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            localStorage.removeItem('trafficLightToken');
            localStorage.removeItem('trafficLightUser');
            
            showAccountNotification('Signed out successfully', 'info');
            
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        })
        .catch(error => {
            // Even if there's an error, clear local storage and reload
            localStorage.removeItem('trafficLightToken');
            localStorage.removeItem('trafficLightUser');
            window.location.reload();
        });
    }
    
    function showAccountNotification(message, type) {
        const colors = {
            success: '#10b981', // green
            error: '#ef4444',   // red
            info: '#0ea5e9'     // blue
        };
        
        const notification = document.createElement('div');
        notification.style.position = 'fixed';
        notification.style.top = '80px';
        notification.style.left = '50%';
        notification.style.transform = 'translateX(-50%)';
        notification.style.backgroundColor = colors[type];
        notification.style.color = 'white';
        notification.style.padding = '10px 15px';
        notification.style.borderRadius = '8px';
        notification.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
        notification.style.zIndex = '200';
        notification.style.display = 'flex';
        notification.style.alignItems = 'center';
        notification.style.animation = 'fadeIn 0.3s';
        
        const icon = document.createElement('i');
        icon.className = `fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} mr-2`;
        
        const text = document.createTextNode(message);
        
        notification.appendChild(icon);
        notification.appendChild(text);
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translate(-50%, -10px)';
            notification.style.transition = 'opacity 0.5s, transform 0.5s';
            
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 500);
        }, 3000);
    }
})();