interface ParsedName {
  family?: string
  given?: string[]
  prefix?: string[]
  suffix?: string[]
}

export function parseName(fullName?: string): ParsedName {
  let prefix: string[] = []
  let suffix: string[] = []
  let given: string[] = []
  let family: string | null = null
  const result: ParsedName = {}

  if (fullName === undefined) {
    return result
  }

  const parts = fullName.trim().split(/\s+/)

  // Cek awalan (prefix)
  while (
    parts.length > 0 &&
    (parts[0].includes('.') || parts[0].includes(','))
  ) {
    prefix.push(parts.shift()!)
  }

  // Cek akhiran (suffix)
  while (parts.length > 0 && parts[parts.length - 1].includes('.')) {
    suffix.push(parts.pop()!)
  }

  if (parts.length === 1) {
    given.push(parts[0].toLowerCase().replace(/\b\w/g, (s) => s.toUpperCase()))
  } else if (parts.length > 1) {
    family = parts
      .pop()!
      .toLowerCase()
      .replace(/\b\w/g, (s) => s.toUpperCase())
    for (let i = 0; i < parts.length; i++) {
      given.push(
        parts[i].toLowerCase().replace(/\b\w/g, (s) => s.toUpperCase()),
      )
    }
  }

  if (family) {
    result.family = family
  }
  if (given.length > 0) {
    result.given = given
  }
  if (prefix.length > 0) {
    result.prefix = prefix
  }
  if (suffix.length > 0) {
    result.suffix = suffix.reverse()
  }

  return result
}
