/* Sentinel — domain data: risk model, clause library, providers, helpers.
   Calibrated against the §5.7 clause risk map & negotiation playbook. */

/* ── Risk model ──────────────────────────────────────────────────────────
   5 levels. Direction of routing follows the PRD §5.3/§5.6 rubric. */
const RISK = {
  minor:    { key: "minor",    label: "Minor",       short: "Minor",  sev: 0, tone: "neutral",  routes: "auto",     routeLabel: "Auto-accept" },
  low:      { key: "low",      label: "Low",         short: "Low",    sev: 1, tone: "success",  routes: "head",     routeLabel: "Head of SP Contracting" },
  medlow:   { key: "medlow",   label: "Medium-Low",  short: "Med-Low",sev: 2, tone: "info",     routes: "head",     routeLabel: "Head of SP Contracting" },
  medhigh:  { key: "medhigh",  label: "Medium-High", short: "Med-High",sev: 3, tone: "warning", routes: "head_ceo", routeLabel: "Head of SP · CEO notified" },
  high:     { key: "high",     label: "High",        short: "High",   sev: 4, tone: "danger",   routes: "ceo",      routeLabel: "CEO" },
};
const RISK_ORDER = ["high", "medhigh", "medlow", "low", "minor"];

/* ── Roles ───────────────────────────────────────────────────────────────*/
const ROLES = {
  rm:    { id: "rm",    name: "Aisha Karega",   title: "Relationship Manager", team: "SP Works contracting", tone: "teal",   avatarRole: "RM" },
  head:  { id: "head",  name: "Daniel Otieno",  title: "Head of SP Contracting", team: "Approver · Tier 1", tone: "green", avatarRole: "Head" },
  ceo:   { id: "ceo",   name: "Moses Mukundi",  title: "Chief Executive Officer", team: "Approver · Tier 2", tone: "orange", avatarRole: "CEO" },
  admin: { id: "admin", name: "Priya Shah",     title: "Platform Admin", team: "Ops / Engineering", tone: "neutral", avatarRole: "Admin" },
};

/* ── Clause library — the 15 §5.7 battlegrounds ──────────────────────────
   Each carries materiality, protected flag, default risk, and Eden Care's
   standard counter-position (verbatim from the playbook). */
const CLAUSES = {
  ehis:        { no: 1,  title: "Real-time EHIS / data access",          protected: true,  risk: "high",    tier: "Moat",
    standard: "Eden Care's real-time access to the EHIS continues for the full term of this Agreement and shall not be suspended, narrowed or revoked save for an uncured material breach. Both systems are authoritative within their respective domains, and the Payer may maintain its own claims records." },
  ownership:   { no: 2,  title: "Data ownership & licence to use data",  protected: true,  risk: "high",    tier: "Moat",
    standard: "The Payer holds an irrevocable, royalty-free licence to use claims and service data for claims management, fraud prevention, actuarial work, product development and regulatory needs. Anonymised and aggregated use is permitted, including disclosure to reinsurers and regulators." },
  payment:     { no: 3,  title: "Claims-payment window",                 protected: true,  risk: "high",    tier: "Moat",
    standard: "Undisputed claims are settled within sixty (60) days of a complete and accurate submission per the submission guidelines. Disputes are notified within fourteen (14) days; undisputed portions are never delayed. No late-payment penalty applies to disputed amounts." },
  liability:   { no: 4,  title: "Liability & indemnity",                 protected: true,  risk: "high",    tier: "Moat",
    standard: "Each party is liable for its own systems (mutual liability). Indemnity is capped at the greater of KES 5,000,000 or one month's average claims. Integration failures are handled on a no-fault, cooperative basis absent gross negligence." },
  localisation:{ no: 5,  title: "Data localisation / cross-border",      protected: true,  risk: "high",    tier: "Moat",
    standard: "Cross-border transfers of data are permitted where lawful safeguards are in place, in line with the Kenya Data Protection Act 2019." },
  credit:      { no: 6,  title: "Credit / deposit security",             protected: false, risk: "medhigh", tier: "Commercial",
    standard: "A deposit may be required only on defined defaults (payment overdue >60 days, on two or more occasions, or a material credit-rating drop). Credit terms are governed solely by Appendix 6 / Clause 7. No unilateral revocation of the credit facility." },
  termination: { no: 7,  title: "Termination for cause",                 protected: false, risk: "medhigh", tier: "Commercial",
    standard: "Termination for cause is limited to: undisputed non-payment exceeding 60 days; documented harm; uncontested loss of licence; or three or more uncured material breaches. Vague risk catch-alls are deleted." },
  preauth:     { no: 8,  title: "Pre-auth / system-failure & emergency", protected: false, risk: "medhigh", tier: "Commercial",
    standard: "Where the Payer's system fails to flag a service, the Payer settles at the SP standard rate. Emergency services rendered are fully recoverable; no percentage cap applies to emergency recovery." },
  fees:        { no: 9,  title: "Fees & charges adjustment",             protected: false, risk: "medhigh", tier: "Commercial",
    standard: "Fee changes are proposed in writing by either party with at least 30 days' notice and take effect by mutual agreement. Neither party may unilaterally reprice." },
  entity:      { no: 10, title: "Entity characterisation (MIP / TPA)",   protected: false, risk: "medlow",  tier: "Regulatory",
    standard: "Eden Care is characterised in accordance with its licensed status and the standard defined terms. The Agreement aligns to that characterisation throughout." },
  exclusion:   { no: 11, title: "Exclusion of services / scope",         protected: false, risk: "medlow",  tier: "Operational",
    standard: "Exclusions are notified within 7 business days; the other party has 5 business days to raise concerns, followed by orderly resolution." },
  dispute:     { no: 12, title: "Dispute resolution process",            protected: false, risk: "medlow",  tier: "Operational",
    standard: "Disputes follow: negotiation → mediation (NCIA, 14 days, costs shared) → arbitration. Governing law and forum are not altered." },
  coordination:{ no: 13, title: "Coordination with SHA / SHIF / NHIF",   protected: false, risk: "medlow",  tier: "Operational",
    standard: "The provider coordinates per the coordination-of-benefits framework and submits claims in the correct payer order, including SHA / SHIF / NHIF where applicable." },
  forcemajeure:{ no: 14, title: "Force majeure / notices",               protected: false, risk: "low",     tier: "Boilerplate",
    standard: "A force majeure event is notified within 7 days. Either party may terminate if the event continues beyond 60 days." },
  housekeeping:{ no: 15, title: "Housekeeping",                          protected: false, risk: "minor",   tier: "Cosmetic",
    standard: "Dates, addresses, party names, placeholder fills, renumbering and typo corrections, where there is no change to rights or obligations." },
};

