/**
 * The 280-character post limit (PDF p.26), counted the way the server counts it.
 *
 * A post is sent as multipart (`communityApi.ts`), and a browser serialises every
 * line break in a multipart text field as CRLF. `CommunityText::normalize()` then
 * measures the raw string with `mb_strlen`, so each line break costs 2 characters
 * there but 1 in the textarea. Counting a break as 2 here keeps the form counter
 * and the server in agreement: a post that shows 280/280 is never refused.
 * (Code points, like `mb_strlen`, not UTF-16 units.)
 */
export const POST_MAX_LENGTH = 280;

const LINE_BREAK = /\r\n|\r|\n/g;

export function postTextLength(text: string | null | undefined): number {
  return Array.from((text ?? "").replace(LINE_BREAK, "\r\n")).length;
}

/** Cuts the text at the last character that still fits the limit. */
export function clampPostText(text: string, max = POST_MAX_LENGTH): string {
  let used = 0;
  const kept: string[] = [];
  for (const ch of text.replace(LINE_BREAK, "\n")) {
    const cost = ch === "\n" ? 2 : 1;
    if (used + cost > max) break;
    kept.push(ch);
    used += cost;
  }
  return kept.join("");
}
