// Application State
let currentUser = null;
let currentUserEmail = null;
let isAdmin = false;
let users = [];
let investments = [];
let transactions = [];
let adminSettings = {
    packages: [],
    referralBonus: {
        level1: 10,
        level2: 2
    },
    recommitment: {
        enabled: true,
        percentage: 50
    }
};

// Investment limits
const MIN_INVESTMENT = 5000;
const MAX_INVESTMENT = 300000;
const MIN_BONUS_WITHDRAWAL = 5000; // Updated minimum for direct bonus withdrawal
const MIN_WITHDRAWAL = 5000;

// DOM Elements
const sections = document.querySelectorAll('.section');
const navLinks = document.querySelectorAll('.nav-link');
const hamburger = document.getElementById('hamburger');
const navMenu = document.getElementById('nav-menu');

const navHome = document.getElementById('nav-home');
const navLogin = document.getElementById('nav-login');
const navRegister = document.getElementById('nav-register');
const navDashboard = document.getElementById('nav-dashboard');
const navLogout = document.getElementById('nav-logout');

const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const forgotPasswordForm = document.getElementById('forgot-password-form');

const userNameElement = document.getElementById('user-name');
const userReferralCodeElement = document.getElementById('user-referral-code');
const userInvestmentsElement = document.getElementById('user-investments');
const transactionHistoryElement = document.getElementById('transaction-history');
const investmentSummary = document.getElementById('investment-summary');
const totalInvestedElement = document.getElementById('total-invested');
const totalExpectedElement = document.getElementById('total-expected');
const activeInvestmentsElement = document.getElementById('active-investments');
const totalProfitElement = document.getElementById('total-profit');
const withdrawalBalanceElement = document.getElementById('withdrawal-balance');
const referralBonusElement = document.getElementById('referral-bonus');
const transferBonusButton = document.getElementById('transfer-bonus'); // Keeps ID but acts as Withdraw Bonus
const withdrawFundsButton = document.getElementById('withdraw-funds');
const packagesGrid = document.getElementById('packages-grid');

const usersListElement = document.getElementById('users-list');
const packageControlsElement = document.getElementById('package-controls');
const addPackageButton = document.getElementById('add-package-btn');
const level1BonusInput = document.getElementById('level1-bonus');
const level2BonusInput = document.getElementById('level2-bonus');
const recommitmentEnabledInput = document.getElementById('recommitment-enabled');
const recommitmentPercentageInput = document.getElementById('recommitment-percentage');
const saveReferralSettingsButton = document.getElementById('save-referral-settings');
const userSearchInput = document.getElementById('user-search');
const withdrawalRequestsListElement = document.getElementById('withdrawal-requests-list');
const pendingInvestmentsListElement = document.getElementById('pending-investments-list');
const pendingWalletRecommitmentsListElement = document.getElementById('pending-wallet-recommitments-list');

const investmentModal = document.getElementById('investment-modal');
const withdrawalModal = document.getElementById('withdrawal-modal');
const walletRecommitmentModal = document.getElementById('wallet-recommitment-modal');
const creditUserModal = document.getElementById('credit-user-modal');
const debitUserModal = document.getElementById('debit-user-modal');
const editBankModal = document.getElementById('edit-bank-modal');
const suspendUserModal = document.getElementById('suspend-user-modal');
const deleteUserModal = document.getElementById('delete-user-modal');
const deleteInvestmentModal = document.getElementById('delete-investment-modal');
const userInvestmentsModal = document.getElementById('user-investments-modal');
const proofViewModal = document.getElementById('proof-view-modal');
const successModal = document.getElementById('success-modal');
const closeModalButtons = document.querySelectorAll('.close');
const confirmInvestmentButton = document.getElementById('confirm-investment');
const confirmWithdrawalButton = document.getElementById('confirm-withdrawal');
const confirmWalletRecommitmentButton = document.getElementById('confirm-wallet-recommitment');
const confirmCreditButton = document.getElementById('confirm-credit');
const confirmDebitButton = document.getElementById('confirm-debit');
const confirmBankEditButton = document.getElementById('confirm-bank-edit');
const confirmSuspendButton = document.getElementById('confirm-suspend');
const confirmDeleteButton = document.getElementById('confirm-delete');
const confirmInvestmentDeleteButton = document.getElementById('confirm-investment-delete');
const cancelInvestmentDeleteButton = document.getElementById('cancel-investment-delete');
const cancelSuspendButton = document.getElementById('cancel-suspend');
const cancelDeleteButton = document.getElementById('cancel-delete');
const successOkButton = document.getElementById('success-ok');
const investmentAmountInput = document.getElementById('investment-amount');
const withdrawalAmountInput = document.getElementById('withdrawal-amount');
const recommitmentAmountInput = document.getElementById('recommitment-amount');
const availableWithdrawalElement = document.getElementById('available-withdrawal');

const previewAmount = document.getElementById('preview-amount');
const previewProfit = document.getElementById('preview-profit');
const previewTotal = document.getElementById('preview-total');
const previewMaturity = document.getElementById('preview-maturity');
const previewDurationDays = document.getElementById('preview-duration-days');

// DOM Elements for Math Challenge
const mathQuestionElement = document.getElementById('math-question');
const mathAnswerInput = document.getElementById('math-answer');
const submitMathBtn = document.getElementById('submit-math-btn');
const challengeFeedback = document.getElementById('challenge-feedback');

let currentInvestmentDetails = {
    package: '',
    duration: 0,
    returnRate: 0
};

let currentManagedUserEmail = null;
let currentInvestmentToDelete = null;
let currentViewingUserEmail = null;

// Cycle 2+ Recommitment Modal Elements (will be created dynamically)
let cycleSettlementModal = null;
let currentCycleSettlementRequirement = null;

// --- AUTHENTICATED FETCH WRAPPER ---
async function authFetch(url, options = {}) {
    const token = localStorage.getItem('authToken');

    const headers = {
        'Content-Type': 'application/json',
        ...options.headers
    };

    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }

    const response = await fetch(url, {
        ...options,
        headers
    });

    if (response.status === 401 || response.status === 403) {
        const data = await response.clone().json();
        if (data.message && data.message.includes('verify your email')) {
            return response;
        }
        logout();
        return null;
    }

    return response;
}

// Initialize the application
document.addEventListener('DOMContentLoaded', function () {
    initializeEventListeners();
    checkURLTokens();
    checkLoginStatus();
    updateReferralCodePlaceholder();
});

// Update referral code placeholder to indicate it's optional
function updateReferralCodePlaceholder() {
    const referralInput = document.getElementById('referral-code');
    if (referralInput) {
        referralInput.placeholder = 'Referral Code (Optional)';
    }
}

// Check for tokens (Reset or Verification) in URL
function checkURLTokens() {
    const urlParams = new URLSearchParams(window.location.search);
    const resetToken = urlParams.get('resetToken');
    const verifyToken = urlParams.get('verifyToken');

    if (resetToken) {
        showSection('reset-password-new-section');
        document.getElementById('reset-token-value').value = resetToken;

        const newPasswordForm = document.getElementById('new-password-form');
        if (newPasswordForm) {
            newPasswordForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const newPassword = document.getElementById('new-password').value;
                const confirmPassword = document.getElementById('confirm-new-password').value;
                const token = document.getElementById('reset-token-value').value;

                if (newPassword !== confirmPassword) {
                    alert("Passwords do not match.");
                    return;
                }

                try {
                    const response = await fetch('/api/auth/reset-password', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ token, newPassword })
                    });

                    const data = await response.json();
                    if (data.success) {
                        showSuccessModal(data.message);
                        window.history.replaceState({}, document.title, "/");
                        showSection('login-section');
                    } else {
                        alert(data.message);
                    }
                } catch (err) {
                    console.error(err);
                    alert("An error occurred.");
                }
            });
        }
    }

    if (verifyToken) {
        verifyEmail(verifyToken);
    }
}

async function verifyEmail(token) {
    try {
        showSuccessModal("Verifying your email...");
        const response = await fetch('/api/auth/verify-email', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ token })
        });

        const data = await response.json();
        if (data.success) {
            showSuccessModal(data.message);
            window.history.replaceState({}, document.title, "/");
            showSection('login-section');
        } else {
            showSuccessModal(data.message || "Verification failed");
        }
    } catch (error) {
        console.error(error);
        showSuccessModal("An error occurred during verification.");
    }
}

function togglePaymentMethod() {
    const method = document.querySelector('input[name="payment-method"]:checked').value;
    const manualSection = document.getElementById('manual-payment-section');

    if (method === 'wallet') {
        manualSection.style.display = 'none';
    } else {
        manualSection.style.display = 'block';
    }
}

