/**
 * Flexi Access Bank - Main JavaScript
 * Handles modals, alerts, forms, and interactive features
 */

// ============================================
// TOAST NOTIFICATIONS
// ============================================
function showToast(message, type = 'success', duration = 4000) {
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
    }

    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
        <div style="display:flex;align-items:center;gap:10px;">
            <span>${type === 'success' ? '✓' : type === 'error' ? '✕' : 'ℹ'}</span>
            <span>${message}</span>
        </div>
    `;
    container.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('hiding');
        setTimeout(() => toast.remove(), 300);
    }, duration);
}

// ============================================
// MODAL SYSTEM
// ============================================
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }
}

// Close modal on backdrop click
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-overlay')) {
        e.target.classList.remove('active');
        document.body.style.overflow = '';
    }
});

// Close modal on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.querySelectorAll('.modal-overlay.active').forEach(modal => {
            modal.classList.remove('active');
        });
        document.body.style.overflow = '';
    }
});

// ============================================
// SIDEBAR TOGGLE
// ============================================
function toggleSidebar() {
    const sidebar = document.querySelector('.sidebar');
    if (sidebar) {
        sidebar.classList.toggle('open');
    }
}

// ============================================
// COPY TO CLIPBOARD
// ============================================
function copyToClipboard(text, btn) {
    navigator.clipboard.writeText(text).then(() => {
        const original = btn.innerHTML;
        btn.innerHTML = '<span>Copied!</span>';
        btn.style.background = '#10B981';
        showToast('Copied to clipboard!', 'success');
        setTimeout(() => {
            btn.innerHTML = original;
            btn.style.background = '';
        }, 2000);
    }).catch(() => {
        // Fallback for older browsers
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        showToast('Copied to clipboard!', 'success');
    });
}

// ============================================
// PIN INPUT AUTO-FOCUS
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    const pinInputs = document.querySelectorAll('.pin-input');
    pinInputs.forEach((input, index) => {
        input.addEventListener('input', function() {
            if (this.value.length === 1 && index < pinInputs.length - 1) {
                pinInputs[index + 1].focus();
            }
        });
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Backspace' && this.value === '' && index > 0) {
                pinInputs[index - 1].focus();
            }
        });
    });
});

// ============================================
// CONFIRM DIALOGS
// ============================================
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// ============================================
// TABS
// ============================================
function switchTab(tabId, contentId) {
    // Hide all tab contents
    const tabContents = document.querySelectorAll('.tab-content');
    tabContents.forEach(content => content.classList.add('hidden'));
    
    // Show selected content
    const selectedContent = document.getElementById(contentId);
    if (selectedContent) {
        selectedContent.classList.remove('hidden');
    }
    
    // Update tab buttons
    const tabButtons = document.querySelectorAll('.tab-btn');
    tabButtons.forEach(btn => btn.classList.remove('active'));
    
    const selectedTab = document.querySelector(`[data-tab="${tabId}"]`);
    if (selectedTab) {
        selectedTab.classList.add('active');
    }
}

// ============================================
// FILE UPLOAD PREVIEW
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    const fileUploads = document.querySelectorAll('.file-upload');
    fileUploads.forEach(upload => {
        const input = upload.querySelector('input[type="file"]');
        const text = upload.querySelector('.file-upload-text');
        const originalText = text ? text.innerHTML : '';
        
        upload.addEventListener('click', () => input.click());
        upload.addEventListener('dragover', (e) => {
            e.preventDefault();
            upload.style.borderColor = 'var(--primary)';
        });
        upload.addEventListener('dragleave', () => {
            upload.style.borderColor = '';
        });
        upload.addEventListener('drop', (e) => {
            e.preventDefault();
            upload.style.borderColor = '';
            input.files = e.dataTransfer.files;
            if (text && input.files.length > 0) {
                text.innerHTML = `<span>${input.files[0].name}</span>`;
            }
        });
        
        if (input) {
            input.addEventListener('change', () => {
                if (text && input.files.length > 0) {
                    text.innerHTML = `<span>${input.files[0].name}</span>`;
                }
            });
        }
    });
});

// ============================================
// AMOUNT FORMATTING
// ============================================
function formatAmount(input) {
    let value = input.value.replace(/[^\d.]/g, '');
    const parts = value.split('.');
    if (parts.length > 2) {
        value = parts[0] + '.' + parts.slice(1).join('');
    }
    input.value = value;
}

// ============================================
// LOADING STATES
// ============================================
function setLoading(button, loading = true) {
    if (loading) {
        button.dataset.originalText = button.innerHTML;
        button.innerHTML = '<span class="loading">Processing...</span>';
        button.disabled = true;
    } else {
        button.innerHTML = button.dataset.originalText || button.innerHTML;
        button.disabled = false;
    }
}

// ============================================
// SEARCH FILTER
// ============================================
function filterTable(input, tableSelector) {
    const filter = input.value.toLowerCase();
    const table = document.querySelector(tableSelector);
    if (!table) return;
    
    const rows = table.querySelectorAll('tbody tr');
    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(filter) ? '' : 'none';
    });
}

// ============================================
// PASSWORD TOGGLE
// ============================================
function togglePassword(inputId, btn) {
    const input = document.getElementById(inputId);
    if (input.type === 'password') {
        input.type = 'text';
        btn.innerHTML = '👁️';
    } else {
        input.type = 'password';
        btn.innerHTML = '👁️‍🗨️';
    }
}

// ============================================
// CONFIRM DELETE
// ============================================
function confirmDelete(message) {
    return confirm(message || 'Are you sure you want to delete this item? This action cannot be undone.');
}

// ============================================
// AJAX HELPERS
// ============================================
function ajaxPost(url, data, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.onload = function() {
        if (callback) callback(xhr.status === 200, xhr.responseText);
    };
    
    const params = new URLSearchParams();
    for (const key in data) {
        params.append(key, data[key]);
    }
    xhr.send(params.toString());
}

function ajaxGet(url, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.onload = function() {
        if (callback) callback(xhr.status === 200, xhr.responseText);
    };
    xhr.send();
}

// ============================================
// LOAN CALCULATOR
// ============================================
function calculateLoan() {
    const amount = parseFloat(document.getElementById('loan-amount').value) || 0;
    const rate = parseFloat(document.getElementById('loan-rate').value) || 0;
    const months = parseInt(document.getElementById('loan-months').value) || 0;
    
    if (amount > 0 && rate > 0 && months > 0) {
        const monthlyRate = rate / 100 / 12;
        const payment = (amount * monthlyRate * Math.pow(1 + monthlyRate, months)) / 
                       (Math.pow(1 + monthlyRate, months) - 1);
        const totalPayment = payment * months;
        const totalInterest = totalPayment - amount;
        
        document.getElementById('loan-monthly').textContent = '$' + payment.toFixed(2);
        document.getElementById('loan-total').textContent = '$' + totalPayment.toFixed(2);
        document.getElementById('loan-interest').textContent = '$' + totalInterest.toFixed(2);
    }
}

// ============================================
// AUTO-DISMISS ALERTS
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        setTimeout(() => {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 500);
        }, 5000);
    });
});

// ============================================
// DROPDOWN MENUS
// ============================================
document.addEventListener('click', function(e) {
    const dropdown = e.target.closest('.dropdown');
    if (dropdown) {
        dropdown.classList.toggle('open');
    }
    
    // Close other dropdowns
    document.querySelectorAll('.dropdown.open').forEach(d => {
        if (d !== dropdown) d.classList.remove('open');
    });
});

// Close dropdowns on outside click
document.addEventListener('click', function(e) {
    if (!e.target.closest('.dropdown')) {
        document.querySelectorAll('.dropdown.open').forEach(d => d.classList.remove('open'));
    }
});
