/* ===================================================== FraudLens — Frontend Logic Matches: fraudlens-2o2ev52.public.builtwithrocket.new ===================================================== */ 'use strict'; // ------------------------------------------------------- // LUCIDE ICONS INIT // ------------------------------------------------------- function startup() { if (window.lucide) { lucide.createIcons(); initApp(); } else { const script = document.createElement('script'); script.src = "https://unpkg.com/lucide@latest"; script.onload = () => { lucide.createIcons(); initApp(); }; document.head.appendChild(script); } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', startup); } else { startup(); } // ------------------------------------------------------- // STATE // ------------------------------------------------------- let currentResult = null; // ------------------------------------------------------- // UTILITY: Toast // ------------------------------------------------------- function showToast(message, type = 'info', duration = 3000) { const container = document.getElementById('toastContainer'); const toast = document.createElement('div'); toast.className = `toast ${type}`; const icons = { success: '✓', error: '⚠', info: 'ℹ' }; toast.innerHTML = `${icons[type] || 'ℹ'} ${message}`; container.appendChild(toast); setTimeout(() => { toast.style.transition = 'all 0.3s ease'; toast.style.opacity = '0'; toast.style.transform = 'translateX(20px)'; setTimeout(() => toast.remove(), 300); }, duration); } // ------------------------------------------------------- // NAVIGATION: switch between form / result screens // ------------------------------------------------------- function showScreen(name) { const screens = { form: 'formScreen', loading: 'loadingScreen', result: 'resultScreen' }; Object.keys(screens).forEach(k => { document.getElementById(screens[k]).classList.add('hidden'); }); document.getElementById(screens[name]).classList.remove('hidden'); // Update nav active state ['navAnalyzeBtn', 'navResultBtn'].forEach(id => { document.getElementById(id)?.classList.remove('active'); }); ['mobileNavAnalyze', 'mobileNavResult'].forEach(id => { document.getElementById(id)?.classList.remove('active'); }); if (name === 'form') { document.getElementById('navAnalyzeBtn')?.classList.add('active'); document.getElementById('mobileNavAnalyze')?.classList.add('active'); } else if (name === 'result') { document.getElementById('navResultBtn')?.classList.add('active'); document.getElementById('mobileNavResult')?.classList.add('active'); } } // ------------------------------------------------------- // COLLAPSIBLE CARDS // ------------------------------------------------------- function initCollapsible() { document.querySelectorAll('.collapsible-card').forEach(card => { const header = card.querySelector('.collapsible-header'); header.addEventListener('click', () => { card.classList.toggle('active'); }); }); } // ------------------------------------------------------- // LIVE RISK PREVIEW (sidebar) // ------------------------------------------------------- const RISK_CONFIG = { low: { label: 'LOW RISK', description: 'Transaction within normal parameters', color: 'var(--legit-green)', bg: 'var(--legit-green-muted)', border: 'var(--legit-green-border)', icon: 'shield-check' }, medium: { label: 'MEDIUM RISK', description: 'Borderline indicators — review recommended', color: 'var(--warn-amber)', bg: 'var(--warn-amber-muted)', border: 'var(--warn-amber-border)', icon: 'alert-triangle' }, high: { label: 'HIGH RISK', description: 'Multiple fraud signals detected', color: 'var(--fraud-red)', bg: 'var(--fraud-red-muted)', border: 'var(--fraud-red-border)', icon: 'shield-alert' }, critical: { label: 'CRITICAL RISK', description: 'Strong fraud indicators present — block and investigate', color: 'var(--fraud-red)', bg: 'rgba(239, 68, 68, 0.18)', border: 'var(--fraud-red-border)', icon: 'alert-octagon' } }; function computeRiskLevel(amount) { if (!amount || isNaN(amount)) return null; const a = parseFloat(amount); if (a > 5000) return 'critical'; if (a > 2000) return 'high'; if (a > 500) return 'medium'; return 'low'; } function updateRiskPreview(riskLevel) { const box = document.getElementById('liveRiskPreview'); if (!riskLevel) { box.innerHTML = `

Enter transaction amount to see a live risk preview

