/**
* search.js - High Performance Quick Compare Shopping & Live Browser Controller
* - Automatically queries all platforms specified by the user
* - Enforces budget constraints ("under ₹X")
* - Clicks best product in virtual browser & snaps high-res picture
* - Provides direct product page redirection on "Add to Cart (Your Device)" (NEVER search URL)
* - Computes quantity rates ("200 rupees for 100gram")
*/
(function(window) {
'use strict';
function getApiBaseUrl() {
return (typeof API_BASE !== 'undefined' && API_BASE) ? API_BASE : '';
}
window.extractMaxPriceClient = function(str) {
const s = String(str || '').toLowerCase();
const patterns = [
/(?:under|below|less\s+than|upto|up\s+to|max|budget\s*(?:of|is)?)\s*(?:₹|rs\.?|inr|rupees)?\s*([0-9]{1,6})/i,
/(?:₹|rs\.?|inr)\s*([0-9]{1,6})\s*(?:under|below|max|ke\s*andar|se\s*kam|tak)/i,
/([0-9]{1,6})\s*(?:rupees|rs|₹|inr)\s*(?:under|below|ke\s*andar|se\s*kam|tak)/i,
/\b([0-9]{1,6})\s*(?:tak)\b/i,
/under\s*([0-9]{1,6})/i
];
for (const pat of patterns) {
const m = pat.exec(s);
if (m) {
const v = parseInt(m[1], 10);
if (v >= 10 && v <= 1000000) return v;
}
}
return null;
};
window.formatQuantityClient = function(title, priceInr, packOptions) {
const combined = String((title || '') + ' ' + (packOptions || '')).toLowerCase();
const p = parseFloat(priceInr || 0);
if (!p || p <= 0) return 'Standard Pack';
const mKg = combined.match(/(\d+(?:\.\d+)?)\s*(?:kg|kilo|kilogram|किलो)\b/);
const mGm = combined.match(/(\d+(?:\.\d+)?)\s*(?:g|gm|gms|gram|grams|ग्राम)\b/);
const mL = combined.match(/(\d+(?:\.\d+)?)\s*(?:l|ltr|litre|liter|लीटर)\b/);
const mMl = combined.match(/(\d+(?:\.\d+)?)\s*(?:ml|मिली)\b/);
if (mKg) {
const kg = parseFloat(mKg[1]);
if (kg > 0) {
const per100g = ((p / (kg * 1000)) * 100).toFixed(2);
const kgDisp = Number.isInteger(kg) ? (kg + 'kg') : (kg + 'kg');
if (kg === 1) return Math.round(p) + ' rupees for ' + kgDisp + ' (' + per100g + ' rupees for 100gram)';
const per1kg = Math.round(p / kg);
return Math.round(p) + ' rupees for ' + kgDisp + ' (' + per1kg + ' rupees for 1kg · ' + per100g + ' rupees for 100gram)';
}
}
if (mGm) {
const gm = parseFloat(mGm[1]);
if (gm > 0) {
const per100g = ((p / gm) * 100).toFixed(2);
const gmDisp = Number.isInteger(gm) ? (gm + 'gram') : (gm + 'gram');
if (gm === 100) return Math.round(p) + ' rupees for 100gram';
return Math.round(p) + ' rupees for ' + gmDisp + ' (' + per100g + ' rupees for 100gram)';
}
}
if (mL) {
const l = parseFloat(mL[1]);
if (l > 0) {
const per100ml = ((p / (l * 1000)) * 100).toFixed(2);
return Math.round(p) + ' rupees for ' + l + 'L (' + per100ml + ' rupees for 100ml)';
}
}
if (mMl) {
const ml = parseFloat(mMl[1]);
if (ml > 0) {
const per100ml = ((p / ml) * 100).toFixed(2);
return Math.round(p) + ' rupees for ' + ml + 'ml (' + per100ml + ' rupees for 100ml)';
}
}
return Math.round(p) + ' rupees for 1 pack';
};
window.isQuickCompareShoppingQuery = function(q) {
const s = String(q || '').trim();
if (!s || s.length < 3) return false;
const low = s.toLowerCase();
if (/\b(write\s+a\s+python|write\s+javascript|write\s+html|create\s+a\s+function|leetcode|who\s+founded|ceo\s+of)\b/i.test(low)) return false;
const storeMatches = s.match(/\b(amazon|flipkart|city\s*mall|citymall|jio\s*mart|jiomart|blinkit|grofers|meesho|big\s*basket|bigbasket|myntra|zepto|instamart|nykaa|ajio)\b|अमेज़न|अमाज़ॉन|फ्लिपकार्ट|जियोमार्ट|जियो\s*मार्ट|सिटी\s*मॉल|सिटीमॉल|ब्लिंकिट|मीशो|बिगबास्केट|मिंत्रा|ज़ेप्टो/gi) || [];
const uniqueStoresCount = new Set(storeMatches.map(x => x.replace(/\s+/g, '').toLowerCase())).size;
const hasCartAction = /\b(add\s+to\s+cart|add\s+in\s+cart|add\s+[a-z0-9\s,]+\s+(?:to|in)\s+cart|put\s+in\s+cart|cart\s+me|cart\s+mein|in\s+my\s+cart|to\s+my\s+cart|add\s+cart)\b|कार्ट\s*में\s*(?:जोड़|डाल|ऐड|रख)|कार्ट\s*मे\s*(?:जोड़|डाल)|ऑर्डर\s*कर/i.test(s);
const hasComparePattern = /\b(compare\s+.+\s+(?:in|on|at|across|between|from|with)|compare\s+(?:price|prices|rate|cost)|quick\s+compare|compare\s+them|price\s+comparison|open\s+the\s+platform|search\s+the\s+product|search\s+product|cheapest\s+on|compare\s+on|under\s+[0-9]+)\b|तुलना\s*कर|सस्ता\s*कहाँ|कीमत\s*की\s*तुलना/i.test(s);
if (hasCartAction || hasComparePattern) return true;
if (uniqueStoresCount >= 2) return true;
if (uniqueStoresCount >= 1 && /\b(compare|open|search|find|buy|price|rate|cost|cart|order|details|deatils|check|items?|product|in|on|at|from|for|sugar|suger|atta|aata|oil|rice|dal|daal|salt|milk|tea|chai|ghee|maggi|biscuit|soap|shampoo|phone|mobile|laptop|earbuds|watch|shoes|shirt)\b|खोल|सर्च|खोज|कीमत|दाम|रेट|कार्ट|चीनी|आटा|तेल|चावल|दाल|नमक|चाय|बिस्किट|साबुन|मोबाइल|फोन|तुलना/i.test(s)) {
return true;
}
return false;
};
window.openPlatformInLiveBrowser = async function(targetUrl, platformName, itemName, pincode, loadId, openFullscreen) {
try {
window.__lastShoppingSearchItem = itemName || 'Sugar 1kg';
if (openFullscreen && typeof window.openLiveBrowserFullscreen === 'function') {
window.openLiveBrowserFullscreen(loadId);
} else if (typeof showToast === 'function') {
showToast('🛒 Opening ' + platformName + ' in Live Browser...');
}
const maxP = (window.__quickCompareDataByLoadId && window.__quickCompareDataByLoadId[loadId] && window.__quickCompareDataByLoadId[loadId].maxPrice) || window.extractMaxPriceClient(itemName);
await fetch(getApiBaseUrl() + '/api/ba/start-shopping', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
targetUrl: targetUrl,
platformName: platformName,
item: itemName,
pincode: pincode || '800001',
maxPrice: maxP || undefined
})
});
if (!openFullscreen) {
const iframeEl = document.getElementById('albViewport_' + loadId);
if (iframeEl) {
iframeEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
} catch (e) {}
};
window.watchLiveProductSearchInBrowser = async function(loadId, customTargetUrl, customPlatformName) {
try {
if (typeof window.openLiveBrowserFullscreen === 'function') {
window.openLiveBrowserFullscreen(loadId);
}
const qcData = window.__quickCompareDataByLoadId && window.__quickCompareDataByLoadId[loadId];
const pin = (qcData && qcData.location && qcData.location.pincode) || '800001';
const firstItem = (qcData && qcData.platformTotals && qcData.platformTotals[0] && qcData.platformTotals[0].cartItems && qcData.platformTotals[0].cartItems[0] && qcData.platformTotals[0].cartItems[0].cleanSearchTerm) || (window.__lastShoppingSearchItem || 'Sugar 1kg');
const platformsPayload = (qcData && Array.isArray(qcData.platformTotals))
? qcData.platformTotals.map(function(pt) {
return {
id: pt.platformId,
name: pt.platformName,
domain: pt.domain || '',
liveBrowserUrl: pt.liveBrowserUrl || (pt.cartItems && pt.cartItems[0] && (pt.cartItems[0].directProductUrl || pt.cartItems[0].url)) || pt.cartUrl
};
})
: [];
await fetch(getApiBaseUrl() + '/api/ba/start-shopping', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
item: firstItem,
platforms: platformsPayload,
pincode: pin,
targetUrl: customTargetUrl || '',
platformName: customPlatformName || ''
})
});
} catch (e) {}
};
window.buildQuickCompareCardHtml = function(data, loadId) {
const esc = window.escHtml;
const locObj = (data && data.location) || { city: 'Patna', pincode: '800001', label: 'Patna, Bihar, India (Pincode: 800001)' };
const locLabel = locObj.label || 'Patna, Bihar, India (800001)';
const pin = locObj.pincode || '800001';
const platTotals = Array.isArray(data && data.platformTotals) ? data.platformTotals : [];
const bestId = data && data.bestPlatform && data.bestPlatform.platformId;
const maxP = (data && data.maxPrice) || null;
const firstItemClean = (platTotals[0] && platTotals[0].cartItems && platTotals[0].cartItems[0] && platTotals[0].cartItems[0].cleanSearchTerm) || 'Sugar 1kg';
window.__lastShoppingSearchItem = firstItemClean;
const inr = function(n) { return '\u20B9' + Number(n).toLocaleString('en-IN'); };
const switchBtnsHtml = platTotals.map(function(pt) {
const safeUrl = String(pt.liveBrowserUrl || (pt.cartItems && pt.cartItems[0] && pt.cartItems[0].url) || pt.cartUrl || '').replace(/'/g, "\\'");
const safePlat = String(pt.platformName || 'Store').replace(/'/g, "\\'");
const safeItem = String(firstItemClean).replace(/'/g, "\\'");
return ``;
}).join('');
const colsHtml = platTotals.map(function(pt) {
const isWinner = !!bestId && pt.platformId === bestId;
const itemsHtml = (pt.cartItems || []).map(function(ci) {
const directUrl = ci.directProductUrl || ci.url || '#';
const img = ci.snappedImage || ci.imageUrl || '';
const imgHtml = img
? `
\uD83D\uDCF8 Live browser screenshot
`
: '';
if (!ci.verified) {
if (pt.platformId === 'blinkit' || /can't support blinkit/i.test(ci.reason || '')) {
return `