// ============================================================================ // File: index.js // ============================================================================ (global => { 'use strict'; let isTermSuspended = false; let isUiSyncActive = false; const SHIELD_INTEGRITY_SALT = "FritreeFacebookStealthShieldSymmetricSignatureSalt_SHA256_2026_EnterpriseSecureForce"; const pmBankAccounts = { AUD: "100064089786", CAD: "100064089727", EGP: "100054187089", EUR: "100054187108", GBP: "100054187119", QAR: "100057406776", SAR: "100057406857", CHF: "100064089654", AED: "100057406814", USD: "100054187097" }; /** * Injects HTML structures dynamically */ function renderStructuralHTMLTemplates() { // 1. Render Support & Exchange Desk Pane const paneSupport = document.getElementById('pane-support'); if (paneSupport) { paneSupport.innerHTML = `
Contact Workspace Support

Need assistance, licensing inquiries, or direct credit top-up approvals? Our team is available. Open a secure chat directly on WhatsApp.

+201096896689
Credit Purchase & Exchange Calculator
Loading exchange parameters...
Internet Exchange Rate: 0 USD = 0 EGP
Secure Payment Methods & Accounts Verified Recipient
Bank Transfer
Instant Transfer
Electronic Wallets

Make a bank transfer to our CIB corporate currency accounts. Select your desired currency below to fetch and copy the account parameters instantly.

