/**
 * Card #432 — hide inline block markers while a reply is streaming.
 *
 * The LLM emits self-closing markers inline — <product/>, <pricing/>,
 * <case-study/>, <coupon/>, <suggestions/>, <checkout/>. The SERVER strips
 * them post-stream (InlineBlockParser) and re-emits them as block cards on the
 * `done` event, at which point the widget's finalizeMessage swaps the streamed
 * bubble for the cleaned text. But WHILE tokens arrive, message.content still
 * contains the raw marker XML, and the bubble renders it (pre-wrap) — so the
 * visitor briefly sees "<product title=…/>" until `done` lands. This strips the
 * markers at render time so that never shows.
 *
 * Two shapes are handled:
 *   1. A COMPLETE self-closing marker anywhere in the text: <product …/>.
 *   2. A PARTIAL marker still streaming at the very end: "<product title="…"
 *      (no closing "/>" yet), or just the tag name growing in ("<produ").
 *
 * The trailing case is deliberately narrow — a known tag name with attributes
 * in progress, OR a bare "<" + partial lowercase tag name — so a legitimate
 * "<" in prose ("5 < 10", "<3") is never touched. Pure, like
 * {@link stripInlineCitations}; a no-op on finalized text (already stripped
 * server-side).
 */

const BLOCK_TAGS =
    'product|pricing|case-study|coupon|suggestions|checkout|lead-form|lead_form';

/** A fully-formed self-closing marker: <product … />. */
const COMPLETE_MARKER = new RegExp(`\\s*<(?:${BLOCK_TAGS})\\b[^>]*?/>`, 'gi');

/**
 * A marker still streaming at the END of the text: either a known tag whose
 * attributes are still arriving (no ">" yet), or a bare "<" followed by a
 * partial tag name (letters/hyphens only, before any space or attribute).
 * Anchored to end-of-string so it only hides the in-flight marker.
 */
const PARTIAL_TRAILING_MARKER = new RegExp(
    `\\s*<(?:(?:${BLOCK_TAGS})\\b[^>]*|[a-z_-]*)$`,
    'i',
);

export function stripBlockMarkers(text: string): string {
    if (text.indexOf('<') === -1) {
        return text;
    }

    return text
        .replace(COMPLETE_MARKER, '')
        .replace(PARTIAL_TRAILING_MARKER, '');
}
