/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/** Formats a duration in seconds as MM:SS. */
export const formatTime = seconds => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
};

/**
 * Formats the difference between two 'YYYY-MM-DD HH:mm' strings as a
 * human-readable duration (e.g. "1h 4m 23s", "4m 23s", "23s").
 * Returns null when the inputs are missing or the diff is not positive.
 */
export const formatDuration = (from, to) => {
  if (!from || !to) return null;
  const diffMs = new Date(to.replace(' ', 'T')) - new Date(from.replace(' ', 'T'));
  if (isNaN(diffMs) || 0 >= diffMs) return null;
  const totalSec = Math.floor(diffMs / 1000);
  const h = Math.floor(totalSec / 3600);
  const m = Math.floor((totalSec % 3600) / 60);
  const s = totalSec % 60;
  if (0 < h) return `${h}h ${m}m ${s}s`;
  if (0 < m) return `${m}m ${s}s`;
  return `${s}s`;
};

/**
 * Formats an ISO timestamp as a "X min ago" string (minute resolution).
 * Returns 'just now' for differences under one minute.
 */
export const formatSince = isoStr => {
  const diff = Math.floor((Date.now() - new Date(isoStr)) / 60000);
  if (1 > diff) return 'just now';
  if (1 === diff) return '1 min ago';
  return `${diff} min ago`;
};