function initializeEventListeners() {
    navHome.addEventListener('click', () => showSection('home-section'));
    navLogin.addEventListener('click', () => showSection('login-section'));
    navRegister.addEventListener('click', () => showSection('register-section'));
    navDashboard.addEventListener('click', showDashboard);
    navLogout.addEventListener('click', logout);

    loginForm.addEventListener('submit', handleLogin);
    registerForm.addEventListener('submit', handleRegistration);
    forgotPasswordForm.addEventListener('submit', handleForgotPassword);

    document.getElementById('show-register').addEventListener('click', () => showSection('register-section'));
    document.getElementById('show-login').addEventListener('click', () => showSection('login-section'));
    document.getElementById('show-forgot-password').addEventListener('click', () => showSection('forgot-password-section'));
    document.getElementById('show-login-from-reset').addEventListener('click', () => showSection('login-section'));
    document.getElementById('get-started-btn').addEventListener('click', () => showSection('login-section'));

    if (packagesGrid) {
        packagesGrid.addEventListener('click', function (e) {
            if (e.target && e.target.classList.contains('invest-btn')) {
                openInvestmentModal(e);
            }
        });
    }

    investmentAmountInput.addEventListener('input', updateInvestmentPreview);
    if (recommitmentAmountInput) {
        recommitmentAmountInput.addEventListener('input', updateRecommitmentPreview);
    }

    closeModalButtons.forEach(button => {
        button.addEventListener('click', () => {
            investmentModal.style.display = 'none';
            successModal.style.display = 'none';
            withdrawalModal.style.display = 'none';
            walletRecommitmentModal.style.display = 'none';
            creditUserModal.style.display = 'none';
            debitUserModal.style.display = 'none';
            editBankModal.style.display = 'none';
            suspendUserModal.style.display = 'none';
            deleteUserModal.style.display = 'none';
            deleteInvestmentModal.style.display = 'none';
            userInvestmentsModal.style.display = 'none';
            proofViewModal.style.display = 'none';
            if (cycleSettlementModal) {
                cycleSettlementModal.style.display = 'none';
            }
            const optionsModal = document.getElementById('recommitment-options-modal');
            if (optionsModal) optionsModal.style.display = 'none';
            // Also close dynamic bonus modal if open
            const bonusModal = document.getElementById('referral-bonus-withdrawal-modal');
            if (bonusModal) bonusModal.style.display = 'none';
        });
    });

    if (confirmInvestmentButton) confirmInvestmentButton.addEventListener('click', confirmManualInvestment);
    if (confirmWithdrawalButton) confirmWithdrawalButton.addEventListener('click', confirmWithdrawal);
    if (confirmWalletRecommitmentButton) confirmWalletRecommitmentButton.addEventListener('click', confirmWalletRecommitment);
    if (confirmCreditButton) confirmCreditButton.addEventListener('click', confirmCredit);
    if (confirmDebitButton) confirmDebitButton.addEventListener('click', confirmDebit);
    if (confirmBankEditButton) confirmBankEditButton.addEventListener('click', confirmBankEdit);
    if (confirmSuspendButton) confirmSuspendButton.addEventListener('click', confirmSuspend);
    if (confirmDeleteButton) confirmDeleteButton.addEventListener('click', confirmDelete);
    if (cancelSuspendButton) cancelSuspendButton.addEventListener('click', () => suspendUserModal.style.display = 'none');
    if (cancelDeleteButton) cancelDeleteButton.addEventListener('click', () => deleteUserModal.style.display = 'none');
    if (successOkButton) successOkButton.addEventListener('click', () => successModal.style.display = 'none');

    if (confirmInvestmentDeleteButton) confirmInvestmentDeleteButton.addEventListener('click', confirmInvestmentDelete);
    if (cancelInvestmentDeleteButton) cancelInvestmentDeleteButton.addEventListener('click', () => deleteInvestmentModal.style.display = 'none');

    if (withdrawFundsButton) withdrawFundsButton.addEventListener('click', openWithdrawalModal);

    // UPDATED: Transfer bonus button is now "Withdraw Bonus"
    if (transferBonusButton) transferBonusButton.addEventListener('click', openBonusWithdrawalModal);

    if (addPackageButton) addPackageButton.addEventListener('click', addNewPackage);
    if (saveReferralSettingsButton) saveReferralSettingsButton.addEventListener('click', saveReferralSettings);

    if (userSearchInput) userSearchInput.addEventListener('input', loadUsersList);
    if (hamburger) hamburger.addEventListener('click', toggleMobileMenu);

    if (submitMathBtn) {
        submitMathBtn.addEventListener('click', submitMathChallenge);
    }

    window.addEventListener('click', (event) => {
        if (event.target === investmentModal) investmentModal.style.display = 'none';
        if (event.target === successModal) successModal.style.display = 'none';
        if (event.target === withdrawalModal) withdrawalModal.style.display = 'none';
        if (event.target === walletRecommitmentModal) walletRecommitmentModal.style.display = 'none';
        if (event.target === creditUserModal) creditUserModal.style.display = 'none';
        if (event.target === debitUserModal) debitUserModal.style.display = 'none';
        if (event.target === editBankModal) editBankModal.style.display = 'none';
        if (event.target === suspendUserModal) suspendUserModal.style.display = 'none';
        if (event.target === deleteUserModal) deleteUserModal.style.display = 'none';
        if (event.target === deleteInvestmentModal) deleteInvestmentModal.style.display = 'none';
        if (event.target === userInvestmentsModal) userInvestmentsModal.style.display = 'none';
        if (event.target === proofViewModal) proofViewModal.style.display = 'none';
        if (cycleSettlementModal && event.target === cycleSettlementModal) {
            cycleSettlementModal.style.display = 'none';
        }
        // Dynamic bonus modal check
        const bonusModal = document.getElementById('referral-bonus-withdrawal-modal');
        if (bonusModal && event.target === bonusModal) {
            bonusModal.style.display = 'none';
        }
    });
}

function showSection(sectionId) {
    sections.forEach(section => {
        section.classList.remove('active');
    });
    document.getElementById(sectionId).classList.add('active');
    updateNavigation();
    if (navMenu.classList.contains('active')) {
        toggleMobileMenu();
    }
}

function toggleMobileMenu() {
    hamburger.classList.toggle('active');
    navMenu.classList.toggle('active');
}

function updateNavigation() {
    if (currentUser) {
        navLogin.style.display = 'none';
        navRegister.style.display = 'none';
        navDashboard.style.display = 'block';
        navLogout.style.display = 'block';
    } else {
        navLogin.style.display = 'block';
        navRegister.style.display = 'block';
        navDashboard.style.display = 'none';
        navLogout.style.display = 'none';
    }
}

async function checkLoginStatus() {
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('resetToken') || urlParams.get('verifyToken')) return;

    const token = localStorage.getItem('authToken');
    const savedEmail = localStorage.getItem('premierEquationUserEmail');

    if (token && savedEmail) {
        await loadUserData(savedEmail);
    } else {
        showSection('home-section');
    }
}

async function loadUserData(email) {
    try {
        const response = await authFetch(`/api/data/${email}`);
        if (!response) return;

        const data = await response.json();

        if (data.error) {
            logout();
            return;
        }

        currentUser = data.user.fullName;
        currentUserEmail = data.user.email;
        isAdmin = data.user.isAdmin;
        investments = data.investments || [];
        transactions = data.transactions || [];

        if (data.packages && data.packages.length > 0) {
            adminSettings.packages = data.packages;
        }

        localStorage.setItem('premierEquationUserEmail', email);

        showDashboard();
        updatePackageDisplay();

    } catch (error) {
        console.error('Error loading user data:', error);
        logout();
    }
}

async function showDashboard() {
    if (isAdmin) {
        showSection('admin-dashboard-section');
        await loadAdminData();
        loadAdminPackageControls();
        loadAdminSettings();
        loadWithdrawalRequests();
        loadPendingInvestments();
        loadPendingWalletRecommitments();
        loadPendingCycleSettlements();
    } else {
        showSection('user-dashboard-section');
        userNameElement.textContent = currentUser;

        loadDailyChallenge();

        const user = {
            withdrawalBalance: transactions.reduce((acc, t) => {
                if (t.transactionType === 'credit') return acc + (t.amount || 0);
                if (t.transactionType === 'debit') return acc - (t.amount || 0);
                return acc;
            }, 0)
        };

        try {
            const response = await authFetch(`/api/data/${currentUserEmail}`);
            if (response) {
                const data = await response.json();
                const userObj = data.user;

                userReferralCodeElement.textContent = userObj.referralCode || 'N/A';
                withdrawalBalanceElement.textContent = `N${safeNumberFormat(userObj.withdrawalBalance || 0)}`;
                referralBonusElement.textContent = `N${safeNumberFormat(userObj.referralBonus || 0)}`;

                // UPDATED: Configure Transfer button as "Withdraw Bonus"
                if (transferBonusButton) {
                    transferBonusButton.textContent = "Withdraw Bonus";
                    // Enable only if bonus >= MIN_BONUS_WITHDRAWAL (5000)
                    transferBonusButton.disabled = (userObj.referralBonus || 0) < MIN_BONUS_WITHDRAWAL;
                }
            }
        } catch (e) {
            console.error(e);
        }

        loadUserInvestments();
        updateInvestmentSummary();
        loadTransactionHistory();
    }
    updateNavigation();
}

// --- MATH CHALLENGE FUNCTIONS ---

async function loadDailyChallenge() {
    if (!mathQuestionElement) return;

    try {
        const response = await authFetch('/api/challenge/today');
        const data = await response.json();

        if (data.alreadyPlayed) {
            disableChallenge("You have already attempted today's challenge. Come back tomorrow!");
        } else {
            mathQuestionElement.textContent = data.question;
            mathAnswerInput.value = '';
            mathAnswerInput.disabled = false;
            submitMathBtn.disabled = false;
            submitMathBtn.textContent = 'Submit';
            challengeFeedback.textContent = '';
            challengeFeedback.className = 'challenge-feedback';

            mathAnswerInput.style.display = 'block';
            submitMathBtn.style.display = 'block';
            challengeFeedback.style.display = 'block';
        }
    } catch (error) {
        console.error("Error loading challenge:", error);
        mathQuestionElement.textContent = "Check back later for today's question.";
    }
}

async function submitMathChallenge() {
    const answer = mathAnswerInput.value.trim();
    if (!answer) return;

    submitMathBtn.disabled = true;
    submitMathBtn.textContent = 'Checking...';
    mathAnswerInput.disabled = true;

    try {
        const response = await authFetch('/api/challenge/submit', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ answer })
        });

        const data = await response.json();

        if (data.success) {
            challengeFeedback.textContent = data.message;
            challengeFeedback.className = 'challenge-feedback feedback-success';
            await loadUserData(currentUserEmail);
        } else {
            challengeFeedback.textContent = data.message;
            challengeFeedback.className = 'challenge-feedback feedback-error';
        }

    } catch (error) {
        console.error("Submission error:", error);
        challengeFeedback.textContent = "Error submitting answer.";
        submitMathBtn.disabled = false;
        submitMathBtn.textContent = 'Submit';
        mathAnswerInput.disabled = false;
    }
}

function disableChallenge(msg) {
    mathQuestionElement.textContent = "Challenge Completed";
    mathAnswerInput.style.display = 'none';
    submitMathBtn.style.display = 'none';
    challengeFeedback.textContent = msg;
    challengeFeedback.style.display = 'block';
    challengeFeedback.style.color = '#666';
}

async function loadAdminData() {
    try {
        const response = await authFetch('/api/admin/users');
        if (response) {
            const data = await response.json();
            users = data;
            loadUsersList();
        }
    } catch (error) {
        console.error('Error loading admin data:', error);
    }
}

async function handleLogin(e) {
    e.preventDefault();

    const email = document.getElementById('login-email').value;
    const password = document.getElementById('login-password').value;

    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email, password })
        });

        const data = await response.json();

        if (data.success) {
            localStorage.setItem('authToken', data.token);
            await loadUserData(data.user.email);
        } else {
            alert(data.message || 'Invalid credentials');
        }
    } catch (error) {
        console.error('Login Error:', error);
        alert('An error occurred during login.');
    }
}

async function handleRegistration(e) {
    e.preventDefault();

    const fullName = document.getElementById('full-name').value;
    const email = document.getElementById('register-email').value;
    const mobile = document.getElementById('mobile').value;
    const referralCode = document.getElementById('referral-code').value;
    const bankName = document.getElementById('bank-name').value;
    const accountNumber = document.getElementById('account-number').value;
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;

    if (password !== confirmPassword) {
        alert('Passwords do not match. Please try again.');
        return;
    }

    try {
        const response = await fetch('/api/auth/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                fullName, email, mobile, referralCode, bankName, accountNumber, password
            })
        });

        const data = await response.json();

        if (data.success) {
            showSuccessModal(data.message);
            showSection('login-section');
        } else {
            alert(data.message || 'Registration failed.');
        }
    } catch (error) {
        console.error('Registration Error:', error);
        alert('An error occurred during registration.');
    }
}

