/* Sponzza salary/going-rate engine (classic content-script global). */
var SponzzaRates = (function () {
  var byCode = {}, meta = {};
  function load(url) {
    return fetch(url).then(function (r) { return r.json(); }).then(function (d) {
      byCode = d.byCode || {}; meta = d.meta || {}; return meta;
    });
  }
  function get(code) { return byCode[code] || null; }

  function gbp(n) {
    return n == null ? '—' : '£' + Math.round(n).toLocaleString('en-GB');
  }

  // Compute the required salary and (if an offer is known) a pass/fail.
  function assess(code, offered, T) {
    var e = byCode[code];
    if (!e) return null;
    var stdReq = Math.max(T.generalStandard, e.annual || 0);
    var neReq = Math.max(T.generalNewEntrant, e.lowerAnnual || 0);
    var out = {
      title: e.title, code: e.code,
      goingStd: e.annual, goingLower: e.lowerAnnual,
      hourlyStd: e.hourly, hourlyFloor: T.hourlyFloor,
      stdRequired: stdReq, newEntrantRequired: neReq,
      offered: offered || null, meetsStd: null, meetsNE: null
    };
    if (offered) {
      out.meetsStd = offered >= stdReq;
      out.meetsNE = offered >= neReq;
    }
    return out;
  }

  // Best-effort salary extraction from page text (e.g. "£35,000/yr - £40,000").
  function detectSalary(text) {
    if (!text) return null;
    var m = text.match(/£\s?\d[\d,]*\s?[kK]?(?:\s?(?:\/yr|per year|a year|p\.?a\.?))?/g);
    if (!m) return null;
    var vals = m.map(function (s) {
      var num = parseFloat(s.replace(/[£,\s]/g, '').replace(/\/yr|peryear|ayear|pa/gi, ''));
      if (/[kK]/.test(s)) num *= 1000;
      return num;
    }).filter(function (n) { return n >= 12000 && n <= 500000; }); // sane annual range
    if (!vals.length) return null;
    return Math.min.apply(null, vals); // conservative: lower bound of any range
  }

  return { load: load, get: get, assess: assess, gbp: gbp, detectSalary: detectSalary, meta: function () { return meta; } };
})();
