// note-data.jsx — the progress note, provenance-tagged.
//
// The model: every block carries the day it was first authored and an intrinsic
// origin. On any given day, a block that was original thought on an EARLIER day
// is re-classified as copied-forward. Template, auto-populated lab, boilerplate
// and billing blocks regenerate every day and are never original.
//
// Nothing about the headline percentage is hardcoded — noteStats() counts actual
// words in actual rendered text. If the content changes, the number changes.
// Exports on window: buildNote, noteStats, NOTE_DAY_META


const NOTE_DAY_META = [
  { day: 1, date: '04/27/2026', author: 'Weaver, Margaret R, MD', title: 'H&P / Admission Note' },
  { day: 2, date: '04/28/2026', author: 'Okonkwo, Daniel, MD',    title: 'Progress Note' },
  { day: 3, date: '04/29/2026', author: 'Okonkwo, Daniel, MD',    title: 'Progress Note' },
  { day: 4, date: '04/30/2026', author: 'Okonkwo, Daniel, MD',    title: 'Progress Note' },
];

const ROS_SYSTEMS = [
  ['Constitutional','Negative for fever, chills, night sweats, or unintentional weight loss.'],
  ['Eyes','Negative for visual disturbance, diplopia, discharge, or photophobia.'],
  ['ENT','Negative for hearing loss, tinnitus, epistaxis, sore throat, or sinus pressure.'],
  ['Cardiovascular','Negative for chest pain, palpitations, orthopnoea, or paroxysmal nocturnal dyspnoea.'],
  ['Respiratory','Negative for cough, wheeze, haemoptysis, or pleuritic chest discomfort.'],
  ['Gastrointestinal','Negative for nausea, vomiting, diarrhoea, melena, or abdominal distension.'],
  ['Genitourinary','Positive for reduced urine output. Negative for dysuria, haematuria, or flank pain.'],
  ['Musculoskeletal','Negative for arthralgia, myalgia, joint swelling, or reduced range of motion.'],
  ['Integumentary','Negative for rash, pruritus, ulceration, or poor wound healing.'],
  ['Neurological','Negative for headache, focal weakness, paraesthesia, syncope, or seizure activity.'],
  ['Psychiatric','Negative for depressed mood, anxiety, agitation, or sleep disturbance.'],
  ['Endocrine','Positive for polyuria and polydipsia at baseline. Negative for heat or cold intolerance.'],
  ['Haematologic','Negative for easy bruising, epistaxis, or prolonged bleeding.'],
  ['Allergic/Immunologic','Negative for urticaria, angioedema, or recurrent infection.'],
];

const EXAM_SYSTEMS = [
  ['General','Alert, orientated to person, place and time. In no acute distress. Appears stated age.'],
  ['Vitals','Reviewed and incorporated into this note. See flowsheet for complete recorded values.'],
  ['HEENT','Normocephalic, atraumatic. Sclerae anicteric. Oropharynx moist without lesion or exudate.'],
  ['Neck','Supple. No lymphadenopathy. Jugular venous pressure estimated at 8 cm H2O. No thyromegaly.'],
  ['Cardiovascular','Regular rate and rhythm. Normal S1 and S2. No murmur, rub, or gallop appreciated.'],
  ['Respiratory','Bibasilar crackles present. No wheeze. Symmetric expansion. No accessory muscle use.'],
  ['Abdomen','Soft, non-tender, non-distended. Bowel sounds present in all quadrants. No organomegaly.'],
  ['Extremities','Two-plus pitting oedema to mid-shin bilaterally. Distal pulses palpable and symmetric.'],
  ['Skin','Warm and dry. No rash, ulceration, or breakdown identified over pressure points.'],
  ['Neurologic','Cranial nerves two through twelve grossly intact. Strength five out of five throughout.'],
];

const ATTESTATION = `I personally performed the services described in this documentation. I have reviewed the patient's chart, laboratory results, imaging where applicable, and nursing documentation for the preceding twenty-four hour period. The assessment and plan documented above reflect my independent medical decision making. Where a resident or advanced practice provider contributed to this encounter, I have personally reviewed their documentation, was physically present for the key portions of the evaluation, and have edited the note to reflect my own findings and clinical judgment. This note was generated with the assistance of a documentation template. All template-derived content has been reviewed for accuracy and edited where clinically appropriate.`;

const BILLING = `Total time spent on the date of this encounter, including chart review, independent interpretation of laboratory data, coordination of care with consulting services, and documentation, was in excess of thirty-five minutes. Greater than fifty percent of this time was spent in counselling and coordination of care. Medical decision making is of high complexity based on the number and acuity of problems addressed, the volume and complexity of data reviewed, and the risk of complications from the management options selected. This encounter meets criteria for the level of service billed.`;

