import type { ReactNode } from "react";

/** Normaliza marcadores *destaque* (inclui variantes Unicode e **markdown**). */
export function normalizeHighlightMarkers(text: string): string {
  return text
    .replace(/[\u2217\uFF0A\u2055\u204E\u2731]/g, "*")
    .replace(/\*\*(.+?)\*\*/g, "*$1*")
    .replace(/\u200B|\uFEFF/g, "");
}

/** Limpa título para salvar/exibir (uma linha, sem duplicação do canvas). */
export function normalizeHeadlineValue(text: string): string {
  const v = normalizeHighlightMarkers(text).replace(/\s+/g, " ").trim();
  if (v.length < 30) return v;

  const mid = Math.floor(v.length / 2);
  for (let len = mid; len >= 20; len--) {
    const first = v.slice(0, len).trim();
    const second = v.slice(len).trim();
    if (!second || !first) continue;
    const probe = first.slice(0, Math.min(first.length, 28));
    if (second.startsWith(probe)) return first;
  }
  return v;
}

/** Converte *trecho* em spans com classe .pop para destaque no título. */
export function formatHeadline(text: string): ReactNode {
  const normalized = normalizeHeadlineValue(text);
  const parts = normalized.split(/\*(.+?)\*/g);
  if (parts.length === 1) return normalized;

  return parts.map((part, i) =>
    i % 2 === 1 ? (
      <span className="pop" key={i}>
        {part}
      </span>
    ) : (
      <span key={i}>{part}</span>
    )
  );
}
