// docforge-editor — shared, framework-agnostic editor utilities.
//
// Slice 5 of the docforge train (t-paliad-349 / m/paliad#157) begins
// extracting the generic editor plumbing out of the submission-specific
// client bundle so a second consumer (and the slice-6 authoring page) can
// reuse it. This module holds the pure DOM-string helpers — no DOM
// mutation, no editor state — so they unit-test cleanly under bun.

// escapeHtml escapes the five HTML-significant characters for safe
// insertion into element text or an attribute value. Matches the
// server-side emitTextWithDraftVars/htmlEscape contract so preview markup
// round-trips identically.
export function escapeHtml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

// cssEscape escapes a string for use inside a CSS attribute selector
// (e.g. `[data-var="${cssEscape(key)}"]`). Prefers the native CSS.escape
// and falls back to escaping CSS-special characters for older runtimes.
// Placeholder keys ([A-Za-z][A-Za-z0-9_.]*) never carry whitespace or
// quotes, so the fallback is straightforward.
export function cssEscape(s: string): string {
  if (typeof CSS !== "undefined" && typeof CSS.escape === "function") {
    return CSS.escape(s);
  }
  return s.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, "\\$1");
}
