// TrustBeam Credit Dashboard JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // Initialize dashboard components
    initDashboard();
    initNotifications();
    initRealTimeUpdates();
    initSidebarToggle();
    initQuickActions();
    initLogoutConfirmation();
});

// Initialize dashboard
function initDashboard() {
    console.log('TrustBeam Credit Dashboard initialized');
    
    // Add loading states to cards
    const cards = document.querySelectorAll('.overview-card, .balance-card');
    cards.forEach(card => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
    });
    
    // Animate cards on load
    setTimeout(() => {
        cards.forEach((card, index) => {
            setTimeout(() => {
                card.style.transition = 'all 0.6s ease';
                card.style.opacity = '1';
                card.style.transform = 'translateY(0)';
            }, index * 100);
        });
    }, 300);
}

// Initialize notifications
function initNotifications() {
    const notificationBtn = document.querySelector('.notification-btn');
    if (notificationBtn) {
        notificationBtn.addEventListener('click', function() {
            showNotifications();
        });
    }
}

// Show notifications modal
function showNotifications() {
    const modal = document.createElement('div');
    modal.className = 'modal-overlay';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3>Notifications</h3>
                <button class="modal-close">&times;</button>
            </div>
            <div class="modal-body">
                <div class="notification-item">
                    <div class="notification-icon">
                        <i class="fas fa-info-circle"></i>
                    </div>
                    <div class="notification-content">
                        <div class="notification-title">Welcome to TrustBeam Credit</div>
                        <div class="notification-message">Your account has been successfully activated.</div>
                        <div class="notification-time">Just now</div>
                    </div>
                </div>
                <div class="notification-item">
                    <div class="notification-icon">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                    <div class="notification-content">
                        <div class="notification-title">Security Update</div>
                        <div class="notification-message">Your account security has been enhanced.</div>
                        <div class="notification-time">2 hours ago</div>
                    </div>
                </div>
                <div class="notification-item">
                    <div class="notification-icon">
                        <i class="fas fa-credit-card"></i>
                    </div>
                    <div class="notification-content">
                        <div class="notification-title">Card Application</div>
                        <div class="notification-message">Your credit card application is under review.</div>
                        <div class="notification-time">1 day ago</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeModal()">Close</button>
                <button class="btn btn-primary" onclick="markAllRead()">Mark All Read</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Close modal functionality
    const closeBtn = modal.querySelector('.modal-close');
    closeBtn.addEventListener('click', closeModal);
    
    // Close on outside click
    modal.addEventListener('click', function(event) {
        if (event.target === modal) {
            closeModal();
        }
    });
}

// Mark all notifications as read
function markAllRead() {
    const notificationBadge = document.querySelector('.notification-badge');
    if (notificationBadge) {
        notificationBadge.style.display = 'none';
    }
    
    // Update notification count in backend
    fetch('api/notifications/mark-read.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'mark_all_read' })
    }).catch(error => {
        console.log('Notification update failed:', error);
    });
    
    closeModal();
}

// Initialize real-time updates
function initRealTimeUpdates() {
    // Update time every second
    setInterval(updateTime, 1000);
    
    // Update balance every 30 seconds (simulated)
    setInterval(updateBalance, 30000);
    
    // Check for new transactions every minute
    setInterval(checkNewTransactions, 60000);
}

// Update current time
function updateTime() {
    const timeElement = document.querySelector('.time');
    if (timeElement) {
        const now = new Date();
        const timeString = now.toLocaleTimeString('en-US', { 
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        timeElement.textContent = timeString;
    }
}

// Update balance (simulated)
function updateBalance() {
    const balanceElements = document.querySelectorAll('.balance-amount');
    balanceElements.forEach(element => {
        // Add subtle animation
        element.style.transform = 'scale(1.05)';
        setTimeout(() => {
            element.style.transform = 'scale(1)';
        }, 200);
    });
}

// Check for new transactions
function checkNewTransactions() {
    // This would typically make an AJAX call to check for new transactions
    // For now, we'll just log it
    console.log('Checking for new transactions...');
}

// Initialize sidebar toggle for mobile
function initSidebarToggle() {
    const sidebar = document.querySelector('.dashboard-sidebar');
    const toggleBtn = document.getElementById('mobileMenuToggle');
    const overlay = document.getElementById('sidebarOverlay');
    
    if (!sidebar || !toggleBtn) {
        console.log('Sidebar or toggle button not found');
        return;
    }
    
    // Toggle sidebar function
    function toggleSidebar() {
        sidebar.classList.toggle('active');
        if (overlay) {
            overlay.classList.toggle('active');
        }
        
        // Prevent body scroll when sidebar is open
        if (sidebar.classList.contains('active')) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = '';
        }
    }
    
    // Close sidebar function
    function closeSidebar() {
        sidebar.classList.remove('active');
        if (overlay) {
            overlay.classList.remove('active');
        }
        document.body.style.overflow = '';
    }
    
    // Toggle button click event
    toggleBtn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        toggleSidebar();
    });
    
    // Overlay click event (if overlay exists)
    if (overlay) {
        overlay.addEventListener('click', function() {
            closeSidebar();
        });
    }
    
    // Close sidebar when clicking outside (on mobile)
    document.addEventListener('click', function(event) {
        if (window.innerWidth <= 768 && 
            sidebar.classList.contains('active') && 
            !sidebar.contains(event.target) && 
            !toggleBtn.contains(event.target)) {
            closeSidebar();
        }
    });
    
    // Close sidebar on window resize to desktop
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768) {
            closeSidebar();
        }
    });
    
    // Close sidebar on escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape' && sidebar.classList.contains('active')) {
            closeSidebar();
        }
    });
    
    console.log('Sidebar toggle initialized successfully');
}

