/** Decode file/folder labels when API still returns URL-encoded segments. */
export function displayFileName(name: string): string {
  if (!name.includes("%")) {
    return name
  }
  try {
    return decodeURIComponent(name.replace(/\+/g, " "))
  } catch {
    return name
  }
}

function decodedBaseName(name: string): string {
  const decoded = displayFileName(name)
  return decoded.split("/").pop() ?? decoded
}

/** File name without the last extension segment (folders unchanged). */
export function displayFileBaseName(name: string, isDirectory = false): string {
  if (isDirectory) return displayFileName(name)
  const base = decodedBaseName(name)
  const dot = base.lastIndexOf(".")
  if (dot <= 0) return displayFileName(name)
  return base.slice(0, dot)
}

export function fileNameExtension(name: string): string | null {
  const base = decodedBaseName(name)
  const dot = base.lastIndexOf(".")
  if (dot <= 0) return null
  return base.slice(dot + 1).toLowerCase()
}

/** Extension label for list column (uppercase); folders show « Dossier ». */
export function displayFileFormatLabel(
  name: string,
  isDirectory = false
): string {
  if (isDirectory) return "Dossier"
  const ext = fileNameExtension(name)
  if (!ext) return "—"
  return ext.toUpperCase()
}
