/**
 * Derive a friendly site name from a URL or bare domain string.
 *
 * Used by Pages/Sites/Create to auto-fill the Site Name field as the user
 * types a domain — removing a redundant typing step before the onboarding
 * wizard. The user can still override the derived name; the component
 * tracks a "name touched" flag so we never overwrite manual edits.
 *
 * Examples:
 *   "https://myblog.com"       → "Myblog"
 *   "https://www.example.org"  → "Example"
 *   "my-blog.com"              → "My Blog"
 *   "blog.example.com"         → "Blog Example"
 *   ""                         → ""
 *
 * Falls back to an empty string for any input that does not look like a
 * URL or domain so we never replace the user's typed value with garbage.
 */
export function deriveSiteNameFromDomain(input: string): string {
  if (!input) return '';
  let host = input.trim();
  // Strip protocol
  host = host.replace(/^https?:\/\//i, '');
  // Strip path / query / hash / port. Forward-slash inside a character class
  // does not need escaping.
  host = host.split(/[/?#:]/)[0];
  // Strip leading www.
  host = host.replace(/^www\./i, '');
  if (!host) return '';
  // Drop the public suffix (TLD) — keep everything before the last dot.
  // For multi-part hosts (e.g. blog.example.com) we keep all subdomain
  // segments so the name remains specific.
  const lastDot = host.lastIndexOf('.');
  const stem = lastDot > 0 ? host.slice(0, lastDot) : host;
  if (!stem) return '';
  // Tokenize on dots, hyphens, and underscores then capitalise.
  const words = stem
    .split(/[.\-_]+/)
    .filter(Boolean)
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1));
  return words.join(' ');
}