async function handleForgotPassword(e) {
    e.preventDefault();
    const email = document.getElementById('reset-email').value;
    const btn = e.target.querySelector('button');
    const originalText = btn.textContent;

    btn.textContent = 'Sending...';
    btn.disabled = true;

    try {
        const response = await fetch('/api/auth/forgot-password', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email })
        });

        const data = await response.json();
        showSuccessModal(data.message);
    } catch (error) {
        console.error('Error:', error);
        alert('Failed to send request.');
    } finally {
        btn.textContent = originalText;
        btn.disabled = false;
    }
}

function logout() {
    currentUser = null;
    currentUserEmail = null;
    isAdmin = false;
    localStorage.removeItem('premierEquationUserEmail');
    localStorage.removeItem('authToken');
    showSection('home-section');
    updateNavigation();
}

function updatePackageDisplay() {
    packagesGrid.innerHTML = '';

    adminSettings.packages.forEach(pkg => {
        if (pkg.enabled) {
            const packageCard = document.createElement('div');
            packageCard.className = 'package-card';
            packageCard.id = `${pkg.name.toLowerCase()}-package`;

            packageCard.innerHTML = `
                <h4>${pkg.name}</h4>
                <p class="package-return">${pkg.returnRate}% in ${pkg.duration} days</p>
                <p class="package-status">Available</p>
                <button class="btn-primary invest-btn" 
                        data-package="${pkg.name}" 
                        data-duration="${pkg.duration}" 
                        data-return="${pkg.returnRate}">
                    Invest Now
                </button>
            `;

            packagesGrid.appendChild(packageCard);
        }
    });
}

function loadAdminPackageControls() {
    packageControlsElement.innerHTML = '';

    adminSettings.packages.forEach((pkg, index) => {
        const packageControl = document.createElement('div');
        packageControl.className = 'package-control';

        packageControl.innerHTML = `
            <div class="package-control-header">
                <h4>${pkg.name} Package</h4>
                <button class="remove-package" data-index="${index}">Remove</button>
            </div>
            <div class="form-group">
                <label for="package-name-${index}">Package Name</label>
                <input type="text" id="package-name-${index}" value="${pkg.name}" class="package-name-input">
            </div>
            <div class="form-group">
                <label for="package-return-${index}">Return Rate (%)</label>
                <input type="number" id="package-return-${index}" value="${pkg.returnRate}" min="1" max="100" step="0.1" class="package-return-input">
            </div>
            <div class="form-group">
                <label for="package-duration-${index}">Duration (days)</label>
                <input type="number" id="package-duration-${index}" value="${pkg.duration}" min="1" max="365" class="package-duration-input">
            </div>
            <div class="toggle-container">
                <label class="toggle-label">Enable Package:</label>
                <label class="switch">
                    <input type="checkbox" id="package-enabled-${index}" ${pkg.enabled ? 'checked' : ''} class="package-enabled-input">
                    <span class="slider round"></span>
                </label>
            </div>
        `;

        packageControlsElement.appendChild(packageControl);
    });

    document.querySelectorAll('.package-name-input, .package-return-input, .package-duration-input, .package-enabled-input').forEach(input => {
        input.addEventListener('change', updatePackageSettings);
    });

    document.querySelectorAll('.remove-package').forEach(button => {
        button.addEventListener('click', removePackage);
    });
}

async function addNewPackage() {
    const newPackage = {
        id: Date.now(),
        name: 'New Package',
        returnRate: 15,
        duration: 7,
        enabled: true
    };

    adminSettings.packages.push(newPackage);
    await saveSettingsToServer();
    loadAdminPackageControls();
}

async function removePackage(e) {
    const index = parseInt(e.target.getAttribute('data-index'));
    if (adminSettings.packages.length > 1) {
        adminSettings.packages.splice(index, 1);
        await saveSettingsToServer();
        loadAdminPackageControls();
    } else {
        alert('You must have at least one package.');
    }
}

async function updatePackageSettings() {
    adminSettings.packages.forEach((pkg, index) => {
        pkg.name = document.getElementById(`package-name-${index}`).value;
        pkg.returnRate = parseFloat(document.getElementById(`package-return-${index}`).value);
        pkg.duration = parseInt(document.getElementById(`package-duration-${index}`).value);
        pkg.enabled = document.getElementById(`package-enabled-${index}`).checked;
    });

    await saveSettingsToServer();
    updatePackageDisplay();
}

async function saveReferralSettings() {
    adminSettings.referralBonus.level1 = parseFloat(level1BonusInput.value);
    adminSettings.referralBonus.level2 = parseFloat(level2BonusInput.value);

    if (recommitmentEnabledInput && recommitmentPercentageInput) {
        adminSettings.recommitment = {
            enabled: recommitmentEnabledInput.checked,
            percentage: parseFloat(recommitmentPercentageInput.value)
        };
    }

    await saveSettingsToServer();
    showSuccessModal('Global settings (Referral & Recommitment) updated successfully!');
}

async function saveSettingsToServer() {
    try {
        await authFetch('/api/admin/settings', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(adminSettings)
        });
    } catch (error) {
        console.error('Error saving settings:', error);
    }
}

async function loadAdminSettings() {
    try {
        const response = await authFetch('/api/admin/settings');
        if (response) {
            const data = await response.json();
            if (data) {
                if (data.packages) adminSettings.packages = data.packages;
                if (data.referralBonus) adminSettings.referralBonus = data.referralBonus;
                if (data.recommitment) adminSettings.recommitment = data.recommitment;

                if (level1BonusInput) level1BonusInput.value = adminSettings.referralBonus.level1;
                if (level2BonusInput) level2BonusInput.value = adminSettings.referralBonus.level2;

                if (recommitmentEnabledInput) recommitmentEnabledInput.checked = adminSettings.recommitment.enabled;
                if (recommitmentPercentageInput) recommitmentPercentageInput.value = adminSettings.recommitment.percentage;
            }
        }
    } catch (error) {
        console.error('Error loading settings:', error);
    }
}

async function openInvestmentModal(e) {
    const packageName = e.target.getAttribute('data-package');
    const duration = parseInt(e.target.getAttribute('data-duration'));
    const returnRate = parseInt(e.target.getAttribute('data-return'));

    currentInvestmentDetails = {
        package: packageName,
        duration: duration,
        returnRate: returnRate
    };

    document.getElementById('modal-package-name').textContent = packageName;
    document.getElementById('modal-package-return').textContent = `${returnRate}% in ${duration} days`;

    const amountInput = document.getElementById('investment-amount');
    amountInput.min = MIN_INVESTMENT;

    let currentMaxInvestment = MAX_INVESTMENT;
    if (packageName === 'Star') {
        currentMaxInvestment = 50000;
    }

    try {
        const response = await authFetch(`/api/data/${currentUserEmail}`);
        if (response) {
            const data = await response.json();
            const userInvestments = data.investments || [];
            const activeCompletedInvestments = userInvestments.filter(inv =>
                inv.status === 'Active' || inv.status === 'Completed'
            );

            if (activeCompletedInvestments.length > 0) {
                const highestPreviousAmount = Math.max(...activeCompletedInvestments.map(inv => inv.amount));
                if (highestPreviousAmount > MIN_INVESTMENT) {
                    amountInput.min = highestPreviousAmount;
                    alert(`Minimum investment for you is now N${highestPreviousAmount.toLocaleString()} (your previous highest investment).`);
                }
            }
        }
    } catch (error) {
        console.error('Error checking previous investments:', error);
    }

    amountInput.max = currentMaxInvestment;
    amountInput.value = Math.max(amountInput.min, MIN_INVESTMENT);
    amountInput.placeholder = `Enter amount between N${amountInput.min.toLocaleString()} and N${currentMaxInvestment.toLocaleString()}`;

    const proofInput = document.getElementById('investment-proof');
    if (proofInput) {
        proofInput.value = '';
    }

    try {
        const response = await authFetch(`/api/data/${currentUserEmail}`);
        const data = await response.json();
        document.getElementById('modal-wallet-balance').textContent = `N${safeNumberFormat(data.user.withdrawalBalance)}`;
    } catch (err) { console.error(err); }

    document.querySelector('input[value="manual"]').checked = true;
    togglePaymentMethod();

    updateInvestmentPreview();
    investmentModal.style.display = 'block';
}

function updateInvestmentPreview() {
    const amount = parseFloat(document.getElementById('investment-amount').value) || 0;
    const returnRate = currentInvestmentDetails.returnRate;
    const duration = currentInvestmentDetails.duration;

    const profit = amount * (returnRate / 100);
    const totalReturn = amount + profit;

    previewAmount.textContent = `N${amount.toLocaleString()}`;
    previewProfit.textContent = `N${profit.toLocaleString()}`;
    previewTotal.textContent = `N${totalReturn.toLocaleString()}`;
    previewDurationDays.textContent = `${duration} Days (from approval)`;
    previewMaturity.textContent = "Pending Approval";
}

const readFileAsBase64 = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
};

async function confirmManualInvestment() {
    const paymentMethod = document.querySelector('input[name="payment-method"]:checked').value;
    const amount = parseFloat(document.getElementById('investment-amount').value);
    const returnRate = currentInvestmentDetails.returnRate;
    const duration = currentInvestmentDetails.duration;
    const packageName = currentInvestmentDetails.package;

    let currentMax = MAX_INVESTMENT;
    if (packageName === 'Star') {
        currentMax = 50000;
    }

    try {
        const response = await authFetch(`/api/data/${currentUserEmail}`);
        if (response) {
            const data = await response.json();
            const userInvestments = data.investments || [];
            const activeCompletedInvestments = userInvestments.filter(inv =>
                inv.status === 'Active' || inv.status === 'Completed'
            );

            if (activeCompletedInvestments.length > 0) {
                const highestPreviousAmount = Math.max(...activeCompletedInvestments.map(inv => inv.amount));
                if (amount < highestPreviousAmount) {
                    alert(`New investment (N${amount.toLocaleString()}) cannot be lower than your previous highest investment (N${highestPreviousAmount.toLocaleString()}).`);
                    return;
                }
            }
        }
    } catch (error) {
        console.error('Error checking previous investments:', error);
    }

    if (!amount || amount < MIN_INVESTMENT || amount > currentMax) {
        alert(`Please enter a valid investment amount (Min: N${MIN_INVESTMENT.toLocaleString()}, Max: N${currentMax.toLocaleString()}).`);
        return;
    }

    let bodyData = {
        email: currentUserEmail,
        packageName: packageName,
        amount,
        duration: duration,
        returnRate: returnRate,
        paymentMethod: 'Manual'
    };

    if (paymentMethod === 'wallet') {
        bodyData.paymentMethod = 'Wallet';
    } else {
        const fileInput = document.getElementById('investment-proof');
        if (!fileInput || fileInput.files.length === 0) {
            alert('For manual transfers, you MUST upload a screenshot/receipt of your payment.');
            return;
        }

        const file = fileInput.files[0];
        try {
            bodyData.proofImage = await readFileAsBase64(file);
        } catch (error) {
            alert('Error reading the image file. Please try again.');
            return;
        }
    }

    const btn = document.getElementById('confirm-investment');
    const originalText = btn.textContent;
    btn.textContent = 'Processing...';
    btn.disabled = true;

    try {
        const response = await authFetch('/api/invest', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(bodyData)
        });

        const data = await response.json();

        if (data.success) {
            investmentModal.style.display = 'none';
            await loadUserData(currentUserEmail);
            showSuccessModal(data.message || `Investment successful!`);
        } else {
            alert(data.message || 'Investment failed');
        }
    } catch (error) {
        console.error('Investment Error:', error);
        alert('An error occurred processing your investment.');
    } finally {
        btn.textContent = originalText;
        btn.disabled = false;
    }
}

