// escape regex special chars
export function escapeRegex(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// punctuation pattern
export const punctuation = `[.,!?;:"'()\\[\\]{}]*`;

// Highlight words in a part
export function addSpan(part, found, wordOffsets, punctuation, counterRef) {
   
    if (part.startsWith("<") && part.endsWith(">")) {
        return part;
    }

    found.forEach((match, matchIndex) => {
        const regex = new RegExp(`\\b(${escapeRegex(match.bad)})\\b(${punctuation})`, "gi");

        part = part.replace(regex, (match, word, punctuation) => {
            const spanId = `wg-span-${counterRef.current}`;
            wordOffsets.push({
                word,
                spanId,
                matchIndex,
                note: match.note || "",
            });

            const span = `<span id="${spanId}" class="wg-span" data-index="${counterRef.current}" data-word="${word.toLowerCase()}">${word}</span>${punctuation || " "}`;
            counterRef.current += 1;
            return span;
        });
    });

    return part;
}

// Handles word wrapping
export function wordWrapHandler(found, postContent, punctuation, counterRef) {
    let highlighted = postContent;
    const wordOffsets = [];

    // Split into text vs tags
    highlighted = highlighted.replace(/(<[^>]+>)/g, "|||$1|||");
    let parts = highlighted.split("|||");

    parts = parts.map((part) => addSpan(part, found, wordOffsets, punctuation, counterRef));
    highlighted = parts.join("");

    return { highlighted, wordOffsets };
}