// ── Block library ───────────────────────────────────────────────────────────
// fromDay = the day this content was first authored.
function noteBlocks(day) {
  const L = window.LABS, D = window.LAB_DATES;
  const cols = Math.min(D.length, day * 2 - 1);        // the lab dump widens every day
  const dates = D.slice(D.length - cols);

  const labDump = L.map(l => {
    const vals = l.vals.slice(l.vals.length - cols);
    return `${l.name} (reference ${l.ref}): ` +
      dates.map((d, i) => `${d} ${vals[i]}`).join('; ') + '.';
  }).join(' ');

  const medDump = window.MEDS.map(m =>
    `${m.name} ${m.sig}, route ${m.route}, commenced ${m.start}, status ${m.status}.`).join(' ');

  const problemDump = window.PROBLEMS.map(p =>
    `${p.n}. ${p.name} (${p.icd}), onset ${p.onset}, documented by ${p.by}.`).join(' ');

  const allergyDump = window.ALLERGIES.map(a =>
    `${a.agent} — ${a.reaction}, severity ${a.severity}.`).join(' ');

  const vitalDump = window.VITALS.map(v =>
    `${v.t}: blood pressure ${v.bp}, heart rate ${v.hr}, respiratory rate ${v.rr}, temperature ${v.temp} degrees Celsius, oxygen saturation ${v.spo2}.`).join(' ');

  const ioDump = window.IO_DATA.map(r =>
    `${r.date}: oral intake ${r.inPO} mL, intravenous intake ${r.inIV} mL, total output ${r.out} mL, net balance ${r.net > 0 ? 'positive ' : 'negative '}${Math.abs(r.net)} mL, recorded weight ${r.weight}.`).join(' ');

  const consultDump = window.CONSULTS.slice(0, Math.max(0, day - 1)).map(c =>
    `${c.service} (${c.md}): recommendations reviewed and incorporated. Service is ${c.status.toLowerCase()}. Most recent documentation ${c.lastNote}. No change to the current plan was advised at the time of review.`).join(' ');

  const MICRO_LINES = [
    'Blood cultures times two from 04/25: no growth to date.',
    'Sputum culture 04/26: mixed respiratory flora, no predominant pathogen isolated.',
    'MRSA nasal screen 04/25: negative.',
    'Urinalysis 04/27: bland sediment, no casts, no pyuria, no eosinophiluria.',
    'Renal ultrasound 04/27: kidneys measure 10.2 and 10.6 centimetres, increased cortical echogenicity consistent with chronic medical renal disease, no hydronephrosis, no obstructing calculus, normal resistive indices bilaterally.',
    'Chest radiograph 04/29: persistent right basilar opacity, unchanged from prior study, small right pleural effusion, no new consolidation.',
    'Repeat blood cultures 04/29: no growth at forty-eight hours.',
    'Clostridioides difficile PCR 04/30: not detected.',
  ];
  const microDump = MICRO_LINES.slice(0, Math.min(MICRO_LINES.length, (day - 1) * 3)).join(' ');

  const rosText = ROS_SYSTEMS.map(([s, t]) => `${s}: ${t}`).join(' ');
  const examText = EXAM_SYSTEMS.map(([s, t]) => `${s}: ${t}`).join(' ');

  const B = [
    { id:'hpi',       section:'HPI',                    origin:'new', fromDay:1,
      text:'Sixty-seven year old male with chronic kidney disease stage G3a, hypertension, and type two diabetes mellitus with diabetic nephropathy, admitted with acute kidney injury on chronic kidney disease in the setting of healthcare-associated pneumonia. Baseline creatinine 1.4 mg/dL.' },

    { id:'interval2', section:'Interval History',       origin:'new', fromDay:2,
      text:'Creatinine continues to rise despite intravenous fluid resuscitation. Urine output remains reduced at approximately 0.4 mL/kg/hr. Antibiotics were broadened on the recommendation of Infectious Disease.' },

    { id:'interval3', section:'Interval History',       origin:'new', fromDay:3,
      text:'Potassium rose to 5.8 mEq/L overnight, prompting temporary discontinuation of potassium-sparing agents and initiation of intravenous furosemide forty milligrams twice daily. Creatinine peaked at 2.6 mg/dL. Fractional excretion of sodium remains below one percent, consistent with a pre-renal picture.' },

    // Day 4. This is the entirety of today's original clinical thought.
    { id:'interval4', section:'Interval History',       origin:'new', fromDay:4,
      text:'Creatinine down to 2.1 and potassium normalised at 4.2 after two days of diuresis. Net negative 670 mL overnight, weight down 2.5 kg from peak. Renal function is recovering; will restart the ACE inhibitor today and recheck a basic metabolic panel in forty-eight hours.' },

    { id:'ros',       section:'Review of Systems',      origin:'template',    fromDay:1, text: rosText },
    { id:'exam',      section:'Physical Examination',   origin:'template',    fromDay:1, text: examText },
    { id:'vitals',    section:'Vital Signs',            origin:'autolab',     fromDay:1, text: vitalDump },
    { id:'labs',      section:'Laboratory Data',        origin:'autolab',     fromDay:1, text: labDump },
    { id:'io',        section:'Intake and Output',      origin:'autolab',     fromDay:2, text: ioDump },
    { id:'meds',      section:'Active Medications',     origin:'autolab',     fromDay:1, text: medDump },
    { id:'problems',  section:'Active Problem List',    origin:'autolab',     fromDay:1, text: problemDump },
    { id:'allergies', section:'Allergies',              origin:'autolab',     fromDay:1, text: allergyDump },

    { id:'ap1',       section:'Assessment and Plan',    origin:'new', fromDay:1,
      text:'Acute kidney injury on chronic kidney disease stage G3a. Aetiology most consistent with pre-renal physiology in the setting of sepsis and reduced effective circulating volume. Will hold nephrotoxic agents, avoid iodinated contrast, and follow daily basic metabolic panel. Hold ACE inhibitor pending stabilisation of renal function and potassium.' },

    { id:'ap2',       section:'Assessment and Plan',    origin:'new', fromDay:2,
      text:'Healthcare-associated pneumonia. Continue vancomycin and piperacillin-tazobactam per Infectious Disease. Renal dosing per pharmacy. Follow vancomycin trough before the fourth dose. Monitor for further decline in renal function attributable to antimicrobial therapy.' },

    { id:'ap3',       section:'Assessment and Plan',    origin:'new', fromDay:3,
      text:'Hyperkalaemia and metabolic acidosis. Potassium 5.8 mEq/L, bicarbonate 19 mEq/L. Commenced intravenous furosemide and oral sodium bicarbonate. Hold ACE inhibitor pending potassium stabilisation. Continue calcium acetate for phosphate control. Type two diabetes mellitus — continue basal insulin with correctional sliding scale; glycaemic control acceptable inpatient.' },

    { id:'consults',  section:'Consultant Recommendations', origin:'autolab', fromDay:2, text: consultDump },

    { id:'micro',     section:'Microbiology and Imaging', origin:'autolab',  fromDay:2, text: microDump },

    { id:'attest',    section:'Attestation',            origin:'boilerplate', fromDay:1, text: ATTESTATION },
    { id:'billing',   section:'Billing Statement',      origin:'billing',     fromDay:1, text: BILLING },
  ];

  return B
    .filter(b => b.fromDay <= day && b.text && b.text.trim().length > 0)
    .map(b => ({
      ...b,
      // Original thought stays original only on the day it was written.
      origin: b.origin === 'new' && b.fromDay < day ? 'copied' : b.origin,
      copiedFrom: b.origin === 'new' && b.fromDay < day ? b.fromDay : null,
    }));
}