function safeNumberFormat(value, defaultValue = 0) {
    if (value === undefined || value === null || isNaN(value)) {
        return defaultValue.toLocaleString();
    }
    return Number(value).toLocaleString();
}

function safeString(value, defaultValue = '') {
    if (value === undefined || value === null) {
        return defaultValue;
    }
    return String(value);
}

function loadUserInvestments() {
    if (!Array.isArray(investments) || investments.length === 0) {
        userInvestmentsElement.innerHTML = '<p class="no-investments">No active investments</p>';
        return;
    }

    userInvestmentsElement.innerHTML = investments.map(inv => {
        let status = inv.status || 'Active';
        let maturityDateStr = 'Pending Approval';

        if (inv.status === 'Active' || inv.status === 'Completed' || inv.status === 'Withdrawn') {
            const today = new Date();
            const maturityDate = new Date(inv.maturityDate);
            maturityDateStr = maturityDate.toLocaleDateString();

            if (inv.status === 'Active' && today >= maturityDate) {
                status = 'Completed';
            }
            if (inv.withdrawn) {
                status = 'Withdrawn';
            }
        }

        const cycleInfo = inv.investmentCycle ? ` (Cycle ${inv.investmentCycle})` : '';
        const settlementInfo = inv.cycleSettlementRequired ? '<small style="color: #ff9800; font-weight: bold;">Settlement Required</small>' : '';

        return `
        <div class="investment-item">
            <div class="investment-details">
                <strong>${safeString(inv.package, 'Unknown')} Package${cycleInfo}</strong>
                <small>Investment: N${safeNumberFormat(inv.amount)}</small>
                <small>Expected Profit: N${safeNumberFormat(inv.profit)}</small>
                <small>Total Return: N${safeNumberFormat(inv.totalReturn)}</small>
                <small>Start Date: ${safeString(new Date(inv.date).toLocaleDateString(), 'Unknown')}</small>
                <small>Maturity Date: ${safeString(maturityDateStr, 'Unknown')}</small>
                ${status === 'Completed' ? '<small style="color: green; font-weight: bold;">Ready for withdrawal</small>' : ''}
                ${settlementInfo}
            </div>
            <span class="package-status ${safeString(status, 'active').toLowerCase()}">${safeString(status, 'Active')}</span>
        </div>
        `;
    }).join('');
}

function loadTransactionHistory() {
    if (!Array.isArray(transactions) || transactions.length === 0) {
        transactionHistoryElement.innerHTML = '<p class="no-transactions">No transactions yet</p>';
        return;
    }

    const sortedTransactions = [...transactions].sort((a, b) => new Date(b.date) - new Date(a.date));

    transactionHistoryElement.innerHTML = sortedTransactions.map(trans => `
        <div class="transaction-item">
            <div class="transaction-details">
                <div class="transaction-type">${safeString(trans.description, 'Unknown Transaction')}</div>
                <div class="transaction-amount ${safeString(trans.transactionType, 'debit')}">
                    ${safeString(trans.transactionType, 'debit') === 'debit' ? '-' : '+'}N${safeNumberFormat(trans.amount)}
                </div>
            </div>
            <div class="transaction-info">
                <div class="transaction-date">${safeString(new Date(trans.date).toLocaleDateString(), 'Unknown')}</div>
                <span class="transaction-status ${safeString(trans.status, 'completed').toLowerCase()}">${safeString(trans.status, 'Completed')}</span>
            </div>
        </div>
    `).join('');
}

function updateInvestmentSummary() {
    if (!Array.isArray(investments) || investments.length === 0) {
        investmentSummary.style.display = 'none';
        return;
    }

    investmentSummary.style.display = 'block';
    const validInvestments = investments.filter(inv => inv.status !== 'Rejected' && inv.status !== 'Pending');
    const totalInvested = validInvestments.reduce((sum, inv) => sum + (Number(inv.amount) || 0), 0);
    const totalExpected = validInvestments.reduce((sum, inv) => sum + (Number(inv.totalReturn) || 0), 0);
    const activeInvestments = investments.filter(inv => inv.status === 'Active').length;
    const totalProfit = validInvestments.reduce((sum, inv) => sum + (Number(inv.profit) || 0), 0);

    totalInvestedElement.textContent = `N${safeNumberFormat(totalInvested)}`;
    totalExpectedElement.textContent = `N${safeNumberFormat(totalExpected)}`;
    activeInvestmentsElement.textContent = activeInvestments;
    totalProfitElement.textContent = `N${safeNumberFormat(totalProfit)}`;
}

// --- WALLET RECOMMITMENT FUNCTIONS ---

async function checkRecommitmentEligibility() {
    try {
        const response = await authFetch('/api/recommit/eligibility');
        if (response) {
            return await response.json();
        }
        return null;
    } catch (error) {
        console.error('Error checking recommitment eligibility:', error);
        return null;
    }
}

// --- CYCLE 2+ SETTLEMENT FUNCTIONS ---

async function checkCycleSettlementRequirements() {
    try {
        const response = await authFetch('/api/cycle/settlement/requirements');
        if (response) {
            return await response.json();
        }
        return null;
    } catch (error) {
        console.error('Error checking settlement requirements:', error);
        return null;
    }
}

async function openWithdrawalModal() {
    await loadUserData(currentUserEmail);

    try {
        // UPDATED: Removed check for referral bonus here since it now has a dedicated button

        const settlementCheck = await checkCycleSettlementRequirements();

        if (settlementCheck && settlementCheck.requiresSettlement) {
            const firstRequirement = settlementCheck.requirements[0];
            showCycleSettlementModal(firstRequirement);
            return;
        }

        const eligibility = await checkRecommitmentEligibility();

        if (eligibility && eligibility.requiresRecommitment) {
            if (eligibility.hasPendingRecommitment) {
                showSuccessModal(`You have a pending wallet recommitment of N${eligibility.pendingAmount.toLocaleString()} waiting for admin approval. You cannot withdraw until it's approved.`);
                return;
            }

            showRecommitmentOptions(eligibility);
            return;
        }

        const userResponse = await authFetch(`/api/data/${currentUserEmail}`);
        if (userResponse) {
            const userData = await userResponse.json();
            const availableBalance = userData.user.withdrawalBalance || 0;

            availableWithdrawalElement.textContent = `N${safeNumberFormat(availableBalance)}`;
            withdrawalAmountInput.max = availableBalance;
            withdrawalAmountInput.value = Math.min(availableBalance > 0 ? availableBalance : MIN_WITHDRAWAL, MIN_WITHDRAWAL);
            withdrawalModal.style.display = 'block';
        }
    } catch (error) {
        console.error('Error in openWithdrawalModal:', error);
    }
}