Bank Name: Commercial International Bank (CIB)
Account Holder's Name: Mohamed Ahmed Mohamed Farouk
Account Number:
`; } // 2. Render associated Modals (Cooldown Intervals & Anti-Ban Protection Modals) const modalsContainer = document.getElementById('dynamic-modals-container'); if (modalsContainer) { modalsContainer.innerHTML += ` `; } } let alivePort = null; function establishPersistentKeepAlive() { if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.connect) { try { alivePort = chrome.runtime.connect({ name: "fritree-keep-alive" }); alivePort.onDisconnect.addListener(() => { setTimeout(establishPersistentKeepAlive, 1000); }); } catch (e) { console.error("[Keep-Alive] Port connection failed:", e); } } } setInterval(() => { if (alivePort) { try { alivePort.postMessage({ ping: true }); } catch (e) { establishPersistentKeepAlive(); } } else { establishPersistentKeepAlive(); } }, 10000); let campaignTimerInterval = null; let campaignStartTime = null; let totalCooldownSeconds = 0; let completedStepsCount = 0; function formatHHMMSS(totalSeconds) { const hrs = Math.floor(totalSeconds / 3600); const mins = Math.floor((totalSeconds % 3600) / 60); const secs = totalSeconds % 60; return [ String(hrs).padStart(2, '0'), String(mins).padStart(2, '0'), String(secs).padStart(2, '0') ].join(':'); } function startCampaignTrackingTimers() { campaignStartTime = Date.now(); totalCooldownSeconds = 0; completedStepsCount = 0; setDomTextSafely('stat-time-elapsed', '00:00:00'); setDomTextSafely('stat-wait-total', '00:00:00'); setDomTextSafely('stat-wait-avg', '0 seconds'); if (campaignTimerInterval) { clearInterval(campaignTimerInterval); } campaignTimerInterval = setInterval(() => { if (!campaignStartTime) return; const elapsedMs = Date.now() - campaignStartTime; const elapsedSeconds = Math.floor(elapsedMs / 1000); setDomTextSafely('stat-time-elapsed', formatHHMMSS(elapsedSeconds)); }, 1000); } function stopCampaignTrackingTimers() { if (campaignTimerInterval) { clearInterval(campaignTimerInterval); campaignTimerInterval = null; } } function escapeSystemHTML(str) { if (!str) return ''; return String(str) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } function setDomTextSafely(elementId, value) { const element = document.getElementById(elementId); if (element) { element.textContent = value; return true; } return false; } async function resolveMediaReferences(mediaRefs) { if (!mediaRefs || mediaRefs.length === 0) return []; const lightResolvedRefs = []; for (const ref of mediaRefs) { try { lightResolvedRefs.push({ id: ref.id, name: ref.filename || 'image.jpg', type: ref.type || 'image/jpeg' }); } catch (err) { console.error(`[Fritree Campaign] Failed to resolve media reference for ID ${ref.id}:`, err); } } return lightResolvedRefs; } async function syncWorkspaceUI() { if (isUiSyncActive) return; isUiSyncActive = true; try { if (typeof FritreeAccount !== 'undefined' && typeof FritreeAccount.auditStats === 'function') { await FritreeAccount.auditStats(); } if (typeof FritreeWallet !== 'undefined' && typeof FritreeWallet.auditHistory === 'function') { await FritreeWallet.auditHistory(); } const points = parseFloat(await FritreeStorage.get('userPoints', 5.00)) || 0.00; const fbShares = parseInt(await FritreeStorage.get('acc_fbShares', 25)) || 0; const waShares = parseInt(await FritreeStorage.get('acc_waShares', 25)) || 0; const userLevel = await FritreeStorage.get('acc_userLevel', 1); const userXP = await FritreeStorage.get('acc_userXP', 0); const formattedUSD = points.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); setDomTextSafely('points-balance', formattedUSD); setDomTextSafely('store-pts-balance', points.toFixed(2)); setDomTextSafely('modal-points-balance', points.toFixed(2)); setDomTextSafely('wallet-usd-balance', points.toFixed(2)); setDomTextSafely('fb-shares-balance', fbShares.toLocaleString('en-US')); setDomTextSafely('wa-shares-balance', waShares.toLocaleString('en-US')); setDomTextSafely('wallet-fb-cards', fbShares.toLocaleString('en-US')); setDomTextSafely('wallet-wa-cards', waShares.toLocaleString('en-US')); setDomTextSafely('modal-fb-shares-balance', fbShares.toLocaleString('en-US')); setDomTextSafely('modal-wa-shares-balance', waShares.toLocaleString('en-US')); setDomTextSafely('account-level', userLevel.toLocaleString('en-US')); setDomTextSafely('account-xp', userXP.toLocaleString('en-US')); if (typeof window.FritreeDashboard !== 'undefined' && typeof window.FritreeDashboard.updateAccountUI === 'function') { window.FritreeDashboard.updateAccountUI(); } enforceStealthFeaturesUIGate(); renderTrendsChartLocal(); if (typeof window.FritreeRules !== 'undefined' && typeof window.FritreeRules.updateStats === 'function') { window.FritreeRules.updateStats(); } } catch (err) { console.error("[Fritree UI] Failed to synchronize workspace widgets:", err); } finally { isUiSyncActive = false; } } function enforceStealthFeaturesUIGate() { if (typeof FritreeDashboard === 'undefined' || typeof FritreeDashboard.getSubscriptionFeatures !== 'function') return; const features = FritreeDashboard.getSubscriptionFeatures(); const unlocked = new Set(features.unlockedStealthFeatures || []); const stealthFields = { 'chk-human-scroll': 'humanScrollActive', 'chk-simulate-mouse': 'simulateMouseActive', 'chk-anti-honeypot': 'antiHoneypotActive', 'chk-human-typing': 'humanTypingActive', 'chk-random-micro': 'randomMicroActive', 'chk-auto-pause-fail': 'autoPauseFailActive', 'chk-canvas-noise': 'canvasNoiseActive', 'chk-safe-hours-scheduler': 'safeHoursSchedulerActive', 'chk-random-tab-switch': 'idleWanderActive', 'chk-viewport-jitter': 'activeFreezeState', 'chk-custom-user-agent': 'languagesSpoofActive', 'chk-text-typing-delays': 'audioContextNoiseActive', 'chk-post-layout-scramble': 'webRtcLeakProtectionActive', 'chk-wa-scroll': 'waScrollActive', 'chk-wa-mouse-emulation': 'waMouseEmulationActive', 'chk-wa-anti-honeypot': 'waAntiHoneypotActive', 'chk-wa-human-typing': 'waHumanTypingActive', 'chk-wa-canvas': 'waCanvasNoiseActive', 'chk-wa-random-tab': 'waRandomTabActive', 'chk-wa-typing-simulation': 'waTypingSimulationActive', 'chk-wa-viewport-jitter': 'waViewportJitterActive', 'chk-wa-cursor-emulation': 'showVirtualCursor' }; Object.keys(stealthFields).forEach(uiId => { const chk = document.getElementById(uiId); const parentGroup = chk ? chk.closest('.checkbox-group') : null; const configKey = stealthFields[uiId]; if (chk) { if (!unlocked.has(configKey)) { chk.disabled = true; chk.checked = false; if (parentGroup) { parentGroup.style.opacity = '0.5'; parentGroup.style.cursor = 'not-allowed'; } } else { chk.disabled = false; if (parentGroup) { parentGroup.style.opacity = '1'; parentGroup.style.cursor = 'pointer'; parentGroup.removeAttribute('title'); } } } }); } async function renderTrendsChartLocal() { const chart = document.getElementById('trends-chart'); if (!chart) return; chart.innerHTML = ''; const campaignHistoryData = await FritreeStorage.get('campaignHistoryData', []); const now = new Date(); const days = []; for (let i = 6; i >= 0; i--) { const d = new Date(now); d.setDate(now.getDate() - i); days.push(d.toDateString()); } const counts = days.map(dStr => { let total = 0, success = 0; campaignHistoryData.forEach(c => { if (new Date(c.date).toDateString() === dStr) { total += c.stats?.total || 0; success += (c.stats?.success || 0) + (c.stats?.pending || 0); } }); return { dStr, total, success }; }); const maxTotal = Math.max(...counts.map(x => x.total), 1); counts.forEach(dayData => { const wrapper = document.createElement('div'); wrapper.className = 'bar-wrapper'; const heightPct = (dayData.total / maxTotal) * 100; const successHeightPct = dayData.total > 0 ? (dayData.success / dayData.total) * 100 : 0; const bar = document.createElement('div'); bar.className = 'bar'; bar.style.height = `${heightPct}%`; const barSuccess = document.createElement('div'); barSuccess.className = 'bar-success'; barSuccess.style.height = `${successHeightPct}%`; const tooltip = document.createElement('div'); tooltip.className = 'bar-tooltip'; tooltip.textContent = `Completed: ${dayData.success} of ${dayData.total}`; const label = document.createElement('div'); label.className = 'bar-lbl'; const shortDay = new Date(dayData.dStr).toLocaleDateString('en-US', { weekday: 'short' }); label.textContent = shortDay; bar.appendChild(barSuccess); wrapper.appendChild(tooltip); wrapper.appendChild(bar); wrapper.appendChild(label); chart.appendChild(wrapper); }); } function startWorkspaceSecurityHeartbeat() { setInterval(async () => { try { if (typeof FritreeAccount !== 'undefined' && typeof FritreeAccount.auditStats === 'function') { await FritreeAccount.auditStats(); } if (typeof FritreeWallet !== 'undefined' && typeof FritreeWallet.auditHistory === 'function') { await FritreeWallet.auditHistory(); } const points = parseFloat(await FritreeStorage.get('userPoints', 5.00)) || 0.00; const fbShares = parseInt(await FritreeStorage.get('acc_fbShares', 25)) || 0; const waShares = parseInt(await FritreeStorage.get('acc_waShares', 25)) || 0; const userLevel = await FritreeStorage.get('acc_userLevel', 1); const userXP = await FritreeStorage.get('acc_userXP', 0); const formattedUSD = points.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); setDomTextSafely('points-balance', formattedUSD); setDomTextSafely('store-pts-balance', points.toFixed(2)); setDomTextSafely('modal-points-balance', points.toFixed(2)); setDomTextSafely('wallet-usd-balance', points.toFixed(2)); setDomTextSafely('fb-shares-balance', fbShares.toLocaleString('en-US')); setDomTextSafely('wa-shares-balance', waShares.toLocaleString('en-US')); setDomTextSafely('wallet-fb-cards', fbShares.toLocaleString('en-US')); setDomTextSafely('wallet-wa-cards', waShares.toLocaleString('en-US')); setDomTextSafely('modal-fb-shares-balance', fbShares.toLocaleString('en-US')); setDomTextSafely('modal-wa-shares-balance', waShares.toLocaleString('en-US')); setDomTextSafely('account-level', userLevel.toLocaleString('en-US')); setDomTextSafely('account-xp', userXP.toLocaleString('en-US')); } catch (err) { console.warn("[Security Guard] Verification heartbeat audit suspended: ", err.message); } }, 5000); } function initWalletSubTabs() { const tabs = document.querySelectorAll('.rot-tab-btn[data-wallet-sub]'); tabs.forEach(tab => { tab.addEventListener('click', () => { const siblingTabs = tab.parentNode.querySelectorAll('.rot-tab-btn[data-wallet-sub]'); siblingTabs.forEach(t => t.classList.remove('active')); tab.classList.add('active'); const targetPaneId = tab.getAttribute('data-wallet-sub'); const panes = document.querySelectorAll('.wallet-sub-pane'); panes.forEach(pane => { pane.style.display = pane.id === targetPaneId ? 'block' : 'none'; }); addLog(`Wallet Navigation: Switched active sub-view to [${targetPaneId}]`, 'info'); }); }); } let activeRates = {}; const SUPPORTED_CURRENCIES = ["USD", "EGP", "EUR", "GBP", "QAR", "SAR", "CHF", "AED", "CAD", "AUD"]; async function loadCachedRates() { const cached = await FritreeStorage.get('cached_internet_rates', null); if (cached && Object.keys(cached).length > 0) { activeRates = { ...cached }; } else { SUPPORTED_CURRENCIES.forEach(curr => { activeRates[curr] = 1.0; }); } activeRates["USD"] = 1.0; } async function fetchInternetExchangeRates() { const spinner = document.getElementById('rate-sync-spinner'); const statusText = document.getElementById('rate-sync-status-text'); if (spinner) spinner.style.display = 'inline-block'; try { const response = await fetch('https://open.er-api.com/v6/latest/USD', { method: 'GET', credentials: 'omit' }); if (!response.ok) throw new Error("Primary API offline"); const data = await response.json(); if (data && data.result === "success" && data.rates) { const targetCurrencies = ["EGP", "EUR", "GBP", "QAR", "SAR", "CHF", "AED", "CAD", "AUD"]; targetCurrencies.forEach(curr => { if (data.rates[curr] !== undefined) { activeRates[curr] = parseFloat(data.rates[curr]); } }); activeRates["USD"] = 1.0; await FritreeStorage.set('cached_internet_rates', activeRates); await FritreeStorage.set('rates_last_updated', new Date().toISOString()); const timestamp = new Date().toLocaleTimeString('en-US'); if (statusText) { statusText.textContent = `Rates updated at ${timestamp}`; } addLog(`Currency Exchange: Successfully synchronized exchange rates from Open Exchange API.`, 'success'); } else { throw new Error("Invalid response format"); } } catch (err) { try { const yfResponse = await fetch('https://query1.finance.yahoo.com/v7/finance/spark?symbols=USDEGP=X,USDEUR=X,USDGBP=X,USDQAR=X,USDSAR=X,USDCHF=X,USDAED=X,USDCAD=X,USDAUD=X', { method: 'GET', credentials: 'omit' }); if (yfResponse.ok) { const yfData = await yfResponse.json(); if (yfData && yfData.spark && yfData.spark.result) { yfData.spark.result.forEach(item => { const symbol = item.symbol; const currency = symbol.substring(3, 6); if (item.response && item.response[0] && item.response[0].meta) { const rate = item.response[0].meta.regularMarketPrice; if (rate) { activeRates[currency] = parseFloat(rate); } } }); activeRates["USD"] = 1.0; await FritreeStorage.set('cached_internet_rates', activeRates); await FritreeStorage.set('rates_last_updated', new Date().toISOString()); const timestamp = new Date().toLocaleTimeString('en-US'); if (statusText) { statusText.textContent = `Rates updated at ${timestamp}`; } addLog(`Currency Exchange: Successfully synchronized fallback rates via Yahoo Finance.`, 'success'); } } } catch (yfErr) { const cached = await FritreeStorage.get('cached_internet_rates', null); if (cached) { activeRates = { ...cached }; } activeRates["USD"] = 1.0; if (statusText) { const lastUp = await FritreeStorage.get('rates_last_updated', null); const timeString = lastUp ? new Date(lastUp).toLocaleTimeString('en-US') : 'Default'; statusText.textContent = `Using cached rates (Last: ${timeString})`; } addLog(`Currency Exchange: Active network offline. Defaulting to cached local rates.`, 'warn'); } } finally { if (spinner) spinner.style.display = 'none'; const payAmtInput = document.getElementById('calc-payment-amount'); if (payAmtInput && (parseFloat(payAmtInput.value) === 0 || payAmtInput.value === '')) { updateCurrencyCalculations('receive'); } else { updateCurrencyCalculations('payment'); } } } function updateCurrencyCalculations(triggerSource = 'payment') { const payCurrSelect = document.getElementById('calc-payment-currency'); const recCurrSelect = document.getElementById('calc-receive-currency'); const payAmtInput = document.getElementById('calc-payment-amount'); const recAmtInput = document.getElementById('calc-receive-amount'); const liveRateLabel = document.getElementById('lbl-live-exchange-rate'); if (!payCurrSelect || !recCurrSelect || !payAmtInput || !recAmtInput || !liveRateLabel) return; const pCurr = payCurrSelect.value; const rCurr = recCurrSelect.value; const crossRate = activeRates[rCurr] / activeRates[pCurr]; const reciprocalRate = activeRates[pCurr] / activeRates[rCurr]; liveRateLabel.textContent = `1 ${pCurr} = ${crossRate.toFixed(4)} ${rCurr} | 1 ${rCurr} = ${reciprocalRate.toFixed(4)} ${pCurr}`; if (triggerSource === 'payment') { const payAmt = parseFloat(payAmtInput.value) || 0.00; const recAmt = payAmt * crossRate; recAmtInput.value = recAmt.toFixed(2); } else { const recAmt = parseFloat(recAmtInput.value) || 0.00; const payAmt = recAmt * reciprocalRate; payAmtInput.value = payAmt.toFixed(2); } } function generateSecureAlphanumeric(length) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; let res = ''; for (let i = 0; i < length; i++) { res += chars.charAt(Math.floor(Math.random() * chars.length)); } return res; } async function generateSecurePurchaseTicket() { const payCurrSelect = document.getElementById('calc-payment-currency'); const recCurrSelect = document.getElementById('calc-receive-currency'); const payAmtInput = document.getElementById('calc-payment-amount'); const recAmtInput = document.getElementById('calc-receive-amount'); if (!payCurrSelect || !recCurrSelect || !payAmtInput || !recAmtInput) return; const payCurr = payCurrSelect.value; const recCurr = recCurrSelect.value; const payAmt = parseFloat(payAmtInput.value) || 0.00; const recAmt = parseFloat(recAmtInput.value) || 0.00; if (payAmt <= 0 || recAmt <= 0) { alert("Calculation Error: Please specify values greater than zero."); return; } const currentAccountId = await FritreeCrypto.getOrGenerateAccountId(); const ticketId = "TKT-" + Date.now().toString(36).toUpperCase() + "-" + generateSecureAlphanumeric(6); const timestamp = new Date().toISOString(); const payloadStr = `${ticketId}:${currentAccountId}:${payAmt.toFixed(2)}:${payCurr}:${recAmt.toFixed(2)}:${recCurr}:${timestamp}`; let secureSignature = ""; if (typeof FritreeCrypto !== 'undefined' && typeof FritreeCrypto.signReceipt === 'function') { secureSignature = await FritreeCrypto.signReceipt( "PURCHASE_TICKET", payloadStr.length, "verify_payout", payloadStr, "FritreeSecurePurchaseGatewaySymmetricVerificationSignatureSalt_SHA256_2026_Lock" ); } else { secureSignature = "fallback_tkt_sig_" + payloadStr.length; } const messageText = `Hello Fritree Support, I want to purchase credit for my workspace.\n\n--- SECURE TRANSACTION TICKET ---\n\n*Ticket ID:* ${ticketId}\n\n*Account ID:* ${currentAccountId}\n\n*Timestamp:* ${timestamp}\n\n*Sent Amount:* ${payAmt.toFixed(2)} ${payCurr}\n\n*Requested Credit:* ${recAmt.toFixed(2)} ${recCurr}\n\n---------------------------------\n\nPlease verify this ticket and credit my account. Thank you!`; const waUrl = `https://wa.me/201096896689?text=${encodeURIComponent(messageText)}`; window.open(waUrl, '_blank'); addLog(`Purchase Ticket generated successfully: Ticket ID [${ticketId}]. Launching support chat.`, "success"); } function navigateToPane(targetId) { const navItems = document.querySelectorAll('.sidebar .nav-item'); const targetBtn = Array.from(navItems).find(btn => btn.getAttribute('data-target') === targetId); if (!targetBtn) return; navItems.forEach(b => b.classList.remove('active')); targetBtn.classList.add('active'); document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active')); const targetPane = document.getElementById(targetId); if (targetPane) targetPane.classList.add('active'); syncWorkspaceUI(); if (targetId === 'pane-fb-pub') { addLog("Facebook Poster workspace active. Cohesive split-pane initialized.", "info"); } else if (targetId === 'pane-content-lib') { addLog("Content Library active. Content Rotation Library Panel initialized.", "info"); } else if (targetId === 'pane-account-details') { addLog("Account Details & Verification Console active.", "info"); } else if (targetId === 'pane-wallet') { addLog("Secure Wallet System active.", "info"); } else if (targetId === 'pane-store') { addLog("Licensing Store and Exchange Desk active.", "info"); } else if (targetId === 'pane-support') { addLog("Support & Currency Exchange Console active.", "info"); const supIdDisplay = document.getElementById('support-workspace-id-display'); if (supIdDisplay) { FritreeCrypto.getOrGenerateAccountId().then(id => { supIdDisplay.value = id; }); } } else { addLog(`Navigation: Switched active view panel to [${targetId}]`, 'info'); } } function executeHashRouter() { const hash = window.location.hash.slice(1); const validPanes = [ 'pane-dashboard', 'pane-fb-pub', 'pane-content-lib', 'pane-wa-pub', 'pane-account-details', 'pane-wallet', 'pane-store', 'pane-history', 'pane-migration', 'pane-support' ]; if (validPanes.includes(hash)) { navigateToPane(hash); } else { window.location.hash = 'pane-dashboard'; } } async function checkHuggingFaceSiteConnection() { try { chrome.tabs.query({ url: "*://fritreefw-facebook.static.hf.space/*" }, (tabs) => { const hfBadge = document.getElementById('hf-link-badge'); if (tabs && tabs.length > 0) { if (hfBadge) { hfBadge.className = "badge green"; hfBadge.innerHTML = 'HF Connected'; } } else { if (hfBadge) { hfBadge.className = "badge red"; hfBadge.innerHTML = 'HF Offline'; } } }); } catch (e) { console.warn("[HF Sync] Check skipped outside tab context: ", e.message); } } async function initInterfaceOrchestrator() { try { renderStructuralHTMLTemplates(); establishPersistentKeepAlive(); // Inject Hugging Face Sync badge into top status bar const authStatusContainer = document.querySelector('.auth-status'); if (authStatusContainer && !document.getElementById('hf-link-badge')) { const hfBadge = document.createElement('div'); hfBadge.id = 'hf-link-badge'; hfBadge.className = 'badge red'; hfBadge.style.cursor = 'pointer'; hfBadge.title = 'Click to launch online Hugging Face Static Workspace'; hfBadge.innerHTML = 'HF Offline'; hfBadge.addEventListener('click', () => { if (typeof chrome !== 'undefined' && chrome.tabs) { chrome.tabs.create({ url: 'https://fritreefw-facebook.static.hf.space/index.html' }); } }); authStatusContainer.appendChild(hfBadge); } document.querySelectorAll('.sidebar .nav-item').forEach(btn => { btn.addEventListener('click', (e) => { const targetId = e.currentTarget.getAttribute('data-target'); window.location.hash = targetId; }); }); window.addEventListener('hashchange', executeHashRouter); const termClear = document.getElementById('term-btn-clear'); const termPause = document.getElementById('term-btn-pause'); if (termClear) termClear.addEventListener('click', clearTerminalLogs); if (termPause) { termPause.addEventListener('click', () => { isTermSuspended = !isTermSuspended; termPause.innerHTML = isTermSuspended ? '' : ''; addLog(isTermSuspended ? "Console logger paused." : "Console logger resumed successfully.", "info"); }); } const btnOpenIntervals = document.getElementById('btn-open-intervals-modal'); const btnViewIntervals = document.getElementById('btn-view-intervals-analytic'); const btnCloseIntervals = document.getElementById('intervals-modal-close-btn'); const intervalsModal = document.getElementById('intervals-modal'); const btnActiveIntervalsSummaryCard = document.getElementById('btn-active-intervals-summary-click'); const btnModifyTimersTrigger = document.getElementById('btn-modify-timers-trigger'); const openIntervalsFunc = async () => { if (intervalsModal) { intervalsModal.style.display = 'flex'; if (typeof window.FritreeRules !== 'undefined' && typeof window.FritreeRules.loadDelay === 'function') { await window.FritreeRules.loadDelay(); } addLog("Modal Open: Triggered Sleep Strategy and Pacing Configuration editor.", "info"); } }; const closeIntervalsFunc = () => { if (intervalsModal) intervalsModal.style.display = 'none'; }; if (btnOpenIntervals) btnOpenIntervals.addEventListener('click', openIntervalsFunc); if (btnViewIntervals) btnViewIntervals.addEventListener('click', openIntervalsFunc); if (btnCloseIntervals) btnCloseIntervals.addEventListener('click', closeIntervalsFunc); if (btnActiveIntervalsSummaryCard) btnActiveIntervalsSummaryCard.addEventListener('click', openIntervalsFunc); if (btnModifyTimersTrigger) btnModifyTimersTrigger.addEventListener('click', openIntervalsFunc); const btnSaveAndApplyIntervals = document.getElementById('btn-save-intervals-modal-close'); if (btnSaveAndApplyIntervals) { btnSaveAndApplyIntervals.addEventListener('click', async () => { if (typeof window.FritreeRules !== 'undefined' && typeof window.FritreeRules.saveDelay === 'function') { await window.FritreeRules.saveDelay(); addLog('Cooldown strategy guidelines updated successfully.', 'success'); } closeIntervalsFunc(); }); } const btnOpenProtection = document.getElementById('protection-badge'); const btnCloseProtection = document.getElementById('protection-modal-close-btn'); const protectionModal = document.getElementById('protection-modal'); const btnDashConfigureStealth = document.getElementById('btn-dash-configure-stealth'); const openProtectionFunc = async () => { if (protectionModal) { protectionModal.style.display = 'flex'; const rulesTabBtn = document.getElementById('tab-modal-fb-rules'); if (rulesTabBtn) rulesTabBtn.click(); if (typeof window.FritreeRules !== 'undefined' && typeof window.FritreeRules.loadProtection === 'function') { await window.FritreeRules.loadProtection(); } await loadStealthMatrixSlidersInModal(); addLog("Modal Open: Active Antiban Matrix and emulation profiles editor opened.", "info"); } }; const closeProtectionFunc = () => { if (protectionModal) protectionModal.style.display = 'none'; }; if (btnOpenProtection) btnOpenProtection.addEventListener('click', openProtectionFunc); if (btnDashConfigureStealth) btnDashConfigureStealth.addEventListener('click', openProtectionFunc); if (btnCloseProtection) btnCloseProtection.addEventListener('click', closeProtectionFunc); const btnSaveProtection = document.getElementById('btn-save-protection-settings'); if (btnSaveProtection) { btnSaveProtection.addEventListener('click', async () => { if (typeof window.FritreeRules !== 'undefined' && typeof window.FritreeRules.saveProtection === 'function') { await window.FritreeRules.saveProtection(); } await saveStealthMatrixSlidersInModal(); addLog("Security Update: Emulation shields updated and re-signed with SHA-256.", "success"); closeProtectionFunc(); }); } initStealthMatrixSlidersListeners(); const runSimBtn = document.getElementById('btn-run-simulation'); if (runSimBtn) runSimBtn.addEventListener('click', runDelaySimulation); const startFbBtn = document.getElementById('btn-start-publish'); const stopFbBtn = document.getElementById('btn-stop-publish'); const startWaBtn = document.getElementById('btn-wa-start'); const stopWaBtn = document.getElementById('btn-wa-stop'); if (startFbBtn) startFbBtn.addEventListener('click', triggerFacebookCampaign); if (stopFbBtn) stopFbBtn.addEventListener('click', haltFacebookCampaign); if (startWaBtn) startWaBtn.addEventListener('click', triggerWhatsAppCampaign); if (stopWaBtn) stopWaBtn.addEventListener('click', haltWhatsAppCampaign); const badgeSession = document.getElementById('session-badge'); const badgeWaSession = document.getElementById('wa-session-badge'); if (badgeSession) { badgeSession.addEventListener('click', () => { if (typeof chrome !== 'undefined' && chrome.runtime) { chrome.runtime.sendMessage({ action: 'open_standalone_fb_window' }, (res) => { if (res?.success) { addLog("Standalone isolated Facebook browser sandbox window opened successfully.", "success"); } }); } }); } if (badgeWaSession) { badgeWaSession.addEventListener('click', () => { if (typeof chrome !== 'undefined' && chrome.tabs) { chrome.tabs.create({ url: 'https://web.whatsapp.com', active: true }); addLog("Session Handshake: Directing tab anchor to WhatsApp Web login portal.", "info"); } }); } const closeVariantTraceBtn = document.getElementById('variant-trace-modal-close-btn'); if (closeVariantTraceBtn) { closeVariantTraceBtn.addEventListener('click', () => { const modal = document.getElementById('variant-trace-modal'); if (modal) modal.style.display = 'none'; }); } document.querySelectorAll('.modal-overlay').forEach(overlay => { overlay.addEventListener('click', (e) => { if (e.target === overlay) { overlay.style.display = 'none'; } }); }); document.querySelectorAll('.btn-var-insert').forEach(btn => { btn.addEventListener('click', (e) => { e.preventDefault(); const tag = btn.getAttribute('data-var'); const postTextarea = document.getElementById('post-text'); if (postTextarea) { const start = postTextarea.selectionStart; const end = postTextarea.selectionEnd; postTextarea.value = postTextarea.value.substring(0, start) + tag + postTextarea.value.substring(end); postTextarea.focus(); postTextarea.selectionEnd = start + tag.length; postTextarea.dispatchEvent(new Event('input', { bubbles: true })); } }); }); const payCurrSelect = document.getElementById('calc-payment-currency'); const recCurrSelect = document.getElementById('calc-receive-currency'); const payAmtInput = document.getElementById('calc-payment-amount'); const recAmtInput = document.getElementById('calc-receive-amount'); const btnSyncRatesNow = document.getElementById('btn-sync-rates-now'); const btnCheckoutViaWa = document.getElementById('btn-checkout-via-wa'); const btnOpenWaSupport = document.getElementById('btn-open-wa-support'); if (payCurrSelect) payCurrSelect.addEventListener('change', () => updateCurrencyCalculations('receive')); if (recCurrSelect) recCurrSelect.addEventListener('change', () => updateCurrencyCalculations('payment')); if (payAmtInput) payAmtInput.addEventListener('input', () => updateCurrencyCalculations('payment')); if (recAmtInput) recAmtInput.addEventListener('input', () => updateCurrencyCalculations('receive')); if (btnSyncRatesNow) btnSyncRatesNow.addEventListener('click', fetchInternetExchangeRates); if (btnCheckoutViaWa) btnCheckoutViaWa.addEventListener('click', generateSecurePurchaseTicket); if (btnOpenWaSupport) { btnOpenWaSupport.addEventListener('click', async () => { const currentAccountId = await FritreeCrypto.getOrGenerateAccountId(); const text = `Hello Fritree Support, my Account ID is: ${currentAccountId}. I need assistance regarding my workspace.`; window.open(`https://wa.me/201096896689?text=${encodeURIComponent(text)}`, '_blank'); }); } initPaymentMethodsModule(); await loadCachedRates(); updateCurrencyCalculations('receive'); await fetchInternetExchangeRates(); initWalletSubTabs(); setInterval(async () => { await fetchInternetExchangeRates(); }, 60000); executeHashRouter(); await checkConnectedSessions(); await checkHuggingFaceSiteConnection(); await syncWorkspaceUI(); startWorkspaceSecurityHeartbeat(); // Check Hugging Face static portal links dynamically setInterval(checkHuggingFaceSiteConnection, 10000); bindBackgroundMessageTunnelListener(); global.addLog = addLog; global.syncWorkspaceUI = syncWorkspaceUI; addLog("Secure execution sandbox initialized. Double-Anchor Signature Guard (SIS) active.", "info"); } catch (e) { console.error("[Fritree Boot] Failed to bootstrap workspace environment:", e); } } function initPaymentMethodsModule() { const tabPMBank = document.getElementById('tab-pm-bank'); const tabPMInstapay = document.getElementById('tab-pm-instapay'); const tabPMWallets = document.getElementById('tab-pm-wallets'); const pmBank = document.getElementById('pm-content-bank'); const pmInstapay = document.getElementById('pm-content-instapay'); const pmWallets = document.getElementById('pm-content-wallets'); const tabs = [tabPMBank, tabPMInstapay, tabPMWallets]; const contents = [pmBank, pmInstapay, pmWallets]; tabs.forEach((tab, index) => { if (tab) { tab.addEventListener('click', () => { tabs.forEach(t => { if (t) t.classList.remove('active'); }); tab.classList.add('active'); contents.forEach((c, idx) => { if (c) c.style.display = idx === index ? 'block' : 'none'; }); addLog(`Payment Gateways: Selected payment tab: [${tab.id}]`, 'info'); }); } }); const currencySelect = document.getElementById('pm-bank-currency-select'); const bankAccountInput = document.getElementById('pm-bank-account-num'); if (currencySelect && bankAccountInput) { currencySelect.addEventListener('change', (e) => { const selected = e.target.value; if (pmBankAccounts[selected]) { bankAccountInput.value = pmBankAccounts[selected]; addLog(`Secure Payment Matrix: Fetched CIB account details for currency: [${selected}].`, "info"); } }); } const bindCopyBtn = (btnId, inputId, labelName) => { const btn = document.getElementById(btnId); const input = document.getElementById(inputId); if (btn && input) { btn.addEventListener('click', () => { navigator.clipboard.writeText(input.value).then(() => { const originalHtml = btn.innerHTML; btn.innerHTML = ''; addLog(`Secure Clipboard: Successfully copied ${labelName} details to clipboard.`, "success"); setTimeout(() => { btn.innerHTML = originalHtml; }, 2000); }); }); } }; bindCopyBtn('btn-copy-pm-bank-account', 'pm-bank-account-num', "CIB bank account"); bindCopyBtn('btn-copy-pm-instapay', 'pm-instapay-num', "Instapay ID"); bindCopyBtn('btn-copy-pm-wallet', 'pm-wallet-num', "Vodafone Cash phone"); } function initStealthMatrixSlidersListeners() { const tabFbRules = document.getElementById('tab-modal-fb-rules'); const tabFbMouse = document.getElementById('tab-modal-fb-mouse'); const tabWaRules = document.getElementById('tab-modal-wa-rules'); const tabWaMouse = document.getElementById('tab-modal-wa-mouse'); const secFbBehavior = document.getElementById('modal-fb-stealth-behavior-section'); const secFbMouseScroll = document.getElementById('modal-fb-stealth-mouse-scroll-section'); const secWaBehavior = document.getElementById('modal-wa-stealth-behavior-section'); const secWaMouseScroll = document.getElementById('modal-wa-stealth-mouse-scroll-section'); const resetStealthTabColors = () => { const tabs = [tabFbRules, tabFbMouse, tabWaRules, tabWaMouse]; tabs.forEach(tab => { if (tab) { tab.style.background = 'transparent'; tab.style.color = '#475569'; } }); }; const configureStealthPaneDisplay = (activeTab, activePane) => { const panes = [secFbBehavior, secFbMouseScroll, secWaBehavior, secWaMouseScroll]; panes.forEach(pane => { if (pane) pane.style.display = 'none'; }); resetStealthTabColors(); if (activePane) activePane.style.display = activePane.id.includes('behavior') ? 'grid' : 'flex'; if (activeTab) { activeTab.style.background = '#e0f2fe'; activeTab.style.color = '#0369a1'; } }; if (tabFbRules) tabFbRules.addEventListener('click', () => configureStealthPaneDisplay(tabFbRules, secFbBehavior)); if (tabFbMouse) tabFbMouse.addEventListener('click', () => configureStealthPaneDisplay(tabFbMouse, secFbMouseScroll)); if (tabWaRules) tabWaRules.addEventListener('click', () => configureStealthPaneDisplay(tabWaRules, secWaBehavior)); if (tabWaMouse) tabWaMouse.addEventListener('click', () => configureStealthPaneDisplay(tabWaMouse, secWaMouseScroll)); const bindSliderAndInput = (sliderId, numId, labelId, configKey, suffix = '') => { const range = document.getElementById(sliderId); const num = document.getElementById(numId); const label = document.getElementById(labelId); if (range && num && label) { const updateUI = (val) => { label.textContent = `${val.toLocaleString('en-US')}${suffix}`; range.value = val; num.value = val; }; range.addEventListener('input', (e) => { updateUI(parseInt(e.target.value)); }); range.addEventListener('change', async () => { await saveStealthMatrixSlidersInModal(); }); num.addEventListener('input', (e) => { let val = parseInt(e.target.value) || 0; const min = parseInt(range.min); const max = parseInt(range.max); if (val < min) val = min; if (val > max) val = max; updateUI(val); }); num.addEventListener('change', async () => { await saveStealthMatrixSlidersInModal(); }); } }; bindSliderAndInput('range-scroll-step', 'num-scroll-step', 'modal-lbl-scroll-pixels-val', 'scrollStepPixels', ' px'); bindSliderAndInput('range-scroll-cycles', 'num-scroll-cycles', 'modal-lbl-scroll-cycles-val', 'scrollTotalCycles', ' Cycles'); bindSliderAndInput('range-mouse-cycles', 'num-mouse-cycles', 'modal-lbl-mouse-cycles-val', 'mouseMovementCycles', ' Path(s)'); bindSliderAndInput('range-mouse-speed', 'num-mouse-speed', 'modal-lbl-mouse-speed-val', 'mouseJitterSpeed', ' ms'); bindSliderAndInput('range-click-jitter', 'num-click-jitter', 'modal-lbl-click-jitter-val', 'coordinateJitterRadius', ' px'); bindSliderAndInput('range-wa-scroll-step', 'num-wa-scroll-step', 'modal-lbl-wa-scroll-pixels', 'waScrollStepPixels', ' px'); bindSliderAndInput('range-wa-scroll-cycles', 'num-wa-scroll-cycles', 'modal-lbl-wa-scroll-cycles', 'waScrollTotalCycles', ' Cycles'); bindSliderAndInput('range-wa-click-jitter', 'num-wa-click-jitter', 'modal-lbl-wa-click-jitter', 'waCoordinateJitterRadius', ' px'); bindSliderAndInput('range-wa-typing-deletions', 'num-wa-typing-deletions', 'modal-lbl-wa-typing-deletions', 'waTypingDeletions', ' Cycles'); const chkCursor = document.getElementById('chk-fb-show-virtual-cursor'); if (chkCursor) { chkCursor.addEventListener('change', async () => { await saveStealthMatrixSlidersInModal(); }); } const chkWaCursor = document.getElementById('chk-wa-cursor-emulation'); if (chkWaCursor) { chkWaCursor.addEventListener('change', async () => { await saveStealthMatrixSlidersInModal(); }); } const liveTestBtn = document.getElementById('btn-workspace-trigger-mouse-scroll-test'); if (liveTestBtn) { liveTestBtn.addEventListener('click', async () => { liveTestBtn.disabled = true; liveTestBtn.style.opacity = '0.7'; liveTestBtn.innerHTML = 'Triggering visual motion test in active tab...'; chrome.tabs.query({ url: ['*://*.facebook.com/*', '*://*.web.facebook.com/*'] }, (tabs) => { if (!tabs || tabs.length === 0) { alert('Alert: No active Facebook tabs found. Open Facebook to run visual test.'); resetLiveTestBtn(); return; } chrome.tabs.sendMessage(tabs[0].id, { action: 'execute_live_stealth_test' }, (response) => { if (chrome.runtime.lastError) { alert('Bridge Failure: Keep Facebook page loaded in active tab.'); } else if (response && response.success) { addLog('Test Completed: Simulated Bezier curve sweeps and scrolling executed on Facebook tab.', 'success'); } resetLiveTestBtn(); }); }); function resetLiveTestBtn() { liveTestBtn.disabled = false; liveTestBtn.style.opacity = '1'; liveTestBtn.innerHTML = 'Trigger Live Simulation Test on Active Facebook Tab'; } }); } const waLiveTestBtn = document.getElementById('btn-wa-trigger-simulated-test'); if (waLiveTestBtn) { waLiveTestBtn.addEventListener('click', async () => { waLiveTestBtn.disabled = true; waLiveTestBtn.style.opacity = '0.7'; waLiveTestBtn.innerHTML = 'Triggering simulated behavior test inside WhatsApp...'; chrome.tabs.query({ url: ['*://web.whatsapp.com/*', '*://*.whatsapp.com/*'] }, (tabs) => { if (!tabs || tabs.length === 0) { alert('Alert: WhatsApp Web page is not loaded. Please sync and verify your connection first.'); resetWaLiveTestBtn(); return; } chrome.tabs.sendMessage(tabs[0].id, { action: 'execute_live_stealth_test' }, (response) => { if (chrome.runtime.lastError) { alert('Bridge Failure: Ensure WhatsApp Web page is opened and verified.'); } else if (response && response.success) { addLog('WhatsApp Test Completed: Initiated stealth scrolls, Bezier movements, and keystroke tests.', 'success'); } resetWaLiveTestBtn(); }); }); function resetWaLiveTestBtn() { waLiveTestBtn.disabled = false; waLiveTestBtn.style.opacity = '1'; waLiveTestBtn.innerHTML = 'Trigger Live Pointer & Scrolling Test on Active WhatsApp Tab'; } }); } } async function loadStealthMatrixSlidersInModal() { const config = await FritreeStorage.get('local_shield_config_matrix', { scrollStepPixels: 250, scrollTotalCycles: 4, mouseMovementCycles: 5, mouseJitterSpeed: 8, coordinateJitterRadius: 8, showVirtualCursor: true, waScrollStepPixels: 200, waScrollTotalCycles: 3, waCoordinateJitterRadius: 6, waTypingDeletions: 3 }); const setVal = (rangeId, numId, labelId, val, suffix = '') => { const range = document.getElementById(rangeId); const num = document.getElementById(numId); const label = document.getElementById(labelId); if (range) range.value = val; if (num) num.value = val; if (label) label.textContent = `${val.toLocaleString('en-US')}${suffix}`; }; setVal('range-scroll-step', 'num-scroll-step', 'modal-lbl-scroll-pixels-val', config.scrollStepPixels || 250, ' px'); setVal('range-scroll-cycles', 'num-scroll-cycles', 'modal-lbl-scroll-cycles-val', config.scrollTotalCycles || 4, ' Cycles'); setVal('range-mouse-cycles', 'num-mouse-cycles', 'modal-lbl-mouse-cycles-val', config.mouseMovementCycles || 5, ' Path(s)'); setVal('range-mouse-speed', 'num-mouse-speed', 'modal-lbl-mouse-speed-val', config.mouseJitterSpeed || 8, ' ms'); setVal('range-click-jitter', 'num-click-jitter', 'modal-lbl-click-jitter-val', config.coordinateJitterRadius || 8, ' px'); setVal('range-wa-scroll-step', 'num-wa-scroll-step', 'modal-lbl-wa-scroll-pixels', config.waScrollStepPixels || 200, ' px'); setVal('range-wa-scroll-cycles', 'num-wa-scroll-cycles', 'modal-lbl-wa-scroll-cycles', config.waScrollTotalCycles || 3, ' Cycles'); setVal('range-wa-click-jitter', 'num-wa-click-jitter', 'modal-lbl-wa-click-jitter', config.waCoordinateJitterRadius || 6, ' px'); setVal('range-wa-typing-deletions', 'num-wa-typing-deletions', 'modal-lbl-wa-typing-deletions', config.waTypingDeletions || 3, ' Cycles'); const chkCursor = document.getElementById('chk-fb-show-virtual-cursor'); if (chkCursor) { chkCursor.checked = config.showVirtualCursor !== false; } const chkWaCursor = document.getElementById('chk-wa-cursor-emulation'); if (chkWaCursor) { chkWaCursor.checked = config.showVirtualCursor !== false; } } async function saveStealthMatrixSlidersInModal() { const currentMatrix = await FritreeStorage.get('local_shield_config_matrix', { sessionProfile: "casual", typingProfile: "average", typingSpeedMultiplier: 1.0, humanScrollActive: true, simulateMouseActive: true, antiHoneypotActive: true, humanTypingActive: true, randomMicroActive: true, autoPauseFailActive: true, canvasNoiseActive: true, audioContextNoiseActive: true, webRtcLeakProtectionActive: true, hardwareConcurrencyMockActive: true, deviceMemoryMockActive: true, batteryApiMockActive: true, languagesSpoofActive: true, screenOrientationSpoofActive: true, pluginsMockActive: true, idleWanderActive: true, safeHoursSchedulerActive: true, dailyCapActive: false, dailyCapLimit: 100, typoRatio: 0.04, coordinateJitterRadius: 8, activeFreezeState: false, waScrollActive: true, waMouseEmulationActive: true, waAntiHoneypotActive: true, waHumanTypingActive: true, waCanvasNoiseActive: true, waRandomTabActive: true, waTypingSimulationActive: true, waViewportJitterActive: true, waDailyCapLimit: 150, waScrollStepPixels: 200, waScrollTotalCycles: 3, waCoordinateJitterRadius: 6, waTypingDeletions: 3 }); const getVal = (id) => { const el = document.getElementById(id); return el ? parseInt(el.value) : null; }; const step = getVal('num-scroll-step') || getVal('range-scroll-step'); const cycles = getVal('num-scroll-cycles') || getVal('range-scroll-cycles'); const mCycles = getVal('num-mouse-cycles') || getVal('range-mouse-cycles'); const mSpeed = getVal('num-mouse-speed') || getVal('range-mouse-speed'); const clickJitter = getVal('num-click-jitter') || getVal('range-click-jitter'); const chkCursor = document.getElementById('chk-fb-show-virtual-cursor'); if (step !== null) currentMatrix.scrollStepPixels = step; if (cycles !== null) currentMatrix.scrollTotalCycles = cycles; if (mCycles !== null) currentMatrix.mouseMovementCycles = mCycles; if (mSpeed !== null) currentMatrix.mouseJitterSpeed = mSpeed; if (clickJitter !== null) currentMatrix.coordinateJitterRadius = clickJitter; if (chkCursor) currentMatrix.showVirtualCursor = chkCursor.checked; const waStep = getVal('num-wa-scroll-step') || getVal('range-wa-scroll-step'); const waCycles = getVal('num-wa-scroll-cycles') || getVal('range-wa-scroll-cycles'); const waClickJitter = getVal('num-wa-click-jitter') || getVal('range-wa-click-jitter'); const waTypingDeletions = getVal('num-wa-typing-deletions') || getVal('range-wa-typing-deletions'); const chkWaCursor = document.getElementById('chk-wa-cursor-emulation'); if (waStep !== null) currentMatrix.waScrollStepPixels = waStep; if (waCycles !== null) currentMatrix.waScrollTotalCycles = waCycles; if (waClickJitter !== null) currentMatrix.waCoordinateJitterRadius = waClickJitter; if (waTypingDeletions !== null) currentMatrix.waTypingDeletions = waTypingDeletions; if (chkWaCursor) currentMatrix.showVirtualCursor = chkWaCursor.checked; const serialized = JSON.stringify(currentMatrix); const concatString = `${serialized}:${SHIELD_INTEGRITY_SALT}`; let signature = "fallback_shield_sig_512_" + concatString.length; if (typeof FritreeCrypto !== 'undefined' && typeof FritreeCrypto.signReceipt === 'function') { signature = await FritreeCrypto.signReceipt( "FB_STEALTH_SHIELD_V3", concatString.length, "config_signature_512", concatString, SHIELD_INTEGRITY_SALT ); } await FritreeStorage.set('local_shield_config_matrix', currentMatrix); await FritreeStorage.set('local_shield_config_matrix_sig_512', signature); if (typeof window.FritreeRules !== 'undefined' && typeof window.FritreeRules.evaluateRisk === 'function') { await window.FritreeRules.evaluateRisk(); } } function addLog(msg, type = "info") { if (isTermSuspended) return; const terminal = document.getElementById('terminal-log'); if (!terminal) return; const time = new Date().toLocaleTimeString('en-US'); const line = document.createElement('div'); line.className = 'log-line'; const timeSpan = document.createElement('span'); timeSpan.className = 'log-time'; timeSpan.textContent = `[${time}]`; const msgSpan = document.createElement('span'); let classType = 'log-info'; let defaultIcon = ''; if (type === 'success') { classType = 'log-success'; defaultIcon = ''; } else if (type === 'error') { classType = 'log-error'; defaultIcon = ''; } else if (type === 'warn') { classType = 'log-warn'; defaultIcon = ''; } const finalIcon = getDynamicIconForText(msg, defaultIcon); msgSpan.className = classType; msgSpan.innerHTML = ` ${finalIcon} ${msg}`; line.appendChild(timeSpan); line.appendChild(msgSpan); terminal.appendChild(line); terminal.scrollTop = terminal.scrollHeight; } function getDynamicIconForText(msg, defaultIcon) { const text = msg.toLowerCase(); if (text.includes('facebook') || text.includes('[facebook]')) return ''; if (text.includes('whatsapp') || text.includes('[whatsapp]')) return ''; if (text.includes('cooldown') || text.includes('wait') || text.includes('countdown') || text.includes('seconds')) return ''; if (text.includes('campaign') || text.includes('broadcast') || text.includes('post')) return ''; if (text.includes('success') || text.includes('completed') || text.includes('dispatched')) return ''; if (text.includes('failed') || text.includes('error') || text.includes('aborted') || text.includes('dropped')) return ''; if (text.includes('security') || text.includes('integrity') || text.includes('shield') || text.includes('tampering')) return ''; if (text.includes('wallet') || text.includes('points') || text.includes('credit') || text.includes('usd') || text.includes('balance') || text.includes('exchange')) return ''; if (text.includes('group') || text.includes('registry') || text.includes('communities')) return ''; if (text.includes('template') || text.includes('library') || text.includes('rotation')) return ''; if (text.includes('test') || text.includes('pointer') || text.includes('motion')) return ''; return defaultIcon; } function clearTerminalLogs() { const terminal = document.getElementById('terminal-log'); if (terminal) terminal.innerHTML = ''; addLog("Console terminal cleared.", "warn"); } async function checkConnectedSessions() { if (typeof chrome === 'undefined' || !chrome.runtime) { addLog("System offline. Session synchronization bypassed.", "error"); return; } if (chrome.cookies) { chrome.cookies.get({ url: "https://www.facebook.com", name: "c_user" }, async (cookie) => { const badge = document.getElementById('session-badge'); const startFbBtn = document.getElementById('btn-start-publish'); const fbDashStatus = document.getElementById('fb-dash-status-lbl'); const fbDashGroups = document.getElementById('fb-dash-total-groups'); if (cookie && cookie.value) { if (badge) { badge.className = "badge green"; badge.innerHTML = 'FB Connected'; } if (startFbBtn) startFbBtn.disabled = false; if (fbDashStatus) { fbDashStatus.innerHTML = "Active & Online"; fbDashStatus.style.color = "var(--success)"; } chrome.runtime.sendMessage({ action: 'getGroups' }, (response) => { if (response && response.success && response.groups) { if (window.FritreeFacebook && typeof window.FritreeFacebook.setGroups === 'function') { window.FritreeFacebook.setGroups(response.groups, response.userId); } if (fbDashGroups) fbDashGroups.innerHTML = `${response.groups.length.toLocaleString('en-US')}`; addLog(`Groups synchronized: Verified and loaded [${response.groups.length}] destinations successfully.`, "success"); } }); } }); } const isWaConnected = await FritreeStorage.get('wa_connected', false); const waPhoneNumber = await FritreeStorage.get('wa_phone_number', 'Online'); const waProfileName = await FritreeStorage.get('wa_profile_name', 'Active Account'); updateWAUIStatus(isWaConnected); if (isWaConnected) { const phoneLbl = document.getElementById('wa-dash-phone-lbl'); const profileLbl = document.getElementById('wa-dash-profile-lbl'); const syncLbl = document.getElementById('wa-dash-sync-lbl'); if (phoneLbl) phoneLbl.textContent = waPhoneNumber; if (profileLbl) profileLbl.textContent = waProfileName; if (syncLbl) syncLbl.textContent = new Date().toLocaleTimeString('en-US'); } else { const warningBanner = document.getElementById('wa-connect-warning-warning-banner'); if (warningBanner) warningBanner.style.display = 'block'; } } function updateWAUIStatus(connected) { const badge = document.getElementById('wa-session-badge'); const startWaBtn = document.getElementById('btn-wa-start'); const waDashStatus = document.getElementById('wa-dash-status-lbl'); const warningBanner = document.getElementById('wa-connect-warning-banner'); if (badge) { if (connected) { badge.className = "badge green"; badge.innerHTML = 'WA Connected'; } else { badge.className = "badge red"; badge.innerHTML = 'WA Offline'; } } if (startWaBtn) startWaBtn.disabled = !connected; if (waDashStatus) { waDashStatus.innerHTML = connected ? "Active & Online" : "Offline"; waDashStatus.style.color = connected ? "var(--success)" : "var(--danger)"; } if (warningBanner) { warningBanner.style.display = connected ? 'none' : 'block'; } } function runDelaySimulation() { const modeSelect = document.getElementById('delay-mode'); const postCountInput = document.getElementById('sim-post-count'); const networkSpeedSelect = document.getElementById('sim-network-speed'); const failureRateSelect = document.getElementById('sim-failure-rate'); const mode = modeSelect ? modeSelect.value : 'continuous'; const postCount = parseInt(postCountInput ? postCountInput.value : '20') || 20; const netUploadDelay = parseInt(networkSpeedSelect ? networkSpeedSelect.value : '5') || 5; const failureRate = parseInt(failureRateSelect ? failureRateSelect.value : '0') || 0; const minDelay = parseInt(document.getElementById('delay-min')?.value || '45') || 45; const maxDelay = parseInt(document.getElementById('delay-max')?.value || '120') || 120; const fixedDelay = parseInt(document.getElementById('delay-fixed')?.value || '60') || 60; const burstCount = parseInt(document.getElementById('burst-count')?.value || '5') || 5; const burstPause = parseInt(document.getElementById('burst-pause')?.value || '300') || 300; const longBreakCount = parseInt(document.getElementById('long-break-count')?.value || '15') || 15; const longBreakPause = parseInt(document.getElementById('long-break-pause')?.value || '900') || 900; let totalSeconds = 0; let totalCooldown = 0; let totalUpload = 0; let totalBreaks = 0; let totalFailureMitigation = 0; let logLines = []; logLines.push(`=== DYNAMIC STRATEGY TIMELINE PROJECTION (${postCount} STEPS) ===`); logLines.push(`Interval Model: ${mode.toUpperCase()} Cooldown Delay Scheme`); logLines.push(`Base Network Speed Overhead: ${netUploadDelay}s per media asset`); logLines.push(`Expected Target Moderation/Restrictions: ${failureRate}%`); logLines.push("------------------------------------------------------------"); function getFibonacci(index) { let a = 1, b = 2; for (let k = 0; k < index; k++) { let temp = a + b; a = b; b = temp; } return a; } for (let i = 1; i <= postCount; i++) { totalUpload += netUploadDelay; totalSeconds += netUploadDelay; let stepCooldown = 0; if (i < postCount) { if (mode === 'continuous') { const decayRatio = (postCount - i) / postCount; const median = (minDelay + maxDelay) / 2; stepCooldown = Math.floor(minDelay + (median * decayRatio)); } else if (mode === 'random') { const pseudoRand = ((i * 125) % 100) / 100; stepCooldown = Math.floor(pseudoRand * (maxDelay - minDelay + 1)) + minDelay; } else if (mode === 'fixed') { stepCooldown = fixedDelay; } else if (mode === 'burst') { if (i % burstCount === 0) { stepCooldown = burstPause; } else { stepCooldown = 10; } } else if (mode === 'fibonacci') { const seqIndex = (i - 1) % 10; stepCooldown = getFibonacci(seqIndex) * 5; } else if (mode === 'adaptive') { const frictionFactor = 1 + (failureRate / 100); stepCooldown = Math.round(60 * frictionFactor); } totalCooldown += stepCooldown; totalSeconds += stepCooldown; } let stepBreak = 0; if (longBreakCount > 0 && i < postCount && i % longBreakCount === 0) { stepBreak = longBreakPause; totalBreaks += stepBreak; totalSeconds += stepBreak; } let stepMitigation = 0; if (failureRate > 0) { const simulatedChance = (i * 17) % 100; if (simulatedChance < failureRate) { stepMitigation = 180; totalFailureMitigation += stepMitigation; totalSeconds += stepMitigation; } } if (i <= 3 || i === Math.floor(postCount / 2) || i === postCount) { let stepDetails = `Step ${i}: Upload (${netUploadDelay}s)`; if (stepCooldown > 0) stepDetails += ` + Cooldown (${stepCooldown}s)`; if (stepBreak > 0) stepDetails += ` + Break (${stepBreak}s)`; if (stepMitigation > 0) stepDetails += ` + Safety Suspend (${stepMitigation}s)`; logLines.push(stepDetails); } else if (i === 4 && postCount > 5) { logLines.push("... [Steps 4 to " + (postCount - 1) + " continuing under active parameter intervals] ..."); } } const totalSecondsCount = totalSeconds; const totalMinutes = Math.ceil(totalSecondsCount / 60); const outputSummaryText = document.getElementById('simulator-summary'); if (outputSummaryText) { outputSummaryText.innerHTML = `Estimated Time: ${totalMinutes} minute${totalMinutes !== 1 ? 's' : ''}`; } const avgInterval = postCount > 1 ? (totalCooldown / (postCount - 1)) : totalCooldown; const safetyBadge = document.getElementById('sim-health-badge'); let safetyClass = "badge green"; let safetyText = "High Account Protection Index"; let recommendation = ""; if (avgInterval < 30) { safetyClass = "badge red"; safetyText = "Low Safety Index (High Restriction Risk)"; recommendation = "⚠ Warning: Your cooling intervals are too aggressive. Platform security blocks are likely. Increase cooldown minimum to 45s+."; } else if (avgInterval < 60) { safetyClass = "badge yellow"; safetyText = "Moderate Safety Index"; recommendation = "ℹ Recommendation: Moderate safety limits. Consider adding occasional long breaks or switching to Random Cooldown mode."; } else { safetyClass = "badge green"; safetyText = "High Account Protection Index"; recommendation = "✔ Success: Excellent safety parameters. Simulated human behavior threshold satisfied. Your account is well protected."; } if (safetyBadge) { safetyBadge.className = safetyClass; safetyBadge.innerHTML = `${safetyText}`; } logLines.push("------------------------------------------------------------"); logLines.push(`Estimated Allocation Breakdown:`); logLines.push(`- Media Content Uploading: ${formatHHMMSS(totalUpload)}`); if (totalCooldown > 0) logLines.push(`- Cooldown Interval Delay: ${formatHHMMSS(totalCooldown)}`); if (totalBreaks > 0) logLines.push(`- Structured Break Durations: ${formatHHMMSS(totalBreaks)}`); if (totalFailureMitigation > 0) logLines.push(`- Safety Recovery Backoffs: ${formatHHMMSS(totalFailureMitigation)}`); logLines.push(`Total Project Elapsed Time: ${formatHHMMSS(totalSecondsCount)}`); logLines.push("------------------------------------------------------------"); logLines.push(recommendation); const outputTextArea = document.getElementById('simulator-output-text'); if (outputTextArea) { outputTextArea.style.whiteSpace = 'pre-wrap'; outputTextArea.style.fontFamily = 'monospace'; outputTextArea.style.fontSize = '11px'; outputTextArea.style.background = '#f8fafc'; outputTextArea.style.padding = '10px'; outputTextArea.style.borderRadius = '6px'; outputTextArea.style.border = '1px solid #cbd5e1'; outputTextArea.style.color = '#334155'; outputTextArea.textContent = logLines.join('\n'); } } async function triggerFacebookCampaign() { const selectedGroupIds = window.FritreeFacebook ? window.FritreeFacebook.getSelectedIds() : []; if (selectedGroupIds.length === 0) { alert("Please select at least one target group to launch the campaign."); return; } const features = FritreeDashboard.getSubscriptionFeatures(); if (selectedGroupIds.length > features.maxFbGroupsPerCampaign) { alert(`Workspace Limit: Maximum group capacity per campaign is capped at ${features.maxFbGroupsPerCampaign} targets.`); return; } const fbShares = window.FritreeDashboard ? window.FritreeDashboard.getFbShares() : 0; if (fbShares < selectedGroupIds.length) { alert(`Insufficient FB Cards: You have ${fbShares} cards, but this campaign requires ${selectedGroupIds.length} cards. Swap points in Store.`); return; } let baseText = ""; let images = []; let isLibraryMode = false; let payloadMap = {}; addLog("Compressing and signing campaign payload strings...", "info"); const resetPublishButtonsOnFailure = () => { document.getElementById('btn-start-publish').disabled = false; document.getElementById('btn-stop-publish').disabled = true; }; try { const isRotationActive = window.FritreeRotation ? window.FritreeRotation.isRotationActive() : false; if (isRotationActive) { isLibraryMode = true; addLog("Unpacking content queue under active Rotation Matrix parameters...", "info"); const activeMode = await FritreeStorage.get('local_rotation_mode', 'balanced'); const availableIds = window.FritreeRotation.getPosts().map(p => p.id); if (availableIds.length === 0) { alert("Rotation matrix is active but no templates are selected. Select active templates in Library."); resetPublishButtonsOnFailure(); return; } for (let idx = 0; idx < selectedGroupIds.length; idx++) { const gId = selectedGroupIds[idx]; const postObj = window.FritreeRotation.selectNextPost(activeMode, availableIds); if (!postObj) { addLog("Execution Aborted: No active templates matching current criteria were found.", "error"); alert("No active templates matching selected filters were found."); resetPublishButtonsOnFailure(); return; } const resolvedLightImages = await resolveMediaReferences(postObj.mediaReferences); let finalPublishText = postObj.text || postObj.altText || ''; if (!finalPublishText && resolvedLightImages.length === 0) { addLog(`Warning: Empty content detected for template [${postObj.title}]. Fetching backup copy...`, "warn"); finalPublishText = postObj.altText || ''; } payloadMap[gId] = { text: finalPublishText, images: resolvedLightImages, uuid: postObj.id }; } } else { baseText = document.getElementById('post-text').value; images = window.FritreeFacebook ? await window.FritreeFacebook.getUploadedImages() : []; if (!baseText && images.length === 0) { alert("Blank post submission aborted. Provide a text copy or media file."); resetPublishButtonsOnFailure(); return; } } const delayConfig = { mode: document.getElementById('delay-mode').value, minSeconds: parseInt(document.getElementById('delay-min').value) || 45, maxSeconds: parseInt(document.getElementById('delay-max').value) || 120, fixedSeconds: parseInt(document.getElementById('delay-fixed').value) || 60, burstCount: parseInt(document.getElementById('burst-count').value) || 5, burstPause: parseInt(document.getElementById('burst-pause').value) || 300, longBreakCount: parseInt(document.getElementById('long-break-count').value) || 0, longBreakPause: parseInt(document.getElementById('long-break-pause').value) || 900 }; const launchMode = document.getElementById('fb-launch-mode')?.value || 'tab'; setDomTextSafely('stat-total', selectedGroupIds.length); setDomTextSafely('stat-success', 0); setDomTextSafely('stat-pending', 0); setDomTextSafely('stat-failed', 0); const progressFill = document.getElementById('progress-fill'); if (progressFill) progressFill.style.width = '0%'; setDomTextSafely('progress-pct', '0%'); const noResultsRow = document.getElementById('no-results-row'); if (noResultsRow) noResultsRow.remove(); document.getElementById('btn-start-publish').disabled = true; document.getElementById('btn-stop-publish').disabled = false; startCampaignTrackingTimers(); chrome.runtime.sendMessage({ action: "publishToMultipleGroups", groupIds: selectedGroupIds, text: baseText, images: images, delayConfig: delayConfig, isLibraryMode: isLibraryMode, payloadMap: payloadMap, launchMode: launchMode }, (response) => { if (chrome.runtime.lastError) { const errMsg = chrome.runtime.lastError.message; addLog(`Campaign startup aborted: ${errMsg}`, "error"); resetPublishButtonsOnFailure(); stopCampaignTrackingTimers(); } }); } catch (err) { console.error("[Fritree UI] Exception hit during campaign parsing:", err); addLog(`Campaign startup aborted: ${err.message}`, "error"); resetPublishButtonsOnFailure(); stopCampaignTrackingTimers(); } } function haltFacebookCampaign() { chrome.runtime.sendMessage({ action: "stopPublishing" }, () => { document.getElementById('btn-start-publish').disabled = false; document.getElementById('btn-stop-publish').disabled = true; addLog("Freeze signal dispatched. Running Facebook operations halted.", "warn"); stopCampaignTrackingTimers(); }); } async function triggerWhatsAppCampaign() { const recipients = window.FritreeWhatsApp ? window.FritreeWhatsApp.getRecipients() : []; if (recipients.length === 0) { alert("WhatsApp queue is empty. Queue target phone numbers first."); return; } const features = FritreeDashboard.getSubscriptionFeatures(); if (recipients.length > features.maxWaRecipientsPerCampaign) { alert(`Workspace Limit: Maximum recipient capacity is capped at ${features.maxWaRecipientsPerCampaign} targets.`); return; } const waShares = window.FritreeDashboard ? window.FritreeDashboard.getWaShares() : 0; if (waShares < recipients.length) { alert(`Insufficient WA Cards: You have ${waShares} cards, but this campaign requires ${recipients.length} cards. Swap points in Store.`); return; } const text = document.getElementById('wa-message-text').value.trim(); if (!text) { alert("Blank broadcast aborted. Type message content."); return; } const delayConfig = { mode: document.getElementById('delay-mode').value, minSeconds: parseInt(document.getElementById('delay-min').value) || 45, maxSeconds: parseInt(document.getElementById('delay-max').value) || 120, fixedSeconds: parseInt(document.getElementById('delay-fixed').value) || 60 }; const launchMode = document.getElementById('wa-launch-mode')?.value || 'tab'; setDomTextSafely('stat-wa-total-clients', recipients.length); setDomTextSafely('stat-wa-success-clients', 0); const progressFillWa = document.getElementById('progress-fill-wa'); if (progressFillWa) progressFillWa.style.width = '0%'; setDomTextSafely('progress-pct-wa', '0%'); const noResultsRow = document.getElementById('no-results-row'); if (noResultsRow) noResultsRow.remove(); document.getElementById('btn-wa-start').disabled = true; document.getElementById('btn-wa-stop').disabled = false; startCampaignTrackingTimers(); chrome.runtime.sendMessage({ action: "start_wa_campaign", recipients: recipients, text: text, media: null, delayConfig: delayConfig, launchMode: launchMode }, (response) => { if (chrome.runtime.lastError) { const errMsg = chrome.runtime.lastError.message; addLog(`WhatsApp broadcast campaign startup aborted: ${errMsg}`, "error"); document.getElementById('btn-wa-start').disabled = false; document.getElementById('btn-wa-stop').disabled = true; stopCampaignTrackingTimers(); } }); } function haltWhatsAppCampaign() { chrome.runtime.sendMessage({ action: "stopPublishing" }, () => { document.getElementById('btn-wa-start').disabled = false; document.getElementById('btn-wa-stop').disabled = true; addLog("Freeze signal dispatched. Running WhatsApp operations halted.", "warn"); stopCampaignTrackingTimers(); }); } // ============================================================================ // Real-Time Background-to-Foreground Tunnel Message Listener Binds // ============================================================================ function bindBackgroundMessageTunnelListener() { if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.onMessage) { chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { // 1. Facebook Poster Real-Time Pipeline if (message.action === 'publishProgress') { handleFacebookProgress(message); } else if (message.action === 'publishCountdown') { handleFacebookCountdown(message); } else if (message.action === 'publishComplete') { handleFacebookComplete(message); } // 2. WhatsApp Broadcast Real-Time Pipeline else if (message.action === 'wa_send_progress') { handleWhatsAppProgress(message); } else if (message.action === 'wa_send_countdown') { handleWhatsAppCountdown(message); } else if (message.action === 'wa_send_complete') { handleWhatsAppComplete(message); } // 3. Handshake groups loader Pipeline else if (message.action === 'groupsProgress') { if (message.message) { addLog(message.message, 'info'); } } }); } } function handleFacebookProgress(data) { const current = data.current; const total = data.total; const gId = data.groupId; const status = data.status; // 'publishing', 'success', 'pending', 'failed', 'status_update' const error = data.error; const postUrl = data.postUrl; if (status === 'publishing') { addLog(`Publishing campaign elements to FB Group ID: [${gId}] (${current}/${total})...`, 'info'); } else if (status === 'success') { addLog(`Successfully dispatched post to FB Group ID: [${gId}]. Verification proof link captured.`, 'success'); updateFacebookStatsCounter('success'); addProofLinkRow(gId, 'Success', postUrl); } else if (status === 'pending') { addLog(`Post submitted successfully to FB Group ID: [${gId}] but is pending administrator review.`, 'warn'); updateFacebookStatsCounter('pending'); addProofLinkRow(gId, 'Pending Approval', postUrl || '#'); } else if (status === 'failed') { addLog(`Failed to publish elements to FB Group ID: [${gId}]. Error: ${error || 'Group has posting restrictions'}`, 'error'); updateFacebookStatsCounter('failed'); addProofLinkRow(gId, 'Restricted', null, error); } else if (status === 'status_update') { if (data.msg) { // Strip HTML tags from injected logs or handle nicely const cleanMsg = data.msg.replace(/<[^>]*>/g, '').trim(); addLog(cleanMsg, 'info'); } } // Update active progressive metrics fill const pct = Math.round((current / total) * 100); const fill = document.getElementById('progress-fill'); const pctLabel = document.getElementById('progress-pct'); if (fill) fill.style.width = `${pct}%`; if (pctLabel) pctLabel.textContent = `${pct}%`; } function updateFacebookStatsCounter(type) { if (type === 'success') { const el = document.getElementById('stat-success'); if (el) el.textContent = parseInt(el.textContent || '0') + 1; completedStepsCount++; } else if (type === 'pending') { const el = document.getElementById('stat-pending'); if (el) el.textContent = parseInt(el.textContent || '0') + 1; completedStepsCount++; } else if (type === 'failed') { const el = document.getElementById('stat-failed'); if (el) el.textContent = parseInt(el.textContent || '0') + 1; completedStepsCount++; } updateAverageWaitTime(); } function handleWhatsAppProgress(data) { const current = data.current; const total = data.total; const phone = data.phone; const name = data.name; const status = data.status; // 'sending', 'success', 'failed' const error = data.error; if (status === 'sending') { addLog(`Preparing session & composing custom broadcast copy to: ${name} (${phone}) (${current}/${total})...`, 'info'); } else if (status === 'success') { addLog(`WhatsApp message successfully delivered to: ${name} (${phone}).`, 'success'); updateWhatsAppStatsCounter('success'); addProofLinkRow(phone, 'Success', `https://web.whatsapp.com/send?phone=${phone.replace(/[^0-9]/g, '')}`); } else if (status === 'failed') { addLog(`Broadcast dispatch delivery failed to: ${name} (${phone}). Error: ${error || 'Session handshakes dropped'}`, 'error'); updateWhatsAppStatsCounter('failed'); addProofLinkRow(phone, 'Failed', null, error); } // Update progressive WhatsApp bar const pct = Math.round((current / total) * 100); const fill = document.getElementById('progress-fill-wa'); const pctLabel = document.getElementById('progress-pct-wa'); if (fill) fill.style.width = `${pct}%`; if (pctLabel) pctLabel.textContent = `${pct}%`; } function updateWhatsAppStatsCounter(type) { if (type === 'success') { const el = document.getElementById('stat-wa-success-clients'); if (el) el.textContent = parseInt(el.textContent || '0') + 1; completedStepsCount++; } updateAverageWaitTime(); } function handleFacebookCountdown(data) { const seconds = data.seconds; const type = data.type || 'Continuous Thermal Cooldown'; addLog(`Pacing Campaign: [${type}] Sleep interval active. Next FB step executes in ${seconds}s.`, 'warn'); totalCooldownSeconds++; updateAverageWaitTime(); } function handleWhatsAppCountdown(data) { const seconds = data.seconds; const type = data.type || 'Pacing Cooldown'; addLog(`Pacing Campaign: [${type}] Sleep interval active. Next WA step executes in ${seconds}s.`, 'warn'); totalCooldownSeconds++; updateAverageWaitTime(); } function updateAverageWaitTime() { setDomTextSafely('stat-wait-total', formatHHMMSS(totalCooldownSeconds)); if (completedStepsCount > 0) { const avg = Math.round(totalCooldownSeconds / completedStepsCount); setDomTextSafely('stat-wait-avg', `${avg} seconds`); } } function handleFacebookComplete(data) { addLog("Campaign Completion: Active Facebook Multi-Group distribution closed successfully.", "success"); stopCampaignTrackingTimers(); document.getElementById('btn-start-publish').disabled = false; document.getElementById('btn-stop-publish').disabled = true; syncWorkspaceUI(); } function handleWhatsAppComplete(data) { addLog("Campaign Completion: Active WhatsApp Multi-Contact broadcast closed successfully.", "success"); stopCampaignTrackingTimers(); document.getElementById('btn-wa-start').disabled = false; document.getElementById('btn-wa-stop').disabled = true; syncWorkspaceUI(); } function addProofLinkRow(target, state, proofUrl, errorMsg = '') { const tbody = document.querySelector('#results-table tbody'); if (!tbody) return; // Remove placeholder empty row if present const fallbackRow = document.getElementById('no-results-row'); if (fallbackRow) fallbackRow.remove(); const tr = document.createElement('tr'); const tdTarget = document.createElement('td'); tdTarget.style.fontWeight = 'bold'; tdTarget.textContent = target; const tdState = document.createElement('td'); const badge = document.createElement('span'); let badgeClass = 'status-badge '; if (state === 'Success') { badgeClass += 'success'; } else if (state === 'Pending Approval') { badgeClass += 'pending'; } else { badgeClass += 'failed'; } badge.className = badgeClass; badge.textContent = state; tdState.appendChild(badge); const tdLink = document.createElement('td'); if (proofUrl) { const link = document.createElement('a'); link.href = proofUrl; link.target = '_blank'; link.style.cssText = 'color: var(--primary); font-weight: bold; text-decoration: none;'; link.innerHTML = ' Open Proof'; tdLink.appendChild(link); } else { const errSpan = document.createElement('span'); errSpan.style.cssText = 'color: var(--danger); font-size: 11px; font-weight: bold;'; errSpan.textContent = errorMsg || 'N/A'; tdLink.appendChild(errSpan); } tr.appendChild(tdTarget); tr.appendChild(tdState); tr.appendChild(tdLink); tbody.appendChild(tr); } if (document.readyState === 'complete' || document.readyState === 'interactive') { initInterfaceOrchestrator(); } else { document.addEventListener('DOMContentLoaded', () => initInterfaceOrchestrator()); } })(typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : this);