/**
 * A notification body split into text and https links, so a WhatsApp group
 * link the backend puts in the in-app «تم تسجيلك» notice (PDF p.28) can be
 * rendered as a real link — as React elements, never as injected HTML.
 *
 * Only `https:` URLs become links. Trailing punctuation a sentence puts after a
 * URL (`.`, `،`, `)` …) stays text, so it is not glued onto the href.
 */
export type MessageSegment =
  | { type: "text"; text: string }
  | { type: "link"; text: string; href: string };

const URL_PATTERN = /(https:\/\/[^\s<>"']+)/g;
const TRAILING_PUNCTUATION = /[.,;:!?،؛)\]}»"'’”]+$/;

export function splitMessageLinks(message: string): MessageSegment[] {
  const segments: MessageSegment[] = [];
  const pushText = (text: string) => {
    if (!text) return;
    const last = segments[segments.length - 1];
    if (last?.type === "text") last.text += text;
    else segments.push({ type: "text", text });
  };

  for (const part of message.split(URL_PATTERN)) {
    if (!part.startsWith("https://")) {
      pushText(part);
      continue;
    }
    const trailing = part.match(TRAILING_PUNCTUATION)?.[0] ?? "";
    const candidate = trailing ? part.slice(0, -trailing.length) : part;
    let href: string | null = null;
    try {
      const url = new URL(candidate);
      if (url.protocol === "https:" && url.hostname) href = url.href;
    } catch {
      href = null;
    }
    if (href) {
      segments.push({ type: "link", text: candidate, href });
      pushText(trailing);
    } else {
      pushText(part);
    }
  }
  return segments;
}
