/* Utility functions for search results parser. */
function add(r, n, t) { for (var e = [], u = Math.max(r.length, n.length), l = 0, o = 0; o < u || l;) { var a, i = l + (o < r.length ? r[o] : 0) + (o < n.length ? n[o] : 0); e.push(i % t), l = Math.floor(i / t), o++ } return e } function multiplyByNumber(r, n, t) { if (r < 0) return null; if (0 == r) return []; for (var e = [], u = n; 1 & r && (e = add(e, u, t)), 0 != (r >>= 1);)u = add(u, u, t); return e } function parseToDigitsArray(r, n) { for (var t = r.split(""), e = [], u = t.length - 1; u >= 0; u--) { var l = parseInt(t[u], n); if (isNaN(l)) return null; e.push(l) } return e } function decToHex(r) { var n = convertBase(r, 10, 16); return n ? "0x" + n : null } function convertBase(r, n, t) { var e = parseToDigitsArray(r, n); if (null === e) return null; for (var u = [], l = [1], o = 0; o < e.length; o++)e[o] && (u = add(u, multiplyByNumber(e[o], l, t), t)), l = multiplyByNumber(n, l, t); for (var a = "", o = u.length - 1; o >= 0; o--)a += u[o].toString(t); return a } function hexToDec(r) { return "0x" === r.substring(0, 2) && (r = r.substring(2)), convertBase(r = r.toLowerCase(), 16, 10) }
const getText = (element, selector) => {
    const el = element.querySelector(selector);
    return el ? el.innerText.trim() : null;
};
function getAddressFromLink(element) {
    const url = element.getAttribute('href');
    
    if (!url) return null;
    const match = url.match(/\/maps\/dir\/\/(.*?)\/data=/);

    if (match && match[1]) {
        const withSpaces = match[1].replace(/\+/g, ' ');
        return decodeURIComponent(withSpaces);
    }

    return null;
}
const isOnlyDigits = (str) => {
  // 1. Remove ALL whitespace characters globally
  if (!str) {
	return false;
  }
  const cleanedStr = str.replace(/\s/g, ''); 
  
  // 2. Now check the cleaned string for strict digits
  const isOnlyDigits = /^\d+$/.test(cleanedStr);
  
  return isOnlyDigits
};

async function* dataParser () {
	const items = document.querySelectorAll('[jscontroller="AtSb"]');
	
	if (!items) {
		console.log('No results found');
		return null;
	}

	for (const item of items) {
		const data = item.querySelector('.rllt__details');
		const links = Array.from(item.querySelectorAll('a'));

		const name = getText(data, '[role="heading"]');
		
		const cidData = item.querySelector('[data-cid]');
		let cid = cidData?.getAttribute('data-cid');
		// let lat = cidData?.getAttribute('data-lat');
		// let long = cidData?.getAttribute('data-lng');
		let rating = getText(data, '.yi40Hd');

		let numberOfReviews = getText(data, '.RDApEe');
		if (numberOfReviews) {
			// Remove parentheses
			numberOfReviews = numberOfReviews.replace(/[()]/g, '').trim();
		}

		let category = null;
		const ratingContainer = data.querySelector('.Y0A0hc')?.closest('div');
		
		if (ratingContainer) {
			const text = ratingContainer.innerText;
			if (text.includes('·')) {
			category = text.split('·').pop().trim();
			}
		}

		let phoneNumber = null;
		const divs = Array.from(data.children);
		
		for (const div of divs) {
			const text = div.innerText;
			if (text.includes('·')) {
				const parts = text.split('·');
				const potentialPhone = parts[parts.length - 1].trim();
				
				if (potentialPhone !== category && /\d/.test(potentialPhone)) {
					phoneNumber = potentialPhone;
				}
			}
		}
		if (!phoneNumber || !isOnlyDigits(phoneNumber)) {
			phoneNumber = "";
		}

		// Address
		let full_address = null;
		let address = null;
		const addLink = links.find(a => {
			const href = a.getAttribute('href');
			return href && href.includes('/maps/dir');
		});

		let websiteLink = links.slice(1).find(l => l.textContent.toLowerCase().includes('website'));
		let website = websiteLink?.href;
		
		if (true) { // click the panel for every result.
			data.querySelector('[role="heading"]').click();
			await sleep(3000);

			const panel =  document.querySelector('.xpdopen') || document.querySelector('g-sticky-content-container');
			full_address = getText(panel, '.LrzXr');

			const panelPhoneElement = document.querySelector('[data-phone-number]');
			if (panelPhoneElement) {
				phoneNumber = panelPhoneElement.getAttribute('data-phone-number');
			}
			
			const panelLinks = Array.from(panel.querySelectorAll("div[jsname='UXbvIb'] a"));
			websiteLink = panelLinks.find(l => l.textContent.toLowerCase().includes('website'));
			website = websiteLink?.href;

			if (!cid) {
				cid = item.querySelector('[data-cid]')?.getAttribute('data-cid');
			}

		} else {
			full_address = getAddressFromLink(addLink);
		}
		let pincode = "";
		let city = "";
		let state = "";

		if (full_address && !isOnlyDigits(full_address)) {
			address = full_address.split('=').slice(-1)[0].replace(/\+/g, ' ');
			pincode = address ? address.match(/\b[1000-999999]+\b/g) : "";
			pincode = pincode.length ? pincode?.pop() : "";
			city = address?.split(',')[0]?.trim();
			state = address?.split(',')[1]?.trim();
		}
		

		
		
		// if there is no website, then check if it's availabe in panel
		
		yield {
			company_name: name,
			cid: cid ? cid : "",
			category: category,
			phone: phoneNumber,
			website: website,
			review: numberOfReviews,
			rating_count: rating,
			city: city,
			state: state,
			// lat: lat,
			// long: long,
			pincode: pincode,
			address: address
		}
	}
}
