/**
 * String formatting utilities
 * Centralized functions for string manipulation and formatting
 */

/**
 * Creates a URL-friendly slug from a title string
 * Removes special characters, converts to lowercase, and replaces spaces with hyphens
 * @param title - The title string to convert to a slug
 * @returns URL-friendly slug string
 */
export const createSlug = (title: string) => {
  if (!title) return '';

  return title
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, '') // Remove special characters
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/-+/g, '-') // Replace multiple hyphens with single
    .trim();
};

/**
 * Capitalizes the first letter of a string
 * @param str - The string to capitalize
 * @returns String with first letter capitalized
 */
export const capitalize = (str: string) => {
  if (!str) return '';
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};

/**
 * Converts a string to title case
 * @param str - The string to convert
 * @returns String in title case
 */
export const toTitleCase = (str: string) => {
  if (!str) return '';
  return str
    .toLowerCase()
    .split(' ')
    .map(word => capitalize(word))
    .join(' ');
};

/**
 * Truncates text to a specified length with ellipsis
 * @param text - The text to truncate
 * @param maxLength - Maximum length before truncation
 * @param suffix - Suffix to add when truncated (default: '...')
 * @returns Truncated text with suffix if needed
 */
export const truncateText = (
  text: string,
  maxLength: number,
  suffix: string = '...'
): string => {
  if (!text || text.length <= maxLength) return text;
  return text.substring(0, maxLength - suffix.length) + suffix;
};

/**
 * Removes extra whitespace and normalizes spacing
 * @param str - The string to normalize
 * @returns String with normalized whitespace
 */
export const normalizeWhitespace = (str: string) => {
  if (!str) return '';
  return str.replace(/\s+/g, ' ').trim();
};

/**
 * Converts camelCase or PascalCase to kebab-case
 * @param str - The string to convert
 * @returns String in kebab-case
 */
export const toKebabCase = (str: string) => {
  if (!str) return '';
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
};

/**
 * Converts kebab-case or snake_case to camelCase
 * @param str - The string to convert
 * @returns String in camelCase
 */
export const toCamelCase = (str: string) => {
  if (!str) return '';
  return str
    .replace(/[-_](.)/g, (_, char) => char.toUpperCase())
    .replace(/^[A-Z]/, char => char.toLowerCase());
};
