import { GRIDDO_ID } from "@ax/constants";

const countKeywords = (html: HTMLDivElement, keywords: string[]) => {
	const frameObject = html.querySelector<HTMLIFrameElement>(".frame-content");
	const frameContent = frameObject?.contentWindow?.document.getElementById(GRIDDO_ID) as HTMLElement;

	if (!frameContent) {
		return {};
	}

	const htmlContent = frameContent.innerText.toLowerCase().normalize("NFC");
	const keywordCounts: Record<string, number> = {};

	keywords.forEach((keyword) => {
		const lowerKeyword = keyword.toLowerCase().normalize("NFC");
		const regex = new RegExp(lowerKeyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi");
		const matches = htmlContent.match(regex);
		keywordCounts[keyword] = matches ? matches.length : 0;
	});

	return keywordCounts;
};

export { countKeywords };