// Initialize quick actions
function initQuickActions() {
    const quickActionCards = document.querySelectorAll('.quick-action-card');
    
    quickActionCards.forEach(card => {
        card.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Add click animation
            card.style.transform = 'scale(0.95)';
            setTimeout(() => {
                card.style.transform = 'scale(1)';
            }, 150);
            
            // Get action type
            const actionType = card.querySelector('h3').textContent;
            
            // Handle different actions
            switch(actionType) {
                case 'Account Info':
                    window.location.href = 'account-info.php';
                    break;
                case 'Deposit':
                    window.location.href = 'deposit.php';
                    break;
                case 'History':
                    window.location.href = 'transactions.php';
                    break;
                default:
                    console.log('Action:', actionType);
            }
        });
    });
}

// Close modal function
function closeModal() {
    const modal = document.querySelector('.modal-overlay');
    if (modal) {
        modal.remove();
    }
}

// Format currency
function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount);
}

// Format date
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}

// Show success message
function showSuccessMessage(message) {
    const successDiv = document.createElement('div');
    successDiv.className = 'success-message';
    successDiv.innerHTML = `
        <i class="fas fa-check-circle"></i>
        <span>${message}</span>
    `;
    
    document.body.appendChild(successDiv);
    
    // Remove after 3 seconds
    setTimeout(() => {
        successDiv.remove();
    }, 3000);
}

// Show error message
function showErrorMessage(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.innerHTML = `
        <i class="fas fa-exclamation-circle"></i>
        <span>${message}</span>
    `;
    
    document.body.appendChild(errorDiv);
    
    // Remove after 5 seconds
    setTimeout(() => {
        errorDiv.remove();
    }, 5000);
}

