/**
 * Split post text into plain runs and hashtags.
 *
 * `\p{L}` rather than `\w`, with the `u` flag: community posts are written in
 * Arabic as often as English, and `#تطوع` has to be recognised as a tag. This
 * is the parsing half of `HashtagText`, kept pure so the Unicode behaviour can
 * be tested without rendering.
 */
/*
 * Kept identical to the backend extractor (`CommunityText::hashtags`): combining
 * marks (`\p{M}`) belong to a tag, so an Arabic tag with diacritics is one tag, and a
 * `#` that follows a letter, mark, digit or underscore (`abc#x`) is not a tag at all —
 * otherwise the site draws a link the post does not carry and `?tag=` finds nothing.
 */
export const HASHTAG_PATTERN = /(?<![\p{L}\p{M}\p{N}_])#([\p{L}\p{M}\p{N}_]+)/gu;

export type HashtagSegment =
  | { kind: "text"; value: string; at: number }
  /** `value` is the tag without its `#`. */
  | { kind: "tag"; value: string; at: number };

export function splitHashtags(text: string): HashtagSegment[] {
  if (!text) return [];

  const segments: HashtagSegment[] = [];
  let lastIndex = 0;
  let match: RegExpExecArray | null;

  // A fresh regex per call: `lastIndex` on a shared global regex would leak
  // between calls and start the next parse mid-string.
  const pattern = new RegExp(HASHTAG_PATTERN);

  while ((match = pattern.exec(text)) !== null) {
    if (match.index > lastIndex) {
      segments.push({
        kind: "text",
        value: text.substring(lastIndex, match.index),
        at: lastIndex,
      });
    }
    segments.push({ kind: "tag", value: match[1], at: match.index });
    lastIndex = match.index + match[0].length;
  }

  if (lastIndex < text.length) {
    segments.push({ kind: "text", value: text.substring(lastIndex), at: lastIndex });
  }

  return segments;
}
