// The Lucia project.
// Copyright 2023-2026 DSP, inc.  All rights reserved.
// Authors:
//   chiayin.kuo@dsp.im (chiayin), 2023/1/31
//   imacat.yang@dsp.im (imacat), 2023/9/23
//   cindy.chang@dsp.im (Cindy Chang), 2024/5/30
/** @module abbreviateNumber Duration abbreviation formatting. */

/**
 * Converts a total number of seconds into a human-readable abbreviated
 * duration string using days, hours, minutes, and seconds.
 *
 * @param {number} totalSeconds - The total number of seconds to convert.
 * @returns {string} The abbreviated duration string (e.g. "2d 3h 15m 30s"),
 *   or "0" if totalSeconds is zero.
 */
export default function abbreviateNumber(totalSeconds) {
  let seconds = 0;
  let minutes = 0;
  let hours = 0;
  let days = 0;
  let result = "";
  let symbols = ["d", "h", "m", "s"];

  totalSeconds = Number.parseInt(totalSeconds);
  if (!Number.isNaN(totalSeconds)) {
    seconds = totalSeconds % 60;
    minutes = (Math.floor(totalSeconds - seconds) / 60) % 60;
    hours = Math.floor(totalSeconds / 3600) % 24;
    days = Math.floor(totalSeconds / (3600 * 24));
  }

  const units = [days, hours, minutes, seconds];
  for (let i = 0; i < units.length; i++) {
    if (units[i] > 0) result += units[i] + symbols[i] + " ";
  }
  result = result.trim();
  if (totalSeconds === 0) result = "0";

  return result;
}
