// Utility to resolve asset URLs. If the input starts with /uploads, resolve it against the API base URL
// so that in development the images are loaded from the backend (e.g., http://localhost:8080/uploads/...)
// and in production it resolves relative to the deployed backend origin.
export function assetUrl(pathOrUrl?: string | null): string | undefined {
  if (!pathOrUrl) return undefined;
  try {
    // If already absolute (http/https/data), return as-is
    if (/^(?:https?:)?\/\//i.test(pathOrUrl) || /^data:/i.test(pathOrUrl)) {
      return pathOrUrl;
    }
    // Rewrite known backend-served asset paths (/uploads, /dist)
    if (pathOrUrl.startsWith('/uploads') || pathOrUrl.startsWith('/dist')) {
      const base = process.env.REACT_APP_API_BASE_URL || process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1';
      // We want the backend origin, not the API path. Construct from the base.
      const baseUrl = new URL(base);
      baseUrl.pathname = '/';
      return new URL(pathOrUrl, baseUrl).toString();
    }
    // Otherwise return as-is (relative or other paths)
    return pathOrUrl;
  } catch {
    return pathOrUrl || undefined;
  }
}

export function isUploadPath(pathOrUrl?: string | null): boolean {
  return !!pathOrUrl && /^\/uploads\//.test(pathOrUrl);
}

/**
 * Sanitizes club names by removing common suffixes and abbreviating long formal names
 * Examples:
 *  - "Tělovýchovná jednota Valašské Meziříčí, spolek" -> "TJ Valašské Meziříčí"
 *  - "MFK Slavoj Bruntál, z. s." -> "MFK Slavoj Bruntál"
 */
export function sanitizeClubName(name?: string | null): string {
  if (!name) return '';
  
  let sanitized = name.trim();
  
  // Replace full form "Tělovýchovná jednota" with "TJ"
  sanitized = sanitized.replace(/^Tělovýchovná jednota\s+/i, 'TJ ');
  
  // Replace full form "Sportovní klub" with "SK"
  sanitized = sanitized.replace(/^Sportovní klub\s+/i, 'SK ');
  
  // Replace full form "Fotbalový klub" with "FK"
  sanitized = sanitized.replace(/^Fotbalový klub\s+/i, 'FK ');
  
  // Replace full form "Fotbal klub" with "FK"
  sanitized = sanitized.replace(/^Fotbal klub\s+/i, 'FK ');
  
  // Replace full form "Sokol" abbreviation
  sanitized = sanitized.replace(/^Sokol\s+/i, 'SK ');
  
  // Remove common legal suffixes at the end
  sanitized = sanitized.replace(/,\s*(spolek|z\.\s*s\.|o\.\s*s\.|z\s*s|o\s*s|spolková\s+organizace|spolek\s+registrovaný|z\.s\.|o\.s\.)$/i, '');
  
  return sanitized.trim();
}
