type WordEntry = { word: string; replacement: string };

let blockedWords: WordEntry[] = [];

export function setBlockedWords(words: WordEntry[]) {
  blockedWords = words ?? [];
}

export function filterText(text: string): string {
  if (!text || !blockedWords.length) return text;
  let result = text;
  for (const entry of blockedWords) {
    if (!entry.word) continue;
    const escaped = entry.word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    result = result.replace(new RegExp(escaped, 'gi'), entry.replacement);
  }
  return result;
}

export async function loadBlockedWords(): Promise<void> {
  try {
    const res = await fetch('/api/config/blocked-words', { credentials: 'include' });
    if (!res.ok) return;
    const data = (await res.json()) as { words?: WordEntry[] };
    setBlockedWords(data.words ?? []);
  } catch {
    // fail silently — filtering is best-effort
  }
}