// NEW FUNCTION: Direct Bonus Withdrawal Modal
async function openBonusWithdrawalModal() {
    await loadUserData(currentUserEmail);

    try {
        const response = await authFetch(`/api/data/${currentUserEmail}`);
        if (!response) return;
        const data = await response.json();
        const availableBonus = data.user.referralBonus || 0;

        // Clean up any existing dynamic modal
        const existingModal = document.getElementById('referral-bonus-withdrawal-modal');
        if (existingModal) existingModal.remove();

        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'referral-bonus-withdrawal-modal';
        modal.style.display = 'block';

        modal.innerHTML = `
            <div class="modal-content" style="max-width: 500px;">
                <span class="close" id="close-bonus-modal">&times;</span>
                <h3>💰 Withdraw Referral Bonus</h3>
                <p>Available Bonus: <strong>N${availableBonus.toLocaleString()}</strong></p>
                
                <div class="form-group">
                    <label for="bonus-withdrawal-amount">Amount to Withdraw (N)</label>
                    <input type="number" id="bonus-withdrawal-amount" min="${MIN_BONUS_WITHDRAWAL}" max="${availableBonus}" value="${Math.max(MIN_BONUS_WITHDRAWAL, availableBonus)}">
                    <small>Minimum: N${MIN_BONUS_WITHDRAWAL.toLocaleString()} | Maximum: N${availableBonus.toLocaleString()}</small>
                </div>
                
                <div style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0; border-left: 4px solid #28a745;">
                    <p><strong>Note:</strong> Referral bonus withdrawals do not require recommitment and will be processed directly from the bonus container.</p>
                </div>
                
                <div style="display: flex; gap: 10px; margin-top: 20px;">
                    <button id="confirm-bonus-withdrawal" class="btn-primary" style="flex: 1;">
                        Submit Withdrawal Request
                    </button>
                    <button id="cancel-bonus-withdrawal" class="btn-secondary" style="flex: 1;">
                        Cancel
                    </button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // Event listeners for the new modal
        const closeBtn = modal.querySelector('#close-bonus-modal');
        const cancelBtn = modal.querySelector('#cancel-bonus-withdrawal');
        const confirmBtn = modal.querySelector('#confirm-bonus-withdrawal');
        const input = modal.querySelector('#bonus-withdrawal-amount');

        const closeModal = () => { modal.style.display = 'none'; };

        closeBtn.onclick = closeModal;
        cancelBtn.onclick = closeModal;

        modal.addEventListener('click', (e) => {
            if (e.target === modal) closeModal();
        });

        confirmBtn.onclick = async () => {
            const amount = parseFloat(input.value);

            if (amount < MIN_BONUS_WITHDRAWAL || amount > availableBonus) {
                alert(`Please enter a valid amount between N${MIN_BONUS_WITHDRAWAL.toLocaleString()} and N${availableBonus.toLocaleString()}`);
                return;
            }

            confirmBtn.textContent = 'Processing...';
            confirmBtn.disabled = true;

            try {
                // Call the new specific endpoint for direct bonus withdrawal
                const response = await authFetch('/api/withdraw/referral', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ amount: amount })
                });

                const data = await response.json();

                if (data.success) {
                    modal.style.display = 'none';
                    showSuccessModal(`Referral bonus withdrawal request for N${amount.toLocaleString()} submitted! No recommitment required. Waiting for admin approval.`);
                    await loadUserData(currentUserEmail);
                } else {
                    alert(data.message || 'Withdrawal failed');
                    confirmBtn.textContent = 'Submit Withdrawal Request';
                    confirmBtn.disabled = false;
                }
            } catch (error) {
                console.error('Bonus Withdrawal Error:', error);
                alert('An error occurred processing withdrawal request.');
                confirmBtn.textContent = 'Submit Withdrawal Request';
                confirmBtn.disabled = false;
            }
        };

    } catch (e) {
        console.error(e);
        alert('Error preparing bonus withdrawal');
    }
}

function showRecommitmentOptions(eligibility) {
    window.currentRecommitmentEligibility = eligibility;

    const percent = eligibility.percentage || 50;
    const optionsHtml = `
        <div style="background-color: #fff; padding: 20px; border-radius: 10px; margin: 20px 0; border: 2px solid #ffd700;">
            <h3 style="color: #004d40; margin-bottom: 15px;">Withdrawal Recommitment Required</h3>
            <p>To withdraw funds, you need to recommit at least <strong>N${eligibility.minimumRecommitment.toLocaleString()}</strong> (equal to your highest previous investment).</p>
            
            <div style="margin: 20px 0; padding: 15px; background-color: #f8f9fa; border-radius: 5px;">
                <h4 style="color: #004d40; margin-bottom: 10px;">Choose Recommitment Method:</h4>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 15px;">
                    <div style="border: 2px solid #004d40; border-radius: 8px; padding: 15px; text-align: center;">
                        <h5 style="color: #004d40; margin-bottom: 10px;">💰 Wallet-Based Recommitment</h5>
                        <p style="font-size: 0.9em; margin-bottom: 10px;">• Pay ${percent}% from wallet now</p>
                        <p style="font-size: 0.9em; margin-bottom: 10px;">• Requires admin approval</p>
                        <p style="font-size: 0.9em; margin-bottom: 10px;">• Eligible immediately after approval</p>
                        <button onclick="handleWalletRecommitmentClick()" 
                                style="background-color: #004d40; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; width: 100%; margin-top: 10px;">
                            Use Wallet Balance
                        </button>
                    </div>
                    
                    <div style="border: 2px solid #6c757d; border-radius: 8px; padding: 15px; text-align: center;">
                        <h5 style="color: #6c757d; margin-bottom: 10px;">📈 Investment-Based Recommitment</h5>
                        <p style="font-size: 0.9em; margin-bottom: 10px;">• Invest in a new package (minimum N${eligibility.minimumRecommitment.toLocaleString()})</p>
                        <p style="font-size: 0.9em; margin-bottom: 10px;">• Pay 50% to company investment account.</p>
                        <p style="font-size: 0.9em; margin-bottom: 10px;">• Requires admin approval</p>
                        <p style="font-size: 0.9em; margin-bottom: 10px;">• Eligible after approval</p>
                        <button onclick="showInvestmentPackages()" 
                                style="background-color: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; width: 100%; margin-top: 10px;">
                            Browse Packages
                        </button>
                    </div>
                </div>
            </div>
            
            <p style="font-size: 0.9em; color: #666; margin-top: 15px;">
                <strong>Note:</strong> Wallet-based recommitment deducts ${percent}% immediately (as configured in admin settings) and requires admin approval.
            </p>
        </div>
    `;

    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.id = 'recommitment-options-modal';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-content">
            <span class="close" onclick="document.getElementById('recommitment-options-modal').style.display='none'">&times;</span>
            ${optionsHtml}
        </div>
    `;

    document.body.appendChild(modal);

    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    });

    modal.querySelector('.close').addEventListener('click', () => {
        modal.style.display = 'none';
    });
}

function handleWalletRecommitmentClick() {
    const optionsModal = document.getElementById('recommitment-options-modal');
    if (optionsModal) {
        optionsModal.style.display = 'none';
    }

    if (window.currentRecommitmentEligibility) {
        openWalletRecommitmentModal(window.currentRecommitmentEligibility);
    } else {
        console.error('Eligibility data missing for wallet recommitment');
    }
}

function showInvestmentPackages() {
    const optionsModal = document.getElementById('recommitment-options-modal');
    if (optionsModal) optionsModal.style.display = 'none';

    showSection('user-dashboard-section');

    setTimeout(() => {
        document.querySelector('.packages-container').scrollIntoView({ behavior: 'smooth' });
    }, 100);
}

function openWalletRecommitmentModal(eligibilityData) {
    const optionsModal = document.getElementById('recommitment-options-modal');
    if (optionsModal) optionsModal.style.display = 'none';

    window.currentRecommitmentPercentage = eligibilityData.percentage || 50;
    const percent = window.currentRecommitmentPercentage;

    document.getElementById('last-investment-display').textContent = `N${eligibilityData.lastInvestmentAmount.toLocaleString()}`;

    const minDisplay = document.getElementById('minimum-recommitment-display');
    minDisplay.textContent = `N${eligibilityData.minimumRecommitment.toLocaleString()}`;

    if (eligibilityData.highestInvestmentAmount > eligibilityData.lastInvestmentAmount) {
        minDisplay.innerHTML += ` <small style='color:orange'>(Highest Previous)</small>`;
    }

    document.getElementById('wallet-balance-display').textContent = `N${eligibilityData.walletBalance.toLocaleString()}`;

    const initialDeduction = eligibilityData.minimumRecommitment * (percent / 100);
    document.getElementById('required-deduction-display').textContent = `N${initialDeduction.toLocaleString()}`;

    document.getElementById('recommitment-percent-display').textContent = percent;
    document.getElementById('preview-percent-label').textContent = percent;
    document.getElementById('note-percent-label').textContent = percent;

    const recommitmentInput = document.getElementById('recommitment-amount');
    recommitmentInput.min = eligibilityData.minimumRecommitment;
    recommitmentInput.value = eligibilityData.minimumRecommitment;

    recommitmentInput.max = eligibilityData.walletBalance * (100 / percent);

    updateRecommitmentPreview();

    walletRecommitmentModal.style.display = 'block';
}

function updateRecommitmentPreview() {
    const recommitmentAmount = parseFloat(document.getElementById('recommitment-amount').value) || 0;
    const walletBalance = parseFloat(document.getElementById('wallet-balance-display').textContent.replace('N', '').replace(/,/g, '').split(' ')[0]) || 0;

    const percent = window.currentRecommitmentPercentage || 50;
    const walletDeduction = recommitmentAmount * (percent / 100);
    const newWalletBalance = walletBalance - walletDeduction;
    const minimumRequired = parseFloat(document.getElementById('minimum-recommitment-display').textContent.replace('N', '').replace(/,/g, '').split(' ')[0]) || 0;

    document.getElementById('required-deduction-display').textContent = `N${walletDeduction.toLocaleString()}`;

    document.getElementById('preview-recommitment').textContent = `N${recommitmentAmount.toLocaleString()}`;
    document.getElementById('preview-deduction').textContent = `N${walletDeduction.toLocaleString()}`;
    document.getElementById('preview-new-balance').textContent = `N${newWalletBalance.toLocaleString()}`;

    const confirmBtn = document.getElementById('confirm-wallet-recommitment');
    if (recommitmentAmount < minimumRequired) {
        document.getElementById('recommitment-error').textContent = `Amount must be at least N${minimumRequired.toLocaleString()}`;
        confirmBtn.disabled = true;
    } else if (walletDeduction > walletBalance) {
        document.getElementById('recommitment-error').textContent = `Insufficient wallet balance for ${percent}% deduction`;
        confirmBtn.disabled = true;
    } else {
        document.getElementById('recommitment-error').textContent = '';
        confirmBtn.disabled = false;
    }
}

async function confirmWalletRecommitment() {
    const recommitmentAmount = parseFloat(document.getElementById('recommitment-amount').value);
    const percent = window.currentRecommitmentPercentage || 50;
    const walletDeduction = recommitmentAmount * (percent / 100);

    const confirmMessage = `Are you sure you want to submit a wallet-based recommitment?\n\n` +
        `Recommitment Amount: N${recommitmentAmount.toLocaleString()}\n` +
        `${percent}% Wallet Deduction: N${walletDeduction.toLocaleString()} (as configured in admin settings)\n` +
        `This amount will be deducted immediately and requires admin approval.`;

    if (!confirm(confirmMessage)) {
        return;
    }

    const btn = document.getElementById('confirm-wallet-recommitment');
    const originalText = btn.textContent;
    btn.textContent = 'Processing...';
    btn.disabled = true;

    try {
        const response = await authFetch('/api/recommit/wallet', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ recommitmentAmount: recommitmentAmount })
        });

        const data = await response.json();

        if (data.success) {
            walletRecommitmentModal.style.display = 'none';
            showSuccessModal(data.message);

            await loadUserData(currentUserEmail);
        } else {
            alert(data.message || 'Recommitment failed');
        }
    } catch (error) {
        console.error('Wallet Recommitment Error:', error);
        alert('An error occurred during wallet recommitment.');
    } finally {
        btn.textContent = originalText;
        btn.disabled = false;
    }
}

