import { QuickviewWordHighlight } from "./quickview-word-highlight.js";
import { TextParser } from "./text-parser.js";
const HIGHLIGHT_PREFIX = 'CoveoHighlight';
function findHighlightedElements(iframe) {
    const root = iframe?.contentDocument?.body;
    if (!root) return [];
    const selector = `[id^="${HIGHLIGHT_PREFIX}"]`;
    const query = root.querySelectorAll(selector);
    return Array.from(query);
}
class IframeParser {
    parse() {
        const elements = findHighlightedElements(this.iframe);
        for (const element of elements){
            const identifier = this.parseIdentifier(element);
            if (!identifier) throw new Error('Invalid keyword identifier for quickview');
            const text = this.textParser.parse(element);
            if (!text) continue;
            const alreadyScannedKeyword = this.wordsHighlights[identifier];
            if (alreadyScannedKeyword) {
                alreadyScannedKeyword.addElement(element);
                continue;
            }
            const color = element.style.backgroundColor;
            const highlight = new QuickviewWordHighlight(identifier, text, color, element);
            this.wordsHighlights[identifier] = highlight;
        }
        return this.wordsHighlights;
    }
    parseIdentifier(element) {
        const parts = element.id.substring(HIGHLIGHT_PREFIX.length + 1).match(/^([0-9]+)\.([0-9]+)\.([0-9]+)$/);
        if (!parts || parts.length <= 3) return null;
        return parts[1];
    }
    constructor(stemmingInfoFromIndex, iframe){
        this.stemmingInfoFromIndex = stemmingInfoFromIndex;
        this.iframe = iframe;
        this.textParser = new TextParser(this.stemmingInfoFromIndex);
        this.wordsHighlights = {};
    }
}
const getWordsHighlights = (stemmingInfoFromIndex, iframe)=>{
    const parser = new IframeParser(stemmingInfoFromIndex, iframe);
    return parser.parse();
};
export { HIGHLIGHT_PREFIX, getWordsHighlights };
