const escapeHtml = (value: string): string =>
  value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

export const buildSnippet = (text: string | null, keyword: string | null): string => {
  const source = (text ?? "").trim();
  if (!source) {
    return "暂无正文内容";
  }
  const safeSource = escapeHtml(source);
  if (!keyword) {
    return `${safeSource.slice(0, 120)}${safeSource.length > 120 ? "…" : ""}`;
  }
  const pattern = new RegExp(escapeRegExp(keyword), "gi");
  const match = pattern.exec(safeSource);
  if (!match) {
    return `${safeSource.slice(0, 120)}${safeSource.length > 120 ? "…" : ""}`;
  }
  const start = Math.max(0, match.index - 20);
  const end = Math.min(safeSource.length, match.index + keyword.length + 80);
  const segment = safeSource.slice(start, end);
  return segment.replace(pattern, (found) => `<mark>${found}</mark>`);
};
