/**
 * Texto de documento unificado para tabla y cards (mismas fuentes de datos que la columna Documento).
 * @param {object} row
 * @param {string} [fallbackValue]
 * @returns {string}
 */
export function buildPersonaDocumentoLabel(row, fallbackValue) {
  const rawCombined =
    row?.documento
    ?? row?.document
    ?? row?.documentoCompleto
    ?? row?.nroDocumento
    ?? row?.numeroDocumento
    ?? row?.dni
    ?? row?.legalIdentifierNumber
    ?? row?.legalIdentifier?.number
    ?? fallbackValue
    ?? '';

  const rawType =
    row?.tipoDocumento
    ?? row?.documentType
    ?? row?.tipo_documento
    ?? row?.legalIdentifierType
    ?? row?.legalIdentifier?.type
    ?? '';

  const rawNumber =
    row?.numeroDocumento
    ?? row?.documentNumber
    ?? row?.nroDocumento
    ?? row?.numero_documento
    ?? row?.dni
    ?? row?.legalIdentifierNumber
    ?? row?.legalIdentifier?.number
    ?? '';

  const normalizeType = (v) => String(v ?? '').trim();
  const normalizeNumber = (v) => String(v ?? '').trim();

  const combined = String(rawCombined ?? '').trim();
  const mColon = combined.match(/^([^:]+):\s*(.+)$/);
  if (mColon) {
    const type = normalizeType(mColon[1]);
    const number = normalizeNumber(mColon[2]);
    if (!type && !number) return '';
    if (!type) return number;
    if (!number) return `${type}:`;
    return `${type}: ${number}`;
  }

  const typeFromFields = normalizeType(rawType);
  const numberFromFields = normalizeNumber(rawNumber);
  if (typeFromFields || numberFromFields) {
    if (typeFromFields && numberFromFields) return `${typeFromFields}: ${numberFromFields}`;
    if (typeFromFields) return `${typeFromFields}:`;
    return numberFromFields;
  }

  const mSpace = combined.match(/^([A-Za-zÁÉÍÓÚÜÑáéíóúüñ]+)\s*[-\s]\s*(.+)$/);
  if (mSpace) {
    const type = normalizeType(mSpace[1]);
    const number = normalizeNumber(mSpace[2]);
    if (type && number) return `${type}: ${number}`;
  }

  return combined;
}
