'use strict';

function formatDuration(milliseconds, options = {}) {
  const { maxDisplayUnits = 2, minUnit = "second" } = options;
  const effectiveMaxDisplayUnits = Math.max(1, maxDisplayUnits);
  if (milliseconds < 0 || milliseconds === 0) {
    const minUnitValue2 = minUnit || "second";
    return [{ value: 0, unit: minUnitValue2 }];
  }
  const units = [
    { value: 365 * 24 * 60 * 60 * 1e3, unit: "year" },
    { value: 30 * 24 * 60 * 60 * 1e3, unit: "month" },
    { value: 7 * 24 * 60 * 60 * 1e3, unit: "week" },
    { value: 24 * 60 * 60 * 1e3, unit: "day" },
    { value: 60 * 60 * 1e3, unit: "hour" },
    { value: 60 * 1e3, unit: "minute" },
    { value: 1e3, unit: "second" },
    { value: 1, unit: "millisecond" }
  ];
  const minUnitValue = minUnit || "second";
  const minUnitIndex = units.findIndex((u) => u.unit === minUnitValue);
  if (minUnitIndex === -1) {
    const defaultMinUnitIndex = units.findIndex((u) => u.unit === "second");
    const filteredUnits2 = units.slice(0, defaultMinUnitIndex + 1);
    const parts2 = [];
    let remaining2 = milliseconds;
    for (const unitDef of filteredUnits2) {
      if (remaining2 >= unitDef.value) {
        const count = Math.floor(remaining2 / unitDef.value);
        remaining2 = remaining2 % unitDef.value;
        parts2.push({
          value: count,
          unit: unitDef.unit
        });
        if (parts2.length >= effectiveMaxDisplayUnits) {
          break;
        }
      }
    }
    if (parts2.length === 0) {
      return [{ value: 0, unit: "second" }];
    }
    return parts2;
  }
  const filteredUnits = units.slice(0, minUnitIndex + 1);
  const parts = [];
  let remaining = milliseconds;
  for (const unitDef of filteredUnits) {
    if (remaining >= unitDef.value) {
      const count = Math.floor(remaining / unitDef.value);
      remaining = remaining % unitDef.value;
      parts.push({
        value: count,
        unit: unitDef.unit
      });
      if (parts.length >= effectiveMaxDisplayUnits) {
        break;
      }
    }
  }
  if (parts.length === 0) {
    return [{ value: 0, unit: minUnitValue || "second" }];
  }
  return parts;
}

exports.formatDuration = formatDuration;
