/* OSCE Nexus v2 – shared JS helpers */
(function () {
  'use strict';

  window.OSCE = window.OSCE || {};

  // CSRF token from meta tag
  OSCE.csrfToken = function () {
    const m = document.querySelector('meta[name="csrf-token"]');
    return m ? m.content : '';
  };

  OSCE.fetchJSON = async function (url, opts) {
    opts = opts || {};
    opts.headers = Object.assign({
      'Accept': 'application/json',
      'X-CSRF-Token': OSCE.csrfToken(),
    }, opts.headers || {});
    if (opts.body && typeof opts.body !== 'string') {
      opts.headers['Content-Type'] = 'application/json';
      opts.body = JSON.stringify(opts.body);
    }
    const r = await fetch(url, opts);
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    return r.json();
  };

  // Debounce
  OSCE.debounce = function (fn, ms) {
    let t;
    return function () {
      const args = arguments, ctx = this;
      clearTimeout(t);
      t = setTimeout(() => fn.apply(ctx, args), ms);
    };
  };

  // Format mm:ss
  OSCE.fmtTime = function (sec) {
    sec = Math.max(0, Math.floor(sec));
    const m = Math.floor(sec / 60), s = sec % 60;
    return String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0');
  };

  // Countdown widget tied to absolute end timestamp (server-corrected).
  OSCE.startTimer = function (opts) {
    // opts: {endMs, serverNowMs, boxEl, textEl, onWarn2, onWarn1, onEnd, mutedFn}
    const offset = Date.now() - opts.serverNowMs;
    let w2 = false, w1 = false, done = false;
    function tick() {
      const now = Date.now() - offset;
      let diff = Math.max(0, opts.endMs - now);
      const sec = Math.floor(diff / 1000);
      if (opts.textEl) opts.textEl.textContent = OSCE.fmtTime(sec);
      const m = Math.floor(sec / 60);
      if (m <= 2 && !w2) { w2 = true; if (opts.boxEl) opts.boxEl.classList.add('warn-2'); if (opts.onWarn2) opts.onWarn2(); }
      if (m <= 1 && !w1) { w1 = true; if (opts.boxEl) opts.boxEl.classList.add('warn-1'); if (opts.onWarn1) opts.onWarn1(); }
      if (diff <= 0 && !done) {
        done = true;
        if (opts.boxEl) opts.boxEl.classList.add('done');
        if (opts.onEnd) opts.onEnd();
      }
    }
    tick();
    return setInterval(tick, 1000);
  };

})();
