// bha-data.jsx — Single source of truth for per-member health data.
// Loaded BEFORE bha-screens.jsx so that the screens' `window.X = window.X || {…}`
// fallbacks become no-ops and every screen reads this unified, per-profile store.
//
// Switching the active member mutates the live USER object IN PLACE (never replaces it)
// so the `const USER = window.__bhaUserProfile` captured by each screen file stays valid,
// then fires `bha-member-change` so the whole app re-renders with that person's data.

;(function () {

  // ── Full per-member profiles ─────────────────────────────────
  // Each profile is complete & self-contained: demographics, clinical profile,
  // insurance, medications, appointment, and lab results.
  const PROFILES = {
    self: {
      id: 'self', name: 'Marcus Johnson', firstName: 'Marcus', lastName: 'Johnson',
      initials: 'MJ', role: 'You', age: 47, gender: 'male', sex: 'M', state: 'GA',
      ancestry: 'Black/African American', smoker: false, bmi: 29.5,
      conditions: ['Hypertension', 'Type 2 Diabetes', 'High Cholesterol'],
      familyHistory: { 'Hypertension': 3, 'Type 2 Diabetes': 2, 'Heart Disease': 1, 'Stroke': 1, 'Prostate Cancer': 1 },
      family: ['Heart disease', 'Type 2 diabetes'],
      insurance: { provider: 'BlueCross BlueShield', memberId: '●●●●●● 4821', planType: 'PPO — Individual' },
      appt: { title: 'Cardiology Appointment', when: 'Tomorrow · 10:30 AM', doctor: 'Dr. Amara Osei' },
      meds: [
        { id: 'm1', name: 'Lisinopril',   dose: '10mg',    time: '8:00 AM', taken: false },
        { id: 'm2', name: 'Metformin',    dose: '500mg',   time: '8:00 AM', taken: false },
        { id: 'm3', name: 'Atorvastatin', dose: '40mg',    time: '9:00 PM', taken: true  },
      ],
      medList: [
        { name: 'Lisinopril',   dose: '10mg · Once daily',            condition: 'Hypertension',     color: '#C0392B' },
        { name: 'Metformin',    dose: '500mg · Twice daily',          condition: 'Type 2 Diabetes',  color: '#16A34A' },
        { name: 'Atorvastatin', dose: '40mg · Once daily (bedtime)',  condition: 'High Cholesterol', color: '#D4A017' },
      ],
      labs: [
        { name: 'Complete Blood Panel', date: 'Apr 17, 2026', status: 'review', values: [
          { marker: 'Hemoglobin', value: '11.2', unit: 'g/dL', range: '13.5–17.5', flag: 'L',
            explanation: 'Hemoglobin carries oxygen through your body. A low level can mean mild anemia, which is more common in people of African descent — sometimes due to sickle cell trait, iron deficiency, or chronic conditions.',
            nextSteps: ['Ask doctor to rule out sickle cell trait if not already tested', 'Request iron panel and ferritin levels', 'Discuss dietary iron + vitamin C intake'] },
          { marker: 'HbA1c', value: '7.8', unit: '%', range: '< 5.7', flag: 'H',
            explanation: 'HbA1c measures your average blood sugar over the past 3 months. 7.8% indicates diabetes is not well-controlled. Black Americans face higher rates of diabetes complications including kidney disease and amputation.',
            nextSteps: ['Discuss medication adjustment with your doctor', 'Schedule annual diabetic eye exam + foot check', 'Request a referral to a culturally-competent diabetes educator'] },
          { marker: 'LDL Cholesterol', value: '142', unit: 'mg/dL', range: '< 100', flag: 'H',
            explanation: 'LDL is "bad" cholesterol that builds up in arteries. High LDL combined with hypertension significantly raises heart attack and stroke risk — concerns especially elevated in Black men.',
            nextSteps: ['Ask about statin therapy options', 'Discuss DASH or Mediterranean diet adapted for cultural foods', 'Request a coronary calcium scan if not already done'] },
          { marker: 'Creatinine', value: '1.1', unit: 'mg/dL', range: '0.7–1.3', flag: null,
            explanation: 'Creatinine reflects kidney function. Your level is in the normal range. Note: many labs no longer use race-based eGFR adjustments, which historically masked kidney disease in Black patients.',
            nextSteps: ['Confirm your lab uses race-neutral eGFR formula', 'Request annual kidney function check given diabetes + hypertension'] },
          { marker: 'Vitamin D', value: '18', unit: 'ng/mL', range: '30–80', flag: 'L',
            explanation: 'Vitamin D deficiency is extremely common in Black adults — up to 80% are deficient — because melanin reduces UV-driven vitamin D synthesis. Low D affects bone health, immunity, and may worsen blood pressure.',
            nextSteps: ['Ask about vitamin D3 supplementation (typically 2000–4000 IU daily)', 'Recheck levels in 3 months', 'Discuss safe sun exposure strategies'] },
        ]},
        { name: 'Cardiac Stress Test', date: 'Mar 22, 2026', status: 'normal', values: [] },
      ],
    },

    spouse: {
      id: 'spouse', name: 'Jasmine Johnson', firstName: 'Jasmine', lastName: 'Johnson',
      initials: 'JJ', role: 'Spouse', age: 39, gender: 'female', sex: 'F', state: 'GA',
      ancestry: 'Black/African American', smoker: false, bmi: 24.1,
      conditions: ['Anemia'],
      familyHistory: { 'Fibroids': 2, 'Hypertension': 2, 'Breast Cancer': 1 },
      family: ['Fibroids', 'Hypertension'],
      insurance: { provider: 'BlueCross BlueShield', memberId: '●●●●●● 4822', planType: 'PPO — Family' },
      appt: { title: 'OB-GYN Annual', when: 'Apr 28 · 2:00 PM', doctor: 'Dr. Nia Williams' },
      meds: [
        { id: 'm4', name: 'Ferrous Sulfate', dose: '325mg', time: '9:00 AM', taken: false },
        { id: 'm5', name: 'Vitamin D3',      dose: '2000 IU', time: '9:00 AM', taken: true },
      ],
      medList: [
        { name: 'Ferrous Sulfate', dose: '325mg · Once daily', condition: 'Anemia',        color: '#C0392B' },
        { name: 'Vitamin D3',      dose: '2000 IU · Once daily', condition: 'Vitamin D Deficiency', color: '#D4A017' },
      ],
      labs: [
        { name: 'Iron Panel + CBC', date: 'Apr 12, 2026', status: 'review', values: [
          { marker: 'Hemoglobin', value: '10.4', unit: 'g/dL', range: '12.0–15.5', flag: 'L',
            explanation: 'Hemoglobin carries oxygen in your blood. A low level means anemia, which can make you feel tired and short of breath. Iron-deficiency anemia is more common in Black women, often linked to heavy periods or fibroids.',
            nextSteps: ['Ask for a full iron panel, not just a CBC', 'Discuss whether fibroids are contributing', 'Pair iron-rich foods with vitamin C to boost absorption'] },
          { marker: 'Ferritin', value: '11', unit: 'ng/mL', range: '15–150', flag: 'L',
            explanation: 'Ferritin is your body\'s stored iron. A low level confirms iron deficiency even before anemia gets severe. It is the most useful single test for catching low iron early.',
            nextSteps: ['Ask about an iron supplement and how to take it', 'Recheck ferritin in 8–12 weeks', 'Discuss heavy-period evaluation if relevant'] },
          { marker: 'Vitamin D', value: '22', unit: 'ng/mL', range: '30–80', flag: 'L',
            explanation: 'Vitamin D supports bones and immunity. Low levels are very common in Black adults because melanin lowers how much vitamin D the skin makes from sunlight.',
            nextSteps: ['Ask about a daily vitamin D3 supplement', 'Recheck in 3 months'] },
          { marker: 'TSH (Thyroid)', value: '2.1', unit: 'mIU/L', range: '0.4–4.0', flag: null,
            explanation: 'TSH checks how your thyroid is working. Your level is normal, which helps rule out thyroid problems as a cause of fatigue.',
            nextSteps: ['No action needed — recheck only if symptoms change'] },
        ]},
      ],
    },

    teen: {
      id: 'teen', name: 'Maya Johnson', firstName: 'Maya', lastName: 'Johnson',
      initials: 'MJ', role: 'Daughter · 15', age: 15, gender: 'female', sex: 'F', dob: '2010-04-12', state: 'GA',
      ancestry: 'Black/African American', smoker: false, bmi: 21.0,
      conditions: [],
      familyHistory: { 'Asthma': 2, 'Sickle Cell Trait': 1 },
      family: ['Asthma', 'Sickle cell trait'],
      insurance: { provider: 'BlueCross BlueShield', memberId: '●●●●●● 4823', planType: 'PPO — Family (Dependent)' },
      appt: { title: 'Well-Teen Visit', when: 'May 10 · 3:30 PM', doctor: 'Dr. Imani Clarke' },
      meds: [],
      medList: [],
      labs: [
        { name: 'Sickle Cell Trait Screen', date: 'Feb 02, 2026', status: 'review', values: [
          { marker: 'Hemoglobin S', value: 'Trait (AS)', unit: '', range: 'Negative', flag: 'L',
            explanation: 'This test shows Maya carries one sickle cell gene — called sickle cell trait. She does NOT have sickle cell disease and will be healthy, but it matters for the future and for family planning.',
            nextSteps: ['Keep this result in her records', 'Share it with future doctors and during sports physicals', 'Learn the basics so the family understands what trait means'] },
        ]},
        { name: 'Well-Teen Blood Panel', date: 'Feb 02, 2026', status: 'normal', values: [] },
      ],
    },

    child: {
      id: 'child', name: 'Amir Johnson', firstName: 'Amir', lastName: 'Johnson',
      initials: 'AJ', role: 'Son · 8', age: 8, gender: 'male', sex: 'M', dob: '2017-07-22', state: 'GA',
      ancestry: 'Black/African American', smoker: false, bmi: 16.8,
      conditions: ['Asthma'],
      familyHistory: { 'Asthma': 2, 'Sickle Cell Trait': 1 },
      family: ['Asthma', 'Sickle cell trait'],
      insurance: { provider: 'BlueCross BlueShield', memberId: '●●●●●● 4824', planType: 'PPO — Family (Dependent)' },
      appt: { title: 'Pediatric Asthma Follow-up', when: 'May 6 · 11:15 AM', doctor: 'Dr. Imani Clarke' },
      meds: [
        { id: 'm6', name: 'Albuterol', dose: '2 puffs', time: 'As needed', taken: false },
      ],
      medList: [
        { name: 'Albuterol', dose: '2 puffs · As needed (rescue inhaler)', condition: 'Asthma', color: '#2563EB' },
      ],
      labs: [
        { name: 'Well-Child Blood Panel', date: 'Jan 18, 2026', status: 'normal', values: [] },
      ],
    },

    mom: {
      id: 'mom', name: 'Denise Johnson', firstName: 'Denise', lastName: 'Johnson',
      initials: 'DJ', role: 'Mother', age: 68, gender: 'female', sex: 'F', state: 'GA',
      ancestry: 'Black/African American', smoker: false, bmi: 31.2,
      conditions: ['Type 2 Diabetes', 'Arthritis'],
      familyHistory: { 'Stroke': 2, 'Type 2 Diabetes': 2, 'Heart Disease': 1 },
      family: ['Stroke', 'Diabetes'],
      insurance: { provider: 'Medicare Advantage', memberId: '●●●●●● 7781', planType: 'HMO — Individual' },
      appt: { title: 'Endocrinology Follow-up', when: 'May 3 · 9:00 AM', doctor: 'Dr. Marcus Reed' },
      meds: [
        { id: 'm7', name: 'Metformin',  dose: '1000mg', time: '7:30 AM',  taken: true  },
        { id: 'm8', name: 'Ibuprofen',  dose: '400mg',  time: '12:00 PM', taken: false },
        { id: 'm9', name: 'Lisinopril', dose: '20mg',   time: '8:00 AM',  taken: false },
      ],
      medList: [
        { name: 'Metformin',  dose: '1000mg · Twice daily',  condition: 'Type 2 Diabetes', color: '#16A34A' },
        { name: 'Ibuprofen',  dose: '400mg · As needed',     condition: 'Arthritis',       color: '#D4A017' },
        { name: 'Lisinopril', dose: '20mg · Once daily',     condition: 'Hypertension',    color: '#C0392B' },
      ],
      labs: [
        { name: 'Diabetes Management Panel', date: 'Apr 09, 2026', status: 'review', values: [
          { marker: 'HbA1c', value: '8.2', unit: '%', range: '< 7.0', flag: 'H',
            explanation: 'HbA1c is your average blood sugar over 3 months. 8.2% is higher than the goal, so the diabetes needs a little more help. Getting this number down lowers the risk of eye, kidney, and nerve problems.',
            nextSteps: ['Talk with the doctor about adjusting medication', 'Book the yearly diabetic eye and foot check', 'Ask about a diabetes educator who understands your foods'] },
          { marker: 'eGFR (Kidney)', value: '62', unit: 'mL/min', range: '> 60', flag: null,
            explanation: 'eGFR shows how well the kidneys clean the blood. Your number is just inside the normal range, so it is worth watching closely with diabetes.',
            nextSteps: ['Recheck kidney function in 6 months', 'Confirm the lab uses the race-neutral formula'] },
          { marker: 'LDL Cholesterol', value: '118', unit: 'mg/dL', range: '< 100', flag: 'H',
            explanation: 'LDL is the "bad" cholesterol. A high level slowly clogs arteries and raises stroke risk — important given the family history of stroke.',
            nextSteps: ['Ask whether a statin is right for you', 'Discuss heart-healthy versions of favorite meals'] },
          { marker: 'Vitamin D', value: '24', unit: 'ng/mL', range: '30–80', flag: 'L',
            explanation: 'Low vitamin D is common and can affect bones and energy. It is easy to fix with a daily supplement.',
            nextSteps: ['Ask about a vitamin D3 supplement', 'Recheck in 3 months'] },
        ]},
      ],
    },
  }

  const ORDER = ['self', 'spouse', 'teen', 'child', 'mom']

  // ── Active member (persisted) ────────────────────────────────
  let active = 'self'
  try { const saved = localStorage.getItem('bha_active_member'); if (saved && PROFILES[saved]) active = saved } catch (e) {}
  window.__bhaActiveMember = active

  // ── Derived stores (consumed by existing screens) ────────────
  // __bhaMembers — the family switcher list (keeps every field the screens read).
  window.__bhaMembers = ORDER.map(id => {
    const p = PROFILES[id]
    const m = { id, name: p.name, role: p.role, initials: p.initials, age: p.age, conditions: p.conditions.slice(), family: p.family.slice() }
    if (p.dob) m.dob = p.dob
    if (p.sex) m.sex = p.sex
    if (p.state) m.state = p.state
    return m
  })

  // Per-member medications (Home "Daily Medications" format) & appointments.
  window.__bhaMeds = {}
  window.__bhaAppt = {}
  window.__bhaLabs = {}
  ORDER.forEach(id => {
    window.__bhaMeds[id] = PROFILES[id].meds.map(d => ({ ...d }))
    window.__bhaAppt[id] = PROFILES[id].appt || null
    window.__bhaLabs[id] = PROFILES[id].labs
  })

  // Expose the full profile map + helpers.
  window.__bhaProfiles = PROFILES
  window.__bhaActiveProfile = function () { return PROFILES[window.__bhaActiveMember] || PROFILES.self }

  // ── The live USER object (mutated in place on switch) ────────
  // Screens do `const USER = window.__bhaUserProfile`; we keep this exact object
  // identity forever and only swap its contents.
  function clinicalFields(id) {
    const p = PROFILES[id]
    return {
      firstName: p.firstName, lastName: p.lastName, initials: p.initials,
      age: p.age, gender: p.gender, sex: p.sex, ancestry: p.ancestry,
      conditions: p.conditions.slice(),
      familyHistory: Object.assign({}, p.familyHistory),
      smoker: p.smoker, bmi: p.bmi,
      insurance: p.insurance.provider, insuranceDetail: Object.assign({}, p.insurance),
      role: p.role, name: p.name,
    }
  }
  window.__bhaUserProfile = window.__bhaUserProfile || {}
  Object.assign(window.__bhaUserProfile, clinicalFields(active))

  // ── The global switch ────────────────────────────────────────
  window.__bhaSetActiveMember = function (id) {
    if (!PROFILES[id]) return
    window.__bhaActiveMember = id
    // Mutate USER in place so captured `const USER` references stay live.
    const next = clinicalFields(id)
    Object.keys(window.__bhaUserProfile).forEach(k => { if (!(k in next)) delete window.__bhaUserProfile[k] })
    Object.assign(window.__bhaUserProfile, next)
    // If the member is a minor, point the immunization view at them.
    const p = PROFILES[id]
    if (p.age != null && p.age <= 18) window.__bhaImmunFocusId = id
    try { localStorage.setItem('bha_active_member', id) } catch (e) {}
    // Tell the whole app to re-render.
    window.dispatchEvent(new CustomEvent('bha-member-change', { detail: { id } }))
  }

  // ── AUTH: Cloudflare Pages Function-based verification ─────────────────
  // Server validates codes and sets sessions. No localStorage secrets.
  window.__bhaAuth = window.__bhaAuth || {}

  window.__bhaStartVerification = async function (email) {
    try {
      const res = await fetch('/api/auth/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email })
      })
      const data = await res.json()
      if (data.error) return { error: data.error }
      console.log('[bha-auth] Code sent to: ' + email)
      return { email }
    } catch (e) {
      console.error('[bha-auth] Start failed:', e)
      return { error: e.message }
    }
  }

  window.__bhaCheckVerification = async function (code, email) {
    try {
      const res = await fetch('/api/auth/check', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code, email })
      })
      const data = await res.json()
      if (data.error) return { error: data.error }
      console.log('[bha-auth] Verified: ' + email)
      return { verified: true, email: data.email }
    } catch (e) {
      console.error('[bha-auth] Check failed:', e)
      return { error: e.message }
    }
  }

  window.__bhaIsVerified = async function () {
    try {
      const res = await fetch('/api/auth/status', { credentials: 'include' })
      const data = await res.json()
      return data.verified === true
    } catch (e) {
      return false
    }
  }

})();
