/**
 * Extract a probable target keyword from a URL slug or page title.
 * Used by the Competitor Intel gap bridge to turn content gap pages
 * into keyword-level opportunities.
 */

export function extractKeywordFromUrl(url: string): string {
  try {
    const pathname = new URL(url).pathname;
    const segments = pathname.split("/").filter(Boolean);
    // Skip language prefixes (es, en, fr, etc.) and common generic segments
    const skip = new Set(["news", "blog", "articles", "posts", "category", "tag", "page", "es", "en", "fr", "de", "pt"]);
    const meaningful = segments.filter((s) => s.length > 2 && !skip.has(s));
    const slug = meaningful[meaningful.length - 1] ?? "";
    return slug
      .replace(/[-_]/g, " ")
      .replace(/\s+/g, " ")
      .trim()
      .toLowerCase();
  } catch {
    return url
      .replace(/^https?:\/\/[^/]+\/?/, "")
      .replace(/[-_/]/g, " ")
      .replace(/\s+/g, " ")
      .trim()
      .toLowerCase();
  }
}

export function extractKeywordFromTitle(title: string | null, domain: string): string | null {
  if (!title) return null;
  // Strip brand name / domain from title: "PET Scan | Vital Heart" → "PET Scan"
  const cleaned = title
    .split(/\s*[|–—·]\s*/)
    .filter((part) => !domain.toLowerCase().includes(part.toLowerCase().trim().split(" ")[0]))
    .join(" ")
    .trim();
  return cleaned.length > 3 ? cleaned.toLowerCase() : null;
}