function showCycleSettlementModal(requirement) {
    if (cycleSettlementModal) {
        cycleSettlementModal.remove();
    }

    currentCycleSettlementRequirement = requirement;

    cycleSettlementModal = document.createElement('div');
    cycleSettlementModal.className = 'modal';
    cycleSettlementModal.id = 'cycle-settlement-modal';
    cycleSettlementModal.style.display = 'block';

    cycleSettlementModal.innerHTML = `
        <div class="modal-content" style="max-width: 600px;">
            <span class="close" onclick="document.getElementById('cycle-settlement-modal').style.display='none'">&times;</span>
            <h3>🔄 Cycle ${requirement.cycle} Settlement Required</h3>
            
            <div style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0;">
                <p><strong>Investment Details:</strong></p>
                <p>Package: ${requirement.package}</p>
                <p>Cycle: ${requirement.cycle}</p>
                <p>Original Amount: N${requirement.amount.toLocaleString()}</p>
                <p>Total Return: <span style="color: green; font-weight: bold;">N${requirement.totalReturn.toLocaleString()}</span></p>
            </div>
            
            <div style="background-color: #fff3cd; padding: 15px; border-radius: 5px; margin: 20px 0; border-left: 4px solid #ffc107;">
                <h4 style="color: #856404;">Settlement Breakdown</h4>
                <p><strong>Settlement Amount:</strong> N${requirement.settlementAmount.toLocaleString()} (100% of original)</p>
                <p>• N${requirement.remainingBalance.toLocaleString()} completes Cycle ${requirement.cycle} balance</p>
                <p>• N${requirement.nextCycleAmount.toLocaleString()} registers for Cycle ${requirement.cycle + 1}</p>
            </div>
            
            <div class="form-group">
                <label>Payment Method</label>
                <div style="display: flex; gap: 15px; margin-bottom: 15px;">
                    <label style="font-weight: normal; cursor: pointer;">
                        <input type="radio" name="cycle-payment-method" value="wallet" checked>
                        Wallet Balance
                    </label>
                    <label style="font-weight: normal; cursor: pointer;">
                        <input type="radio" name="cycle-payment-method" value="manual">
                        Bank Transfer
                    </label>
                </div>
            </div>
            
            <div id="cycle-manual-payment" style="display: none;">
                <div style="padding: 10px; border: 1px dashed #ccc; margin-bottom: 15px;">
                    <p><strong>Bank:</strong> CARBON</p>
                    <p><strong>Account Name:</strong> PREMIER EQUATION ENTERPRISE</p>
                    <p><strong>Account Number:</strong> <span style="color: #e75480; font-weight: bold;">4131522426</span></p>
                </div>
                
                <div class="form-group">
                    <label for="cycle-proof">Upload Payment Proof</label>
                    <input type="file" id="cycle-proof" accept="image/*">
                </div>
            </div>
            
            <div style="display: flex; gap: 10px; margin-top: 20px;">
                <button id="submit-cycle-settlement" class="btn-primary" style="flex: 1;">
                    Submit Settlement
                </button>
                <button onclick="document.getElementById('cycle-settlement-modal').style.display='none'" 
                        class="btn-secondary" style="flex: 1;">
                    Cancel
                </button>
            </div>
        </div>
    `;

    document.body.appendChild(cycleSettlementModal);

    cycleSettlementModal.querySelectorAll('input[name="cycle-payment-method"]').forEach(input => {
        input.addEventListener('change', function () {
            const manualSection = cycleSettlementModal.querySelector('#cycle-manual-payment');
            manualSection.style.display = this.value === 'manual' ? 'block' : 'none';
        });
    });

    cycleSettlementModal.querySelector('#submit-cycle-settlement').addEventListener('click', submitCycleSettlement);

    cycleSettlementModal.addEventListener('click', (e) => {
        if (e.target === cycleSettlementModal) {
            cycleSettlementModal.style.display = 'none';
        }
    });
}

async function submitCycleSettlement() {
    if (!currentCycleSettlementRequirement) return;

    const paymentMethod = document.querySelector('input[name="cycle-payment-method"]:checked').value;
    let proofImage = '';

    if (paymentMethod === 'manual') {
        const fileInput = document.getElementById('cycle-proof');
        if (!fileInput || fileInput.files.length === 0) {
            alert('Please upload payment proof for manual transfer');
            return;
        }

        const file = fileInput.files[0];
        try {
            proofImage = await readFileAsBase64(file);
        } catch (error) {
            alert('Error reading the image file');
            return;
        }
    }

    const btn = document.querySelector('#submit-cycle-settlement');
    const originalText = btn.textContent;
    btn.textContent = 'Processing...';
    btn.disabled = true;

    try {
        const response = await authFetch('/api/cycle/settlement', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                investmentId: currentCycleSettlementRequirement.investmentId,
                paymentMethod: paymentMethod,
                proofImage: proofImage
            })
        });

        const data = await response.json();

        if (data.success) {
            cycleSettlementModal.style.display = 'none';
            showSuccessModal(data.message);

            await loadUserData(currentUserEmail);
        } else {
            alert(data.message);
        }
    } catch (error) {
        console.error('Settlement submission error:', error);
        alert('Error submitting settlement');
    } finally {
        btn.textContent = originalText;
        btn.disabled = false;
    }
}

async function confirmWithdrawal() {
    const amount = parseFloat(withdrawalAmountInput.value);

    if (!amount || amount < MIN_WITHDRAWAL) {
        alert(`Minimum withdrawal amount is N${MIN_WITHDRAWAL.toLocaleString()}`);
        return;
    }

    try {
        const response = await authFetch('/api/withdraw/request', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                amount: amount
            })
        });

        const data = await response.json();

        if (data.success) {
            withdrawalModal.style.display = 'none';
            showSuccessModal(`Withdrawal request for N${amount.toLocaleString()} submitted! Waiting for admin approval.`);
            await loadUserData(currentUserEmail);
        } else {
            alert(data.message || 'Insufficient funds');
        }
    } catch (error) {
        console.error('Withdrawal Error:', error);
        alert('An error occurred processing withdrawal request.');
    }
}

function loadUsersList() {
    const searchTerm = userSearchInput ? userSearchInput.value.toLowerCase() : '';

    let filteredUsers = users;
    if (searchTerm) {
        filteredUsers = users.filter(user =>
            user.fullName.toLowerCase().includes(searchTerm) ||
            user.email.toLowerCase().includes(searchTerm) ||
            (user.referralCode && user.referralCode.toLowerCase().includes(searchTerm)) ||
            (user.referredBy && user.referredBy.toLowerCase().includes(searchTerm))
        );
    }

    if (filteredUsers.length === 0) {
        usersListElement.innerHTML = '<p>No users found</p>';
        return;
    }

    usersListElement.innerHTML = filteredUsers.map((user, index) => {
        let investmentHtml = '';
        if (user.activeInvestments && user.activeInvestments.length > 0) {
            investmentHtml = user.activeInvestments.map(inv => {
                const maturityDate = new Date(inv.maturityDate).toLocaleDateString();
                return `
                    <div style="background: #e0f2f1; padding: 5px 8px; border-radius: 4px; margin-top: 5px; font-size: 0.85rem; border-left: 3px solid #004d40;">
                        <strong>${safeString(inv.package)}:</strong> N${safeNumberFormat(inv.amount)} 
                        <span style="color: #666;">&rarr;</span> 
                        <strong style="color: #2e7d32;">N${safeNumberFormat(inv.totalReturn)}</strong>
                        <br>
                        <span style="font-size: 0.8em; color: #555;">Matures: ${maturityDate}</span>
                    </div>
                `;
            }).join('');
        } else {
            investmentHtml = `<div style="font-size: 0.8rem; color: #999; font-style: italic; margin-top: 5px;">No active investments</div>`;
        }

        return `
        <div class="user-item ${user.suspended ? 'suspended' : ''}" style="align-items: flex-start;">
            <div class="user-info">
                <strong>${safeString(user.fullName, 'Unknown')}</strong>
                <span class="user-status ${user.suspended ? 'status-suspended' : 'status-active'}">
                    ${user.suspended ? 'Suspended' : 'Active'}
                </span>
                <div class="user-details">
                    <small>${safeString(user.email, 'No email')} | ${safeString(user.mobile, 'No mobile')}</small><br>
                    <small>Referral Code: ${safeString(user.referralCode, 'None')} | Referred By: ${safeString(user.referredBy, 'None')}</small><br>
                    <small>Bank: ${safeString(user.bankName, 'Unknown')} | Account: ${safeString(user.accountNumber, 'Unknown')}</small>
                </div>

                <div class="user-investments-snapshot" style="margin-top: 10px; padding-top: 5px; border-top: 1px dashed #ddd;">
                    ${investmentHtml}
                </div>

                <div class="user-stats">
                    <div class="user-stat">Withdrawal: N${safeNumberFormat(user.withdrawalBalance || 0)}</div>
                    <div class="user-stat">Bonus: N${safeNumberFormat(user.referralBonus || 0)}</div>
                </div>
            </div>
            <div class="user-actions">
                <button class="user-action-btn btn-credit" onclick="openCreditModal('${user.email}')">Credit</button>
                <button class="user-action-btn btn-debit" onclick="openDebitModal('${user.email}')">Debit</button>
                <button class="user-action-btn btn-edit-bank" onclick="openEditBankModal('${user.email}')">Edit Bank</button>
                <button class="user-action-btn btn-view-investments" onclick="loadUserInvestmentsModal('${user.email}')" style="background-color: #6f42c1; color: white;">View Investments</button>
                <button class="user-action-btn ${user.suspended ? 'btn-unsuspend' : 'btn-suspend'}" 
                        onclick="openSuspendModal('${user.email}', ${user.suspended})">
                    ${user.suspended ? 'Unsuspend' : 'Suspend'}
                </button>
                <button class="user-action-btn btn-delete" onclick="openDeleteModal('${user.email}')">Delete</button>
            </div>
        </div>
        `;
    }).join('');
}

async function loadWithdrawalRequests() {
    try {
        const response = await authFetch('/api/admin/withdrawals');
        if (response) {
            const requests = await response.json();
            renderWithdrawalRequests(requests);
        }
    } catch (error) {
        console.error('Error loading withdrawals:', error);
    }
}

function renderWithdrawalRequests(requests) {
    if (!withdrawalRequestsListElement) return;
    const pendingRequests = requests.filter(r => r.status === 'Pending');

    if (pendingRequests.length === 0) {
        withdrawalRequestsListElement.innerHTML = '<p class="no-transactions">No pending withdrawal requests.</p>';
        return;
    }

    withdrawalRequestsListElement.innerHTML = pendingRequests.map(req => `
        <div class="withdrawal-request-card" style="border: 1px solid #ddd; border-left: 5px solid #ffd700; padding: 15px; margin-bottom: 10px; border-radius: 5px; display: flex; justify-content: space-between; align-items: center; background: #fff;">
            <div class="req-info">
                <strong>${req.userEmail}</strong>
                <div class="req-amount" style="font-size: 1.2em; font-weight: bold; color: #e75480;">N${safeNumberFormat(req.amount)}</div>
                <div class="req-bank" style="background: #f9f9f9; padding: 5px; margin-top: 5px; border-radius: 4px; font-size: 0.9em;">
                    ${req.bankName}<br>
                    ${req.accountNumber}
                </div>
                <small class="req-date">${new Date(req.requestDate).toLocaleDateString()}</small>
            </div>
            <div class="req-actions" style="display: flex; gap: 10px; flex-direction: column;">
                <button class="btn-approve" onclick="processWithdrawal('${req._id}', 'approve')" style="background-color: #28a745; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">Approve</button>
                <button class="btn-reject" onclick="processWithdrawal('${req._id}', 'reject')" style="background-color: #dc3545; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">Reject</button>
            </div>
        </div>
    `).join('');
}

window.processWithdrawal = async function (id, action) {
    if (!confirm(`Are you sure you want to ${action} this withdrawal?`)) return;
    try {
        const response = await authFetch('/api/admin/withdrawals/action', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ withdrawalId: id, action: action })
        });
        const data = await response.json();
        if (data.success) {
            showSuccessModal(`Withdrawal ${action}ed successfully.`);
            loadWithdrawalRequests();
            loadAdminData();
        } else {
            alert(data.message || 'Action failed');
        }
    } catch (error) {
        console.error('Error processing withdrawal:', error);
    }
};