/* ── Providers ───────────────────────────────────────────────────────────*/
const PROVIDERS = {
  nairobiwest: { name: "Nairobi West Hospital", type: "Hospital",   tone: "green" },
  premier:     { name: "Premier Hospital",      type: "Hospital",   tone: "teal" },
  cerba:       { name: "Cerba Lancet",          type: "Laboratory", tone: "orange" },
  sonar:       { name: "Sonar Imaging",         type: "Diagnostics", tone: "neutral" },
  coptic:      { name: "Coptic Hospital",       type: "Hospital",   tone: "teal" },
  goodlife:    { name: "Goodlife Pharmacy",     type: "Pharmacy",   tone: "green" },
  plainsview:  { name: "Plainsview Hospital",   type: "Hospital",   tone: "orange" },
  ritesh:      { name: "Dr Ritesh Clinic",      type: "Clinic",     tone: "neutral" },
};

/* ── Helpers ─────────────────────────────────────────────────────────────*/
const fmtKsh = (n) => "KES " + n.toLocaleString("en-KE");

/* SLA: 4-hour (240 min) clock from upload. We anchor each contract's upload
   at NOW - elapsedMin so the countdown is live. */
const SLA_MIN = 240;
const NOW0 = Date.now();
function uploadedAt(elapsedMin) { return NOW0 - elapsedMin * 60000; }
function slaRemainingMin(uploadedMs) { return SLA_MIN - (Date.now() - uploadedMs) / 60000; }
function fmtDuration(mins) {
  const neg = mins < 0; let m = Math.abs(Math.round(mins));
  const h = Math.floor(m / 60); m = m % 60;
  const s = (h > 0 ? h + "h " : "") + m + "m";
  return (neg ? "+" : "") + s;
}
function slaTone(remainingMin) {
  if (remainingMin < 0) return "danger";
  if (remainingMin < 45) return "warning";
  return "success";
}
function timeAgo(ms) {
  const mins = Math.round((Date.now() - ms) / 60000);
  if (mins < 60) return mins + "m ago";
  const h = Math.floor(mins / 60), r = mins % 60;
  return h + "h " + (r ? r + "m " : "") + "ago";
}

/* Standard-template clause numbers (the canonical clause # per battleground). */
const STD_CLAUSE = {
  ehis: "14.2", ownership: "4.1", payment: "9.1", liability: "11.4", localisation: "6.3",
  credit: "7.3", termination: "16.1", preauth: "8.5", fees: "5.2", entity: "2.4",
  exclusion: "12.2", dispute: "18.1", coordination: "13.1", forcemajeure: "22.0", housekeeping: "1.2",
};
const CLAUSE_KEY_BY_TITLE = Object.fromEntries(Object.entries(CLAUSES).map(([k, v]) => [v.title, k]));

Object.assign(window, {
  RISK, RISK_ORDER, ROLES, CLAUSES, PROVIDERS, STD_CLAUSE, CLAUSE_KEY_BY_TITLE,
  fmtKsh, SLA_MIN, uploadedAt, slaRemainingMin, fmtDuration, slaTone, timeAgo,
});