const SECTION_ORDER = [
  'HPI','Interval History','Review of Systems','Physical Examination','Vital Signs',
  'Laboratory Data','Intake and Output','Microbiology and Imaging','Active Medications',
  'Active Problem List','Allergies','Consultant Recommendations','Assessment and Plan',
  'Attestation','Billing Statement',
];

function buildNote(day) {
  const blocks = noteBlocks(day);
  const bySection = [];
  SECTION_ORDER.forEach(sec => {
    const items = blocks.filter(b => b.section === sec);
    if (items.length) bySection.push({ section: sec, blocks: items });
  });
  return bySection;
}

const countWords = (s) => (s.trim().match(/\S+/g) || []).length;

// Derived, not asserted.
function noteStats(sections) {
  const byOrigin = {};
  let total = 0;
  sections.forEach(s => s.blocks.forEach(b => {
    const w = countWords(b.text);
    byOrigin[b.origin] = (byOrigin[b.origin] || 0) + w;
    total += w;
  }));
  const newWords = byOrigin.new || 0;
  return {
    total,
    byOrigin,
    newWords,
    newPct: total ? (newWords / total) * 100 : 0,
  };
}

function noteTrend() {
  return [1, 2, 3, 4].map(d => {
    const st = noteStats(buildNote(d));
    return { day: d, total: st.total, newWords: st.newWords, newPct: st.newPct };
  });
}

Object.assign(window, { buildNote, noteStats, noteTrend, NOTE_DAY_META, countWords });
