import type { SamplePlant } from '../../types/appTypes';
import type { SavedPlantProfile } from '../../types/plantScan';

const CONFIDENCE_SUFFIX = /\s*(?:[-\u2013\u2014]\s*)?\d+(?:\.\d+)?%\s*(?:confidence)?\s*$/i;

function stripConfidenceSuffix(value?: string | null): string {
  return typeof value === 'string'
    ? value.replace(CONFIDENCE_SUFFIX, '').replace(/\s+/g, ' ').trim()
    : '';
}

function titleCaseWord(word: string): string {
  if (/^[A-Z]{2,3}$/.test(word)) return word;
  return word
    .split('-')
    .map(part => part ? `${part.charAt(0).toUpperCase()}${part.slice(1).toLowerCase()}` : part)
    .join('-');
}

function normalizeCommonNameCase(value: string): string {
  const letters = value.replace(/[^A-Za-z]/g, '');
  if (!letters) return value;

  const isUniformCase = letters === letters.toLowerCase() || letters === letters.toUpperCase();
  if (!isUniformCase) return value;
  return value.replace(/[A-Za-z][A-Za-z'-]*/g, titleCaseWord);
}

export function cleanPlantDisplayName(value?: string | null): string {
  const clean = stripConfidenceSuffix(value);
  return clean ? normalizeCommonNameCase(clean) : 'Plant';
}

export function getSavedPlantDisplayName(plant: SavedPlantProfile): string {
  const preferredName = [plant.name, plant.commonName]
    .map(stripConfidenceSuffix)
    .find(Boolean);
  return cleanPlantDisplayName(preferredName);
}

export function getSamplePlantDisplayName(plant: SamplePlant): string {
  return cleanPlantDisplayName(plant.name);
}

export function cleanScientificName(value?: string | null): string {
  const clean = stripConfidenceSuffix(value);
  if (!clean) return '';

  let botanicalWordIndex = 0;
  return clean
    .split(/(\s+)/)
    .map(token => {
      if (!/[A-Za-z]/.test(token) || token === '×') return token;
      if (/^[\"']/.test(token)) return token;

      if (botanicalWordIndex === 0) {
        botanicalWordIndex += 1;
        return token.replace(/[A-Za-z][A-Za-z-]*/, word =>
          `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`,
        );
      }

      if (botanicalWordIndex === 1) {
        botanicalWordIndex += 1;
        return token.replace(/[A-Za-z][A-Za-z-]*/, word => word.toLowerCase());
      }

      return token;
    })
    .join('');
}
