import type { Mention } from './mentions';

export interface MarkPart {
  text: string;
  mark: boolean;
}

/** The composer text split so picked mention names and emote shortcodes can be highlighted behind the textarea. */
export function markMentions(text: string, mentions: Mention[], extra: string[] = []): MarkPart[] {
  const names = [...new Set([...mentions.map((m) => m.text), ...extra].filter(Boolean))].sort((a, b) => b.length - a.length);
  if (!names.length || !text) return [{ text, mark: false }];
  const parts: MarkPart[] = [];
  let rest = text;
  while (rest) {
    let at = -1;
    let hit = '';
    for (const name of names) {
      const i = rest.indexOf(name);
      if (i >= 0 && (at < 0 || i < at)) {
        at = i;
        hit = name;
      }
    }
    if (at < 0) {
      parts.push({ text: rest, mark: false });
      break;
    }
    if (at > 0) parts.push({ text: rest.slice(0, at), mark: false });
    parts.push({ text: hit, mark: true });
    rest = rest.slice(at + hit.length);
  }
  return parts;
}