async function loadPendingInvestments() {
    try {
        const response = await authFetch('/api/admin/investments/pending');
        if (response) {
            const investments = await response.json();
            renderPendingInvestments(investments);
        }
    } catch (error) {
        console.error('Error loading pending investments:', error);
    }
}

function renderPendingInvestments(investments) {
    if (!pendingInvestmentsListElement) return;

    if (investments.length === 0) {
        pendingInvestmentsListElement.innerHTML = '<p class="no-transactions">No pending investment approvals.</p>';
        return;
    }

    pendingInvestmentsListElement.innerHTML = investments.map(inv => {
        const isWalletInvestment = inv.paymentMethod === 'Wallet';
        const borderColor = isWalletInvestment ? '#28a745' : '#007bff';
        const titleColor = isWalletInvestment ? '#28a745' : '#007bff';

        let proofHtml = '';
        let actionButtons = '';
        let notificationBar = '';

        actionButtons = `
            <button class="btn-approve-inv" onclick="processInvestment('${inv._id}', 'approve')" style="background-color: #28a745; color: white; border: none; padding: 6px 10px; border-radius: 4px; cursor: pointer;">Approve</button>
            <button class="btn-reject-inv" onclick="processInvestment('${inv._id}', 'reject')" style="background-color: #dc3545; color: white; border: none; padding: 6px 10px; border-radius: 4px; cursor: pointer;">Reject</button>
        `;

        if (isWalletInvestment) {
            proofHtml = `<span style="color: #999; font-style: italic;">Wallet Balance Payment</span>`;

            notificationBar = `
                <div style="background-color: #e8f5e8; border-left: 4px solid #28a745; padding: 10px; margin-top: 10px; border-radius: 4px;">
                    <p style="margin: 0; color: #155724; font-size: 0.9em;">
                        it was wallet balance investment hence no proof of payment is required
                    </p>
                </div>
            `;
        } else {
            if (inv.proofImage && inv.proofImage !== 'Wallet-Payment') {
                proofHtml = `<button class="btn-view-proof" onclick="viewProof('${inv.proofImage}')" style="background-color: #17a2b8; color: white; border: none; padding: 6px 10px; border-radius: 4px; cursor: pointer;">View Proof</button>`;
            } else {
                proofHtml = `<span style="color: #999;">Withdrawal Balance Investment</span>`;
            }
        }

        const statusBadge = isWalletInvestment
            ? `<span style="background-color: #28a745; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em; font-weight: bold;">Wallet</span>`
            : `<span style="background-color: #007bff; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em; font-weight: bold;">Manual</span>`;

        return `
        <div class="investment-approval-card" style="border: 1px solid #ddd; border-left: 5px solid ${borderColor}; padding: 15px; margin-bottom: 10px; border-radius: 5px; background: #fff;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                <div class="req-info" style="flex: 1;">
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                        <strong>${inv.userEmail}</strong>
                        ${statusBadge}
                    </div>
                    <div class="req-amount" style="font-size: 1.2em; font-weight: bold; color: ${titleColor};">
                        ${inv.package}: N${safeNumberFormat(inv.amount)}
                    </div>
                    <div style="color: #666; font-size: 0.9em; margin-top: 5px;">
                        <div>Return: ${inv.returnRate}% in ${inv.duration} days</div>
                        <div>Expected Return: N${safeNumberFormat(inv.totalReturn || (inv.amount * (1 + inv.returnRate / 100)))}</div>
                        <div>Requested: ${new Date(inv.date).toLocaleDateString()}</div>
                    </div>
                </div>
                <div class="req-actions" style="display: flex; gap: 5px; flex-direction: column; text-align: center;">
                    ${proofHtml}
                    ${actionButtons}
                </div>
            </div>
            ${notificationBar}
        </div>
        `;
    }).join('');
}

window.viewProof = function (imageUrl) {
    const imgDisplay = document.getElementById('proof-image-display');
    imgDisplay.src = imageUrl;
    proofViewModal.style.display = 'block';
};

window.processInvestment = async function (id, action) {
    if (!confirm(`Are you sure you want to ${action} this investment? This cannot be undone.`)) return;

    try {
        const response = await authFetch('/api/admin/investments/action', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                investmentId: id,
                action: action
            })
        });

        const data = await response.json();

        if (data.success) {
            showSuccessModal(`Investment ${action}ed successfully.`);
            loadPendingInvestments();
            loadAdminData();
        } else {
            alert(data.message || 'Action failed');
        }
    } catch (error) {
        console.error('Error processing investment:', error);
    }
};

async function loadPendingWalletRecommitments() {
    try {
        const response = await authFetch('/api/admin/recommitments/pending');
        if (response) {
            const recommitments = await response.json();
            renderPendingWalletRecommitments(recommitments);
        }
    } catch (error) {
        console.error('Error loading pending wallet recommitments:', error);
    }
}

function renderPendingWalletRecommitments(recommitments) {
    const container = document.getElementById('pending-wallet-recommitments-list');
    if (!container) return;

    if (recommitments.length === 0) {
        container.innerHTML = '<p class="no-transactions">No pending wallet recommitments</p>';
        return;
    }

    container.innerHTML = recommitments.map(rec => `
        <div class="recommitment-card" style="border: 1px solid #ddd; border-left: 5px solid #007bff; padding: 15px; margin-bottom: 10px; border-radius: 5px; background: #fff;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                <div style="flex: 1;">
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                        <strong>${rec.user.fullName}</strong>
                        <span style="background-color: #007bff; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;">Wallet Recommitment</span>
                    </div>
                    <div style="font-size: 1.2em; font-weight: bold; color: #007bff;">
                        N${rec.recommitmentAmount.toLocaleString()}
                    </div>
                    <div style="color: #666; font-size: 0.9em; margin-top: 5px;">
                        <div>Original Investment: N${rec.originalInvestmentAmount.toLocaleString()}</div>
                        <div>Wallet Deduction: N${rec.walletDeduction.toLocaleString()} (${Math.round((rec.walletDeduction / rec.recommitmentAmount) * 100)}%)</div>
                        <div>User Wallet Balance: N${rec.user.walletBalance.toLocaleString()}</div>
                        <div>Requested: ${new Date(rec.date).toLocaleDateString()}</div>
                    </div>
                </div>
                <div style="display: flex; gap: 5px; flex-direction: column;">
                    <button class="btn-approve" onclick="processWalletRecommitment('${rec._id}', 'approve')" 
                            style="background-color: #28a745; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">
                        Approve
                    </button>
                    <button class="btn-reject" onclick="processWalletRecommitment('${rec._id}', 'reject')" 
                            style="background-color: #dc3545; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">
                        Reject
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

window.processWalletRecommitment = async function (id, action) {
    if (!confirm(`Are you sure you want to ${action} this wallet recommitment?`)) return;

    try {
        const response = await authFetch('/api/admin/recommitments/action', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ recommitmentId: id, action: action })
        });

        const data = await response.json();
        if (data.success) {
            showSuccessModal(`Recommitment ${action}ed successfully`);
            loadPendingWalletRecommitments();
        } else {
            alert(data.message || 'Action failed');
        }
    } catch (error) {
        console.error('Error processing wallet recommitment:', error);
        alert('Error processing recommitment');
    }
};

async function loadPendingCycleSettlements() {
    try {
        const response = await authFetch('/api/admin/cycle/settlements/pending');
        if (response) {
            const settlements = await response.json();
            renderPendingCycleSettlements(settlements);
        }
    } catch (error) {
        console.error('Error loading pending cycle settlements:', error);
    }
}

function renderPendingCycleSettlements(settlements) {
    const container = document.getElementById('cycle-settlements-list');
    if (!container) return;

    if (settlements.length === 0) {
        container.innerHTML = '<p class="no-transactions">No pending cycle settlements</p>';
        return;
    }

    container.innerHTML = settlements.map(settlement => `
        <div class="settlement-card" style="border: 1px solid #ddd; border-left: 5px solid #17a2b8; padding: 15px; margin-bottom: 10px; border-radius: 5px; background: #fff;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                <div style="flex: 1;">
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                        <strong>${settlement.userEmail}</strong>
                        <span style="background-color: #17a2b8; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;">
                            Cycle ${settlement.investmentCycle}
                        </span>
                    </div>
                    <div style="font-size: 1.2em; font-weight: bold; color: #17a2b8;">
                        N${settlement.settlementAmount.toLocaleString()}
                    </div>
                    <div style="color: #666; font-size: 0.9em; margin-top: 5px;">
                        <div>Package: ${settlement.package}</div>
                        <div>Original Amount: N${settlement.amount.toLocaleString()}</div>
                        <div>Returns to Release: N${settlement.totalReturn.toLocaleString()}</div>
                        <div>Payment Method: ${settlement.paymentMethod}</div>
                        <div>Submitted: ${new Date(settlement.settlementDate).toLocaleDateString()}</div>
                    </div>
                </div>
                <div style="display: flex; gap: 5px; flex-direction: column;">
                    <button class="btn-approve" onclick="approveCycleSettlement('${settlement._id}')" 
                            style="background-color: #28a745; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">
                        Approve & Release Returns
                    </button>
                    <button class="btn-reject" onclick="rejectCycleSettlement('${settlement._id}')" 
                            style="background-color: #dc3545; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">
                        Reject
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

window.approveCycleSettlement = async function (investmentId) {
    if (!confirm(`Are you sure you want to approve this cycle settlement and release returns to the user?`)) return;

    try {
        const response = await authFetch('/api/admin/cycle/settlement/approve', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ investmentId: investmentId })
        });

        const data = await response.json();
        if (data.success) {
            showSuccessModal(`Cycle settlement approved successfully. Returns released to user.`);
            loadPendingCycleSettlements();
            loadAdminData();
        } else {
            alert(data.message || 'Approval failed');
        }
    } catch (error) {
        console.error('Error approving cycle settlement:', error);
        alert('Error approving settlement');
    }
};

window.rejectCycleSettlement = async function (investmentId) {
    const reason = prompt("Please enter a reason for rejecting this settlement:");
    if (reason === null) return;

    if (!confirm(`Are you sure you want to REJECT this cycle settlement? The funds will be refunded to the user's wallet (if paid via wallet) and they will have to restart the settlement process.`)) return;

    try {
        const response = await authFetch('/api/admin/cycle/settlement/reject', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ investmentId: investmentId, reason: reason })
        });

        const data = await response.json();
        if (data.success) {
            showSuccessModal(data.message);
            loadPendingCycleSettlements();
            loadAdminData();
        } else {
            alert(data.message || 'Rejection failed');
        }
    } catch (error) {
        console.error('Error rejecting cycle settlement:', error);
        alert('Error rejecting settlement');
    }
};