`; box.className = 'risk-preview-empty'; if (window.lucide) lucide.createIcons(); return; } const cfg = RISK_CONFIG[riskLevel]; box.className = 'risk-preview-filled'; box.style.background = cfg.bg; box.style.borderColor = cfg.border; box.innerHTML = `

${cfg.label}

${cfg.description}

`; if (window.lucide) lucide.createIcons(); } // ------------------------------------------------------- // COMPUTE FEATURE CONTRIBUTIONS (client-side, matching original) // ------------------------------------------------------- function computeFeatureContributions(formData) { const amount = parseFloat(formData.amount) || 0; const distHome = parseFloat(formData.distanceFromHome) || 0; const distLast = parseFloat(formData.distanceFromLastTxn) || 0; const creditLimit = parseFloat(formData.creditLimit) || 1; const currentBalance = parseFloat(formData.currentBalance) || 0; const accountAge = parseFloat(formData.accountAge) || 0; const utilization = currentBalance / creditLimit; const highRiskCategories = ['crypto', 'online_retail', 'travel']; const categoryRisk = highRiskCategories.includes(formData.merchantCategory) ? 0.7 : 0.2; const contributions = [ { feature: 'Transaction Amount', contribution: Math.min(0.95, (amount / 10000) * 0.9), direction: 'positive', value: `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2 })}` }, { feature: 'Credit Utilization', contribution: utilization > 0.8 ? 0.75 : utilization * 0.7, direction: utilization > 0.5 ? 'positive' : 'negative', value: `${(utilization * 100).toFixed(0)}%` }, { feature: 'Merchant Category', contribution: categoryRisk, direction: categoryRisk > 0.5 ? 'positive' : 'negative', value: formData.merchantCategory.replace('_', ' ') }, { feature: 'Account Age', contribution: accountAge < 12 ? 0.55 : 0.15, direction: accountAge < 12 ? 'positive' : 'negative', value: `${accountAge} mo` }, { feature: 'Distance from Home', contribution: Math.min(0.8, distHome / 500), direction: distHome > 50 ? 'positive' : 'negative', value: `${distHome.toFixed(1)} km` }, { feature: 'Distance from Last Txn', contribution: Math.min(0.65, distLast / 400), direction: distLast > 30 ? 'positive' : 'negative', value: `${distLast.toFixed(1)} km` }, { feature: 'Address Match', contribution: formData.addressMatch === 'no' ? 0.6 : 0.1, direction: formData.addressMatch === 'no' ? 'positive' : 'negative', value: formData.addressMatch === 'yes' ? 'Matched' : 'Mismatch' }, { feature: 'Country Match', contribution: formData.countryMatch === 'no' ? 0.55 : 0.08, direction: formData.countryMatch === 'no' ? 'positive' : 'negative', value: formData.countryMatch === 'yes' ? 'Same' : 'Cross-border' }, { feature: 'Email Domain', contribution: ['protonmail.com', 'temp.com', 'guerrillamail.com'].some(d => (formData.emailDomain || '').includes(d)) ? 0.44 : 0.12, direction: ['protonmail.com', 'temp.com'].some(d => (formData.emailDomain || '').includes(d)) ? 'positive' : 'negative', value: formData.emailDomain || '—' }, { feature: 'Card Type', contribution: formData.cardType === 'debit' ? 0.21 : 0.38, direction: formData.cardType === 'credit' ? 'positive' : 'negative', value: formData.cardType } ]; return contributions.sort((a, b) => b.contribution - a.contribution); } function computeRiskLevelFromProb(prob) { if (prob >= 0.7) return 'critical'; if (prob >= 0.5) return 'high'; if (prob >= 0.3) return 'medium'; return 'low'; } function generateTxnId() { return 'TXN-' + Date.now().toString(36).toUpperCase() + '-' + Math.floor(Math.random() * 9000 + 1000); } // ------------------------------------------------------- // GAUGE ANIMATION // ------------------------------------------------------- const GAUGE_CIRCUMFERENCE = 251.2; // half circle circumference ≈ π * r = π * 80 function setGauge(prob) { const fill = document.getElementById('gaugeFill'); const needleLine = document.getElementById('needleLine'); const needleOuter = document.getElementById('needleCircleOuter'); const scoreText = document.getElementById('gaugeScoreText'); const riskLabel = document.getElementById('gaugeRiskLabel'); const color = prob >= 0.7 ? '#ef4444' : prob >= 0.5 ? '#f97316' : prob >= 0.3 ? '#f59e0b' : '#22c55e'; const offset = GAUGE_CIRCUMFERENCE * (1 - prob); fill.style.strokeDashoffset = offset; // Needle position: angle from 0 (left=0%) to π (right=100%) over half-circle const angle = Math.PI * prob; // 0 = left, π = right const needleX = 110 + 72 * Math.cos(Math.PI - angle); const needleY = 110 - 72 * Math.sin(Math.PI - angle); needleLine.setAttribute('x2', needleX); needleLine.setAttribute('y2', needleY); needleLine.setAttribute('stroke', color); needleLine.style.filter = `drop-shadow(0 0 4px ${color})`; needleOuter.setAttribute('fill', color); // Animate score counter const startTime = performance.now(); const duration = 1400; function tick(now) { const t = Math.min((now - startTime) / duration, 1); const eased = 1 - Math.pow(1 - t, 3); // ease-out cubic const current = eased * prob; scoreText.textContent = (current * 100).toFixed(1); scoreText.style.color = color; if (t < 1) requestAnimationFrame(tick); } requestAnimationFrame(tick); // Risk label const labels = { low: 'LOW RISK', medium: 'MEDIUM RISK', high: 'HIGH RISK', critical: 'CRITICAL RISK' }; const rl = computeRiskLevelFromProb(prob); riskLabel.textContent = labels[rl]; riskLabel.style.color = color; // Zone bars updateZoneBars(prob); } function updateZoneBars(prob) { const zones = [ { el: document.querySelector('[data-zone="safe"]'), active: prob < 0.3, color: '#22c55e' }, { el: document.querySelector('[data-zone="review"]'), active: prob >= 0.3 && prob < 0.5, color: '#f59e0b' }, { el: document.querySelector('[data-zone="high"]'), active: prob >= 0.5 && prob < 0.7, color: '#f97316' }, { el: document.querySelector('[data-zone="fraud"]'), active: prob >= 0.7, color: '#ef4444' } ]; zones.forEach(({ el, active, color }) => { if (!el) return; el.innerHTML = `
${el.dataset.label} `; el.style.background = active ? `${color}18` : 'transparent'; el.style.borderColor = active ? `${color}40` : 'transparent'; }); } // ------------------------------------------------------- // RENDER RESULT SCREEN // ------------------------------------------------------- function renderResultScreen(result) { const prob = result.fraudProbability; const level = result.riskLevel; const formData = result.formData || {}; // --- Top verdict badge --- const isFraud = prob >= 0.5; const isReview = prob >= 0.3 && prob < 0.5; const verdictBadge = document.getElementById('verdictTopBadge'); if (isFraud) { verdictBadge.textContent = '⚠ FRAUD FLAGGED'; verdictBadge.style.background = 'var(--fraud-red-muted)'; verdictBadge.style.borderColor = 'var(--fraud-red-border)'; verdictBadge.style.color = 'var(--fraud-red)'; } else if (isReview) { verdictBadge.textContent = '◎ REVIEW REQUIRED'; verdictBadge.style.background = 'var(--warn-amber-muted)'; verdictBadge.style.borderColor = 'var(--warn-amber-border)'; verdictBadge.style.color = 'var(--warn-amber)'; } else { verdictBadge.textContent = '✓ LEGITIMATE'; verdictBadge.style.background = 'var(--legit-green-muted)'; verdictBadge.style.borderColor = 'var(--legit-green-border)'; verdictBadge.style.color = 'var(--legit-green)'; } // Gradient divider color const divider = document.getElementById('resultDivider'); if (isFraud) { divider.style.background = 'linear-gradient(90deg, var(--fraud-red) 0%, var(--border) 40%, transparent 100%)'; } else if (isReview) { divider.style.background = 'linear-gradient(90deg, var(--warn-amber) 0%, var(--border) 40%, transparent 100%)'; } else { divider.style.background = 'linear-gradient(90deg, var(--legit-green) 0%, var(--border) 40%, transparent 100%)'; } // --- Transaction ID & Timestamp --- const now = new Date(); const dateStr = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')} at ${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}`; document.getElementById('resultTxnId').textContent = result.transactionId; document.getElementById('resultTimestamp').textContent = dateStr; document.getElementById('copyTxnIdText').textContent = result.transactionId; // --- Gauge --- setTimeout(() => setGauge(prob), 150); // --- Verdict Card --- const verdictCard = document.getElementById('verdictCard'); const verdictIcon = document.getElementById('verdictIcon'); const verdictIconBox = document.getElementById('verdictIconBox'); const verdictLabel = document.getElementById('verdictLabel'); const verdictSublabel = document.getElementById('verdictSublabel'); const verdictDesc = document.getElementById('verdictDescription'); if (isFraud) { verdictCard.className = 'verdict-card fraud animate-fade-in-up'; verdictIconBox.style.background = 'rgba(239, 68, 68, 0.2)'; verdictIconBox.style.borderColor = 'var(--fraud-red-border)'; verdictIcon.setAttribute('data-lucide', 'shield-off'); verdictLabel.textContent = 'FRAUDULENT'; verdictLabel.style.color = 'var(--fraud-red)'; verdictSublabel.textContent = 'Transaction flagged for fraud'; verdictDesc.textContent = 'This transaction has been flagged by the ML model as likely fraudulent. Immediate review and potential block recommended.'; } else if (isReview) { verdictCard.className = 'verdict-card review animate-fade-in-up'; verdictIconBox.style.background = 'rgba(245, 158, 11, 0.2)'; verdictIconBox.style.borderColor = 'var(--warn-amber-border)'; verdictIcon.setAttribute('data-lucide', 'alert-triangle'); verdictLabel.textContent = 'REVIEW REQUIRED'; verdictLabel.style.color = 'var(--warn-amber)'; verdictSublabel.textContent = 'Manual review recommended'; verdictDesc.textContent = 'Borderline risk score detected. Manual analyst review is recommended before approving or declining this transaction.'; } else { verdictCard.className = 'verdict-card legit animate-fade-in-up'; verdictIconBox.style.background = 'rgba(34, 197, 94, 0.2)'; verdictIconBox.style.borderColor = 'var(--legit-green-border)'; verdictIcon.setAttribute('data-lucide', 'check-circle'); verdictLabel.textContent = 'LEGITIMATE'; verdictLabel.style.color = 'var(--legit-green)'; verdictSublabel.textContent = 'Transaction appears genuine'; verdictDesc.textContent = 'The ML model indicates this transaction is within normal parameters. Low fraud risk detected.'; } // --- Confidence Analysis --- const confidence = isFraud ? Math.min(0.99, prob + 0.08) : Math.min(0.99, 1 - prob + 0.05); const ciLow = Math.max(0, prob - 0.06); const ciHigh = Math.min(1, prob + 0.06); document.getElementById('confidenceText').textContent = `${(confidence * 100).toFixed(1)}%`; document.getElementById('confidenceText').style.color = 'var(--foreground)'; setTimeout(() => { document.getElementById('confidenceBar').style.width = `${confidence * 100}%`; }, 300); document.getElementById('ciLow').textContent = `${(ciLow * 100).toFixed(1)}%`; document.getElementById('ciMid').textContent = `${(prob * 100).toFixed(1)}%`; document.getElementById('ciHigh').textContent = `${(ciHigh * 100).toFixed(1)}%`; // --- Feature Contributions --- const contributions = result.featureContributions || []; const maxContrib = Math.max(...contributions.map(c => c.contribution)); const list = document.getElementById('contributionsList'); list.innerHTML = ''; contributions.forEach((c, i) => { const isPositive = c.direction === 'positive'; const color = isPositive ? 'var(--fraud-red)' : 'var(--legit-green)'; const barWidth = maxContrib > 0 ? (c.contribution / maxContrib) * 100 : 0; const isTop = i === 0; const row = document.createElement('div'); row.className = 'contribution-row'; row.style.animationDelay = `${0.2 + 0.07 * i}s`; row.innerHTML = `
${isTop ? 'TOP' : ''} ${c.feature}
${c.value} ${isPositive ? '+' : '-'}${(c.contribution * 100).toFixed(0)}%
`; list.appendChild(row); }); // Animate bars after small delay setTimeout(() => { list.querySelectorAll('.progress-fill').forEach(fill => { fill.style.width = fill.dataset.width + '%'; }); }, 200); // --- Transaction Summary --- const creditLimit = parseFloat(formData.creditLimit) || 1; const currentBalance = parseFloat(formData.currentBalance) || 0; const utilization = ((currentBalance / creditLimit) * 100).toFixed(0); const txnAmount = parseFloat(formData.amount) || 0; const summaryFields = [ { label: 'Amount', value: `₹${txnAmount.toLocaleString('en-IN', { minimumFractionDigits: 2 })}`, mono: true }, { label: 'Type', value: formData.transactionType || '—', mono: false }, { label: 'Merchant', value: formData.merchantName || '—', mono: false }, { label: 'Category', value: (formData.merchantCategory || '—').replace('_', ' '), mono: false }, { label: 'Product CD', value: formData.productCD || '—', mono: true }, { label: 'Card type', value: `${formData.cardCategory || ''} ${formData.cardType || ''}`.trim(), mono: false }, { label: 'Acct age', value: `${formData.accountAge || '—'} mo`, mono: true }, { label: 'Credit limit', value: `₹${parseFloat(formData.creditLimit || 0).toLocaleString('en-IN')}`, mono: true }, { label: 'Utilization', value: `${utilization}%`, mono: true, highlight: parseInt(utilization) > 80 }, { label: 'Email domain', value: formData.emailDomain || '—', mono: false } ]; const txnList = document.getElementById('txnSummaryList'); txnList.innerHTML = ''; summaryFields.forEach(f => { const row = document.createElement('div'); row.className = 'txn-summary-row' + (f.highlight ? ' highlight' : ''); row.innerHTML = ` ${f.label} ${f.value} `; txnList.appendChild(row); }); // --- Analyst Actions (reset state) --- resetAnalystActions(level); // Re-run lucide icons if (window.lucide) lucide.createIcons(); } function resetAnalystActions(riskLevel) { const panel = document.getElementById('analystActionsPanel'); const isHighRisk = riskLevel === 'critical' || riskLevel === 'high'; panel.innerHTML = `
`; if (window.lucide) lucide.createIcons(); document.getElementById('btnBlockTransaction')?.addEventListener('click', async () => { if (!currentResult) return; const btn = document.getElementById('btnBlockTransaction'); btn.disabled = true; btn.innerHTML = ` Blocking...`; if (window.lucide) lucide.createIcons(); await delay(900); showActionResult('blocked', currentResult.transactionId); }); document.getElementById('btnApproveTransaction')?.addEventListener('click', async () => { if (!currentResult) return; const btn = document.getElementById('btnApproveTransaction'); btn.disabled = true; btn.innerHTML = ` Approving...`; if (window.lucide) lucide.createIcons(); await delay(900); showActionResult('approved', currentResult.transactionId); }); document.getElementById('btnFlagEscalation')?.addEventListener('click', () => { showToast('Transaction flagged for escalation', 'info', 3000); }); } function showActionResult(action, txnId) { const panel = document.getElementById('analystActionsPanel'); const isBlocked = action === 'blocked'; panel.innerHTML = `