// Add CSS for notifications and messages
const dashboardStyles = document.createElement('style');
dashboardStyles.textContent = `
    .notification-item {
        display: flex;
        align-items: flex-start;
        gap: 15px;
        padding: 15px 0;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .notification-item:last-child {
        border-bottom: none;
    }
    
    .notification-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #667eea;
        font-size: 1.1rem;
        flex-shrink: 0;
    }
    
    .notification-content {
        flex: 1;
    }
    
    .notification-title {
        font-weight: 600;
        color: #333;
        margin-bottom: 5px;
    }
    
    .notification-message {
        color: #6c757d;
        margin-bottom: 5px;
        line-height: 1.4;
    }
    
    .notification-time {
        font-size: 0.8rem;
        color: #999;
    }
    
    .success-message,
    .error-message {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 10001;
        display: flex;
        align-items: center;
        gap: 10px;
        animation: slideIn 0.3s ease;
    }
    
    .success-message {
        background: #28a745;
    }
    
    .error-message {
        background: #dc3545;
    }
    
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    /* Mobile Menu Toggle Styles */
    .mobile-menu-toggle {
        display: none;
        position: fixed;
        top: 20px;
        left: 20px;
        z-index: 1001;
        background: #667eea;
        color: white;
        border: none;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        font-size: 1.2rem;
        cursor: pointer;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        transition: all 0.3s ease;
    }
    
    .mobile-menu-toggle:hover {
        background: #5a6fd8;
        transform: scale(1.05);
    }
    
    .sidebar-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 998;
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    
    .sidebar-overlay.active {
        display: block;
        opacity: 1;
    }
    
    @media (max-width: 768px) {
        .mobile-menu-toggle {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .dashboard-sidebar {
            position: fixed;
            left: -300px;
            top: 0;
            height: 100vh;
            z-index: 999;
            transition: left 0.3s ease;
            width: 280px;
        }
        
        .dashboard-sidebar.active {
            left: 0;
        }
        
        .dashboard-main {
            margin-left: 0;
        }
    }
    
    .overview-card,
    .balance-card {
        transition: all 0.6s ease;
    }
    
    .quick-action-card {
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .quick-action-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
    }
    
    /* Logout Confirmation Modal Styles */
    .logout-modal {
        max-width: 450px;
        margin: 50px auto;
    }
    
    .logout-modal .modal-header h3 {
        color: #dc3545;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .logout-message {
        display: flex;
        align-items: center;
        gap: 20px;
        padding: 20px 0;
    }
    
    .logout-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background: #fff3cd;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #856404;
        font-size: 1.5rem;
        flex-shrink: 0;
    }
    
    .logout-text {
        flex: 1;
    }
    
    .logout-text p {
        margin: 0 0 10px 0;
        line-height: 1.5;
    }
    
    .logout-text p:last-child {
        margin-bottom: 0;
        color: #6c757d;
        font-size: 0.95rem;
    }
    
    .modal-footer {
        display: flex;
        gap: 15px;
        justify-content: flex-end;
        padding: 20px 0 0 0;
        border-top: 1px solid #e9ecef;
    }
    
    .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 6px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        gap: 8px;
        text-decoration: none;
    }
    
    .btn-secondary {
        background: #6c757d;
        color: white;
    }
    
    .btn-secondary:hover {
        background: #5a6268;
        transform: translateY(-1px);
    }
    
    .btn-danger {
        background: #dc3545;
        color: white;
    }
    
    .btn-danger:hover {
        background: #c82333;
        transform: translateY(-1px);
    }
    
    /* Logout Loading Styles */
    .logout-loading {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10002;
    }
    
    .loading-content {
        background: white;
        padding: 40px;
        border-radius: 10px;
        text-align: center;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    }
    
    .loading-content i {
        font-size: 2rem;
        color: #667eea;
        margin-bottom: 15px;
    }
    
    .loading-content p {
        margin: 0;
        font-size: 1.1rem;
        color: #2c3e50;
        font-weight: 500;
    }
    
    /* Modal Overlay Styles */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10001;
        animation: fadeIn 0.3s ease;
    }
    
    .modal-content {
        background: white;
        border-radius: 10px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        max-width: 90%;
        max-height: 90%;
        overflow: auto;
        animation: slideIn 0.3s ease;
    }
    
    .modal-header {
        padding: 20px 25px 15px;
        border-bottom: 1px solid #e9ecef;
    }
    
    .modal-body {
        padding: 20px 25px;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    @keyframes slideIn {
        from { 
            transform: translateY(-20px);
            opacity: 0;
        }
        to { 
            transform: translateY(0);
            opacity: 1;
        }
    }
`;

document.head.appendChild(dashboardStyles);

// Initialize logout confirmation
function initLogoutConfirmation() {
    const logoutLinks = document.querySelectorAll('a[href*="logout.php"]');
    
    logoutLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            showLogoutConfirmation(link.href);
        });
    });
    
    console.log('Logout confirmation initialized');
}

// Show logout confirmation dialog
function showLogoutConfirmation(logoutUrl) {
    const modal = document.createElement('div');
    modal.className = 'modal-overlay';
    modal.innerHTML = `
        <div class="modal-content logout-modal">
            <div class="modal-header">
                <h3><i class="fas fa-sign-out-alt"></i> Confirm Logout</h3>
            </div>
            <div class="modal-body">
                <div class="logout-message">
                    <div class="logout-icon">
                        <i class="fas fa-question-circle"></i>
                    </div>
                    <div class="logout-text">
                        <p><strong>Are you sure you want to logout?</strong></p>
                        <p>You will need to sign in again to access your account.</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeLogoutModal()">
                    <i class="fas fa-times"></i> No, Cancel
                </button>
                <button class="btn btn-danger" onclick="confirmLogout('${logoutUrl}')">
                    <i class="fas fa-sign-out-alt"></i> Yes, Logout
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Close on outside click
    modal.addEventListener('click', function(event) {
        if (event.target === modal) {
            closeLogoutModal();
        }
    });
    
    // Close on escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeLogoutModal();
        }
    });
}

// Close logout modal
function closeLogoutModal() {
    const modal = document.querySelector('.modal-overlay');
    if (modal) {
        modal.remove();
    }
}

// Confirm logout and redirect
function confirmLogout(logoutUrl) {
    closeLogoutModal();
    
    // Show loading state
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'logout-loading';
    loadingDiv.innerHTML = `
        <div class="loading-content">
            <i class="fas fa-spinner fa-spin"></i>
            <p>Logging out...</p>
        </div>
    `;
    document.body.appendChild(loadingDiv);
    
    // Redirect after short delay
    setTimeout(() => {
        window.location.href = logoutUrl;
    }, 1000);
}
