ET
EvaTrade
Live Markets
ET
EvaTrade
Total Net Asset Value $0.00
Live Pricing Active

Pricing matrices automatically sync with live global markets every 15s.

ALT/USDT

Loading...

ALT

Place Trade

Potential Win (65%): 1.65 USDT

Active Trades

No active trades
AVAILABLE BALANCE 0.00 USDT Ready to trade
IN TRADE 0.00 USDT Active stakes
WIN RATE 0% 0 trades closed
CREDIT SCORE 100/100
PROFIT RATE 65% Win payout per trade
t first if they are currently signed in) function goToLoginFromSuccess() { currentAuthMode = 'login'; isJustRegistered = false; const proceed = () => { // Restore default logo header const authHeader = document.getElementById('auth-header'); if (authHeader) authHeader.classList.remove('hidden'); // Show login form, hide others document.getElementById('login-form').classList.remove('hidden'); document.getElementById('signup-form').classList.add('hidden'); const successContainer = document.getElementById('signup-success-container'); if (successContainer) successContainer.classList.add('hidden'); // Restore footer toggle text const toggleText = document.getElementById('auth-toggle-text'); if (toggleText) { toggleText.classList.remove('hidden'); toggleText.innerHTML = `Don't have an account? Register Now`; } // Reset inputs document.getElementById('signup-form').reset(); // Ensure defaults const authTitle = document.getElementById('auth-title'); const authSubtitle = document.getElementById('auth-subtitle'); if (authTitle) if(authTitle) authTitle.innerText = "Secure Platform Login"; if (authSubtitle) if(authSubtitle) authSubtitle.innerText = "Access your digital assets and professional trading platform"; }; if (isFirebaseActive && auth && auth.currentUser) { auth.signOut().then(proceed).catch(proceed); } else { proceed(); } } // Set Up Form Listeners function setupFormListeners() { // 1. Login Submit const el_login_form = document.getElementById('login-form'); if (el_login_form) el_login_form.addEventListener('submit', (e) => { e.preventDefault(); const email = document.getElementById('login-email').value.trim(); const pass = document.getElementById('login-password').value; if (isFirebaseActive) { auth.signInWithEmailAndPassword(email, pass) .then((cred) => { // On successful login, also add to local cache to keep it up-to-date let registeredEmails = []; try { const stored = localStorage.getItem(KEYS.REGISTERED_FIREBASE_EMAILS); if (stored) registeredEmails = JSON.parse(stored); } catch (ex) {} if (!registeredEmails.includes(email.toLowerCase())) { registeredEmails.push(email.toLowerCase()); localStorage.setItem(KEYS.REGISTERED_FIREBASE_EMAILS, JSON.stringify(registeredEmails)); } showToast("Secure connection established!", "success"); }) .catch((err) => { const errMsg = err.message || ''; const errCode = err.code || ''; // Handle classic clear status codes if (errCode === 'auth/user-not-found' || errMsg.includes('user-not-found')) { showToast("Signup First", "error"); return; } if (errCode === 'auth/wrong-password' || errMsg.includes('wrong-password')) { showToast("Wrong Password", "error"); return; } // If modern email protection returns auth/invalid-credential: if (errCode === 'auth/invalid-credential' || errMsg.includes('invalid-credential')) { const normalizedEmail = email.toLowerCase(); // 1. First check client local registered cache let registeredEmails = []; try { const stored = localStorage.getItem(KEYS.REGISTERED_FIREBASE_EMAILS); if (stored) registeredEmails = JSON.parse(stored); } catch (ex) {} if (registeredEmails.includes(normalizedEmail)) { showToast("Wrong Password", "error"); return; } // 2. Try fetchSignInMethodsForEmail (highly reliable check in standard configuration) auth.fetchSignInMethodsForEmail(email) .then((methods) => { if (methods && methods.length > 0) { // Email is registered in Auth! Update cache and show correct toast if (!registeredEmails.includes(normalizedEmail)) { registeredEmails.push(normalizedEmail); localStorage.setItem(KEYS.REGISTERED_FIREBASE_EMAILS, JSON.stringify(registeredEmails)); } showToast("Wrong Password", "error"); } else { // 3. Fallback to querying Firestore registered_emails collection db.collection('registered_emails').doc(normalizedEmail).get() .then((doc) => { if (doc.exists) { if (!registeredEmails.includes(normalizedEmail)) { registeredEmails.push(normalizedEmail); localStorage.setItem(KEYS.REGISTERED_FIREBASE_EMAILS, JSON.stringify(registeredEmails)); } showToast("Wrong Password", "error"); } else { showToast("Signup First", "error"); } }) .catch((dbErr) => { showToast("Signup First", "error"); }); } }) .catch((fetchErr) => { // Fallback to querying Firestore registered_emails collection if fetchSignInMethodsForEmail is blocked db.collection('registered_emails').doc(normalizedEmail).get() .then((doc) => { if (doc.exists) { if (!registeredEmails.includes(normalizedEmail)) { registeredEmails.push(normalizedEmail); localStorage.setItem(KEYS.REGISTERED_FIREBASE_EMAILS, JSON.stringify(registeredEmails)); } showToast("Wrong Password", "error"); } else { showToast("Signup First", "error"); } }) .catch((dbErr) => { showToast("Signup First", "error"); }); }); } else { showToast(err.message, "error"); } }); } else { currentUser = { uid: 'sim-user', email: email }; try { localStorage.setItem('is_logged_in', 'true'); } catch (e) {} showToast("Local session started!", "success"); showScreen('app-screen'); } }); // 2. Signup Submit const el_signup_form = document.getElementById('signup-form'); if (el_signup_form) el_signup_form.addEventListener('submit', (e) => { e.preventDefault(); const username = document.getElementById('signup-username').value.trim(); const countryCode = document.getElementById('signup-country-code').value; let inputPhone = document.getElementById('signup-phone').value.trim(); if (inputPhone.startsWith('0')) { inputPhone = inputPhone.substring(1); } const phone = inputPhone.startsWith('+') ? inputPhone : (countryCode + " " + inputPhone); const email = document.getElementById('signup-email').value.trim(); const pass = document.getElementById('signup-password').value; const confirmPass = document.getElementById('signup-confirm-password').value; if (pass !== confirmPass) { showToast("Passwords do not match!", "error"); return; } if (isFirebaseActive) { isJustRegistered = true; auth.createUserWithEmailAndPassword(email, pass) .then((cred) => { // Add to local cache of registered Firebase emails let registeredEmails = []; try { const stored = localStorage.getItem(KEYS.REGISTERED_FIREBASE_EMAILS); if (stored) registeredEmails = JSON.parse(stored); } catch (ex) {} if (!registeredEmails.includes(email.toLowerCase())) { registeredEmails.push(email.toLowerCase()); localStorage.setItem(KEYS.REGISTERED_FIREBASE_EMAILS, JSON.stringify(registeredEmails)); } // Create user doc and registered_emails doc in Firestore const batch = db.batch(); const userRef = db.collection('users').doc(cred.user.uid); const emailRef = db.collection('registered_emails').doc(email.toLowerCase()); batch.set(userRef, { username: username, phone: phone, email: email, password: pass, accountBalance: DEFAULTS.USDT.balance, inTradeBalance: 0, creditScore: 100, binWins: 0, binTradesClosed: 0, createdAt: firebase.firestore.FieldValue.serverTimestamp() }); batch.set(emailRef, { registered: true }); return batch.commit(); }) .then(() => { showToast("Account created & secured successfully!", "success"); showSignupSuccess(); }) .catch((err) => { isJustRegistered = false; const errCode = err.code || ''; const errMsg = err.message || ''; if (errCode === 'auth/email-already-in-use' || errMsg.includes('email-already-in-use')) { // Self-healing: update registered_emails collection and local cache const normalizedEmail = email.toLowerCase(); let registeredEmails = []; try { const stored = localStorage.getItem(KEYS.REGISTERED_FIREBASE_EMAILS); if (stored) registeredEmails = JSON.parse(stored); } catch (ex) {} if (!registeredEmails.includes(normalizedEmail)) { registeredEmails.push(normalizedEmail); localStorage.setItem(KEYS.REGISTERED_FIREBASE_EMAILS, JSON.stringify(registeredEmails)); } db.collection('registered_emails').doc(normalizedEmail).set({ registered: true }) .catch(() => {}); showToast("Account already exists! Please Login", "warning"); } else { showToast(err.message, "error"); } }); } else { currentUser = { uid: 'sim-user', email: email }; try { localStorage.setItem('is_logged_in', 'true'); } catch (e) {} showToast("Local session started!", "success"); showScreen('app-screen'); } }); // 3. Logout Buttons const el_btn_logout = document.getElementById('btn-logout'); if (el_btn_logout) el_btn_logout.addEventListener('click', performLogout); // 5. Firebase configuration form submit const el_firebase_config_form = document.getElementById('firebase-config-form'); if (el_firebase_config_form) el_firebase_config_form.addEventListener('submit', (e) => { e.preventDefault(); const config = { apiKey: document.getElementById('fb-apiKey').value.trim(), authDomain: document.getElementById('fb-authDomain').value.trim(), projectId: document.getElementById('fb-projectId').value.trim(), storageBucket: document.getElementById('fb-storageBucket').value.trim(), appId: document.getElementById('fb-appId').value.trim() }; if (!config.apiKey || !config.projectId) { showToast("Please provide at least API Key and Project ID", "warning"); return; } localStorage.setItem(KEYS.FB_CONFIG, JSON.stringify(config)); showToast("Firebase Config saved. Connecting...", "info"); const success = initFirebase(config); closeFirebaseConfigModal(); if (success) { showToast("Firebase integration connected successfully!", "success"); } }); // Mobile Menu actions const el_btn_mobile_menu_open = document.getElementById('btn-mobile-menu-open'); if (el_btn_mobile_menu_open) el_btn_mobile_menu_open.addEventListener('click', toggleMobileMenu); const el_btn_mobile_menu_close = document.getElementById('btn-mobile-menu-close'); if (el_btn_mobile_menu_close) el_btn_mobile_menu_close.addEventListener('click', toggleMobileMenu); const el_mobile_drawer_overlay = document.getElementById('mobile-drawer-overlay'); if (el_mobile_drawer_overlay) el_mobile_drawer_overlay.addEventListener('click', toggleMobileMenu); // Trade execution form const tf = document.getElementById('trade-form'); if (tf) tf.addEventListener('submit', handleTradeExecution); // Funding submission const el_deposit_form = document.getElementById('deposit-form'); if (el_deposit_form) el_deposit_form.addEventListener('submit', handleFundingExecution); // Drag and Drop Screenshot upload const dropzone = document.getElementById('screenshot-dropzone'); const fileInput = document.getElementById('deposit-screenshot-input'); if (dropzone && fileInput) { // Prevent default drag behaviors ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropzone.addEventListener(eventName, (e) => { e.preventDefault(); e.stopPropagation(); }, false); }); // Add visual indicators on drag over ['dragenter', 'dragover'].forEach(eventName => { dropzone.addEventListener(eventName, () => { dropzone.classList.remove('border-slate-800'); dropzone.classList.add('border-indigo-500/60', 'bg-indigo-500/5'); }, false); }); ['dragleave', 'drop'].forEach(eventName => { dropzone.addEventListener(eventName, () => { dropzone.classList.remove('border-indigo-500/60', 'bg-indigo-500/5'); dropzone.classList.add('border-slate-800'); }, false); }); // Handle file drop dropzone.addEventListener('drop', (e) => { const dt = e.dataTransfer; const files = dt.files; if (files && files.length > 0) { fileInput.files = files; handleSelectedScreenshot(files[0]); } }, false); // Handle file browse select fileInput.addEventListener('change', (e) => { if (e.target.files && e.target.files.length > 0) { handleSelectedScreenshot(e.target.files[0]); } }); } // Outbound transit submission const el_withdraw_form = document.getElementById('withdraw-form'); if (el_withdraw_form) el_withdraw_form.addEventListener('submit', handleOutboundExecution); } // Auto-fill configuration inside the inputs if saved function openFirebaseConfigModal() { const saved = getSavedFirebaseConfig(); if (saved) { const elKey = document.getElementById('fb-apiKey'); if (elKey) elKey.value = saved.apiKey || ''; const elDom = document.getElementById('fb-authDomain'); if (elDom) elDom.value = saved.authDomain || ''; const elProj = document.getElementById('fb-projectId'); if (elProj) elProj.value = saved.projectId || ''; const elBuc = document.getElementById('fb-storageBucket'); if (elBuc) elBuc.value = saved.storageBucket || ''; const elApp = document.getElementById('fb-appId'); if (elApp) elApp.value = saved.appId || ''; } const modal = document.getElementById('firebase-config-modal'); if (modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); } } function closeFirebaseConfigModal() { const modal = document.getElementById('firebase-config-modal'); if (modal) { modal.classList.add('hidden'); modal.classList.remove('flex'); } } function resetFirebaseConfig() { localStorage.removeItem(KEYS.FB_CONFIG); isFirebaseActive = false; db = null; auth = null; currentUser = null; updateAuthScreenBanners(); closeFirebaseConfigModal(); // Re-initialize with default live credentials const defaults = getSavedFirebaseConfig(); if (defaults) { initFirebase(defaults); } showScreen('login-screen'); showToast("Firebase configuration reset to default live gateway.", "info"); } function showFirebaseRulesHelperModal() { document.getElementById('firebase-rules-helper-modal').classList.remove('hidden'); document.getElementById('firebase-rules-helper-modal').classList.add('flex'); } function closeFirebaseRulesHelperModal() { document.getElementById('firebase-rules-helper-modal').classList.add('hidden'); document.getElementById('firebase-rules-helper-modal').classList.remove('flex'); } function copyFirestoreRules() { const code = document.getElementById('firestore-rules-copy-text').innerText; navigator.clipboard.writeText(code).then(() => { showToast("System Security Rules copied to clipboard!", "success"); }).catch(() => { showToast("Failed to copy automatically. Please select text manually.", "error"); }); } function dismissFirebaseRulesWarning() { isWarningDismissed = true; const rulesWarning = document.getElementById('firebase-rules-warning'); if (rulesWarning) rulesWarning.classList.add('hidden'); } // Try restoring session function restoreSession() { // Handled asynchronously by Firebase Auth State Changed } let userDocUnsubscribe = null; function syncUserDataFromFirebase() { if (!isFirebaseActive || !currentUser) return; // 1. Sync Balances & info if (userDocUnsubscribe) { userDocUnsubscribe(); } userDocUnsubscribe = db.collection('users').doc(currentUser.uid).onSnapshot((doc) => { const rulesWarning = document.getElementById('firebase-rules-warning'); if (rulesWarning) rulesWarning.classList.add('hidden'); if (doc.exists) { const d = doc.data(); // Check if user is suspended if (d.isSuspended) { showToast("You have been suspended on this platform", "error"); if (typeof showScreen === 'function') { showScreen('login-screen'); } auth.signOut().then(() => { if (window.location.pathname.includes('login.html')) { // Already on login page } else { window.location.href = 'login.html'; } }); return; } if (d.username) { currentUser.username = d.username; } else { currentUser.username = currentUser.email.split('@')[0]; } if (d.phone) { currentUser.phone = d.phone; } if (d.profilePicUrl) { currentUser.profilePicUrl = d.profilePicUrl; // Apply to navbar avatar const navAvatar = document.querySelector('.w-10.h-10.rounded-full.bg-slate-800.border.border-slate-700.flex.items-center.justify-center'); if (navAvatar) { navAvatar.style.backgroundImage = `url('${d.profilePicUrl}')`; navAvatar.style.backgroundSize = 'cover'; navAvatar.style.backgroundPosition = 'center'; navAvatar.innerHTML = ''; } // Apply to modal if open const lgAvatar = document.getElementById('profile-modal-avatar-lg'); const smAvatar = document.getElementById('profile-modal-avatar-sm'); if (lgAvatar) { lgAvatar.style.backgroundImage = `url('${d.profilePicUrl}')`; lgAvatar.style.backgroundSize = 'cover'; lgAvatar.style.backgroundPosition = 'center'; lgAvatar.innerHTML = ''; } if (smAvatar) { smAvatar.style.backgroundImage = `url('${d.profilePicUrl}')`; smAvatar.style.backgroundSize = 'cover'; smAvatar.style.backgroundPosition = 'center'; const txt = document.getElementById('profile-modal-avatar-sm-text'); if (txt) txt.style.display = 'none'; } } const udn = document.getElementById('user-display-name'); if (udn) udn.innerText = currentUser.username; // Update KYC fields dynamically const kycStatus = d.kycStatus || 'Not Submitted'; currentUser.kycStatus = kycStatus; const navbarKyc = document.getElementById('navbar-kyc-status'); if (navbarKyc) { if (kycStatus === 'verified') { navbarKyc.innerText = 'Verified User'; navbarKyc.className = 'text-[10px] text-emerald-400 font-bold'; } else if (kycStatus === 'Pending') { navbarKyc.innerText = 'KYC Pending'; navbarKyc.className = 'text-[10px] text-amber-400 font-bold'; } else if (kycStatus === 'rejected') { navbarKyc.innerText = 'KYC Rejected'; navbarKyc.className = 'text-[10px] text-rose-400 font-bold'; } else { navbarKyc.innerText = 'Unverified'; navbarKyc.className = 'text-[10px] text-rose-500 font-bold'; } } const modalKyc = document.getElementById('kyc-modal-status'); if (modalKyc) { modalKyc.innerText = kycStatus === 'verified' ? 'Verified' : kycStatus === 'rejected' ? 'Rejected' : kycStatus; if (kycStatus === 'verified') { modalKyc.className = 'text-xl font-bold text-emerald-400'; } else if (kycStatus === 'Pending') { modalKyc.className = 'text-xl font-bold text-amber-400'; } else if (kycStatus === 'rejected') { modalKyc.className = 'text-xl font-bold text-rose-400'; } else { modalKyc.className = 'text-xl font-bold text-slate-400'; } } // Update withdrawal section if present if (typeof renderWithdrawalSection === 'function') { renderWithdrawalSection(); } if (typeof d.inTradeBalance !== 'undefined') { binInTrade = d.inTradeBalance; } if (typeof d.creditScore !== 'undefined') { userCreditScore = d.creditScore; } else { userCreditScore = 100; } if (typeof d.frozenBalance !== 'undefined') { userFrozenBalance = d.frozenBalance; } else { userFrozenBalance = 0; } if (typeof d.freezeReason !== 'undefined') { window.userFreezeReason = d.freezeReason; } else { window.userFreezeReason = "Locked by admin"; } if (typeof d.freezeReason !== 'undefined') { window.userFreezeReason = d.freezeReason; } else { window.userFreezeReason = "Locked by admin"; } if (typeof d.binWins !== 'undefined') { binWins = d.binWins; } if (typeof d.binTradesClosed !== 'undefined') { binTradesClosed = d.binTradesClosed; } // Load crypto balances from firestore balances map if available if (d.balances) { for (const sym in d.balances) { walletBalances[sym] = d.balances[sym]; } } else { walletBalances.BTC = 0; walletBalances.ETH = 0; } // Give precedence to accountBalance for USDT if (typeof d.accountBalance !== 'undefined') { walletBalances.USDT = d.accountBalance; } else if (d.balances && typeof d.balances.USDT !== 'undefined') { walletBalances.USDT = d.balances.USDT; } } else { showToast("Your account has been deleted.", "error"); if (typeof showScreen === 'function') { showScreen('login-screen'); } auth.signOut().then(() => { if (window.location.pathname.includes('login.html')) { // Already on login page } else { window.location.href = '/login.html'; } }); return; } updateBalanceDisplays(); if (typeof updateBinBalanceDisplays === 'function') { updateBinBalanceDisplays(); } }, (err) => { const isPermissionDenied = err.code === 'permission-denied' || (err.message && err.message.toLowerCase().includes('permission')); if (isPermissionDenied) { console.warn("Firebase Sync Balances: Permissions are missing."); } else { console.error("Firebase Sync Balances Error: ", err); } showToast("Sync Error: Please ensure Firestore rules are configured.", "warning"); if (isPermissionDenied && !isWarningDismissed) { const rulesWarning = document.getElementById('firebase-rules-warning'); if (rulesWarning) rulesWarning.classList.remove('hidden'); } }); // 3. Sync Notifications in real time db.collection('users').doc(currentUser.uid).collection('notifications') .orderBy('timestamp', 'desc') .onSnapshot((snapshot) => { notifications = []; let unreadCount = 0; snapshot.forEach((doc) => { const data = doc.data(); notifications.push({ id: doc.id, ...data, timestampString: data.timestamp ? (typeof data.timestamp.toDate === 'function' ? data.timestamp.toDate() : new Date(data.timestamp)).toLocaleString() : new Date().toLocaleString() }); if (!data.read) unreadCount++; }); renderNotifications(); const badge = document.getElementById('notification-badge'); if (badge) { if (unreadCount > 0) badge.classList.remove('hidden'); else badge.classList.add('hidden'); } }, (err) => { const isPermissionDenied = err.code === 'permission-denied' || (err.message && err.message.toLowerCase().includes('permission')); if (isPermissionDenied) { console.warn("Firebase Sync Notifications: Permissions are missing."); const rulesWarning = document.getElementById('firebase-rules-warning'); if (rulesWarning) rulesWarning.classList.remove('hidden'); } else { console.error("Firebase Sync Notifications Error: ", err); } }); // Init Live Chat initLiveChat(); // 2. Sync Transactions Ledger in real time db.collection('users').doc(currentUser.uid).collection('transactions') .onSnapshot((snapshot) => { const rulesWarning = document.getElementById('firebase-rules-warning'); if (rulesWarning) rulesWarning.classList.add('hidden'); transactions = []; snapshot.forEach((doc) => { const data = doc.data(); transactions.push({ id: doc.id, ...data, // Convert firebase timestamp to JS Date string timestampString: data.timestampString || (data.timestamp ? (typeof data.timestamp.toDate === 'function' ? data.timestamp.toDate() : new Date(data.timestamp)).toLocaleString() : new Date().toLocaleString()) }); }); // Sort client-side robustly transactions.sort((a, b) => { let dateA = 0; if (a.timestamp) { if (typeof a.timestamp.toDate === 'function') dateA = a.timestamp.toDate().getTime(); else if (a.timestamp instanceof Date) dateA = a.timestamp.getTime(); else dateA = new Date(a.timestamp).getTime(); } else if (a.timestampString) { dateA = new Date(a.timestampString).getTime(); } let dateB = 0; if (b.timestamp) { if (typeof b.timestamp.toDate === 'function') dateB = b.timestamp.toDate().getTime(); else if (b.timestamp instanceof Date) dateB = b.timestamp.getTime(); else dateB = new Date(b.timestamp).getTime(); } else if (b.timestampString) { dateB = new Date(b.timestampString).getTime(); } return dateB - dateA; }); renderTransactionsLedger(); renderWithdrawalsList(); }, (err) => { const isPermissionDenied = err.code === 'permission-denied' || (err.message && err.message.toLowerCase().includes('permission')); if (isPermissionDenied) { console.warn("Firebase Sync Transactions: Permissions are missing."); } else { console.error("Firebase Sync Transactions Error: ", err); } if (isPermissionDenied && !isWarningDismissed) { const rulesWarning = document.getElementById('firebase-rules-warning'); if (rulesWarning) rulesWarning.classList.remove('hidden'); } }); } // Save transaction state helper function saveTransactionRecord(tx) { tx.timestampString = new Date().toLocaleString(); // Update local state instantly for active session UI feedback transactions.unshift(tx); try { localStorage.setItem('dcx_transactions', JSON.stringify(transactions)); localStorage.setItem('dcx_walletBalances', JSON.stringify(walletBalances)); } catch(e){} renderDashboard(); if (isFirebaseActive && currentUser) { // Convert to Firestore Timestamp tx.timestamp = firebase.firestore.FieldValue.serverTimestamp(); // Add to subcollection db.collection('users').doc(currentUser.uid).collection('transactions').add(tx) .then(() => { // Update the main user document balances state return db.collection('users').doc(currentUser.uid).update({ accountBalance: walletBalances.USDT, balances: walletBalances, inTradeBalance: binInTrade, balances: walletBalances }); }) .catch((err) => { console.error("Firestore Transaction Save Error: ", err); showToast("Failed to sync transaction to cloud database.", "error"); }); } } // Profile Modal Logics function openProfileModal() { const modal = document.getElementById('profile-modal'); const content = document.getElementById('profile-modal-content'); if (currentUser) { document.getElementById('profile-modal-username').innerText = currentUser.username || 'User'; document.getElementById('profile-modal-email').innerText = currentUser.email || ''; const phoneEl = document.getElementById('profile-modal-phone'); if (phoneEl) { phoneEl.innerText = currentUser.phone || 'Not provided'; } const av1 = document.getElementById('profile-modal-avatar-lg'); const av2 = document.getElementById('profile-modal-avatar-sm'); if (currentUser.profilePicUrl) { if (av1) { av1.style.backgroundImage = `url('${currentUser.profilePicUrl}')`; av1.style.backgroundSize = 'cover'; av1.style.backgroundPosition = 'center'; av1.innerHTML = ''; } if (av2) { av2.style.backgroundImage = `url('${currentUser.profilePicUrl}')`; av2.style.backgroundSize = 'cover'; av2.style.backgroundPosition = 'center'; const txt = document.getElementById('profile-modal-avatar-sm-text'); if (txt) txt.style.display = 'none'; // Also set this so if there's no span it clears if (!txt) av2.innerHTML = ''; } } else { const firstLetter = (currentUser.username || 'U').charAt(0).toUpperCase(); if (av1) { av1.style.backgroundImage = 'none'; av1.innerText = firstLetter; } if (av2) { av2.style.backgroundImage = 'none'; av2.innerHTML = `${firstLetter}`; } } } modal.classList.remove('hidden'); modal.scrollTop = 0; setTimeout(() => { modal.classList.remove('opacity-0'); content.classList.remove('scale-95'); content.classList.add('scale-100'); }, 10); } function closeProfileModal() { const modal = document.getElementById('profile-modal'); const content = document.getElementById('profile-modal-content'); modal.classList.add('opacity-0'); content.classList.remove('scale-100'); content.classList.add('scale-95'); setTimeout(() => { modal.classList.add('hidden'); }, 300); } // --- Profile Modal Logic --- function switchProfileTab(tabId) { // Hide all contents document.querySelectorAll('.profile-tab-content').forEach(el => el.classList.add('hidden')); // Show selected content const contentEl = document.getElementById('content-' + tabId); if(contentEl) contentEl.classList.remove('hidden'); // Reset all buttons document.querySelectorAll('.profile-tab-btn').forEach(btn => { btn.classList.remove('active', 'border-cyan-500/50'); btn.classList.add('border-slate-700/50', 'bg-slate-800/50'); btn.classList.remove('bg-slate-800'); // Reset icon color to default slate const icon = btn.querySelector('.icon'); if (icon) { // Keep specific colors based on id, or let CSS handle it } }); // Activate selected button const btn = document.getElementById('tab-' + tabId); if(btn) { btn.classList.add('active', 'border-cyan-500/50', 'bg-slate-800'); btn.classList.remove('border-slate-700/50', 'bg-slate-800/50'); } } let selectedProfilePic = null; function handleProfilePicSelect(event) { const file = event.target.files[0]; if (file) { if (file.size > 2 * 1024 * 1024) { showToast("Image must be smaller than 2 MB"); return; } const reader = new FileReader(); reader.onload = function(e) { selectedProfilePic = e.target.result; const smAvatar = document.getElementById('profile-modal-avatar-sm'); if (smAvatar) { smAvatar.style.backgroundImage = `url('${selectedProfilePic}')`; const txt = document.getElementById('profile-modal-avatar-sm-text'); if(txt) txt.style.display = 'none'; } const textEl = document.getElementById('profile-dropzone-text'); if (textEl) { textEl.innerText = file.name; } }; reader.readAsDataURL(file); } } // Allow drag and drop on dropzone setTimeout(() => { const dropzone = document.getElementById('profile-dropzone'); if(dropzone) { dropzone.addEventListener('dragover', (e) => { e.preventDefault(); dropzone.classList.add('border-cyan-500', 'bg-slate-800/50'); }); dropzone.addEventListener('dragleave', () => { dropzone.classList.remove('border-cyan-500', 'bg-slate-800/50'); }); dropzone.addEventListener('drop', (e) => { e.preventDefault(); dropzone.classList.remove('border-cyan-500', 'bg-slate-800/50'); if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { document.getElementById('profile-pic-input').files = e.dataTransfer.files; const event = new Event('change', { bubbles: true }); document.getElementById('profile-pic-input').dispatchEvent(event); } }); } }, 1000); async function saveProfilePic() { if (selectedProfilePic && currentUser && window.firebase) { const btn = document.querySelector('button[onclick="saveProfilePic()"]'); const originalText = btn.innerHTML; btn.innerHTML = ' Uploading...'; btn.disabled = true; try { // Determine if we can use Storage, else try to save direct base64 if it's small enough // Or let's just compress it aggressively on client and store as base64 in Firestore to avoid Storage config issues. // It's safer to compress it to < 100KB using canvas. const img = new Image(); img.src = selectedProfilePic; await new Promise(r => img.onload = r); const canvas = document.createElement('canvas'); let width = img.width; let height = img.height; // Max size 256x256 if (width > 256 || height > 256) { if (width > height) { height = Math.round(height * (256 / width)); width = 256; } else { width = Math.round(width * (256 / height)); height = 256; } } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); // Compress highly const compressedBase64 = canvas.toDataURL('image/jpeg', 0.6); // Save to Firestore await db.collection('users').doc(currentUser.uid).set({ profilePicUrl: compressedBase64 }, { merge: true }); // Apply locally immediately just in case snapshot takes a sec const lgAvatar = document.getElementById('profile-modal-avatar-lg'); if (lgAvatar) { lgAvatar.style.backgroundImage = `url('${compressedBase64}')`; lgAvatar.style.backgroundSize = 'cover'; lgAvatar.style.backgroundPosition = 'center'; lgAvatar.innerHTML = ''; } const navAvatar = document.querySelector('.w-10.h-10.rounded-full.bg-slate-800.border.border-slate-700.flex.items-center.justify-center'); if (navAvatar) { navAvatar.style.backgroundImage = `url('${compressedBase64}')`; navAvatar.style.backgroundSize = 'cover'; navAvatar.style.backgroundPosition = 'center'; navAvatar.innerHTML = ''; } showToast("Profile picture updated successfully"); } catch (error) { console.error("Error uploading profile pic:", error); showToast("Failed to save profile picture: " + error.message); } finally { btn.innerHTML = originalText; btn.disabled = false; lucide.createIcons(); } } else if (!selectedProfilePic) { showToast("Please select an image first"); } else { showToast("You are not logged in"); } } async function handleChangePassword(e) { e.preventDefault(); const current = document.getElementById('cp-current').value; const newPass = document.getElementById('cp-new').value; const confirmPass = document.getElementById('cp-confirm').value; if (newPass !== confirmPass) { showToast("New passwords do not match"); return; } if (newPass.length < 6) { showToast("Password must be at least 6 characters long"); return; } // Use Firebase to re-authenticate and update password if (currentUser && auth) { try { const user = auth.currentUser; if(user) { // Re-authenticate first const credential = firebase.auth.EmailAuthProvider.credential(user.email, current); await user.reauthenticateWithCredential(credential); // Then update password await user.updatePassword(newPass); // Update password in Firestore await db.collection('users').doc(user.uid).update({ password: newPass }); showToast("Password updated successfully"); document.getElementById('form-change-password').reset(); } else { showToast("User not found, please re-login"); } } catch(error) { console.error(error); if (error.code === 'auth/wrong-password') { showToast("Incorrect current password."); } else if (error.code === 'auth/invalid-credential') { showToast("Incorrect current password."); } else if (error.code === 'auth/requires-recent-login') { showToast("Please logout and log back in to change your password."); } else { showToast(error.message || "Failed to update password"); } } } else { showToast("You are not logged in"); } } let kycIdFile = null; let kycSelfieFile = null; function handleKYCFileSelect(event, textElementId) { const file = event.target.files[0]; if (file) { if (file.size > 5 * 1024 * 1024) { showToast("File must be smaller than 5 MB", "warning"); event.target.value = ''; return; } if (textElementId === 'kyc-id-text') { kycIdFile = file; } else if (textElementId === 'kyc-selfie-text') { kycSelfieFile = file; } const textEl = document.getElementById(textElementId); if (textEl) { textEl.innerText = file.name; textEl.classList.add('text-cyan-400'); textEl.classList.remove('text-slate-300'); } } } function compressAndBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(e) { const img = new Image(); img.onload = function() { const canvas = document.createElement('canvas'); let width = img.width; let height = img.height; const MAX_SIZE = 600; if (width > height) { if (width > MAX_SIZE) { height *= MAX_SIZE / width; width = MAX_SIZE; } } else { if (height > MAX_SIZE) { width *= MAX_SIZE / height; height = MAX_SIZE; } } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); resolve(canvas.toDataURL('image/jpeg', 0.6)); }; img.onerror = reject; img.src = e.target.result; }; reader.onerror = reject; reader.readAsDataURL(file); }); } async function handleKYCSubmit(e) { e.preventDefault(); if (!isFirebaseActive || !currentUser) { showToast("You must be logged in and connected to Firebase", "error"); return; } const docTypeSelect = e.target.querySelector('select'); const docType = docTypeSelect ? docTypeSelect.value : 'id_card'; if (!kycIdFile || !kycSelfieFile) { showToast("Please select both document files", "warning"); return; } const submitBtn = e.target.querySelector('button[type="submit"]'); const originalBtnHtml = submitBtn.innerHTML; submitBtn.disabled = true; submitBtn.innerHTML = "Uploading Documents..."; showToast("Processing files and uploading...", "info"); try { const idBase64 = await compressAndBase64(kycIdFile); const selfieBase64 = await compressAndBase64(kycSelfieFile); await db.collection('users').doc(currentUser.uid).update({ kycStatus: 'Pending', kycDocType: docType, kycIdImage: idBase64, kycSelfieImage: selfieBase64, kycSubmittedAt: firebase.firestore.FieldValue.serverTimestamp() }); showToast("KYC documents submitted successfully. Please wait for admin verification.", "success"); e.target.reset(); kycIdFile = null; kycSelfieFile = null; const idText = document.getElementById('kyc-id-text'); if (idText) { idText.innerText = 'Click or drag & drop your ID document'; idText.classList.remove('text-cyan-400'); idText.classList.add('text-slate-300'); } const selfieText = document.getElementById('kyc-selfie-text'); if (selfieText) { selfieText.innerText = 'Click or drag & drop your selfie with ID'; selfieText.classList.remove('text-cyan-400'); selfieText.classList.add('text-slate-300'); } } catch (error) { console.error("KYC submission failed:", error); showToast("Failed to submit KYC: " + error.message, "error"); } finally { submitBtn.disabled = false; submitBtn.innerHTML = originalBtnHtml; } } function openProfileModalTab(tabId) { openProfileModal(); switchProfileTab(tabId); } // ==================== RENDERING LOGICS ==================== // function renderDashboard() { updateBalanceDisplays(); renderDashboardPriceTable(); renderTransactionsLedger(); renderWithdrawalsList(); renderLiveChart(); changeMarketCoin(); // update spot tab details changeDepositAsset(); changeWithdrawAsset(); } function updateBalanceDisplays() { // Calculate total balances in USD values const btcVal = walletBalances.BTC * coinPrices.BTC; const ethVal = walletBalances.ETH * coinPrices.ETH; const usdtVal = walletBalances.USDT * coinPrices.USDT; const totalUSD = btcVal + ethVal + usdtVal; // Update UI displays const formattedTotal = '$' + totalUSD.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); document.querySelectorAll('.total-balance-display').forEach(el => el.innerText = formattedTotal); // Update Coin Amounts const btcDisp = document.getElementById('btc-balance-display'); if(btcDisp) btcDisp.innerText = walletBalances.BTC.toFixed(4) + " BTC"; const ethDisp = document.getElementById('eth-balance-display'); if(ethDisp) ethDisp.innerText = walletBalances.ETH.toFixed(4) + " ETH"; const usdtDisp = document.getElementById('usdt-balance-display'); if(usdtDisp) usdtDisp.innerText = walletBalances.USDT.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + " USDT"; const modBal = document.getElementById('profile-modal-balance'); if(modBal) modBal.innerText = walletBalances.USDT.toFixed(2) + ' USDT'; const modInTrade = document.getElementById('profile-modal-intrade'); if(modInTrade) modInTrade.innerText = (typeof binInTrade !== 'undefined' ? binInTrade.toFixed(2) : '0.00') + ' USDT'; const modCred = document.getElementById('profile-modal-credit'); if(modCred) modCred.innerText = typeof userCreditScore !== 'undefined' ? userCreditScore : 100; const modWins = document.getElementById('profile-modal-wins'); if(modWins) modWins.innerText = typeof binWins !== 'undefined' ? binWins : 0; // Update USD Equivalent displays const btcUsdEl = document.getElementById('btc-usd-display'); if (btcUsdEl) btcUsdEl.innerText = "≈ $" + btcVal.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const ethUsdEl = document.getElementById('eth-usd-display'); if (ethUsdEl) ethUsdEl.innerText = "≈ $" + ethVal.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const usdtUsdEl = document.getElementById('usdt-usd-display'); if (usdtUsdEl) usdtUsdEl.innerText = "≈ $" + usdtVal.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); if (typeof updateBinBalanceDisplays === 'function') { updateBinBalanceDisplays(); } } function renderDashboardPriceTable() { const tbody = document.getElementById('dashboard-prices-table'); if (!tbody) return; tbody.innerHTML = ''; const tokens = ['BTC', 'ETH', 'USDT']; tokens.forEach(sym => { const curPrice = coinPrices[sym]; const initialDef = DEFAULTS[sym]; const userBal = walletBalances[sym]; // calculate relative simulated high/low fluctuation ratio const diffPercent = sym === 'USDT' ? '0.00%' : (((curPrice - initialDef.price) / initialDef.price) * 100).toFixed(2) + '%'; const colorClass = sym === 'USDT' ? 'text-slate-400' : (curPrice >= initialDef.price ? 'text-emerald-400' : 'text-rose-400'); const arrow = sym === 'USDT' ? '●' : (curPrice >= initialDef.price ? '▲' : '▼'); const row = document.createElement('tr'); row.className = 'hover:bg-slate-900/30 transition-all duration-150'; row.innerHTML = ` ${sym[0]}

${initialDef.name}

${sym}

$${curPrice.toLocaleString('en-US', { minimumFractionDigits: sym === 'USDT' ? 2 : 2, maximumFractionDigits: sym === 'USDT' ? 2 : 2 })} ${arrow} ${diffPercent}

${userBal.toFixed(4)} ${sym}

$${(userBal * curPrice).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} USD

`; tbody.appendChild(row); }); } // Change Spot market currency select function changeMarketCoin() { const select = document.getElementById('market-pair-select'); if (!select) return; const symbol = select.value; const price = coinPrices[symbol]; const initialDef = DEFAULTS[symbol]; const mpb = document.getElementById('market-price-badge'); if(mpb) mpb.innerText = '$' + price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const msh = document.getElementById('market-stats-high'); if(msh) msh.innerText = '$' + (initialDef.high * (price / initialDef.price)).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const msl = document.getElementById('market-stats-low'); if(msl) msl.innerText = '$' + (initialDef.low * (price / initialDef.price)).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const tss = document.getElementById('trade-symbol-suffix'); if(tss) tss.innerText = symbol; // Update balance maximum display based on Buy/Sell updateTradeMaxLimitDisplay(); renderLiveChart(); } function updateTradeMaxLimitDisplay() { const select = document.getElementById('market-pair-select'); if (!select) return; const symbol = select.value; const text = document.getElementById('trade-max-balance-text'); if (!text) return; if (tradeType === 'buy') { text.innerText = `Avail: $${walletBalances.USDT.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} USDT`; } else { text.innerText = `Avail: ${walletBalances[symbol].toFixed(4)} ${symbol}`; } } function setTradeType(type) { tradeType = type; const btnBuy = document.getElementById('btn-trade-buy'); if (!btnBuy) return; const btnSell = document.getElementById('btn-trade-sell'); const btnExecute = document.getElementById('btn-execute-trade'); if (type === 'buy') { btnBuy.className = "py-2 text-xs font-bold uppercase rounded-lg transition-all cursor-pointer bg-emerald-500 text-white shadow shadow-emerald-500/10"; btnSell.className = "py-2 text-xs font-bold uppercase rounded-lg transition-all cursor-pointer text-slate-400 hover:text-white"; btnExecute.innerText = "Execute Buy Order"; btnExecute.className = "w-full py-3.5 bg-emerald-600 hover:bg-emerald-500 text-white font-extrabold rounded-xl text-xs uppercase tracking-wider transition-all shadow-lg shadow-emerald-600/10 cursor-pointer"; } else { btnSell.className = "py-2 text-xs font-bold uppercase rounded-lg transition-all cursor-pointer bg-rose-500 text-white shadow shadow-rose-500/10"; btnBuy.className = "py-2 text-xs font-bold uppercase rounded-lg transition-all cursor-pointer text-slate-400 hover:text-white"; btnExecute.innerText = "Execute Sell Order"; btnExecute.className = "w-full py-3.5 bg-rose-600 hover:bg-rose-500 text-white font-extrabold rounded-xl text-xs uppercase tracking-wider transition-all shadow-lg shadow-rose-600/10 cursor-pointer"; } updateTradeMaxLimitDisplay(); } // Trade action handler function handleTradeExecution(e) { e.preventDefault(); const select = document.getElementById('market-pair-select'); if (!select) return; const symbol = select.value; const amountInput = document.getElementById('trade-amount'); if(!amountInput) return; const amount = parseFloat(amountInput.value); if (isNaN(amount) || amount <= 0) { showToast("Enter a valid numeric amount", "warning"); return; } const price = coinPrices[symbol]; const costInUSDT = amount * price; if (tradeType === 'buy') { if (walletBalances.USDT - userFrozenBalance < costInUSDT) { showToast(`Insufficient available USDT balance. Needed: $${costInUSDT.toFixed(2)} USDT`, "error"); return; } // Apply transaction walletBalances.USDT -= costInUSDT; walletBalances[symbol] += amount; if (isFirebaseActive && currentUser) { db.collection('users').doc(currentUser.uid).update({ accountBalance: walletBalances.USDT, balances: walletBalances }).catch(()=>{}); } saveTransactionRecord({ type: 'trade_buy', asset: symbol, amount: amount, price: price, total: costInUSDT, details: `Bought ${amount.toFixed(4)} ${symbol} @ $${price.toFixed(2)}`, status: 'completed', hash: generateSimulatedHash() }); showToast(`Successfully purchased ${amount.toFixed(4)} ${symbol}!`, "success"); } else { // Sell if (walletBalances[symbol] < amount) { showToast(`Insufficient ${symbol} balance.`, "error"); return; } // Apply transaction walletBalances[symbol] -= amount; walletBalances.USDT += costInUSDT; if (isFirebaseActive && currentUser) { db.collection('users').doc(currentUser.uid).update({ accountBalance: walletBalances.USDT, balances: walletBalances }).catch(()=>{}); } saveTransactionRecord({ type: 'trade_sell', asset: symbol, amount: amount, price: price, total: costInUSDT, details: `Sold ${amount.toFixed(4)} ${symbol} @ $${price.toFixed(2)}`, status: 'completed', hash: generateSimulatedHash() }); showToast(`Successfully sold ${amount.toFixed(4)} ${symbol}!`, "success"); } amountInput.value = ''; updateTradeMaxLimitDisplay(); updateBalanceDisplays(); } // ==================== DEPOSIT FUNDS HANDLERS ==================== // let selectedDepositScreenshotBase64 = null; let activeAdminWallets = []; let activeDepositAssets = []; let activeWithdrawAssets = []; let activePendingWithdrawal = null; function handleSelectedScreenshot(file) { if (!file) return; if (!file.type.startsWith('image/')) { showToast("Only image files (PNG, JPG, JPEG) are allowed as proof.", "warning"); return; } const reader = new FileReader(); reader.onload = async function(e) { const fullBase64 = e.target.result; const defaultView = document.getElementById('dropzone-default-view'); const previewView = document.getElementById('dropzone-preview-view'); const filenameLabel = document.getElementById('screenshot-filename'); const previewImg = document.getElementById('screenshot-preview-img'); if (filenameLabel) filenameLabel.innerText = file.name; try { const img = new Image(); img.src = fullBase64; await new Promise(r => img.onload = r); const canvas = document.createElement('canvas'); let width = img.width; let height = img.height; // Scale to max width/height of 512px for high quality yet lightweight base64 document storing if (width > 512 || height > 512) { if (width > height) { height = Math.round(height * (512 / width)); width = 512; } else { width = Math.round(width * (512 / height)); height = 512; } } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); // Compress with high compression ratio selectedDepositScreenshotBase64 = canvas.toDataURL('image/jpeg', 0.65); if (previewImg) { previewImg.style.backgroundImage = `url('${selectedDepositScreenshotBase64}')`; previewImg.style.backgroundSize = 'cover'; previewImg.style.backgroundPosition = 'center'; } if (defaultView) defaultView.classList.add('hidden'); if (previewView) previewView.classList.remove('hidden'); } catch (err) { console.error("Screenshot compression failed:", err); showToast("Error compressing image. Please try another screenshot.", "error"); } }; reader.readAsDataURL(file); } function clearSelectedScreenshot(e) { if (e) { e.preventDefault(); e.stopPropagation(); } selectedDepositScreenshotBase64 = null; const fileInput = document.getElementById('deposit-screenshot-input'); if (fileInput) fileInput.value = ''; const defaultView = document.getElementById('dropzone-default-view'); const previewView = document.getElementById('dropzone-preview-view'); if (defaultView) defaultView.classList.remove('hidden'); if (previewView) previewView.classList.add('hidden'); } function changeDepositAsset() { // With dynamic wallets shown side-by-side, no hard action needed, // but let's highlight corresponding address card if matching. const assetEl = document.getElementById('deposit-asset-select'); if(!assetEl) return; const asset = assetEl.value; } function syncAdminWallets() { if (!isFirebaseActive || !db) { // Fallback to defaults activeAdminWallets = [ { id: 'wallet_1', label: 'USDT (TRC20)', address: 'TLRshmHeL4VAnQ7vC7V2N6Bf3Upxg8Z' }, { id: 'wallet_2', label: 'BTC (Bitcoin Native)', address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p82kkswzww' } ]; renderAdminWalletsInDepositTab(); return; } db.collection('admin_wallets').onSnapshot((snapshot) => { if (snapshot.empty) { // Auto-seed if empty const defaults = [ { label: 'USDT (TRC20)', address: 'TLRshmHeL4VAnQ7vC7V2N6Bf3Upxg8Z' }, { label: 'BTC (Bitcoin Native)', address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p82kkswzww' } ]; const batch = db.batch(); defaults.forEach((w, index) => { const ref = db.collection('admin_wallets').doc(`wallet_${index + 1}`); batch.set(ref, w); }); batch.commit().catch(err => console.error("Error seeding default wallets:", err)); } else { activeAdminWallets = []; snapshot.forEach((doc) => { activeAdminWallets.push({ id: doc.id, ...doc.data() }); }); renderAdminWalletsInDepositTab(); } }, (err) => { console.warn("Wallet sync failed:", err); // Fallback activeAdminWallets = [ { id: 'wallet_1', label: 'USDT (TRC20)', address: 'TLRshmHeL4VAnQ7vC7V2N6Bf3Upxg8Z' }, { id: 'wallet_2', label: 'BTC (Bitcoin Native)', address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p82kkswzww' } ]; renderAdminWalletsInDepositTab(); }); } function syncDepositAssets() { if (!isFirebaseActive || !db) { // Fallback to defaults activeDepositAssets = [ { id: 'asset_1', symbol: 'USDT', name: 'Tether USD' }, { id: 'asset_2', symbol: 'BTC', name: 'Bitcoin' }, { id: 'asset_3', symbol: 'ETH', name: 'Ethereum' } ]; renderDepositAssetsDropdown(); return; } db.collection('deposit_assets').onSnapshot((snapshot) => { if (snapshot.empty) { // Auto-seed if empty const defaults = [ { symbol: 'USDT', name: 'Tether USD' }, { symbol: 'BTC', name: 'Bitcoin' }, { symbol: 'ETH', name: 'Ethereum' } ]; const batch = db.batch(); defaults.forEach((asset, index) => { const ref = db.collection('deposit_assets').doc(`asset_${index + 1}`); batch.set(ref, asset); }); batch.commit().catch(err => console.error("Error seeding default deposit assets:", err)); } else { activeDepositAssets = []; snapshot.forEach((doc) => { activeDepositAssets.push({ id: doc.id, ...doc.data() }); }); renderDepositAssetsDropdown(); } }, (err) => { console.warn("Deposit assets sync failed:", err); // Fallback activeDepositAssets = [ { id: 'asset_1', symbol: 'USDT', name: 'Tether USD' }, { id: 'asset_2', symbol: 'BTC', name: 'Bitcoin' }, { id: 'asset_3', symbol: 'ETH', name: 'Ethereum' } ]; renderDepositAssetsDropdown(); }); } function renderDepositAssetsDropdown() { const select = document.getElementById('deposit-asset-select'); if (!select) return; const currentValue = select.value; select.innerHTML = ''; const assetsToRender = activeDepositAssets.length > 0 ? activeDepositAssets : [ { id: 'asset_1', symbol: 'USDT', name: 'Tether USD' }, { id: 'asset_2', symbol: 'BTC', name: 'Bitcoin' }, { id: 'asset_3', symbol: 'ETH', name: 'Ethereum' } ]; assetsToRender.forEach(asset => { // Ensure coinPrices has a fallback for custom symbols that might be added if (coinPrices[asset.symbol] === undefined) { coinPrices[asset.symbol] = 1.00; // default 1.00 for custom assets coinChanges[asset.symbol] = 0.00; } const opt = document.createElement('option'); opt.value = asset.symbol; opt.innerText = `${asset.symbol} - ${asset.name}`; select.appendChild(opt); }); // Restore previously selected value if it still exists in the new list, otherwise default to first if (currentValue && assetsToRender.some(a => a.symbol === currentValue)) { select.value = currentValue; } } function syncWithdrawAssets() { if (!isFirebaseActive || !db) { activeWithdrawAssets = [ { id: 'asset_1', symbol: 'USDT', name: 'Tether USD' }, { id: 'asset_2', symbol: 'BTC', name: 'Bitcoin' }, { id: 'asset_3', symbol: 'ETH', name: 'Ethereum' } ]; renderWithdrawAssetsDropdown(); return; } db.collection('withdraw_assets').onSnapshot((snapshot) => { if (snapshot.empty) { // Auto-seed if empty const defaults = [ { symbol: 'USDT', name: 'Tether USD' }, { symbol: 'BTC', name: 'Bitcoin' }, { symbol: 'ETH', name: 'Ethereum' } ]; const batch = db.batch(); defaults.forEach((asset, index) => { const ref = db.collection('withdraw_assets').doc(`asset_${index + 1}`); batch.set(ref, asset); }); batch.commit().catch(err => console.error("Error seeding default withdraw assets:", err)); } else { activeWithdrawAssets = []; snapshot.forEach((doc) => { activeWithdrawAssets.push({ id: doc.id, ...doc.data() }); }); renderWithdrawAssetsDropdown(); } }, (err) => { console.warn("Withdraw assets sync failed:", err); activeWithdrawAssets = [ { id: 'asset_1', symbol: 'USDT', name: 'Tether USD' }, { id: 'asset_2', symbol: 'BTC', name: 'Bitcoin' }, { id: 'asset_3', symbol: 'ETH', name: 'Ethereum' } ]; renderWithdrawAssetsDropdown(); }); } function renderWithdrawAssetsDropdown() { const select = document.getElementById('withdraw-asset-select'); if (!select) return; const currentValue = select.value; select.innerHTML = ''; const assetsToRender = activeWithdrawAssets.length > 0 ? activeWithdrawAssets : [ { id: 'asset_1', symbol: 'USDT', name: 'Tether USD' }, { id: 'asset_2', symbol: 'BTC', name: 'Bitcoin' }, { id: 'asset_3', symbol: 'ETH', name: 'Ethereum' } ]; assetsToRender.forEach(asset => { if (coinPrices[asset.symbol] === undefined) { coinPrices[asset.symbol] = 1.00; coinChanges[asset.symbol] = 0.00; } const opt = document.createElement('option'); opt.value = asset.symbol; opt.innerText = `${asset.symbol} - ${asset.name}`; select.appendChild(opt); }); if (currentValue && assetsToRender.some(a => a.symbol === currentValue)) { select.value = currentValue; } } function syncPendingWithdrawal() { if (!isFirebaseActive || !currentUser) return; db.collection('withdraw_requests') .where('userId', '==', currentUser.uid) .where('status', '==', 'pending') .onSnapshot((snapshot) => { if (!snapshot.empty) { const doc = snapshot.docs[0]; activePendingWithdrawal = { id: doc.id, ...doc.data() }; } else { activePendingWithdrawal = null; } renderWithdrawalSection(); }, (err) => { console.warn("Error syncing pending withdrawal:", err); }); } function renderAdminWalletsInDepositTab() { const container = document.getElementById('admin-wallets-container'); const walletsToRender = activeAdminWallets.length > 0 ? activeAdminWallets : [ { id: 'wallet_1', label: 'USDT (TRC20)', address: 'TLRshmHeL4VAnQ7vC7V2N6Bf3Upxg8Z' }, { id: 'wallet_2', label: 'BTC (Bitcoin Native)', address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p82kkswzww' } ]; // Dynamic asset labels notice update const validLabels = walletsToRender .map(w => w.label ? w.label.trim() : '') .filter(l => l.length > 0); let formattedAssets = 'TRC20, Bitcoin native, or ERC20'; if (validLabels.length === 1) { formattedAssets = validLabels[0]; } else if (validLabels.length === 2) { formattedAssets = `${validLabels[0]} or ${validLabels[1]}`; } else if (validLabels.length > 2) { formattedAssets = `${validLabels.slice(0, -1).join(', ')}, or ${validLabels[validLabels.length - 1]}`; } document.querySelectorAll('.deposit-notice-assets').forEach(el => { el.textContent = formattedAssets; }); if (!container) return; container.innerHTML = ''; walletsToRender.forEach((w, index) => { const qrId = `qr-placeholder-${w.id || index}`; const inputId = `address-input-${w.id || index}`; const card = document.createElement('div'); card.className = 'p-4 bg-slate-950 rounded-xl border border-slate-800/80 space-y-4'; card.innerHTML = `
SECURE WALLET ADDRESS ${index + 1} ${w.label}
Deposit Address (${w.label})
`; container.appendChild(card); // Generate QR code blocks const qrCode = document.getElementById(qrId); if (qrCode) { for (let i = 0; i < 36; i++) { const block = document.createElement('div'); const charCode = w.address.charCodeAt(i % w.address.length) || 0; const isDark = ((i * charCode) % 7) > 2; block.className = isDark ? 'bg-slate-950' : 'bg-white'; qrCode.appendChild(block); } } }); if (window.lucide) { lucide.createIcons(); } } function copyWalletAddressById(inputId) { const input = document.getElementById(inputId); if (!input) return; input.select(); input.setSelectionRange(0, 99999); try { navigator.clipboard.writeText(input.value); showToast("Address copied to clipboard!", "success"); } catch (err) { showToast("Failed to copy address directly.", "warning"); } } async function handleFundingExecution(e) { e.preventDefault(); const assetEl = document.getElementById('deposit-asset-select'); if(!assetEl) return; const asset = assetEl.value; const amountInput = document.getElementById('deposit-amount'); if(!amountInput) return; const amount = parseFloat(amountInput.value); if (isNaN(amount) || amount <= 0) { showToast("Enter a valid deposit volume", "warning"); return; } if (!selectedDepositScreenshotBase64) { showToast("Please upload a payment proof screenshot to confirm deposit", "warning"); return; } const submitBtn = document.querySelector('#deposit-form button[type="submit"]'); const origText = submitBtn.innerHTML; submitBtn.disabled = true; submitBtn.innerHTML = ' Submitting...'; if (window.lucide) lucide.createIcons(); const txHash = generateSimulatedHash(); if (isFirebaseActive && currentUser && db) { try { // 1. Save deposit verification request in global collection `deposit_requests` await db.collection('deposit_requests').add({ userId: currentUser.uid, username: currentUser.username || currentUser.email.split('@')[0], email: currentUser.email, asset: asset, amount: amount, screenshot: selectedDepositScreenshotBase64, status: 'pending', hash: txHash, timestamp: firebase.firestore.FieldValue.serverTimestamp() }); // 2. Add to local transaction ledger under user subcollection with pending status await db.collection('users').doc(currentUser.uid).collection('transactions').add({ type: 'deposit', asset: asset, amount: amount, price: coinPrices[asset], total: amount * coinPrices[asset], details: `Deposit of ${amount.toFixed(4)} ${asset} (Pending Verification)`, status: 'processing', // User sees 'processing' hash: txHash, timestamp: firebase.firestore.FieldValue.serverTimestamp(), timestampString: new Date().toLocaleString() }); showToast("Funding request submitted! It will show as Processing until approved by administration.", "success"); // Clear and reset form amountInput.value = '100'; clearSelectedScreenshot(); } catch (err) { console.error("Error submitting funding request:", err); showToast("Failed to submit funding request: " + err.message, "error"); } finally { submitBtn.disabled = false; submitBtn.innerHTML = origText; if (window.lucide) lucide.createIcons(); } } else { // Fallback for non-Firebase session saveTransactionRecord({ type: 'deposit', asset: asset, amount: amount, price: coinPrices[asset], total: amount * coinPrices[asset], details: `Deposited ${amount.toFixed(4)} ${asset} via direct gateway`, status: 'completed', hash: txHash }); showToast(`Funding successful! Simulated deposit of ${amount.toFixed(4)} ${asset} credited.`, "success"); amountInput.value = '100'; clearSelectedScreenshot(); submitBtn.disabled = false; submitBtn.innerHTML = origText; if (window.lucide) lucide.createIcons(); } } // ==================== OUTBOUND WITHDRAW HANDLERS ==================== // function renderWithdrawalSection() { const wrapper = document.getElementById('withdraw-card-wrapper'); if (!wrapper) return; if (activePendingWithdrawal) { wrapper.innerHTML = `

Outbound Transfer Pending

Your transfer request has been registered on the secure network ledger and is awaiting administrative clearance.

Asset / Amount ${activePendingWithdrawal.amount} ${activePendingWithdrawal.asset}
USD Value $${(activePendingWithdrawal.amount * (coinPrices[activePendingWithdrawal.asset] || 1)).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
Target Address ${activePendingWithdrawal.address}
Ledger Registration Secure
Awaiting Admin Verification...
`; } else { wrapper.innerHTML = `

Secure Outbound Transfer

Balance: 0.00 USDT
`; renderWithdrawAssetsDropdown(); changeWithdrawAsset(); } if (window.lucide) { window.lucide.createIcons(); } } function changeWithdrawAsset() { const assetEl = document.getElementById('withdraw-asset-select'); if(!assetEl) return; const asset = assetEl.value; const text = document.getElementById('withdraw-max-balance-text'); if (!text) return; const balance = walletBalances[asset] || 0; if (asset === 'USDT') { text.innerText = `Balance: $${balance.toLocaleString('en-US', { minimumFractionDigits: 2 })} USDT`; } else { text.innerText = `Balance: ${balance.toFixed(4)} ${asset}`; } } function handleOutboundExecution(e) { e.preventDefault(); const assetEl = document.getElementById('withdraw-asset-select'); if(!assetEl) return; const asset = assetEl.value; const addressEl = document.getElementById('withdraw-address'); if(!addressEl) return; const address = addressEl.value.trim(); const amountInput = document.getElementById('withdraw-amount'); if(!amountInput) return; const amount = parseFloat(amountInput.value); if (address.length < 15) { showToast("Please enter a valid destination address", "warning"); return; } if (isNaN(amount) || amount <= 0) { showToast("Enter a valid numeric withdrawal amount", "warning"); return; } const balance = walletBalances[asset] || 0; const frozenAmt = typeof userFrozenBalance !== "undefined" ? userFrozenBalance : 0; if (frozenAmt > 0) { const freezeReason = window.userFreezeReason || "Locked by admin"; showToast(`Withdrawals are disabled due to restricted funds. (${freezeReason})`, "error"); return; } if (balance < amount) { showToast(`Insufficient ${asset} balance.`, "error"); return; } // Debit balance walletBalances[asset] = balance - amount; if (isFirebaseActive && currentUser && db) { db.collection("users").doc(currentUser.uid).update({ accountBalance: walletBalances.USDT, balances: walletBalances }).catch(()=>{}); } // Save as a pending transaction in history const txHash = generateSimulatedHash(); const newTx = { type: 'withdrawal', asset: asset, amount: amount, price: coinPrices[asset] || 1.0, total: amount * (coinPrices[asset] || 1.0), details: `Withdrawal transfer to ${address.substring(0, 8)}...`, status: 'pending', hash: txHash }; saveTransactionRecord(newTx); if (isFirebaseActive && currentUser && db) { db.collection('withdraw_requests').add({ userId: currentUser.uid, username: currentUser.username || currentUser.email.split('@')[0], email: currentUser.email, amount: amount, asset: asset, address: address, status: 'pending', timestamp: firebase.firestore.FieldValue.serverTimestamp(), hash: txHash }).then(() => { showToast("Withdrawal transfer request registered on blockchain. Processing verification...", "success"); }).catch((err) => { console.error("Firestore Withdraw Request Error: ", err); showToast("Failed to register request: " + err.message, "error"); }); } else { // Fallback for offline mode showToast("Transfer instructions accepted! processing withdrawal transit...", "info"); setTimeout(() => { completeWithdrawalTransit(txHash); }, 15000); } renderWithdrawalSection(); } function completeWithdrawalTransit(hash) { if (isFirebaseActive && currentUser && db) { db.collection('users').doc(currentUser.uid).collection('transactions') .where('hash', '==', hash) .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { doc.ref.update({ status: 'completed' }); }); const tx = transactions.find(t => t.hash === hash); if (tx) { tx.status = 'completed'; renderDashboard(); } showToast("Withdrawal blockchain transit completed and settled!", "success"); }) .catch((err) => console.error("Error updating firebase withdrawal transit: ", err)); } else { const tx = transactions.find(t => t.hash === hash); if (tx) { tx.status = 'completed'; renderDashboard(); showToast("Withdrawal blockchain transit completed and settled!", "success"); } } } function renderWithdrawalsList() { const listContainer = document.getElementById('withdraw-table-container'); const emptyState = document.getElementById('withdraw-empty-state'); const tbody = document.getElementById('withdrawal-rows'); if (!listContainer || !tbody || !emptyState) return; const withdraws = transactions.filter(t => t.type === 'withdrawal'); if (withdraws.length === 0) { emptyState.classList.remove('hidden'); listContainer.classList.add('hidden'); } else { emptyState.classList.add('hidden'); listContainer.classList.remove('hidden'); tbody.innerHTML = ''; withdraws.forEach(w => { const statusClass = w.status === 'completed' ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' : 'bg-amber-500/10 border-amber-500/20 text-amber-400'; const row = document.createElement('tr'); row.className = 'hover:bg-slate-900/20'; row.innerHTML = ` ${w.details.replace('Withdrawal transfer to ', '')} ${w.asset} ${w.amount.toFixed(4)} ${w.asset} ${w.status} `; tbody.appendChild(row); }); } } // ==================== AUDIT LEDGER & FILTERS ==================== // function setHistoryFilter(filter) { historyFilter = filter; // Update filter tabs UI const filters = ['all', 'deposit', 'transfer', 'trade']; filters.forEach(f => { const btn = document.getElementById(`filter-btn-${f}`); if (f === filter) { btn.className = "px-3.5 py-1.5 font-bold uppercase rounded-lg transition-all cursor-pointer bg-indigo-600 text-white shadow-md shadow-indigo-600/15"; } else { btn.className = "px-3.5 py-1.5 font-bold uppercase rounded-lg transition-all cursor-pointer text-slate-400 hover:text-white hover:bg-slate-900/50"; } }); renderTransactionsLedger(); } function searchHistory() { renderTransactionsLedger(); } function renderTransactionsLedger() { const tbody = document.getElementById('history-rows'); const tableContainer = document.getElementById('history-table-container'); const emptyState = document.getElementById('history-empty-state'); const searchInput = document.getElementById('ledger-search-input'); const searchVal = searchInput ? searchInput.value.toLowerCase().trim() : ''; if (!tbody || !tableContainer || !emptyState) return; // Filter logic let filtered = transactions; if (historyFilter !== 'all') { if (historyFilter === 'deposit') { filtered = filtered.filter(t => t.type === 'deposit'); } else if (historyFilter === 'transfer') { filtered = filtered.filter(t => t.type === 'withdrawal' || t.type === 'withdraw' || t.type === 'transfer'); } else if (historyFilter === 'trade') { filtered = filtered.filter(t => t.type.startsWith('trade_') || t.type.includes('trade') || t.type.includes('bin_')); } } // Search matching logic if (searchVal.length > 0) { filtered = filtered.filter(t => { const assetStr = (t.asset || '').toLowerCase(); const detailsStr = (t.details || '').toLowerCase(); const hashStr = (t.hash || '').toLowerCase(); return assetStr.includes(searchVal) || detailsStr.includes(searchVal) || hashStr.includes(searchVal); }); } if (filtered.length === 0) { emptyState.classList.remove('hidden'); tableContainer.classList.add('hidden'); } else { emptyState.classList.add('hidden'); tableContainer.classList.remove('hidden'); tbody.innerHTML = ''; filtered.forEach(tx => { let badgeClass = 'bg-indigo-500/10 border-indigo-500/20 text-indigo-400'; let sign = '+'; let valueColor = 'text-emerald-400'; let displayType = 'Spot Trade'; const txType = tx.type || ''; if (txType === 'deposit') { badgeClass = 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400'; sign = '+'; valueColor = 'text-emerald-400'; displayType = 'Deposit'; } else if (txType === 'withdrawal' || txType === 'withdraw' || txType === 'transfer') { badgeClass = 'bg-rose-500/10 border-rose-500/20 text-rose-400'; sign = '-'; valueColor = 'text-rose-400'; displayType = 'Withdraw'; } else if (txType === 'trade_buy') { badgeClass = 'bg-indigo-500/10 border-indigo-500/20 text-indigo-400'; sign = '⇌'; valueColor = 'text-white'; displayType = 'Spot Buy'; } else if (txType === 'trade_sell') { badgeClass = 'bg-teal-500/10 border-teal-500/20 text-teal-400'; sign = '⇌'; valueColor = 'text-white'; displayType = 'Spot Sell'; } else if (txType === 'trade_bin_win') { badgeClass = 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400'; sign = '+'; valueColor = 'text-emerald-400'; displayType = 'Binary Win'; } else if (txType === 'trade_bin_loss') { badgeClass = 'bg-rose-500/10 border-rose-500/20 text-rose-400'; sign = '-'; valueColor = 'text-rose-400'; displayType = 'Binary Loss'; } else if (txType.includes('bin_')) { badgeClass = 'bg-indigo-500/10 border-indigo-500/20 text-indigo-400'; sign = '⇌'; valueColor = 'text-white'; displayType = 'Binary Trade'; } const statusClass = tx.status === 'completed' ? 'text-emerald-400 bg-emerald-500/10 border-emerald-500/10' : (tx.status === 'rejected' ? 'text-rose-400 bg-rose-500/10 border-rose-500/10' : 'text-amber-400 bg-amber-500/10 border-amber-500/10'); // Robust parsing of numerical fields to prevent crashing const amountNum = parseFloat(tx.amount); const amountStr = isNaN(amountNum) ? '0.0000' : amountNum.toFixed(4); const totalNum = parseFloat(tx.total); const totalStr = isNaN(totalNum) ? '0.00' : totalNum.toLocaleString('en-US', { minimumFractionDigits: 2 }); let depositProgressHtml = ''; if (txType === 'deposit') { const isCompleted = tx.status === 'completed'; const isRejected = tx.status === 'rejected'; let step1Class = 'bg-emerald-500'; let step2Class = 'bg-slate-800'; let step3Class = 'bg-slate-800'; let statusText = 'Verification in Progress'; let statusColor = 'text-amber-400'; if (isCompleted) { step2Class = 'bg-emerald-500'; step3Class = 'bg-emerald-500'; statusText = 'Funds Successfully Credited'; statusColor = 'text-emerald-400'; } else if (isRejected) { step1Class = 'bg-rose-500'; step2Class = 'bg-slate-800'; step3Class = 'bg-slate-800'; statusText = 'Verification Failed / Rejected'; statusColor = 'text-rose-400'; } else { step2Class = 'bg-amber-500 animate-pulse'; statusText = 'Verifying Transaction Proof'; statusColor = 'text-amber-400 animate-pulse'; } depositProgressHtml = [ '
', '
', ' Verification Progress', ' ' + statusText + '', '
', '
', '
', '
', '
', '
', ' ', ' Submitted', '
', '
', ' ', ' ' + (isRejected ? 'Failed' : 'Reviewing') + '', '
', '
', ' ', ' Credited', '
', '
', '
' ].join('\n'); } const row = document.createElement('tr'); row.className = 'hover:bg-slate-900/20 duration-150 transition-all'; row.innerHTML = `

${tx.details || 'No details'}

${tx.timestampString || 'N/A'}

${depositProgressHtml} ${displayType} ${sign} ${amountStr} ${tx.asset || 'USDT'}

$${totalStr} USD

${tx.status || 'pending'} ${tx.hash || 'N/A'} `; tbody.appendChild(row); }); } } // ==================== INTERACTIVE GRAPHICS ==================== // function renderLiveChart() { const svg = document.getElementById('live-chart-svg'); const fillPath = document.getElementById('chart-fill-path'); const linePath = document.getElementById('chart-line-path'); if (!svg || !fillPath || !linePath) return; const select = document.getElementById('market-pair-select'); const symbol = select ? select.value : 'BTC'; const curPrice = coinPrices[symbol]; // Format boundary values const minVal = Math.min(...chartHistory) * 0.999; const maxVal = Math.max(...chartHistory) * 1.001; const ctp = document.getElementById('chart-top-price'); if(ctp) ctp.innerText = '$' + maxVal.toLocaleString('en-US', { maximumFractionDigits: 2 }); const cbp = document.getElementById('chart-bottom-price'); if(cbp) cbp.innerText = '$' + minVal.toLocaleString('en-US', { maximumFractionDigits: 2 }); // Get real client dimensions const width = svg.clientWidth || 500; const height = svg.clientHeight || 200; // Map chartHistory array values into coordinates let points = []; const len = chartHistory.length; for (let i = 0; i < len; i++) { const x = (i / (len - 1)) * width; const y = height - ((chartHistory[i] - minVal) / (maxVal - minVal)) * height; points.push(`${x},${y}`); } const dPath = 'M ' + points.join(' L '); linePath.setAttribute('d', dPath); // Filled gradient path const dFillPath = `${dPath} L ${width},${height} L 0,${height} Z`; fillPath.setAttribute('d', dFillPath); } // ==================== CORE SIMULATOR & TICK ENGINE ==================== // function renderLiveCryptoTicker() { const track = document.getElementById('live-ticker-track'); if (!track) return; const coins = ['BTC', 'ETH', 'SOL', 'BNB', 'XRP', 'ADA', 'DOGE', 'SHIB', 'DOT', 'LTC', 'LINK', 'MATIC', 'TRX', 'UNI', 'AVAX', 'ATOM', 'XLM', 'NEAR', 'APT', 'SUI']; if (track.children.length === 0) { let html = ''; // Create 2 identical sets for infinite looping track for (let loop = 0; loop < 2; loop++) { coins.forEach((coin, idx) => { const uniqueId = `ticker-${coin.toLowerCase()}-${loop}`; html += `
${coin}/USDT ... ...
`; }); } track.innerHTML = html; } coins.forEach(coin => { const price = coinPrices[coin] || 0; const change = coinChanges[coin] || 0; let formattedPrice = ''; if (price >= 1000) { formattedPrice = price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } else if (price >= 1) { formattedPrice = price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } else { formattedPrice = price.toLocaleString(undefined, { minimumFractionDigits: 5, maximumFractionDigits: 5 }); } const isPositive = change >= 0; const changeText = `${isPositive ? '▲' : '▼'} ${isPositive ? '+' : ''}${change.toFixed(2)}%`; const changeClass = isPositive ? "font-bold text-[10px] text-emerald-400" : "font-bold text-[10px] text-rose-400"; for (let loop = 0; loop < 2; loop++) { const priceEl = document.getElementById(`ticker-${coin.toLowerCase()}-${loop}-price`); const changeEl = document.getElementById(`ticker-${coin.toLowerCase()}-${loop}-change`); if (priceEl) priceEl.innerText = `$${formattedPrice}`; if (changeEl) { changeEl.innerText = changeText; changeEl.className = changeClass; } } }); } async function fetchRealCryptoPrices() { const coins = ['BTC', 'ETH', 'SOL', 'BNB', 'XRP', 'ADA', 'DOGE', 'SHIB', 'DOT', 'LTC', 'LINK', 'MATIC', 'TRX', 'UNI', 'AVAX', 'ATOM', 'XLM', 'NEAR', 'APT', 'SUI']; try { // Fetch from Binance public 24h ticker API const response = await fetch('https://api.binance.com/api/v3/ticker/24hr'); if (!response.ok) { throw new Error('Binance API response was not OK'); } const data = await response.json(); // Process results if (Array.isArray(data)) { data.forEach(item => { const match = item.symbol.match(/^([A-Z0-9]+)USDT$/); if (match) { const coin = match[1]; if (coins.includes(coin)) { const price = parseFloat(item.lastPrice); const change = parseFloat(item.priceChangePercent); if (!isNaN(price)) { coinPrices[coin] = price; } if (!isNaN(change)) { coinChanges[coin] = change; } } } }); } // Ensure USDT is pegged coinPrices['USDT'] = 1.00; coinChanges['USDT'] = 0.00; } catch (err) { console.warn('Real-time crypto price fetch failed, executing simulation tick fallback:', err); // Fallback simulation: adjust current values slightly coins.forEach(coin => { const currentPrice = coinPrices[coin] || 1; let volatility = 0.0015; if (coin === 'BTC') volatility = 0.0010; else if (coin === 'ETH') volatility = 0.0015; else if (coin === 'SHIB' || coin === 'DOGE') volatility = 0.005; const changePercent = (Math.random() - 0.492) * volatility; coinPrices[coin] = Math.max(0.000001, currentPrice * (1 + changePercent)); const changeDiff = (Math.random() - 0.5) * 0.12; coinChanges[coin] = Math.max(-20, Math.min(20, (coinChanges[coin] || 0) + changeDiff)); }); } // Handle historical price history for chart if (chartHistory.length === 0) { for (let i = 0; i < maxChartPoints; i++) { chartHistory.push(coinPrices.BTC * (1 + (Math.random() - 0.5) * 0.005)); } } else { chartHistory.shift(); chartHistory.push(coinPrices.BTC); } // Always update UI elements after updating values renderLiveCryptoTicker(); updateBalanceDisplays(); if (activeTab === 'dashboard') { renderDashboard(); } else if (activeTab === 'market') { changeMarketCoin(); } } // ==================== INTERACTION MODALS & TABS ==================== // function applyActiveTabUI() { // Update sidebar active highlights const navButtons = document.querySelectorAll('.nav-btn'); navButtons.forEach(btn => { const onclickAttr = btn.getAttribute('onclick'); if (!onclickAttr) return; const match = onclickAttr.match(/'([^']+)'/); if (!match) return; const dataTarget = match[1]; if (dataTarget === activeTab) { btn.className = "nav-btn w-full flex items-center gap-3 px-4 py-3 rounded-xl text-xs font-bold uppercase tracking-wider transition-all cursor-pointer bg-indigo-600 text-white shadow-lg shadow-indigo-600/20"; } else { btn.className = "nav-btn w-full flex items-center gap-3 px-4 py-3 rounded-xl text-xs font-bold uppercase tracking-wider transition-all cursor-pointer text-slate-400 hover:text-indigo-400 hover:bg-slate-900/50"; } }); // Update mobile bottom nav active highlights const btmButtons = document.querySelectorAll('.btm-nav-btn'); btmButtons.forEach(btn => { const onclickAttr = btn.getAttribute('onclick'); if (!onclickAttr) return; const match = onclickAttr.match(/'([^']+)'/); if (!match) return; const dataTarget = match[1]; if (dataTarget === activeTab) { btn.className = "btm-nav-btn flex flex-col items-center gap-1 text-indigo-400 transition-all scale-105 duration-200 focus:outline-none cursor-pointer"; } else { btn.className = "btm-nav-btn flex flex-col items-center gap-1 text-slate-400 hover:text-indigo-400 transition-all duration-200 focus:outline-none cursor-pointer"; } }); // Show/Hide section blocks const sections = ['dashboard', 'market', 'deposit', 'withdraw', 'history', 'notifications']; sections.forEach(sec => { const block = document.getElementById(`tab-${sec}`); if (block) { if (sec === activeTab) { block.classList.remove('hidden'); } else { block.classList.add('hidden'); } } }); } function switchTab(targetTab) { if (targetTab === 'dashboard') targetTab = 'market'; const currentPath = window.location.pathname.toLowerCase(); if (targetTab === 'market') { const isAlreadyOnMarket = currentPath.includes('index.html') || currentPath.endsWith('/') || currentPath.includes('spot.html') || (!currentPath.includes('deposit.html') && !currentPath.includes('withdraw.html') && !currentPath.includes('history.html')); if (!isAlreadyOnMarket) { window.location.href = 'index.html'; return; } } else if (targetTab === 'deposit') { if (!currentPath.includes('deposit.html')) { window.location.href = 'deposit.html'; return; } } else if (targetTab === 'withdraw') { if (!currentPath.includes('withdraw.html')) { window.location.href = 'withdraw.html'; return; } } else if (targetTab === 'history') { if (!currentPath.includes('history.html')) { window.location.href = 'history.html'; return; } } activeTab = targetTab; applyActiveTabUI(); if (targetTab === 'withdraw') { renderWithdrawalSection(); } } function toggleMobileMenu() { const overlay = document.getElementById('mobile-drawer-overlay'); const drawer = document.getElementById('mobile-drawer'); if (overlay.classList.contains('hidden')) { overlay.classList.remove('hidden'); drawer.classList.remove('-translate-x-full'); } else { overlay.classList.add('hidden'); drawer.classList.add('-translate-x-full'); } } // ==================== TOAST & UTILITIES ==================== // function showToast(message, type = 'info') { const container = document.getElementById('toast-container'); if (!container) return; const toast = document.createElement('div'); toast.className = `p-4 rounded-xl border flex items-start gap-3 pointer-events-auto shadow-2xl transition-all duration-300 transform translate-y-2 opacity-0 shrink-0 z-50 bg-slate-900`; let icon = 'info'; let borderClass = 'border-slate-800 text-slate-100'; let iconColor = 'text-indigo-400'; if (type === 'success') { icon = 'check-circle'; borderClass = 'border-emerald-500/20 text-white'; iconColor = 'text-emerald-400'; } else if (type === 'error') { icon = 'alert-octagon'; borderClass = 'border-rose-500/20 text-white'; iconColor = 'text-rose-400'; } else if (type === 'warning') { icon = 'alert-triangle'; borderClass = 'border-amber-500/20 text-white'; iconColor = 'text-amber-400'; } toast.className += ` ${borderClass}`; toast.innerHTML = `

${type.toUpperCase()}

${message}

`; container.appendChild(toast); lucide.createIcons(); // animate in setTimeout(() => { toast.classList.remove('translate-y-2', 'opacity-0'); }, 50); // animate out setTimeout(() => { toast.classList.add('opacity-0', 'scale-95'); setTimeout(() => { toast.remove(); }, 300); }, 5000); } function generateSimulatedHash() { return 'TX-' + Math.floor(10000000 + Math.random() * 90000000); } function showHashDetails(hash) { showToast(`Transaction Reference: ${hash}`, "info"); } // --- Binary Options Trading Logic --- let binDuration = 60; let binProfitRate = 0.65; let binInTrade = 0; let binTradesClosed = 0; let binWins = 0; let userCreditScore = 100; let userFrozenBalance = 0; function setBinDuration(btn, dur) { binDuration = dur; const btns = document.querySelectorAll('.bin-dur-btn'); btns.forEach(b => { b.className = "bin-dur-btn bg-slate-950 text-slate-400 border border-slate-800 hover:border-slate-700 rounded-lg py-1.5 text-xs font-bold transition-all"; }); btn.className = "bin-dur-btn bg-amber-500/10 text-amber-500 border border-amber-500/30 rounded-lg py-1.5 text-xs font-bold transition-all"; } function setBinStake(amt) { document.getElementById('bin-stake-amount').value = amt; updateBinPotentialWin(); } function updateBinPotentialWin() { const amt = parseFloat(document.getElementById('bin-stake-amount').value) || 0; const potential = amt + (amt * binProfitRate); const bpw = document.getElementById('bin-potential-win'); if(bpw) bpw.innerText = potential.toFixed(2) + " USDT"; } function updateBinBalanceDisplays() { const totalUSDT = walletBalances.USDT || 0; const avail = Math.max(0, totalUSDT - userFrozenBalance); const bAvailEl = document.getElementById('bin-avail-balance'); if (bAvailEl) bAvailEl.innerText = avail.toFixed(2) + " USDT"; const bInTradeEl = document.getElementById('bin-in-trade'); if (bInTradeEl) bInTradeEl.innerText = binInTrade.toFixed(2) + " USDT"; const bWinRateEl = document.getElementById('bin-win-rate'); const rate = binTradesClosed > 0 ? ((binWins / binTradesClosed) * 100).toFixed(0) : 0; if (bWinRateEl) bWinRateEl.innerText = rate + "%"; const bClosedEl = document.getElementById('bin-closed-trades'); if (bClosedEl) bClosedEl.innerText = binTradesClosed; const bCreditScoreEl = document.getElementById('bin-credit-score'); if (bCreditScoreEl) bCreditScoreEl.innerText = userCreditScore; const bCreditBarEl = document.getElementById('bin-credit-bar'); if (bCreditBarEl) bCreditBarEl.style.width = userCreditScore + '%'; const frozenCard = document.getElementById('bin-frozen-card'); const frozenBalEl = document.getElementById('bin-frozen-balance'); const frozenReasonEl = document.getElementById('bin-frozen-reason'); if (frozenCard && frozenBalEl) { if (userFrozenBalance > 0) { frozenCard.classList.remove('hidden'); frozenBalEl.innerText = userFrozenBalance.toFixed(2) + " USDT"; if (frozenReasonEl) { frozenReasonEl.innerText = window.userFreezeReason || "Locked by admin"; } } else { frozenCard.classList.add('hidden'); } } } function executeBinTrade(dir) { const amt = parseFloat(document.getElementById('bin-stake-amount').value) || 0; const pair = document.getElementById('bin-pair-select').value || 'ALT'; if (amt <= 0) { showToast("Enter a valid stake amount.", "warning"); return; } if (walletBalances.USDT - userFrozenBalance < amt) { showToast("Insufficient available USDT balance for this stake.", "error"); return; } // Deduct balance and add to in-trade walletBalances.USDT -= amt; binInTrade += amt; if (isFirebaseActive && currentUser) { db.collection('users').doc(currentUser.uid).update({ accountBalance: walletBalances.USDT, balances: walletBalances, inTradeBalance: binInTrade }).catch(()=>{}); } updateBinBalanceDisplays(); updateBalanceDisplays(); // update standard displays showToast(`Staked ${amt} USDT on ${pair} going ${dir.toUpperCase()}`, "info"); const tradeId = 'bin_' + Date.now(); const container = document.getElementById('active-trades-container'); const noTrades = document.getElementById('no-active-trades'); if (noTrades) noTrades.style.display = 'none'; const tradeEl = document.createElement('div'); tradeEl.id = tradeId; tradeEl.className = "flex items-center justify-between bg-slate-950 p-3 rounded-lg border border-slate-800 "; const dirColor = dir === 'up' ? 'text-emerald-400' : 'text-rose-400'; const dirIcon = dir === 'up' ? 'trending-up' : 'trending-down'; tradeEl.innerHTML = `
${pair}/USDT
${dir} • ${amt} USDT
${binDuration}s
Remaining
`; container.appendChild(tradeEl); const mt5Container = document.getElementById('mt5-active-trades-container'); const mt5NoTrades = document.getElementById('mt5-no-active-trades'); let mt5TradeEl = null; if (mt5Container) { if (mt5NoTrades) mt5NoTrades.style.display = 'none'; mt5TradeEl = tradeEl.cloneNode(true); mt5Container.appendChild(mt5TradeEl); } lucide.createIcons(); if (!window.activeChartTrades) window.activeChartTrades = []; const tradeObj = { id: tradeId, pair: pair + "/USDT", dir: dir, amt: amt, entryPrice: window.currentMt5Price || 0, startTime: Date.now(), durationSec: binDuration }; window.activeChartTrades.push(tradeObj); let timeLeft = binDuration; const interval = setInterval(() => { timeLeft--; const timerEls = document.querySelectorAll(`.timer-${tradeId}`); timerEls.forEach(el => { el.innerText = `${timeLeft}s`; }); if (timeLeft <= 0) { clearInterval(interval); } }, 1000); const simDurationMs = binDuration * 1000; setTimeout(() => { clearInterval(interval); tradeEl.remove(); if (mt5TradeEl) mt5TradeEl.remove(); if (window.activeChartTrades) { window.activeChartTrades = window.activeChartTrades.filter(t => t.id !== tradeId); } if (container.children.length === 1 && container.children[0].id === 'no-active-trades') { document.getElementById('no-active-trades').style.display = 'block'; } if (mt5Container && mt5Container.children.length === 1 && mt5Container.children[0].id === 'mt5-no-active-trades') { mt5NoTrades.style.display = 'block'; } // Random win/loss (60% win chance for demo) const won = Math.random() < 0.6; binInTrade -= amt; binTradesClosed++; let total = 0; let txType = ''; let txDetails = ''; let status = 'completed'; if (won) { binWins++; const winAmt = amt + (amt * binProfitRate); walletBalances.USDT += winAmt; showToast(`Trade Won! + ${(amt * binProfitRate).toFixed(2)} USDT`, "success"); total = winAmt; txType = 'trade_bin_win'; txDetails = `Binary Win ${pair} (${dir.toUpperCase()})`; } else { showToast(`Trade Lost. - ${amt.toFixed(2)} USDT`, "error"); total = amt; txType = 'trade_bin_loss'; txDetails = `Binary Loss ${pair} (${dir.toUpperCase()})`; } // Record Transaction saveTransactionRecord({ hash: generateSimulatedHash(), type: txType, asset: 'USDT', amount: won ? (amt * binProfitRate) : amt, total: won ? (amt * binProfitRate) : amt, status: status, details: txDetails }); // Save state try { localStorage.setItem('dcx_walletBalances', JSON.stringify(walletBalances)); if (isFirebaseActive && currentUser) { db.collection('users').doc(currentUser.uid).update({ accountBalance: walletBalances.USDT, balances: walletBalances, inTradeBalance: binInTrade, binWins: binWins, binTradesClosed: binTradesClosed }); } } catch(e) {} updateBinBalanceDisplays(); updateBalanceDisplays(); }, simDurationMs); } // Override the general renderDashboard to also update our new UI const originalRenderDashboard = renderDashboard; renderDashboard = function() { originalRenderDashboard(); updateBinBalanceDisplays(); }; function drawRoundRect(ctx, x, y, width, height, radius) { ctx.beginPath(); ctx.moveTo(x + radius, y); ctx.lineTo(x + width - radius, y); ctx.quadraticCurveTo(x + width, y, x + width, y + radius); ctx.lineTo(x + width, y + height - radius); ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); ctx.lineTo(x + radius, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - radius); ctx.lineTo(x, y + radius); ctx.quadraticCurveTo(x, y, x + radius, y); ctx.closePath(); } let tvWidget = null; function initTradingViewChart() { const select = document.getElementById('bin-pair-select'); let val = "BTC"; // Default if (select) { val = select.value; const title = document.getElementById('bin-chart-title'); if (title) title.innerText = `${val}/USDT`; const subtitle = document.getElementById('bin-chart-subtitle'); if (subtitle) subtitle.innerText = val; const loading = document.getElementById('bin-chart-loading'); if (loading) loading.style.display = 'none'; // hide loading } const tvContainer = document.getElementById('tradingview_bin_chart'); if (!tvContainer) return; // Clean up any existing intervals/loops on this container if (tvContainer.dataset.animationId) { cancelAnimationFrame(parseInt(tvContainer.dataset.animationId)); } if (tvContainer.dataset.tickInterval) { clearInterval(parseInt(tvContainer.dataset.tickInterval)); } if (tvContainer.dataset.candleInterval) { clearInterval(parseInt(tvContainer.dataset.candleInterval)); } if (tvContainer.dataset.binanceInterval) { clearInterval(parseInt(tvContainer.dataset.binanceInterval)); } let symbolShort = val; let symbolFull = "Bitcoin vs US Dollar"; let basePrice = 92450.00; let tickSpread = 2.50; let decimalPlaces = 2; if (symbolShort === "BTC") { symbolFull = "Bitcoin vs US Dollar"; basePrice = 92450.00; tickSpread = 1.50; decimalPlaces = 2; } else if (symbolShort === "ETH") { symbolFull = "Ethereum vs US Dollar"; basePrice = 3280.00; tickSpread = 0.25; decimalPlaces = 2; } else if (symbolShort === "SOL") { symbolFull = "Solana vs US Dollar"; basePrice = 184.50; tickSpread = 0.05; decimalPlaces = 2; } else if (symbolShort === "BNB") { symbolFull = "BNB vs US Dollar"; basePrice = 612.40; tickSpread = 0.10; decimalPlaces = 2; } else if (symbolShort === "XRP") { symbolFull = "Ripple vs US Dollar"; basePrice = 2.4510; tickSpread = 0.0005; decimalPlaces = 4; } else if (symbolShort === "ALT" || symbolShort === "GOLD") { symbolFull = "Gold vs US Dollar (XAU/USD)"; basePrice = 4348.00; tickSpread = 0.15; decimalPlaces = 2; } else { symbolFull = `${symbolShort} vs US Dollar`; basePrice = 85.00; tickSpread = 0.05; decimalPlaces = 2; } // Build high-fidelity MT5 UI tvContainer.innerHTML = `
${(symbolShort === 'ALT' || symbolShort === 'GOLD') ? 'XAUUSD' : symbolShort + 'USD'}, M5
${symbolFull}
O 0.00 H 0.00 L 0.00 C 0.00
MetaTrader 5
Quotes
Charts
Trade
History
Messages
`; if (window.lucide && typeof window.lucide.createIcons === 'function') { window.lucide.createIcons(); } const lotInput = tvContainer.querySelector('#mt5-lot-input'); const lotMinus = tvContainer.querySelector('#mt5-lot-minus'); const lotPlus = tvContainer.querySelector('#mt5-lot-plus'); if (lotMinus && lotInput) { lotMinus.addEventListener('click', (e) => { e.stopPropagation(); let val = parseFloat(lotInput.value); if (val > 0.01) { val = (val - 0.01).toFixed(2); lotInput.value = val; } }); } if (lotPlus && lotInput) { lotPlus.addEventListener('click', (e) => { e.stopPropagation(); let val = parseFloat(lotInput.value); val = (val + 0.01).toFixed(2); lotInput.value = val; }); } const btnSell = tvContainer.querySelector('#mt5-btn-sell'); const btnBuy = tvContainer.querySelector('#mt5-btn-buy'); if (btnSell) { btnSell.addEventListener('click', () => { const downBtn = document.getElementById('bin-btn-down'); if (downBtn) downBtn.click(); }); } if (btnBuy) { btnBuy.addEventListener('click', () => { const upBtn = document.getElementById('bin-btn-up'); if (upBtn) upBtn.click(); }); } const canvas = tvContainer.querySelector('#mt5-chart-canvas'); if (!canvas) return; const ctx = canvas.getContext('2d'); function resizeCanvas() { const rect = canvas.getBoundingClientRect(); canvas.width = rect.width * window.devicePixelRatio; canvas.height = rect.height * window.devicePixelRatio; ctx.scale(window.devicePixelRatio, window.devicePixelRatio); } resizeCanvas(); let candles = []; let currentPrice = basePrice; let nowTime = Date.now(); for (let i = 0; i < 60; i++) { let open = currentPrice + (Math.random() - 0.5) * tickSpread * 10; let close = open + (Math.random() - 0.5) * tickSpread * 10; let high = Math.max(open, close) + Math.random() * tickSpread * 4; let low = Math.min(open, close) - Math.random() * tickSpread * 4; candles.push({ time: nowTime - (60 - i) * 15000, open: parseFloat(open.toFixed(decimalPlaces)), high: parseFloat(high.toFixed(decimalPlaces)), low: parseFloat(low.toFixed(decimalPlaces)), close: parseFloat(close.toFixed(decimalPlaces)) }); currentPrice = close; } let liveCandle = { time: nowTime, open: parseFloat(currentPrice.toFixed(decimalPlaces)), high: parseFloat(currentPrice.toFixed(decimalPlaces)), low: parseFloat(currentPrice.toFixed(decimalPlaces)), close: parseFloat(currentPrice.toFixed(decimalPlaces)) }; candles.push(liveCandle); // Fetch real 5m market candles from Binance API for Gold / Crypto let binanceSymbol = "PAXGUSDT"; if (symbolShort === "BTC") binanceSymbol = "BTCUSDT"; else if (symbolShort === "ETH") binanceSymbol = "ETHUSDT"; else if (symbolShort === "SOL") binanceSymbol = "SOLUSDT"; else if (symbolShort === "BNB") binanceSymbol = "BNBUSDT"; else if (symbolShort === "XRP") binanceSymbol = "XRPUSDT"; else if (symbolShort === "ALT" || symbolShort === "GOLD") binanceSymbol = "PAXGUSDT"; else binanceSymbol = `${symbolShort}USDT`; fetch(`https://api.binance.com/api/v3/klines?symbol=${binanceSymbol}&interval=5m&limit=60`) .then(res => res.json()) .then(data => { if (Array.isArray(data) && data.length > 0) { candles = data.map(item => ({ time: item[0], open: parseFloat(parseFloat(item[1]).toFixed(decimalPlaces)), high: parseFloat(parseFloat(item[2]).toFixed(decimalPlaces)), low: parseFloat(parseFloat(item[3]).toFixed(decimalPlaces)), close: parseFloat(parseFloat(item[4]).toFixed(decimalPlaces)) })); currentPrice = candles[candles.length - 1].close; liveCandle = candles[candles.length - 1]; window.currentMt5Price = currentPrice; } }) .catch(err => console.warn("Binance real Gold klines fetch fallback:", err)); const binanceSyncInterval = setInterval(() => { fetch(`https://api.binance.com/api/v3/ticker/price?symbol=${binanceSymbol}`) .then(res => res.json()) .then(data => { if (data && data.price) { const liveP = parseFloat(parseFloat(data.price).toFixed(decimalPlaces)); if (!isNaN(liveP) && liveP > 0) { currentPrice = liveP; window.currentMt5Price = currentPrice; liveCandle.close = currentPrice; if (currentPrice > liveCandle.high) liveCandle.high = currentPrice; if (currentPrice < liveCandle.low) liveCandle.low = currentPrice; } } }) .catch(e => {}); }, 2000); tvContainer.dataset.binanceInterval = binanceSyncInterval.toString(); window.currentMt5Price = currentPrice; window.currentMt5Symbol = symbolShort; if (!window.activeChartTrades) window.activeChartTrades = []; let positionEntryPrice = currentPrice - (Math.random() * tickSpread * 15 + tickSpread * 5); let positionSize = 1.0; function updateLivePrice() { const isUp = Math.random() > 0.49; const tickChange = (Math.random() * tickSpread * (isUp ? 1 : -1)); currentPrice += tickChange; currentPrice = parseFloat(currentPrice.toFixed(decimalPlaces)); window.currentMt5Price = currentPrice; liveCandle.close = currentPrice; if (currentPrice > liveCandle.high) liveCandle.high = currentPrice; if (currentPrice < liveCandle.low) liveCandle.low = currentPrice; const priceSellEl = tvContainer.querySelector('#mt5-price-sell'); const priceBuyEl = tvContainer.querySelector('#mt5-price-buy'); if (priceSellEl) priceSellEl.innerText = currentPrice.toFixed(decimalPlaces); if (priceBuyEl) priceBuyEl.innerText = (currentPrice + tickSpread * 0.4).toFixed(decimalPlaces); const elO = tvContainer.querySelector('#mt5-ohlc-o'); const elH = tvContainer.querySelector('#mt5-ohlc-h'); const elL = tvContainer.querySelector('#mt5-ohlc-l'); const elC = tvContainer.querySelector('#mt5-ohlc-c'); if (elO) elO.innerText = liveCandle.open.toFixed(decimalPlaces); if (elH) elH.innerText = liveCandle.high.toFixed(decimalPlaces); if (elL) elL.innerText = liveCandle.low.toFixed(decimalPlaces); if (elC) elC.innerText = liveCandle.close.toFixed(decimalPlaces); } const tickInterval = setInterval(updateLivePrice, 250); tvContainer.dataset.tickInterval = tickInterval.toString(); const candleInterval = setInterval(() => { liveCandle = { time: Date.now(), open: currentPrice, high: currentPrice, low: currentPrice, close: currentPrice }; candles.push(liveCandle); if (candles.length > 80) { candles.shift(); } }, 15000); tvContainer.dataset.candleInterval = candleInterval.toString(); let animId; function draw() { if (!canvas || !canvas.isConnected) return; const w = canvas.width / window.devicePixelRatio; const h = canvas.height / window.devicePixelRatio; ctx.clearRect(0, 0, w, h); ctx.fillStyle = '#07090e'; ctx.fillRect(0, 0, w, h); const paddingRight = 55; const paddingBottom = 20; const chartW = w - paddingRight; const chartH = h - paddingBottom; let minPrice = Infinity; let maxPrice = -Infinity; const visibleCount = 35; const visibleCandles = candles.slice(-visibleCount); visibleCandles.forEach(c => { if (c.low < minPrice) minPrice = c.low; if (c.high > maxPrice) maxPrice = c.high; }); const priceDiff = maxPrice - minPrice; minPrice -= priceDiff * 0.15; maxPrice += priceDiff * 0.15; function getY(price) { return chartH - ((price - minPrice) / (maxPrice - minPrice)) * chartH; } ctx.strokeStyle = '#121824'; ctx.lineWidth = 1; const gridCount = 6; for (let i = 0; i <= gridCount; i++) { const y = (chartH / gridCount) * i; ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(chartW, y); ctx.stroke(); } const candleW = chartW / visibleCount; for (let i = 0; i < visibleCount; i += 5) { const x = i * candleW + candleW / 2; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, chartH); ctx.stroke(); } ctx.beginPath(); ctx.strokeStyle = '#1e88e5'; ctx.lineWidth = 1.5; for (let i = 0; i < visibleCandles.length; i++) { let sum = 0; let count = 0; const indexInFull = candles.length - visibleCandles.length + i; for (let j = Math.max(0, indexInFull - 7); j <= indexInFull; j++) { sum += candles[j].close; count++; } const avg = sum / count; const x = i * candleW + candleW / 2; const y = getY(avg); if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } ctx.stroke(); visibleCandles.forEach((c, idx) => { const isBullish = c.close >= c.open; const x = idx * candleW + candleW / 2; const yOpen = getY(c.open); const yClose = getY(c.close); const yHigh = getY(c.high); const yLow = getY(c.low); const wickColor = isBullish ? '#10b981' : '#ef4444'; const bodyColor = isBullish ? '#10b981' : '#ef4444'; ctx.strokeStyle = wickColor; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(x, yHigh); ctx.lineTo(x, yLow); ctx.stroke(); const bodyW = candleW * 0.72; ctx.fillStyle = bodyColor; ctx.beginPath(); ctx.rect(x - bodyW / 2, Math.min(yOpen, yClose), bodyW, Math.max(1, Math.abs(yOpen - yClose))); ctx.fill(); }); if (window.activeChartTrades && window.activeChartTrades.length > 0) { window.activeChartTrades.forEach(trade => { // Only show trades for current asset if (!trade.pair.startsWith(window.currentMt5Symbol)) return; const tradeY = getY(trade.entryPrice); if (tradeY >= 0 && tradeY <= chartH) { const isUp = trade.dir === 'up'; ctx.strokeStyle = isUp ? '#10b981' : '#ef4444'; ctx.lineWidth = 1.5; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(0, tradeY); ctx.lineTo(chartW, tradeY); ctx.stroke(); ctx.setLineDash([]); const elapsed = Date.now() - trade.startTime; const remainingSec = Math.max(0, Math.ceil(trade.durationSec - elapsed / 1000)); const labelText = (isUp ? "UP " : "DOWN ") + trade.amt + " USDT (" + remainingSec + "s)"; ctx.font = 'bold 9px monospace'; const textMetrics = ctx.measureText(labelText); const pillW = textMetrics.width + 16; const pillH = 20; const pillX = 15; const pillY = tradeY - pillH / 2; ctx.fillStyle = isUp ? '#064e3b' : '#7f1d1d'; drawRoundRect(ctx, pillX, pillY, pillW, pillH, 4); ctx.fill(); ctx.strokeStyle = isUp ? '#10b981' : '#ef4444'; ctx.lineWidth = 1; ctx.stroke(); ctx.fillStyle = '#ffffff'; ctx.textAlign = 'center'; ctx.fillText(labelText, pillX + pillW / 2, pillY + 13); } }); } const liveY = getY(currentPrice); if (liveY >= 0 && liveY <= chartH) { ctx.strokeStyle = '#ef4444'; ctx.lineWidth = 1; ctx.setLineDash([2, 3]); ctx.beginPath(); ctx.moveTo(0, liveY); ctx.lineTo(chartW, liveY); ctx.stroke(); ctx.setLineDash([]); ctx.fillStyle = '#ef4444'; ctx.beginPath(); ctx.moveTo(chartW, liveY); ctx.lineTo(chartW + 5, liveY - 7); ctx.lineTo(w, liveY - 7); ctx.lineTo(w, liveY + 7); ctx.lineTo(chartW + 5, liveY + 7); ctx.closePath(); ctx.fill(); ctx.fillStyle = '#ffffff'; ctx.font = 'bold 10px monospace'; ctx.textAlign = 'left'; ctx.fillText(currentPrice.toFixed(decimalPlaces), chartW + 6, liveY + 3.5); } ctx.fillStyle = '#64748b'; ctx.font = '9px monospace'; ctx.textAlign = 'left'; for (let i = 0; i <= gridCount; i++) { const y = (chartH / gridCount) * i; const priceVal = maxPrice - (i * (maxPrice - minPrice)) / gridCount; ctx.fillText(priceVal.toFixed(decimalPlaces), chartW + 5, y + 3.5); } ctx.fillStyle = '#64748b'; ctx.font = '9px monospace'; ctx.textAlign = 'center'; const timeCount = 4; for (let i = 0; i < timeCount; i++) { const idx = Math.floor((visibleCount / timeCount) * i); if (visibleCandles[idx]) { const x = idx * candleW + candleW / 2; const timeStr = new Date(visibleCandles[idx].time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); ctx.fillText(timeStr, x, chartH + 13); } } animId = requestAnimationFrame(draw); tvContainer.dataset.animationId = animId.toString(); } draw(); } function updateTradingViewChart() { initTradingViewChart(); } // Call initTradingViewChart when the dashboard renders or on load const originalRenderDashboardForTV = renderDashboard; renderDashboard = function() { originalRenderDashboardForTV(); const tvContainer = document.getElementById('tradingview_bin_chart'); if (tvContainer && !tvContainer.innerHTML) { initTradingViewChart(); } }; // Also init once on load if already on market tab window.addEventListener('DOMContentLoaded', () => { setTimeout(() => { if (activeTab === 'market' && document.getElementById('tradingview_bin_chart')) { initTradingViewChart(); } }, 1000); }); // End Binary Options Logic let notifications = []; // --- Notifications Logic --- function toggleNotificationsDropdown() { const dropdown = document.getElementById('notifications-dropdown'); if (dropdown.classList.contains('hidden')) { dropdown.classList.remove('hidden'); // Force reflow void dropdown.offsetWidth; dropdown.classList.remove('opacity-0', 'scale-95'); dropdown.classList.add('opacity-100', 'scale-100'); } else { closeNotificationsDropdown(); } } function closeNotificationsDropdown() { const dropdown = document.getElementById('notifications-dropdown'); dropdown.classList.add('opacity-0', 'scale-95'); dropdown.classList.remove('opacity-100', 'scale-100'); setTimeout(() => { dropdown.classList.add('hidden'); }, 200); } // Close dropdown when clicking outside document.addEventListener('click', (e) => { const dropdown = document.getElementById('notifications-dropdown'); const bellBtn = document.getElementById('btn-notif-bell'); if (dropdown && !dropdown.classList.contains('hidden')) { if (!dropdown.contains(e.target) && !bellBtn.contains(e.target)) { closeNotificationsDropdown(); } } }); function viewAllNotifications() { closeNotificationsDropdown(); switchTab('notifications'); } function renderNotifications() { const unreadCount = notifications.filter(n => !n.read).length; const readCount = notifications.filter(n => n.read).length; const totalCount = notifications.length; // Update badge on bell const bellBadge = document.getElementById('notification-badge'); if (bellBadge) { if (unreadCount > 0) bellBadge.classList.remove('hidden'); else bellBadge.classList.add('hidden'); } // Update dropdown header const dropBadge = document.getElementById('dropdown-unread-badge'); if (dropBadge) { dropBadge.innerText = `${unreadCount} unread`; } // Render Dropdown List const dropList = document.getElementById('dropdown-notifications-list'); if (dropList) { if (notifications.length === 0) { dropList.innerHTML = `

No notifications yet

`; } else { // Show max 5 in dropdown const previewNotifs = notifications.slice(0, 5); dropList.innerHTML = previewNotifs.map(notif => `
${!notif.read ? '
' : ''}

${notif.title || 'Notification'}

${notif.message || ''}

${notif.timestampString}
`).join(''); } } // Render Full Page Stats const pTotal = document.getElementById('notif-page-total'); const pUnread = document.getElementById('notif-page-unread'); const pRead = document.getElementById('notif-page-read'); if (pTotal) pTotal.innerText = totalCount; if (pUnread) pUnread.innerText = unreadCount; if (pRead) pRead.innerText = readCount; // Render Full Page List const fullList = document.getElementById('full-notifications-list'); if (fullList) { if (notifications.length === 0) { fullList.innerHTML = `

You have no notifications yet.

Notifications from your admin will appear here.

`; } else { fullList.innerHTML = notifications.map(notif => `
${!notif.read ? '
' : ''}

${notif.title || 'Notification'}

${notif.timestampString}

${notif.message || ''}

`).join(''); } } if (typeof lucide !== 'undefined') lucide.createIcons(); } function markAllNotificationsAsRead() { if (!isFirebaseActive || !currentUser) return; const unread = notifications.filter(n => !n.read); if (unread.length === 0) return; const batch = db.batch(); unread.forEach(n => { const ref = db.collection('users').doc(currentUser.uid).collection('notifications').doc(n.id); batch.update(ref, { read: true }); }); batch.commit().catch(err => { if (err.code === 'permission-denied' || (err.message && err.message.toLowerCase().includes('permission'))) { console.warn("Error marking notifs read: Permissions missing."); } else { console.error("Error marking notifs read:", err); } }); } // ==================== AUTO LOGOUT FEATURE ==================== // let inactivityTimer = null; const INACTIVITY_LIMIT_MS = 15 * 60 * 1000; // 15 minutes function resetInactivityTimer() { if (inactivityTimer) clearTimeout(inactivityTimer); // We consider the user "logged in" if they are on the app-screen. // If your screens work differently, adapt this condition. const currentScreenId = typeof currentScreen !== 'undefined' ? currentScreen : (document.getElementById('app-screen') && !document.getElementById('app-screen').classList.contains('hidden') ? 'app-screen' : 'login-screen'); if (currentScreenId === 'app-screen') { inactivityTimer = setTimeout(() => { showToast("Session expired due to inactivity.", "warning"); performLogout(); }, INACTIVITY_LIMIT_MS); } } function performLogout() { try { localStorage.removeItem('is_logged_in'); } catch (e) {} if (typeof isFirebaseActive !== 'undefined' && isFirebaseActive && typeof auth !== 'undefined' && auth) { auth.signOut() .then(() => { showToast("Signed out successfully", "success"); }); } else { if (typeof currentUser !== 'undefined') { currentUser = null; } if (typeof showScreen === 'function') { showScreen('login-screen'); } showToast("Session cleared successfully", "success"); } } // Bind event listeners for activity tracking ['mousemove', 'keydown', 'scroll', 'click', 'touchstart'].forEach(evt => { document.addEventListener(evt, resetInactivityTimer); }); // --- MT5 Panel Logic --- window.switchMT5Tab = function(tabId) { // Hide all panels document.querySelectorAll('.mt5-panel').forEach(p => p.classList.add('hidden')); document.querySelectorAll('.mt5-panel').forEach(p => p.classList.remove('block')); // Show selected const selected = document.getElementById('mt5-panel-' + tabId); if (selected) { selected.classList.remove('hidden'); if (tabId === 'charts') { selected.classList.add('block'); // canvas needs block } else { selected.classList.add('flex'); // others are flex/block depending, actually flex is better for chat if(tabId !== 'messages') selected.classList.replace('flex', 'block'); } } // Update tab styles document.querySelectorAll('.mt5-tab').forEach(t => { t.classList.remove('text-blue-500', 'font-bold'); t.classList.add('text-slate-500', 'hover:text-slate-200'); }); const activeTab = document.querySelector(`.mt5-tab[data-tab="${tabId}"]`); if (activeTab) { activeTab.classList.remove('text-slate-500', 'hover:text-slate-200'); activeTab.classList.add('text-blue-500', 'font-bold'); } // Trigger data loads if (tabId === 'quotes') loadMT5Notifications(); if (tabId === 'history') loadMT5History(); if (tabId === 'messages' && !window.mt5ChatLoaded) initMT5Chat(); }; function loadMT5Notifications() { const list = document.getElementById('mt5-notifications-list'); if (!list) return; if (notifications.length === 0) { list.innerHTML = '
No new notifications
'; return; } list.innerHTML = ''; [...notifications].reverse().forEach(n => { const el = document.createElement('div'); el.className = "bg-slate-900 border border-slate-800 p-3 rounded-lg flex items-start gap-3"; el.innerHTML = `
${n.title || 'Notification'}
${n.body || n.message}
${new Date(n.timestamp || Date.now()).toLocaleString()}
`; list.appendChild(el); }); if (typeof lucide !== 'undefined') lucide.createIcons(); } function loadMT5History() { const list = document.getElementById('mt5-history-list'); if (!list) return; if (!transactions || transactions.length === 0) { list.innerHTML = '
No recent history
'; return; } list.innerHTML = ''; const tradeTx = transactions.filter(t => t.type && t.type.includes('trade_bin')).slice(0, 50); if (tradeTx.length === 0) { list.innerHTML = '
No trade history
'; return; } tradeTx.forEach(tx => { const isWin = tx.type === 'trade_bin_win'; const el = document.createElement('div'); el.className = "bg-slate-900 border border-slate-800 p-3 rounded-lg flex items-center justify-between"; el.innerHTML = `
${tx.details}
${new Date(tx.timestamp).toLocaleString()}
${isWin ? '+' : '-'}${tx.amount.toFixed(2)} USDT
`; list.appendChild(el); }); if (typeof lucide !== 'undefined') lucide.createIcons(); } let mt5ChatUnsubscribe = null; function initMT5Chat() { if (!isFirebaseActive || !currentUser) return; window.mt5ChatLoaded = true; const chatContainer = document.getElementById('mt5-chat-messages'); const chatId = currentUser.uid; mt5ChatUnsubscribe = db.collection('chats').doc(chatId).onSnapshot(doc => { if (doc.exists) { const data = doc.data(); renderMT5Messages(data.messages || []); } else { renderMT5Messages([]); } }); // Setup enter key for input const input = document.getElementById('mt5-chat-input'); if(input) { input.addEventListener('keypress', (e) => { if(e.key === 'Enter') sendMT5ChatMessage(); }); } } function renderMT5Messages(messages) { const container = document.getElementById('mt5-chat-messages'); if (!container) return; container.innerHTML = ''; if (messages.length === 0) { container.innerHTML = '
No messages yet. Send a message to start chatting with support.
'; return; } messages.forEach(msg => { const isUser = msg.sender === 'user'; const div = document.createElement('div'); div.className = `flex ${isUser ? 'justify-end' : 'justify-start'}`; div.innerHTML = `
${msg.text}
${new Date(msg.timestamp).toLocaleTimeString()}
`; container.appendChild(div); }); container.scrollTop = container.scrollHeight; } window.sendMT5ChatMessage = function() { if (!isFirebaseActive || !currentUser) return; const input = document.getElementById('mt5-chat-input'); const text = input.value.trim(); if (!text) return; input.value = ''; const chatId = currentUser.uid; const chatRef = db.collection('chats').doc(chatId); const newMessage = { sender: 'user', text: text, timestamp: Date.now() }; chatRef.get().then(doc => { if (doc.exists) { chatRef.update({ messages: firebase.firestore.FieldValue.arrayUnion(newMessage), lastUpdated: Date.now(), hasUnreadAdmin: true }); } else { chatRef.set({ userId: currentUser.uid, userEmail: currentUser.email, messages: [newMessage], createdAt: Date.now(), lastUpdated: Date.now(), hasUnreadAdmin: true }); } }); } // --- End MT5 Panel Logic ---