${isBlocked ? 'Transaction Blocked' : 'Transaction Approved'}

Action recorded at ${new Date().toLocaleTimeString('en-US', { hour12: false })}

`; showToast( isBlocked ? `Transaction ${txnId} has been blocked` : `Transaction ${txnId} approved`, isBlocked ? 'error' : 'success', 4000 ); } function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // ------------------------------------------------------- // FORM SUBMIT // ------------------------------------------------------- async function handleFormSubmit(e) { e.preventDefault(); const form = document.getElementById('analyzerForm'); const formData = new FormData(form); const data = Object.fromEntries(formData.entries()); // Basic validation let hasError = false; const required = ['amount', 'merchantName', 'accountAge', 'creditLimit', 'currentBalance']; required.forEach(field => { const errEl = document.getElementById(`error-${field}`); const val = data[field]; if (!val || val.toString().trim() === '') { if (errEl) { errEl.textContent = 'This field is required'; errEl.classList.remove('hidden'); } hasError = true; } else { if (errEl) errEl.classList.add('hidden'); } }); if (hasError) { showToast('Please fill in all required fields', 'error'); return; } // Show loading showScreen('loading'); document.getElementById('btnSubmit').disabled = true; try { // Call the Gradio backend via Gradio Client const { client } = await import("https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js"); const app = await client(window.location.origin); const apiResponse = await app.predict("/predict", [JSON.stringify(data)]); const serverResult = JSON.parse(apiResponse.data[0]); const mlProb = serverResult.fraud_probability ?? 0.5; // Compute feature contributions client-side (matching original behaviour) const contributions = computeFeatureContributions(data); const riskLevel = computeRiskLevelFromProb(mlProb); const txnId = generateTxnId(); const result = { fraudProbability: parseFloat(mlProb.toFixed(4)), riskLevel, transactionId: txnId, featureContributions: contributions, formData: data }; // Persist to sessionStorage try { sessionStorage.setItem('fraudPredictionResult', JSON.stringify(result)); } catch (ex) {} currentResult = result; showToast('Analysis complete — reviewing fraud verdict', 'success', 2500); showScreen('result'); renderResultScreen(result); } catch (err) { console.error('API error:', err); // Fallback: use client-side computation only const contributions = computeFeatureContributions(data); const amount = parseFloat(data.amount) || 0; let baseProb = Math.min(0.95, amount / 12000); if (data.addressMatch === 'no') baseProb += 0.15; if (data.countryMatch === 'no') baseProb += 0.12; if (['crypto', 'online_retail'].includes(data.merchantCategory)) baseProb += 0.2; if ((parseFloat(data.currentBalance) / (parseFloat(data.creditLimit) || 1)) > 0.85) baseProb += 0.1; baseProb = Math.min(0.99, baseProb); const riskLevel = computeRiskLevelFromProb(baseProb); const txnId = generateTxnId(); const result = { fraudProbability: parseFloat(baseProb.toFixed(4)), riskLevel, transactionId: txnId, featureContributions: contributions, formData: data }; try { sessionStorage.setItem('fraudPredictionResult', JSON.stringify(result)); } catch (ex) {} currentResult = result; showToast('Analysis complete (offline mode)', 'info', 2500); showScreen('result'); renderResultScreen(result); } finally { document.getElementById('btnSubmit').disabled = false; } } // ------------------------------------------------------- // COPY TXN ID // ------------------------------------------------------- function initCopyTxnId() { document.getElementById('btnCopyTxnId')?.addEventListener('click', () => { if (!currentResult) return; navigator.clipboard.writeText(currentResult.transactionId).then(() => { const btn = document.getElementById('btnCopyTxnId'); const originalHtml = btn.innerHTML; btn.innerHTML = ` Copied!`; if (window.lucide) lucide.createIcons(); showToast('Transaction ID copied', 'success', 2000); setTimeout(() => { btn.innerHTML = originalHtml; if (window.lucide) lucide.createIcons(); }, 2000); }).catch(() => showToast('Could not copy to clipboard', 'error')); }); } // ------------------------------------------------------- // INIT APP // ------------------------------------------------------- function initApp() { // Collapsible initCollapsible(); // Live risk preview on amount change document.getElementById('amount')?.addEventListener('input', e => { updateRiskPreview(computeRiskLevel(e.target.value)); }); // Form submit document.getElementById('analyzerForm')?.addEventListener('submit', handleFormSubmit); // Clear form document.getElementById('btnClearForm')?.addEventListener('click', () => { document.getElementById('analyzerForm').reset(); updateRiskPreview(null); document.querySelectorAll('.input-error').forEach(el => el.classList.add('hidden')); showToast('Form cleared', 'info', 1500); }); // Nav: Analyze Transaction document.getElementById('navAnalyzeBtn')?.addEventListener('click', e => { e.preventDefault(); showScreen('form'); closeMobileMenu(); }); // Nav: Last Result document.getElementById('navResultBtn')?.addEventListener('click', e => { e.preventDefault(); loadLastResult(); closeMobileMenu(); }); // Mobile nav links document.getElementById('mobileNavAnalyze')?.addEventListener('click', e => { e.preventDefault(); showScreen('form'); closeMobileMenu(); }); document.getElementById('mobileNavResult')?.addEventListener('click', e => { e.preventDefault(); loadLastResult(); closeMobileMenu(); }); // Mobile menu toggle document.getElementById('mobileMenuBtn')?.addEventListener('click', toggleMobileMenu); // Back to form from result document.getElementById('btnNewAnalysis')?.addEventListener('click', () => { showScreen('form'); document.getElementById('navAnalyzeBtn').classList.add('active'); document.getElementById('navResultBtn').classList.remove('active'); }); // Analyze another (footer of result) document.getElementById('btnAnalyzeAnother')?.addEventListener('click', () => { showScreen('form'); document.getElementById('navAnalyzeBtn').classList.add('active'); document.getElementById('navResultBtn').classList.remove('active'); }); // Export Report document.getElementById('btnExportReport')?.addEventListener('click', () => { if (!currentResult) return; const json = JSON.stringify(currentResult, null, 2); const blob = new Blob([json], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${currentResult.transactionId}_fraud_report.json`; a.click(); URL.revokeObjectURL(url); showToast('Report exported as JSON', 'success'); }); // Copy Txn ID initCopyTxnId(); // Logo link → form document.getElementById('logoLink')?.addEventListener('click', e => { e.preventDefault(); showScreen('form'); document.getElementById('navAnalyzeBtn').classList.add('active'); document.getElementById('navResultBtn').classList.remove('active'); }); // Try to restore session try { const saved = sessionStorage.getItem('fraudPredictionResult'); if (saved) { const parsed = JSON.parse(saved); currentResult = parsed; } } catch (ex) {} } // ------------------------------------------------------- // LOAD LAST RESULT (from sessionStorage or demo) // ------------------------------------------------------- function loadLastResult() { let result = currentResult; if (!result) { try { const saved = sessionStorage.getItem('fraudPredictionResult'); if (saved) result = JSON.parse(saved); } catch (ex) {} } if (!result) { // Demo data (matches original site's demo) result = { fraudProbability: 0.8312, riskLevel: 'critical', transactionId: 'TXN-M3X7K2-8841', featureContributions: [ { feature: 'Transaction Amount', contribution: 0.82, direction: 'positive', value: '₹3,247.00' }, { feature: 'Credit Utilization', contribution: 0.74, direction: 'positive', value: '91%' }, { feature: 'Merchant Category', contribution: 0.63, direction: 'positive', value: 'crypto' }, { feature: 'Account Age', contribution: 0.51, direction: 'positive', value: '8 mo' }, { feature: 'Email Domain', contribution: 0.44, direction: 'positive', value: 'protonmail.com' }, { feature: 'Card Type', contribution: 0.21, direction: 'negative', value: 'credit' } ], formData: { amount: '3247.00', transactionType: 'purchase', merchantCategory: 'crypto', merchantName: 'CoinBase Pro', productCD: 'R', cardType: 'credit', cardCategory: 'visa', cardIssuerBank: '185', accountAge: '8', creditLimit: '5000', currentBalance: '4550', previousBalance: '420', emailDomain: 'protonmail.com', addressMatch: 'no', distanceFromHome: '312.4', distanceFromLastTxn: '287.1', countryMatch: 'no' } }; } currentResult = result; showScreen('result'); renderResultScreen(result); } // ------------------------------------------------------- // MOBILE MENU // ------------------------------------------------------- function toggleMobileMenu() { const nav = document.getElementById('mobileNav'); const open = document.getElementById('menuIconOpen'); const close = document.getElementById('menuIconClose'); if (nav.classList.contains('hidden')) { nav.classList.remove('hidden'); open.style.display = 'none'; close.style.display = 'block'; } else { closeMobileMenu(); } } function closeMobileMenu() { const nav = document.getElementById('mobileNav'); const open = document.getElementById('menuIconOpen'); const close = document.getElementById('menuIconClose'); nav.classList.add('hidden'); open.style.display = 'block'; close.style.display = 'none'; }