window.loadUserInvestmentsModal = async function (email) {
    try {
        const response = await authFetch(`/api/admin/users/${email}/investments`);
        const data = await response.json();

        if (!data.success) {
            alert('Error loading user investments');
            return;
        }

        currentViewingUserEmail = email;

        document.getElementById('user-investments-modal-title').textContent = `${data.user.fullName}'s Investments`;
        document.getElementById('user-investments-modal-subtitle').textContent = `Email: ${data.user.email}`;

        const investmentsList = document.getElementById('user-investments-list');
        if (data.investments.length === 0) {
            investmentsList.innerHTML = '<p class="no-investments">No investments found</p>';
        } else {
            investmentsList.innerHTML = data.investments.map(inv => {
                const statusClass = inv.status.toLowerCase();
                const isDeletable = ['Pending', 'Active'].includes(inv.status);
                const deleteButton = isDeletable ?
                    `<button class="user-action-btn btn-delete" onclick="deleteUserInvestment('${data.user.email}', '${inv._id}')" style="margin-top: 5px; padding: 4px 8px; font-size: 0.8rem;">
                        Delete
                    </button>` :
                    '<small style="color: #999; font-style: italic;">Cannot delete</small>';

                const cycleInfo = inv.investmentCycle ? ` (Cycle ${inv.investmentCycle})` : '';
                const settlementInfo = inv.cycleSettlementRequired ? '<span style="color: #ff9800; font-weight: bold;"> - Settlement Required</span>' : '';

                return `
                <div class="investment-item" style="margin-bottom: 10px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background-color: #f9f9f9;">
                    <div class="investment-details">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <strong>${inv.package} Package${cycleInfo}${settlementInfo}</strong>
                            <span class="package-status ${statusClass}" style="font-size: 0.8rem; padding: 3px 8px;">${inv.status}</span>
                        </div>
                        <div style="display: flex; justify-content: space-between; margin-top: 10px;">
                            <div>
                                <small>Amount: N${inv.amount.toLocaleString()}</small><br>
                                <small>Payment: ${inv.paymentMethod}</small><br>
                                <small>Date: ${new Date(inv.date).toLocaleDateString()}</small>
                            </div>
                            <div style="text-align: right;">
                                ${deleteButton}
                            </div>
                        </div>
                        ${inv.profit ? `<small style="color: #666; display: block; margin-top: 5px;">Expected Profit: N${inv.profit.toLocaleString()}</small>` : ''}
                    </div>
                </div>
                `;
            }).join('');
        }

        userInvestmentsModal.style.display = 'block';

    } catch (error) {
        console.error('Error loading user investments:', error);
        alert('Error loading investments');
    }
};

window.deleteUserInvestment = async function (userEmail, investmentId) {
    try {
        const response = await authFetch(`/api/admin/users/${userEmail}/investments`);
        const data = await response.json();

        if (!data.success) {
            alert('Error fetching investment details');
            return;
        }

        const investment = data.investments.find(inv => inv._id === investmentId);
        if (!investment) {
            alert('Investment not found');
            return;
        }

        if (!['Pending', 'Active'].includes(investment.status)) {
            alert(`Cannot delete investment with status: ${investment.status}. Only Pending or Active investments can be deleted.`);
            return;
        }

        currentInvestmentToDelete = {
            id: investmentId,
            userEmail: userEmail,
            userName: data.user.fullName,
            investment: investment
        };

        document.getElementById('delete-investment-user-name').textContent = data.user.fullName;

        const detailsHtml = `
            <div>
                <p><strong>Package:</strong> ${investment.package}</p>
                <p><strong>Amount:</strong> N${investment.amount.toLocaleString()}</p>
                <p><strong>Status:</strong> ${investment.status}</p>
                <p><strong>Payment Method:</strong> ${investment.paymentMethod}</p>
                <p><strong>Date:</strong> ${new Date(investment.date).toLocaleDateString()}</p>
                ${investment.profit ? `<p><strong>Expected Profit:</strong> N${investment.profit.toLocaleString()}</p>` : ''}
            </div>
        `;

        document.getElementById('delete-investment-details').innerHTML = detailsHtml;

        const refundNote = document.getElementById('refund-note');
        if (investment.paymentMethod === 'Wallet') {
            refundNote.textContent = 'Funds will be automatically refunded to user wallet.';
        } else {
            refundNote.textContent = 'Manual refund required. Admin will process bank transfer.';
        }

        document.getElementById('delete-investment-reason').value = '';
        deleteInvestmentModal.style.display = 'block';

    } catch (error) {
        console.error('Error opening delete investment modal:', error);
        alert('Error loading investment details');
    }
};

async function confirmInvestmentDelete() {
    if (!currentInvestmentToDelete) return;

    const reason = document.getElementById('delete-investment-reason').value;
    if (!reason.trim()) {
        alert('Please provide a reason for deletion');
        return;
    }

    const confirmMsg = `Are you sure you want to delete this investment?\n\n` +
        `User: ${currentInvestmentToDelete.userName}\n` +
        `Amount: N${currentInvestmentToDelete.investment.amount.toLocaleString()}\n` +
        `Package: ${currentInvestmentToDelete.investment.package}\n` +
        `Reason: ${reason}`;

    if (!confirm(confirmMsg)) {
        return;
    }

    const btn = document.getElementById('confirm-investment-delete');
    const originalText = btn.textContent;
    btn.textContent = 'Processing...';
    btn.disabled = true;

    try {
        const response = await authFetch(`/api/admin/investments/${currentInvestmentToDelete.id}`, {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ reason: reason })
        });

        const data = await response.json();

        if (data.success) {
            deleteInvestmentModal.style.display = 'none';
            showSuccessModal(data.message);

            await loadAdminData();

            if (currentViewingUserEmail) {
                await loadUserInvestmentsModal(currentViewingUserEmail);
            }

        } else {
            alert(data.message || 'Failed to delete investment');
        }

    } catch (error) {
        console.error('Error deleting investment:', error);
        alert('Error deleting investment');
    } finally {
        btn.textContent = originalText;
        btn.disabled = false;
        currentInvestmentToDelete = null;
    }
}

window.openCreditModal = function (email) {
    const user = users.find(u => u.email === email);
    if (!user) return;
    currentManagedUserEmail = email;
    document.getElementById('credit-user-name').textContent = user.fullName;
    document.getElementById('credit-amount').value = 1000;
    document.getElementById('credit-description').value = '';
    creditUserModal.style.display = 'block';
};

window.openDebitModal = function (email) {
    const user = users.find(u => u.email === email);
    if (!user) return;
    currentManagedUserEmail = email;
    document.getElementById('debit-user-name').textContent = user.fullName;
    document.getElementById('debit-current-balance').textContent = `N${safeNumberFormat(user.withdrawalBalance || 0)}`;
    document.getElementById('debit-amount').value = 1000;
    document.getElementById('debit-description').value = '';
    debitUserModal.style.display = 'block';
};

window.openEditBankModal = function (email) {
    const user = users.find(u => u.email === email);
    if (!user) return;
    currentManagedUserEmail = email;
    document.getElementById('edit-bank-user-name').textContent = user.fullName;
    document.getElementById('edit-bank-name').value = user.bankName || '';
    document.getElementById('edit-account-number').value = user.accountNumber || '';
    editBankModal.style.display = 'block';
};

window.openSuspendModal = function (email, isSuspended) {
    const user = users.find(u => u.email === email);
    if (!user) return;
    currentManagedUserEmail = email;
    document.getElementById('suspend-user-name').textContent = user.fullName;
    document.getElementById('suspend-action-text').textContent = isSuspended ? 'unsuspend' : 'suspend';
    document.getElementById('suspend-reason').value = '';
    const confirmButton = document.getElementById('confirm-suspend');
    confirmButton.textContent = isSuspended ? 'Unsuspend User' : 'Suspend User';
    confirmButton.className = isSuspended ? 'btn-primary' : 'btn-danger';
    suspendUserModal.style.display = 'block';
};

window.openDeleteModal = function (email) {
    const user = users.find(u => u.email === email);
    if (!user) return;
    currentManagedUserEmail = email;
    document.getElementById('delete-user-name').textContent = user.fullName;
    document.getElementById('delete-reason').value = '';
    deleteUserModal.style.display = 'block';
};

async function handleAdminAction(action, details) {
    try {
        const response = await authFetch('/api/admin/user-action', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                userEmail: currentManagedUserEmail,
                action: action,
                ...details
            })
        });
        const data = await response.json();
        if (data.success) {
            await loadAdminData();
            return true;
        } else {
            alert(data.message || 'Action failed');
            return false;
        }
    } catch (error) {
        console.error('Admin Action Error:', error);
        return false;
    }
}

async function confirmCredit() {
    const amount = parseFloat(document.getElementById('credit-amount').value);
    const description = document.getElementById('credit-description').value;

    if (!amount || amount < 100) {
        alert('Please enter a valid amount (minimum N100)');
        return;
    }

    const success = await handleAdminAction('credit', { amount, description });
    if (success) {
        creditUserModal.style.display = 'none';
        showSuccessModal('User account credited successfully.');
    }
}

async function confirmDebit() {
    const amount = parseFloat(document.getElementById('debit-amount').value);
    const description = document.getElementById('debit-description').value;

    if (!amount || amount < 100) {
        alert('Please enter a valid amount (minimum N100)');
        return;
    }

    const success = await handleAdminAction('debit', { amount, description });
    if (success) {
        debitUserModal.style.display = 'none';
        showSuccessModal('User account debited successfully.');
    }
}

async function confirmBankEdit() {
    const bankName = document.getElementById('edit-bank-name').value;
    const accountNumber = document.getElementById('edit-account-number').value;

    if (!bankName.trim() || !accountNumber.trim()) {
        alert('Please fill in all bank details');
        return;
    }

    const success = await handleAdminAction('edit-bank', { bankName, accountNumber });
    if (success) {
        editBankModal.style.display = 'none';
        showSuccessModal('Bank details updated successfully.');
    }
}

async function confirmSuspend() {
    const reason = document.getElementById('suspend-reason').value;
    const user = users.find(u => u.email === currentManagedUserEmail);
    const action = user.suspended ? 'unsuspend' : 'suspend';

    const success = await handleAdminAction(action, { description: reason });
    if (success) {
        suspendUserModal.style.display = 'none';
        showSuccessModal(`User account ${action}ed successfully.`);
    }
}

async function confirmDelete() {
    const reason = document.getElementById('delete-reason').value;

    const success = await handleAdminAction('delete', { description: reason });
    if (success) {
        deleteUserModal.style.display = 'none';
        showSuccessModal('User deleted successfully.');
    }
}

function showSuccessModal(message) {
    document.getElementById('success-message').textContent = message;
    successModal.style.display = 'block';
}