/* Sentinel — contract instances with full per-change detail.
   Each change: clause, type, risk, plain-language delta, the diff (standard
   vs provider), the AI's proposed counter-redline, confidence, provenance
   trail, and precedent. Wording drawn from the §5.7 playbook. */

/* change types: edit | deletion | addition | missing */
const CONTRACTS = [
  /* ───────────────────────── CT-2841 · Nairobi West ─────────────────────
     Round 1 HSA — contains High items → surfaces to CEO. */
  {
    id: "CT-2841", provider: "nairobiwest", type: "Hospital Services Agreement",
    round: 1, rm: "Aisha Karega", uploadedMs: uploadedAt(212), status: "in_review",
    changes: [
      { id: "C1", clause: "ehis", clauseRef: "14.2", changeType: "edit", risk: "high", confidence: 91,
        summary: "Provider reframes our real-time EHIS access as “limited, non-transferable and revocable”, suspendable at the provider's discretion, and names their EHIS as the sole authoritative system of record.",
        delta: "Removes our guaranteed term-long access and lets the provider switch it off unilaterally — directly weakens our core data position.",
        standard: "Eden Care shall have real-time access to the EHIS for the duration of the Term. Such access shall not be suspended, narrowed or revoked except in the case of an uncured material breach. Each party's system shall be authoritative within its own domain.",
        provider: "The Provider grants Eden Care limited, non-transferable and revocable access to the EHIS, which may be suspended at the Provider's discretion. The Provider's EHIS shall be the sole authoritative system of record.",
        counter: "Eden Care's real-time access to the EHIS continues for the full Term and shall not be suspended, narrowed or revoked save for an uncured material breach remaining unremedied for 30 days. Both systems are authoritative within their respective domains, and the Payer may maintain its own claims records.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 1 · protected (moat). Default risk High. AI may not lower a protected-clause rating." },
          { label: "Semantic delta", ok: false, detail: "Access changed from guaranteed-for-term to revocable-at-will. Authority shifted entirely to provider." },
          { label: "Precedent", ok: true, detail: "Premier (R1) asked the same; we held term-long access. Provider accepted." },
        ],
        precedent: { provider: "Premier Hospital", round: 1, outcome: "Held — term-long access retained", accepted: true } },

      { id: "C2", clause: "payment", clauseRef: "9.1", changeType: "edit", risk: "high", confidence: 88,
        summary: "Claims-settlement window shortened from 60 days to 30 days, with a 2%/month late-payment penalty added.",
        delta: "Compresses our payment cycle by half and introduces a penalty — material cash-flow and liability exposure.",
        standard: "Eden Care shall settle undisputed claims within sixty (60) days of a complete and accurate submission made in accordance with the submission guidelines.",
        provider: "Eden Care shall settle all claims within thirty (30) days of submission. Late payment shall attract interest at two per cent (2%) per month.",
        counter: "Eden Care settles undisputed claims 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.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 3 · protected (moat). Payment-window change against us → High." },
          { label: "Semantic delta", ok: false, detail: "Window 60→30d; penalty introduced; ‘complete & accurate’ precondition deleted." },
          { label: "Precedent", ok: true, detail: "Goodlife (R2) pushed 30d; settled at 45d as a one-off concession." },
        ],
        precedent: { provider: "Goodlife Pharmacy", round: 2, outcome: "Compromised at 45 days (one-off)", accepted: false } },

      { id: "C3", clause: "liability", clauseRef: "11.4", changeType: "deletion", risk: "high", confidence: 84,
        summary: "Entire indemnity-cap sub-clause deleted, and a line added making the provider not liable for its own system failures.",
        delta: "Removes our liability cap and shifts integration-failure risk onto us — unbounded exposure.",
        standard: "The indemnity of either party under this Agreement shall not exceed the greater of KES 5,000,000 or one (1) month's average claims. Each party shall be liable for the failure of its own systems.",
        provider: "[Clause 11.4 deleted by provider.] The Provider shall not be liable for any losses arising from system or integration failures howsoever caused.",
        counter: "Re-insert standard Clause 11.4: 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.",
        checks: [
          { label: "Clause rule", ok: false, detail: "Clause 4 · protected (moat). Deletion of a protected clause → High by default." },
          { label: "Semantic delta", ok: false, detail: "Cap removed; one-sided liability shift inserted in its place." },
          { label: "Precedent", ok: true, detail: "First time a provider has deleted the cap outright. No prior precedent." },
        ],
        precedent: null },

      { id: "C4", clause: "credit", clauseRef: "7.3", changeType: "edit", risk: "medhigh", confidence: 79,
        summary: "Provider inserts a right to demand a deposit on any creditworthiness concern and to revoke the credit facility without notice.",
        delta: "Gives the provider unilateral credit control — commercially significant but within negotiable tolerance.",
        standard: "A deposit may be required only where payment is overdue beyond 60 days on two or more occasions, or upon a material drop in Eden Care's credit rating. Credit terms are governed solely by Appendix 6.",
        provider: "The Provider may require a deposit upon any concern as to Eden Care's creditworthiness and may revoke the credit facility at any time without notice.",
        counter: "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. There shall be no unilateral revocation of the credit facility.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 6 · commercial. Unilateral fee/credit right inserted → Medium-High." },
          { label: "Semantic delta", ok: false, detail: "‘Defined defaults’ replaced by ‘any concern’; no-notice revocation added." },
          { label: "Precedent", ok: true, detail: "Cerba (R1) sought the same; narrowed to defined defaults. Accepted." },
        ],
        precedent: { provider: "Cerba Lancet", round: 1, outcome: "Narrowed to defined defaults", accepted: true } },

      { id: "C5", clause: "dispute", clauseRef: "18.1", changeType: "edit", risk: "medlow", confidence: 86,
        summary: "Adds an option to escalate straight to arbitration, skipping mediation. Governing law unchanged.",
        delta: "Alters the dispute ladder but keeps forum and governing law — limited downside.",
        standard: "Disputes shall be resolved by negotiation, then mediation under the NCIA (14 days, costs shared), then arbitration.",
        provider: "Either party may refer a dispute directly to arbitration without first attempting mediation.",
        counter: "Disputes follow negotiation → mediation (NCIA, 14 days, costs shared) → arbitration. Direct escalation is available only where the counterparty fails to engage in mediation within 14 days.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 12 · operational. Process change, forum unchanged → Medium-Low." },
          { label: "Semantic delta", ok: true, detail: "Mediation step made skippable; governing law and forum preserved." },
          { label: "Precedent", ok: true, detail: "Standard ladder retained in 4 of 4 prior agreements." },
        ],
        precedent: { provider: "Coptic Hospital", round: 1, outcome: "Mediation step retained", accepted: true } },

      { id: "C6", clause: "forcemajeure", clauseRef: "22.0", changeType: "edit", risk: "low", confidence: 93,
        summary: "Force-majeure notice period extended from 7 to 10 days; termination threshold unchanged at 60 days.",
        delta: "Minor boilerplate softening, neutral to us.",
        standard: "A force majeure event shall be notified within seven (7) days. Either party may terminate if the event continues beyond sixty (60) days.",
        provider: "A force majeure event shall be notified within ten (10) days. Either party may terminate if the event continues beyond sixty (60) days.",
        counter: "Accept 10-day notice; retain 60-day termination threshold. No further change required.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 14 · boilerplate. Notice tweak within tolerance → Low." },
          { label: "Semantic delta", ok: true, detail: "Notice 7→10d; termination threshold preserved." },
          { label: "Precedent", ok: true, detail: "10-day notice accepted previously without issue." },
        ],
        precedent: { provider: "Sonar Imaging", round: 1, outcome: "Accepted", accepted: true } },

      { id: "C7", clause: "housekeeping", clauseRef: "1.2", changeType: "edit", risk: "minor", confidence: 99,
        summary: "Provider populated the party-name placeholder and corrected two cross-references.",
        delta: "No change to rights or obligations.",
        standard: "This Agreement is made between Eden Care Medical Limited and [PROVIDER NAME].",
        provider: "This Agreement is made between Eden Care Medical Limited and Nairobi West Hospital Limited.",
        counter: "Auto-accepted. Placeholder fill and cross-reference fixes — logged with rationale.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 15 · minor-edit allow-list (placeholder fill, cross-ref). Auto-accept-eligible." },
          { label: "Semantic delta", ok: true, detail: "Party-name fill + 2 cross-reference corrections. No substantive effect." },
          { label: "Confidence", ok: true, detail: "99% — above the 95% auto-accept gate. AI agrees with the rule." },
        ],
        precedent: null, auto: true },
    ],
  },

  /* ───────────────────────── CT-2842 · Cerba Lancet · DPA ───────────────*/
  {
    id: "CT-2842", provider: "cerba", type: "Data Processing Agreement",
    round: 1, rm: "Aisha Karega", uploadedMs: uploadedAt(168), status: "in_review",
    changes: [
      { id: "C1", clause: "ownership", clauseRef: "4.1", changeType: "edit", risk: "high", confidence: 90,
        summary: "Provider asserts it owns all data and bars Eden Care from selling, sharing or commercialising anonymised data without the provider's consent.",
        delta: "Strips our irrevocable data licence — undermines fraud, actuarial and product use of claims data.",
        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.",
        provider: "The Provider owns all data. Eden Care shall not sell, share or commercialise any data, including anonymised data, without the Provider's prior written consent.",
        counter: "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.",
        checks: [
          { label: "Clause rule", ok: false, detail: "Clause 2 · protected (moat). Restriction on data commercialisation → High." },
          { label: "Semantic delta", ok: false, detail: "Licence reduced to consent-gated; anonymised use blocked." },
          { label: "Precedent", ok: true, detail: "No provider has previously secured ownership; licence always retained." },
        ],
        precedent: { provider: "Sonar Imaging", round: 1, outcome: "Licence retained in full", accepted: true } },

      { id: "C2", clause: "localisation", clauseRef: "6.3", changeType: "addition", risk: "high", confidence: 87,
        summary: "Provider inserts a clause prohibiting any transfer of data outside Kenya.",
        delta: "Hard data-localisation bar conflicts with our cross-border processing and reinsurer reporting.",
        standard: "Cross-border transfers of data are permitted where lawful safeguards are in place, in line with the Kenya Data Protection Act 2019.",
        provider: "Data shall not be transferred outside the Republic of Kenya under any circumstances.",
        counter: "Cross-border transfers of data are permitted where lawful safeguards (adequacy, SCCs or consent) are in place, in line with the Kenya Data Protection Act 2019.",
        checks: [
          { label: "Clause rule", ok: false, detail: "Clause 5 · protected (moat). Cross-border prohibition → High." },
          { label: "Semantic delta", ok: false, detail: "Absolute bar added; lawful-safeguard pathway removed." },
          { label: "Precedent", ok: true, detail: "First localisation ask in this template. No prior precedent." },
        ],
        precedent: null },

      { id: "C3", clause: "entity", clauseRef: "2.4", changeType: "edit", risk: "medlow", confidence: 82,
        summary: "Provider relabels Eden Care as a “billing platform” rather than a licensed medical insurance provider.",
        delta: "Mischaracterises our regulatory role; CEO notified as regulatory standing is touched.",
        standard: "Eden Care Medical Limited, a licensed medical insurance provider regulated by the IRA.",
        provider: "Eden Care Medical Limited, a billing platform facilitating payments between members and the Provider.",
        counter: "Eden Care Medical Limited, a medical insurance provider licensed and regulated by the Insurance Regulatory Authority (IRA), aligned to the standard defined terms throughout.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 10 · regulatory. Mischaracterisation → Medium-Low; CEO notified (regulatory standing)." },
          { label: "Semantic delta", ok: false, detail: "Licensed-insurer characterisation downgraded to ‘billing platform’." },
          { label: "Precedent", ok: true, detail: "Corrected to licensed characterisation in all prior agreements." },
        ],
        precedent: { provider: "Plainsview Hospital", round: 1, outcome: "Corrected to licensed insurer", accepted: true } },

      { id: "C4", clause: "housekeeping", clauseRef: "0.1", changeType: "edit", risk: "minor", confidence: 98,
        summary: "Effective date filled and the duplicate definitions block removed.",
        delta: "No change to rights or obligations.",
        standard: "This Agreement is effective from [DATE].",
        provider: "This Agreement is effective from 1 June 2026.",
        counter: "Auto-accepted. Date fill + duplicate-clause removal — logged with rationale.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 15 · allow-list (date fill, duplicate removal). Auto-accept-eligible." },
          { label: "Semantic delta", ok: true, detail: "Date populated; redundant definitions deleted. No substantive effect." },
          { label: "Confidence", ok: true, detail: "98% — above the auto-accept gate." },
        ],
        precedent: null, auto: true },
    ],
  },

  /* ───────────────────────── CT-2843 · Goodlife · SLA ───────────────────
     Round 2 — Med-High ceiling, stays with Head. */
  {
    id: "CT-2843", provider: "goodlife", type: "Service Level Agreement",
    round: 2, rm: "Aisha Karega", uploadedMs: uploadedAt(96), status: "in_review",
    changes: [
      { id: "C1", clause: "fees", clauseRef: "5.2", changeType: "edit", risk: "medhigh", confidence: 80,
        summary: "Provider claims a unilateral right to reprice the fee schedule on 7 days' notice.",
        delta: "Unilateral repricing on short notice — commercially significant; CEO notified.",
        standard: "Fee changes shall be proposed in writing by either party with at least 30 days' notice and shall take effect by mutual agreement.",
        provider: "The Provider may revise the fee schedule at its discretion upon seven (7) days' written notice.",
        counter: "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.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 9 · commercial. Unilateral reprice right → Medium-High; CEO notified." },
          { label: "Semantic delta", ok: false, detail: "Mutual 30-day notice replaced by unilateral 7-day reprice." },
          { label: "Precedent", ok: true, detail: "R1 of this contract: held mutual 30-day notice; provider re-opened in R2." },
        ],
        precedent: { provider: "Goodlife Pharmacy", round: 1, outcome: "Held — mutual 30-day notice", accepted: true } },

      { id: "C2", clause: "termination", clauseRef: "16.1", changeType: "edit", risk: "medhigh", confidence: 77,
        summary: "Termination triggers broadened to include vague “service-standard failures” and a single remediable breach.",
        delta: "Widens grounds for termination against us; CEO notified.",
        standard: "Termination for cause is limited to undisputed non-payment >60 days, documented harm, uncontested loss of licence, or 3+ uncured material breaches.",
        provider: "Either party may terminate upon any service-standard failure or a single breach of this Agreement.",
        counter: "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. Delete vague service-standard catch-alls.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 7 · commercial. Termination triggers broadened → Medium-High." },
          { label: "Semantic delta", ok: false, detail: "Adds vague catch-all + single-breach trigger; removes cure period." },
          { label: "Precedent", ok: true, detail: "Narrowed to the standard four triggers in 3 prior agreements." },
        ],
        precedent: { provider: "Premier Hospital", round: 1, outcome: "Narrowed to 4 standard triggers", accepted: true } },

      { id: "C3", clause: "preauth", clauseRef: "8.5", changeType: "edit", risk: "medhigh", confidence: 81,
        summary: "Provider caps emergency-claim recovery at 80% when our pre-auth system fails to flag.",
        delta: "Shifts system-failure cost to us and caps emergency recovery; CEO notified.",
        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.",
        provider: "Where Eden Care's system fails to flag a service, recovery for emergency services shall be capped at eighty per cent (80%).",
        counter: "If 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.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 8 · commercial. Emergency-recovery cap inserted → Medium-High." },
          { label: "Semantic delta", ok: false, detail: "Full recovery reduced to 80%; system-failure cost shifted to Payer." },
          { label: "Precedent", ok: true, detail: "Full recovery retained in prior pharmacy SLAs." },
        ],
        precedent: { provider: "Goodlife Pharmacy", round: 1, outcome: "Full recovery retained", accepted: true } },

      { id: "C4", clause: "exclusion", clauseRef: "12.2", changeType: "edit", risk: "medlow", confidence: 85,
        summary: "Provider extends its window to notify service exclusions from 7 to 14 business days.",
        delta: "Limited operational impact; lengthens our notice visibility.",
        standard: "Exclusions shall be notified within 7 business days; the other party has 5 business days to raise concerns.",
        provider: "The Provider shall notify exclusions within fourteen (14) business days.",
        counter: "Exclusions are notified within 7 business days; the other party has 5 business days to raise concerns, followed by orderly resolution.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 11 · operational. Notice-window change → Medium-Low." },
          { label: "Semantic delta", ok: true, detail: "Notice window 7→14 business days; resolution path unchanged." },
          { label: "Precedent", ok: true, detail: "7-day notice retained in prior agreements." },
        ],
        precedent: { provider: "Coptic Hospital", round: 1, outcome: "7-day notice retained", accepted: true } },

      { id: "C5", clause: "housekeeping", clauseRef: "3.1", changeType: "edit", risk: "minor", confidence: 97,
        summary: "Renumbered Appendix references after the provider re-ordered two schedules.",
        delta: "No change to rights or obligations.",
        standard: "...as set out in Appendix 4.",
        provider: "...as set out in Appendix 5.",
        counter: "Auto-accepted. Cross-reference renumbering after schedule re-order — logged with rationale.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 15 · allow-list (renumbering). Auto-accept-eligible." },
          { label: "Semantic delta", ok: true, detail: "Appendix references renumbered to match re-ordered schedules." },
          { label: "Confidence", ok: true, detail: "97% — above the auto-accept gate." },
        ],
        precedent: null, auto: true },
    ],
  },

  /* ───────── Lighter queue entries (used for queue / dashboard) ─────────*/
  {
    id: "CT-2844", provider: "premier", type: "Hospital Services Agreement",
    round: 1, rm: "Aisha Karega", uploadedMs: uploadedAt(38), status: "in_review",
    changes: [
      { id: "C1", clause: "coordination", clauseRef: "13.1", changeType: "edit", risk: "medlow", confidence: 84,
        summary: "Provider inserts “does not deal with SHA” and adds a rebate term.",
        delta: "COB / payer-order wording needs correcting; limited downside.",
        standard: "The provider coordinates per the coordination-of-benefits framework and submits claims in the correct payer order, including SHA / SHIF / NHIF where applicable.",
        provider: "The Provider does not deal with SHA and shall apply a 3% rebate to Eden Care claims.",
        counter: "The provider coordinates per the coordination-of-benefits framework and submits claims in the correct payer order, including SHA / SHIF / NHIF. Rebate terms are governed by Appendix 6, not inserted ad hoc.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 13 · operational. COB / rebate change → Medium-Low." },
          { label: "Semantic delta", ok: false, detail: "SHA coordination removed; unilateral rebate inserted." },
          { label: "Precedent", ok: true, detail: "COB wording corrected in prior HSAs." },
        ],
        precedent: { provider: "Coptic Hospital", round: 1, outcome: "COB wording corrected", accepted: true } },
      { id: "C2", clause: "housekeeping", clauseRef: "1.1", changeType: "edit", risk: "minor", confidence: 99,
        summary: "Registered address updated.", delta: "No change to rights or obligations.",
        standard: "Registered office: [ADDRESS].", provider: "Registered office: 3rd Floor, Premier Plaza, Mombasa Road, Nairobi.",
        counter: "Auto-accepted. Address fill — logged with rationale.",
        checks: [
          { label: "Clause rule", ok: true, detail: "Clause 15 · allow-list (address fill). Auto-accept-eligible." },
          { label: "Semantic delta", ok: true, detail: "Registered address populated. No substantive effect." },
          { label: "Confidence", ok: true, detail: "99% — above the auto-accept gate." },
        ], precedent: null, auto: true },
    ],
  },
  {
    id: "CT-2845", provider: "sonar", type: "Service Level Agreement",
    round: 1, rm: "Aisha Karega", uploadedMs: uploadedAt(15), status: "classifying", changes: [],
  },
  {
    id: "CT-2846", provider: "coptic", type: "Hospital Services Agreement",
    round: 1, rm: "Aisha Karega", uploadedMs: uploadedAt(280), status: "cleared", clearedMin: 196, changes: [],
  },
  {
    id: "CT-2847", provider: "plainsview", type: "Data Processing Agreement",
    round: 2, rm: "Aisha Karega", uploadedMs: uploadedAt(255), status: "cleared", clearedMin: 142, changes: [],
  },
  {
    id: "CT-2848", provider: "ritesh", type: "Data Sharing Agreement",
    round: 1, rm: "Aisha Karega", uploadedMs: uploadedAt(305), status: "cleared", clearedMin: 88, changes: [],
  },
];

/* Highest unresolved risk in a contract (drives routing + queue badges). */
function highestRisk(contract, decisions) {
  decisions = decisions || {};
  let best = null;
  for (const ch of contract.changes) {
    if (ch.auto) continue;
    const d = decisions[contract.id + ":" + ch.id];
    if (d && d.action) continue; // resolved
    if (!best || RISK[ch.risk].sev > RISK[best].sev) best = ch.risk;
  }
  return best;
}
function pendingChanges(contract, decisions) {
  decisions = decisions || {};
  return contract.changes.filter((ch) => !ch.auto && !(decisions[contract.id + ":" + ch.id] || {}).action);
}
/* Which queue a contract belongs in for a given role. CEO sees a contract
   only if it has a pending High item; Head sees everything else substantive. */
function inQueueFor(role, contract, decisions) {
  if (contract.status === "cleared" || contract.status === "classifying") return false;
  const pend = pendingChanges(contract, decisions);
  if (pend.length === 0) return false;
  if (role === "ceo") return pend.some((c) => c.risk === "high");
  if (role === "head") return pend.some((c) => c.risk !== "high");
  return false;
}

Object.assign(window, { CONTRACTS, highestRisk, pendingChanges, inQueueFor });
