/**
 * Page URL normalisation
 * ───────────────────────
 * GSC ships full absolute URLs (`https://www.brand.com/es/page`), the
 * Site Tag script records whatever was in `window.location.pathname`
 * at the time (usually just `/es/page`), and the Content Audit table
 * in the UI can display either. Anything that compares URLs across
 * those three data sources needs to compare paths, not full URLs.
 *
 * normalizePath does the minimum work to produce a comparable path:
 *   • Strip protocol + host.
 *   • Strip trailing slash (unless the path IS the root).
 *   • Decode URL-encoded characters so /es/latin%20content matches
 *     /es/latin content.
 *   • Lower-case — healthcare paths occasionally appear mixed-case
 *     in GSC but lowercase from the tracker.
 *
 * Returns "/" for a root URL so the caller can `contains` safely.
 */
export function normalizePath(raw: string): string {
  if (!raw) return "";
  let s = raw.trim();
  // Strip protocol + hostname if present.
  try {
    if (/^https?:\/\//i.test(s)) s = new URL(s).pathname;
  } catch { /* fall through with the original string */ }
  try { s = decodeURI(s); } catch { /* leave encoded */ }
  s = s.toLowerCase();
  // Collapse repeated slashes, drop trailing slash unless it IS the root.
  s = s.replace(/\/+/g, "/");
  if (s.length > 1 && s.endsWith("/")) s = s.slice(0, -1);
  if (!s.startsWith("/")) s = "/" + s;
  return s;
}

/** Same normalisation applied to an array — used to pre-compute path
 *  sets for `contains`-free equality matching when we have a
 *  candidate list up front. */
export function normalizePaths(raws: string[]): string[] {
  return raws.map(normalizePath).filter((p) => p.length > 0);
}
