/* Shared pay-by countdown — rewrites every [data-pay-deadline] element
 * on the page once per second with a prose human delta matching the
 * server-rendered ago.human() output:
 *
 *   "in 23 hours, 14 minutes"  →  "in 23 hours, 14 minutes, 8 seconds"
 *
 * Same shape used on /o/{id} (offer detail), /a/{id} (auction detail),
 * and /cart/{id} (negotiation card). Each page sets:
 *
 *   <strong data-pay-deadline="<absolute ms>">in 23 hours, 14 minutes</strong>
 *
 * The script-only version refines the precision; the server-rendered
 * version is the no-JS fallback.
 */
(function () {
  "use strict";

  function fmtRemaining(ms) {
    if (ms <= 0) return "expired";
    var totalSeconds = Math.floor(ms / 1000);
    var units = [
      { name: "day", value: Math.floor(totalSeconds / 86400) },
      { name: "hour", value: Math.floor((totalSeconds % 86400) / 3600) },
      { name: "minute", value: Math.floor((totalSeconds % 3600) / 60) },
      { name: "second", value: totalSeconds % 60 },
    ];
    var parts = [];
    for (var i = 0; i < units.length && parts.length < 2; i++) {
      var u = units[i];
      if (u.value === 0 && parts.length === 0 && i < units.length - 1) continue;
      parts.push(u.value + " " + u.name + (u.value === 1 ? "" : "s"));
    }
    return "in " + parts.join(", ");
  }

  function tick() {
    var nodes = document.querySelectorAll("[data-pay-deadline]");
    if (!nodes.length) return;
    var now = Date.now();
    Array.prototype.forEach.call(nodes, function (node) {
      var raw = node.getAttribute("data-pay-deadline");
      var deadline = parseInt(raw, 10);
      if (isNaN(deadline)) return;
      node.textContent = fmtRemaining(deadline - now);
    });
  }

  function start() {
    tick();
    setInterval(tick, 1000);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", start);
  } else {
    start();
  }
})();
