// bha-screens.jsx — All screen components for Black Healthcare Advocate

window.BHA_COLORS = {
  // BHCA Design System palette
  bg:      '#FFFFFF',          // Clean White - page background (60%)
  bgWarm:  '#F7F3EE',          // Warm Ivory - card backgrounds
  card:    '#F7F3EE',          // Warm Ivory - cards
  cardLt:  '#FFFFFF',          // alt card surface
  text:    '#2E2B28',          // Espresso - primary text/headings
  muted:   '#6B6560',           // Warm Stone - body/labels
  dim:     '#B0AAA5',           // placeholder text
  border:  '#E8E0D5',           // Sand - borders/dividers
  // 30% structure
  midnight:'#1A1A2E',           // Deep Midnight - nav/headers/footer
  // 10% action & delight
  red:     '#C0392B',           // Caduceus Red - primary CTAs
  redDk:   '#993322',           // visited links / hover red
  gold:    '#D4A017',           // Warm Gold - badges/achievements ONLY
  goldLt:  '#E8B84B',           // lighter gold for gradients
  goldDk:  '#8B6914',
  goldBg:  '#FFF8E1',           // gold badge background
  // Alerts (functional only)
  critical:    '#DC2626', criticalBg: '#FEF2F2', criticalText: '#991B1B',
  warning:     '#D97706', warningBg:  '#FFFBEB', warningText:  '#92400E',
  success:     '#16A34A', successBg:  '#F0FDF4', successText:  '#14532D',
  info:        '#2563EB', infoBg:     '#EFF6FF', infoText:     '#1E40AF',
  // Legacy aliases mapped to new palette so existing C.green / C.blue references still work
  green:   '#16A34A',
  greenDk: '#14532D',
  blue:    '#2563EB',
  accent:  '#D4A017',
  shadow:  '0 1px 4px rgba(26,26,46,0.06), 0 0 0 0.5px rgba(232,224,213,0.8)',
  modalOverlay: 'rgba(26,26,46,0.75)',
}
const BHA_COLORS = window.BHA_COLORS
const C = BHA_COLORS

// ── Global card-style theme (reversible: classic ⇆ unified) ──
// All palettes (C, C2, IZ_C, RW_C, RWP_C) reference this one object, so flipping
// the surface tokens restyles every screen at once. Colors are UNCHANGED — the page
// stays white and the warm accent palette is identical. "unified" only swaps card
// surfaces to the clean white-bordered treatment of the Today's Doses section and
// adds a soft separating ring so cards read crisply app-wide.
window.BHA_THEME_PALETTES = {
  classic: { bg: '#FFFFFF', card: '#F7F3EE', shadow: '0 1px 4px rgba(26,26,46,0.06), 0 0 0 0.5px rgba(232,224,213,0.8)' },
  unified: { bg: '#FFFFFF', card: '#FFFFFF', shadow: '0 2px 12px rgba(26,26,46,0.07), 0 0 0 1px rgba(225,216,202,0.95)' },
}
window.applyBHATheme = function (mode) {
  const p = window.BHA_THEME_PALETTES[mode] || window.BHA_THEME_PALETTES.classic
  window.BHA_COLORS.bg = p.bg
  window.BHA_COLORS.card = p.card
  window.BHA_COLORS.shadow = p.shadow
  window.BHA_THEME = mode
  try { localStorage.setItem('bha_theme', mode) } catch (e) {}
}
try { window.applyBHATheme(localStorage.getItem('bha_theme') || 'unified') } catch (e) {}


window.__bhaUserProfile = window.__bhaUserProfile || {
  firstName: 'Marcus',
  lastName: 'Johnson',
  initials: 'MJ',
  age: 47,
  gender: 'male',           // 'male' | 'female' | 'other'
  ancestry: 'Black/African American',
  conditions: ['Hypertension', 'Type 2 Diabetes', 'High Cholesterol'],
  familyHistory: {
    'Hypertension': 3,        // # of relatives
    'Type 2 Diabetes': 2,
    'Heart Disease': 1,
    'Stroke': 1,
    'Prostate Cancer': 1,
  },
  smoker: false,
  bmi: 29.5,
  insurance: 'BlueCross BlueShield',
}
const USER = window.__bhaUserProfile

// ── Shared primitives ──────────────────────────────────────────

function SectionHeader({ title, sub, onBack, backLabel }) {
  return (
    <div style={{ padding: '64px 20px 20px', background: `linear-gradient(to bottom, #FFFFFF, ${C.bg})`, borderBottom: `1px solid ${C.border}` }}>
      {onBack && (
        <button onClick={onBack} className="bha-back-btn" style={{
          background: 'rgba(192,57,43,0.06)', border: '1px solid rgba(192,57,43,0.18)', borderRadius: 20,
          padding: '7px 16px 7px 12px', color: '#C0392B', fontFamily: 'DM Sans, sans-serif',
          fontSize: 13, fontWeight: 600, cursor: 'pointer', marginBottom: 14, display: 'inline-flex', alignItems: 'center', gap: 6,
          transition: 'all 0.18s ease',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M15 18l-6-6 6-6" stroke="#C0392B" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          {backLabel || 'Back'}
        </button>
      )}
      <h1 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 30, color: C.text, lineHeight: 1.15, marginBottom: 6 }}>{title}</h1>
      {sub && <p style={{ color: C.muted, fontSize: 14, lineHeight: 1.5 }}>{sub}</p>}
    </div>
  )
}

function Tag({ label, color }) {
  return <span style={{ background: `${color || C.gold}20`, color: color || C.gold, borderRadius: 6, padding: '3px 8px', fontSize: 11, fontWeight: 600, fontFamily: 'DM Sans, sans-serif' }}>{label}</span>
}

function GoldBtn({ label, onClick, outline, disabled, primary }) {
  // primary=true => red gradient (call-to-action ready state)
  // disabled => muted gray, no shadow, no pointer
  const isDisabled = !!disabled
  let bg, color, border, shadow, cursor
  if (isDisabled) {
    bg = '#E8E0D5'; color = '#A8A29B'; border = '1.5px solid #E8E0D5'; shadow = 'none'; cursor = 'not-allowed'
  } else if (primary) {
    bg = 'linear-gradient(135deg, #C0392B 0%, #8C1225 100%)'
    color = '#fff'; border = 'none'; shadow = '0 6px 18px rgba(192,57,43,0.32)'; cursor = 'pointer'
  } else if (outline) {
    bg = 'transparent'; color = C.gold; border = `1.5px solid ${C.gold}`; shadow = 'none'; cursor = 'pointer'
  } else {
    bg = `linear-gradient(135deg, ${C.goldLt} 0%, ${C.gold} 100%)`
    color = '#fff'; border = 'none'; shadow = '0 4px 14px rgba(122,81,8,0.25)'; cursor = 'pointer'
  }
  return (
    <button onClick={isDisabled ? undefined : onClick} disabled={isDisabled} className={isDisabled ? '' : 'bha-tap'} style={{
      width: '100%', border, background: bg, boxShadow: shadow,
      borderRadius: 14, padding: '15px 24px', color,
      fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 15, cursor,
      transition: 'all 0.25s ease',
    }}>{label}</button>
  )
}

// ── SPLASH ─────────────────────────────────────────────────────

function SplashScreen({ onDone }) {
  const [fade, setFade] = React.useState(0)
  React.useEffect(() => {
    setTimeout(() => setFade(1), 100)
    const t = setTimeout(onDone, 2800)
    return () => clearTimeout(t)
  }, [])
  return (
    <div style={{
      height: '100%', background: 'linear-gradient(160deg, #FDF8F0 0%, #EDE8E0 100%)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      gap: 22, opacity: fade, transition: 'opacity 0.6s ease',
    }}>
      <img src="logo-mark.png" style={{ width: 130, height: 130 }} alt="Black Healthcare Advocate logo: a Sankofa bird with caduceus medical symbol in Pan-African red, gold, and green colors" role="img"/>
      <div style={{ textAlign: 'center' }}>
        <p style={{ color: C.gold, fontFamily: 'DM Sans, sans-serif', fontWeight: 600, fontSize: 12, letterSpacing: 3.5, textTransform: 'uppercase', marginBottom: 8 }}>Black Healthcare</p>
        <h1 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 32, color: C.text, letterSpacing: -0.5 }}>Advocate</h1>
      </div>
      <p style={{ color: C.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 14, textAlign: 'center', lineHeight: 1.7, maxWidth: 230, marginTop: 4 }}>
        AI-driven healthcare navigation<br/>built for the Black community
      </p>
      <div style={{ marginTop: 32, display: 'flex', gap: 6 }}>
        {[C.red, C.gold, C.green].map((col, i) => (
          <div key={i} style={{ width: i === 1 ? 24 : 8, height: 4, borderRadius: 2, background: col, transition: 'all 0.3s' }}/>
        ))}
      </div>
    </div>
  )
}

// ── HOME ───────────────────────────────────────────────────────

// Family plan members — exposed to window for settings access
window.__bhaMembers = window.__bhaMembers || [
  { id: 'self',   name: 'Marcus Johnson', role: 'You',       initials: 'MJ', age: 42, conditions: ['Hypertension','Pre-diabetes'], family: ['Heart disease','Type 2 diabetes'] },
  { id: 'spouse', name: 'Jasmine Johnson',role: 'Spouse',    initials: 'JJ', age: 39, conditions: ['Anemia'],                    family: ['Fibroids','Hypertension'] },
  { id: 'teen',   name: 'Maya Johnson',   role: 'Daughter · 15', initials: 'MJ', age: 15, dob: '2010-04-12', sex: 'F', state: 'GA', conditions: [], family: ['Asthma','Sickle cell trait'] },
  { id: 'child',  name: 'Amir Johnson',   role: 'Son · 8',   initials: 'AJ', age: 8,  dob: '2017-07-22', sex: 'M', state: 'GA', conditions: ['Asthma'], family: ['Asthma','Sickle cell trait'] },
  { id: 'mom',    name: 'Denise Johnson', role: 'Mother',    initials: 'DJ', age: 68, conditions: ['Type 2 diabetes','Arthritis'], family: ['Stroke','Diabetes'] },
]

function insightFor(member) {
  if (!member) return { title: 'Welcome', body: 'Personalized insights will appear as you build your health profile.', cta: null }
  const conds = member.conditions.join(', ').toLowerCase()
  if (conds.includes('hypertension')) return {
    title: 'Hypertension & Black adults',
    body: `Black adults are 2× more likely to develop hypertension. At ${member.age}, consistent monitoring and culturally-competent care are essential.`,
    cta: 'research'
  }
  if (conds.includes('asthma')) return {
    title: 'Pediatric asthma equity',
    body: `Black children experience asthma at 2× the rate of white children and are 7× more likely to die from an attack. Track triggers and ER-readiness.`,
    cta: 'research'
  }
  if (conds.includes('diabetes')) return {
    title: 'Diabetes disparities',
    body: `Black Americans are 60% more likely to be diagnosed with Type 2 diabetes. Regular A1C screening and Black-friendly nutrition support improve outcomes.`,
    cta: 'research'
  }
  if (conds.includes('anemia')) return {
    title: 'Anemia in Black women',
    body: `Iron-deficiency anemia is more common in Black women due to fibroids and menstrual health gaps. Ask your doctor for a full iron panel, not just CBC.`,
    cta: 'results'
  }
  return {
    title: 'Family history insight',
    body: `Your family history of ${member.family.join(' & ')} raises your risk. Screening earlier than standard guidelines may be appropriate — ask your provider.`,
    cta: 'research'
  }
}

window.__bhaMeds = window.__bhaMeds || {
  self:   [
    { 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:'Vitamin D3',    dose:'2000 IU', time:'9:00 AM', taken:true },
  ],
  spouse: [ { id:'m4', name:'Ferrous Sulfate', dose:'325mg', time:'9:00 AM', taken:false } ],
  child:  [ { id:'m5', name:'Albuterol', dose:'2 puffs', time:'As needed', taken:false } ],
  mom:    [
    { id:'m6', name:'Metformin',    dose:'1000mg', time:'7:30 AM', taken:true },
    { id:'m7', name:'Ibuprofen',    dose:'400mg',  time:'12:00 PM',taken:false },
  ],
}

window.__bhaQA = window.__bhaQA || ['prep','results','meds']

window.__bhaAppt = window.__bhaAppt || {
  self:   { title: 'Cardiology Appointment', when: 'Tomorrow · 10:30 AM', doctor: 'Dr. Amara Osei' },
  spouse: { title: 'OB-GYN Annual',          when: 'Apr 28 · 2:00 PM',    doctor: 'Dr. Nia Williams' },
  child:  null,
  mom:    { title: 'Endocrinology Follow-up', when: 'May 3 · 9:00 AM',    doctor: 'Dr. Marcus Reed' },
}

// Default home section order — persists across session
window.__bhaSectionOrder = window.__bhaSectionOrder || ['appointment','engagement','meds','insight','news','family']

// Culturally-relevant news and alerts
const BHA_NEWS = [
  {
    id:'n1', kind:'alert', tag:'HEALTH ALERT', color: '#8C1225',
    title:'Sickle Cell gene therapy approved by FDA for wider access',
    source:'NIH · 2 days ago',
    body:'Casgevy and Lyfgenia — the first cell-based gene therapies for sickle cell disease — are now covered under expanded Medicaid programs in 15 states. Black Americans account for over 90% of U.S. sickle cell cases.'
  },
  {
    id:'n2', kind:'research', tag:'NEW RESEARCH', color:'#1A5228',
    title:'Culturally-adapted diabetes program cuts A1C by 1.2% in Black patients',
    source:'Johns Hopkins · 5 days ago',
    body:'A year-long study shows peer-led, community-based diabetes education more than doubles outcomes vs. standard care. Program expanding to 40 cities in 2026.'
  },
  {
    id:'n3', kind:'policy', tag:'POLICY UPDATE', color:'#1A4A8C',
    title:'CDC expands maternal mortality tracking after Black women\'s rates stay 3× higher',
    source:'CDC · 1 week ago',
    body:'New state-level reporting requirements will identify providers and hospitals with disparate outcomes. Patients can now access provider maternal mortality data by zip code.'
  },
  {
    id:'n4', kind:'study', tag:'CLINICAL TRIAL', color:'#7A5108',
    title:'Hypertension trial seeking Black participants — Atlanta, DC, Houston',
    source:'NHLBI · 2 weeks ago',
    body:'Historic underrepresentation in cardiac trials means current medications weren\'t adequately tested on our community. Compensation up to $1,200. Enrollment now open.'
  },
  {
    id:'n5', kind:'community', tag:'COMMUNITY', color:'#7A5108',
    title:'Free mobile mammography van visits 12 Black churches across the South',
    source:'Susan G. Komen · 3 weeks ago',
    body:'Black women are 40% more likely to die from breast cancer despite similar diagnosis rates. Find a stop near you — no insurance required.'
  },
]

const QA_LIBRARY = [
  { id:'prep',     icon:'📋', label:'Appointment\nPrep',   col: C.red  },
  { id:'results',  icon:'🔬', label:'Test\nResults',       col: C.green },
  { id:'meds',     icon:'💊', label:'My\nMedications',     col: C.gold },
  { id:'schedule', icon:'🗓',  label:'Find\nDoctors',       col: C.blue },
  { id:'forum',    icon:'💬', label:'Health\nForum',       col: C.gold },
  { id:'research', icon:'📚', label:'Research\nLibrary',   col: C.red  },
]

const SECTION_META = {
  appointment:  { name: 'Upcoming Appointment', icon: '📅' },
  engagement:   { name: 'Health Engagement',    icon: '🌟' },
  meds:         { name: 'Daily Medications',    icon: '💊' },
  insight:      { name: 'Daily Insight',        icon: '💡' },
  news:         { name: 'Health News & Alerts', icon: '📰' },
  family:       { name: 'Family Overview',      icon: '👪' },
}

function HomeScreen({ nav }) {
  const [, _bumpMember] = React.useState(0)
  const memberId = window.__bhaActiveMember || 'self'
  const [showSwitcher, setShowSwitcher] = React.useState(false)
  const [showQAEdit, setShowQAEdit] = React.useState(false)
  const [qa, setQA] = React.useState(window.__bhaQA)
  const [meds, setMeds] = React.useState(window.__bhaMeds)
  const [sections, setSections] = React.useState(window.__bhaSectionOrder)
  const [customizing, setCustomizing] = React.useState(false)
  const [dragId, setDragId] = React.useState(null)
  const [dragOverId, setDragOverId] = React.useState(null)
  const [newsIdx, setNewsIdx] = React.useState(0)
  // Re-render Home when the rewards engine changes (dose logging, etc.)
  const [, rwTick] = React.useState(0)
  React.useEffect(() => window.BHA_RW && window.BHA_RW.subscribe(() => rwTick(n => n + 1)), [])
  const [openNews, setOpenNews] = React.useState(null)
  const [shareOpen, setShareOpen] = React.useState(false)

  const members = window.__bhaMembers
  const member = members.find(m => m.id === memberId) || members[0]
  const appt = window.__bhaAppt[memberId]
  const insight = insightFor(member)
  const memberMeds = meds[memberId] || []
  const takenCount = memberMeds.filter(m => m.taken).length

  const setMember = (id) => {
    if (window.__bhaSetActiveMember) window.__bhaSetActiveMember(id)
    else window.__bhaActiveMember = id
    _bumpMember(n => n + 1)   // re-render Home immediately
    setShowSwitcher(false)
  }

  const toggleMed = (medId) => {
    const updated = {
      ...meds,
      [memberId]: meds[memberId].map(m => m.id === medId ? { ...m, taken: !m.taken, takenAt: !m.taken ? new Date().toLocaleTimeString([], {hour:'numeric',minute:'2-digit'}) : null } : m)
    }
    setMeds(updated)
    window.__bhaMeds = updated
  }

  const toggleQA = (id) => {
    let next
    if (qa.includes(id)) next = qa.filter(x => x !== id)
    else if (qa.length >= 3) next = [...qa.slice(1), id]
    else next = [...qa, id]
    setQA(next)
    window.__bhaQA = next
  }

  // Drag & drop section reorder
  const moveSection = (id, dir) => {
    const idx = sections.indexOf(id)
    const newIdx = idx + dir
    if (newIdx < 0 || newIdx >= sections.length) return
    const next = [...sections]
    ;[next[idx], next[newIdx]] = [next[newIdx], next[idx]]
    setSections(next)
    window.__bhaSectionOrder = next
  }

  const onDrop = (targetId) => {
    if (!dragId || dragId === targetId) { setDragId(null); setDragOverId(null); return }
    const fromIdx = sections.indexOf(dragId)
    const toIdx = sections.indexOf(targetId)
    const next = [...sections]
    const [moved] = next.splice(fromIdx, 1)
    next.splice(toIdx, 0, moved)
    setSections(next)
    window.__bhaSectionOrder = next
    setDragId(null)
    setDragOverId(null)
  }

  const resetOrder = () => {
    const def = ['appointment','meds','quickActions','insight','news','family']
    setSections(def)
    window.__bhaSectionOrder = def
  }

  // ── Section renderers ─────────────────────────────────────
  const renderAppointment = () => (
    <>
      <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase', marginBottom: 10, paddingLeft: 4 }}>Upcoming Appointment</p>
      {appt ? (
        <div style={{ background: `linear-gradient(135deg, ${C.red} 0%, #6A0A18 100%)`, borderRadius: 18, padding: 18, boxShadow: '0 6px 24px rgba(140,18,37,0.25)' }}>
          <p style={{ color: '#fff', fontSize: 18, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{appt.title}</p>
          <p style={{ color: 'rgba(255,255,255,0.75)', fontSize: 13, marginTop: 3 }}>{appt.when} · {appt.doctor}</p>
          <button onClick={() => nav('prep')} className="bha-tap" style={{
            marginTop: 14, background: 'rgba(255,255,255,0.18)', border: '1px solid rgba(255,255,255,0.25)',
            borderRadius: 10, padding: '9px 16px', color: '#fff',
            fontFamily: 'DM Sans, sans-serif', fontWeight: 600, fontSize: 13, cursor: 'pointer',
          }}>Prep Questions →</button>
        </div>
      ) : (
        <div style={{ background:'#fff', border:`1px dashed ${C.border}`, borderRadius: 18, padding: 22, textAlign:'center' }}>
          <div style={{ fontSize: 28, marginBottom: 6, opacity: 0.5 }}>📅</div>
          <p style={{ color: C.text, fontSize: 15, fontWeight: 700, fontFamily:'DM Sans, sans-serif' }}>No Upcoming Appointments</p>
          <p style={{ color: C.muted, fontSize: 12, marginTop: 4, lineHeight: 1.5 }}>No visits scheduled for {member.role.toLowerCase()}.</p>
          <button onClick={() => nav('schedule')} className="bha-tap" style={{
            marginTop: 14, background: C.gold, border:'none', borderRadius: 10, padding: '9px 18px',
            color:'#fff', fontFamily:'DM Sans, sans-serif', fontWeight: 700, fontSize: 13, cursor:'pointer'
          }}>Schedule Appointment</button>
        </div>
      )}
    </>
  )

  const renderMeds = () => {
    const RW = window.BHA_RW
    // Primary user's daily meds are the SAME "Today's Doses" the rewards engine
    // tracks — logging/missing here drives streak, pending points & adherence.
    if (RW && memberId === 'self') {
      const doses = RW.get().today.doses
      const loggedCount = doses.filter(d => d.status === 'logged').length
      const doseBtn = (bg, color, border, onClick, label, icon) => (
        <button onClick={onClick} style={{
          flex: 1, padding: '9px 0', borderRadius: 10, cursor: 'pointer',
          background: bg, border: `1.5px solid ${border}`, color,
          fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12.5,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
        }}>{icon} {label}</button>
      )
      return (
        <>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 10, paddingLeft: 4 }}>
            <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase' }}>
              Daily Medications <span style={{ color: C.green, marginLeft: 6 }}>{loggedCount}/{doses.length} logged</span>
            </p>
            <button onClick={() => nav('meds')} style={{ background:'none', border:'none', color: C.gold, fontSize: 11, fontWeight: 700, cursor:'pointer', fontFamily:'DM Sans, sans-serif' }}>View All →</button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {doses.map(d => (
              <div key={d.id} style={{
                border: `1px solid ${d.status === 'logged' ? C.green + '50' : d.status === 'missed' ? C.critical + '50' : C.border}`,
                borderRadius: 14, padding: 13,
                background: d.status === 'logged' ? `${C.green}08` : d.status === 'missed' ? `${C.critical}08` : '#fff',
              }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: d.status === 'pending' ? 10 : 0 }}>
                  <div>
                    <p style={{ color: d.status === 'logged' ? C.muted : C.text, fontSize: 14, fontWeight: 700, fontFamily:'DM Sans, sans-serif', textDecoration: d.status === 'logged' ? 'line-through' : 'none' }}>{d.name} · {d.dose}</p>
                    <p style={{ color: C.muted, fontSize: 11, marginTop: 2, fontFamily:'DM Sans, sans-serif' }}>Scheduled {d.time}</p>
                  </div>
                  {d.status === 'logged' && (
                    <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
                      <span style={{ color: C.green, fontSize: 10, fontWeight: 800, letterSpacing: 0.8, textTransform:'uppercase' }}>✓ Logged +10</span>
                      <button onClick={() => RW.undoDose(d.id)} style={{ background:'none', border:'none', color: C.muted, fontSize: 11, fontWeight: 700, textDecoration:'underline', cursor:'pointer', fontFamily:'DM Sans, sans-serif', padding: 0 }}>Undo</button>
                    </div>
                  )}
                  {d.status === 'missed' && (
                    <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
                      <span style={{ color: C.critical, fontSize: 10, fontWeight: 800, letterSpacing: 0.8, textTransform:'uppercase' }}>Missed −50</span>
                      <button onClick={() => RW.undoDose(d.id)} style={{ background:'none', border:'none', color: C.critical, fontSize: 11, fontWeight: 700, textDecoration:'underline', cursor:'pointer', fontFamily:'DM Sans, sans-serif', padding: 0 }}>Undo</button>
                    </div>
                  )}
                </div>
                {d.status === 'pending' && (
                  <div style={{ display:'flex', gap: 8 }}>
                    {doseBtn(C.green, '#fff', C.green, () => RW.logDose(d.id), 'Log Dose', '✓')}
                    {doseBtn('#fff', C.critical, C.critical + '60', () => RW.missDose(d.id), 'Mark Missed', '✕')}
                  </div>
                )}
              </div>
            ))}
          </div>
          <button onClick={() => nav('rewards')} style={{ width:'100%', marginTop: 8, background:'none', border:'none', color: C.gold, fontSize: 11.5, fontWeight: 700, cursor:'pointer', fontFamily:'DM Sans, sans-serif', textAlign:'left', paddingLeft: 4 }}>
            Logging protects your streak & pending points → 
          </button>
        </>
      )
    }
    // Family members keep their own simple checklist
    return (
    <>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 10, paddingLeft: 4 }}>
        <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase' }}>
          Daily Medications {memberMeds.length > 0 && <span style={{ color: C.green, marginLeft: 6 }}>{takenCount}/{memberMeds.length}</span>}
        </p>
        <button onClick={() => nav('meds')} style={{ background:'none', border:'none', color: C.gold, fontSize: 11, fontWeight: 700, cursor:'pointer', fontFamily:'DM Sans, sans-serif' }}>View All →</button>
      </div>
      {memberMeds.length === 0 ? (
        <div style={{ background:'#fff', border:`1px dashed ${C.border}`, borderRadius: 14, padding: 16, textAlign:'center' }}>
          <p style={{ color: C.muted, fontSize: 13 }}>No medications tracked for {member.role.toLowerCase()}.</p>
        </div>
      ) : memberMeds.map(m => (
        <button key={m.id} onClick={() => toggleMed(m.id)} style={{
          width:'100%', textAlign:'left', background: m.taken ? `${C.green}08` : '#fff',
          border: `1px solid ${m.taken ? C.green+'40' : C.border}`, borderRadius: 14,
          padding: 13, marginBottom: 8, cursor:'pointer',
          display:'flex', alignItems:'center', gap: 12, transition:'all 0.15s'
        }}>
          <div style={{
            width: 26, height: 26, borderRadius: 13, flexShrink: 0,
            border: `2px solid ${m.taken ? C.green : C.border}`,
            background: m.taken ? C.green : 'transparent',
            display:'flex', alignItems:'center', justifyContent:'center',
            color:'#fff', fontSize: 14, fontWeight: 800
          }}>{m.taken ? '✓' : ''}</div>
          <div style={{ flex: 1 }}>
            <p style={{ color: m.taken ? C.muted : C.text, fontSize: 14, fontWeight: 700, fontFamily:'DM Sans, sans-serif', textDecoration: m.taken ? 'line-through' : 'none' }}>{m.name} · {m.dose}</p>
            <p style={{ color: C.muted, fontSize: 11, marginTop: 2 }}>
              {m.taken ? `Taken at ${m.takenAt || 'today'}` : `Scheduled: ${m.time}`}
            </p>
          </div>
          {m.taken && <span style={{ color: C.green, fontSize: 10, fontWeight: 700, letterSpacing: 0.8, textTransform:'uppercase' }}>Taken</span>}
        </button>
      ))}
    </>
    )
  }

  const renderQuickActions = () => (
    <>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 12, paddingLeft: 4 }}>
        <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase' }}>Quick Actions</p>
        <button onClick={() => setShowQAEdit(x => !x)} style={{ background:'none', border:'none', color: C.gold, fontSize: 11, fontWeight: 700, cursor:'pointer', fontFamily:'DM Sans, sans-serif' }}>
          {showQAEdit ? 'Done' : '✎ Edit'}
        </button>
      </div>
      {!showQAEdit ? (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
          {qa.map(id => {
            const a = QA_LIBRARY.find(x => x.id === id)
            if (!a) return null
            return (
              <button key={a.id} onClick={() => nav(a.id)} style={{
                background: C.card, border: `1px solid ${C.border}`, borderRadius: 14,
                padding: '18px 8px', cursor: 'pointer',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
              }}>
                <div style={{ width: 40, height: 40, borderRadius: 12, background: `${a.col}20`, display:'flex', alignItems:'center', justifyContent:'center', fontSize: 20 }}>{a.icon}</div>
                <span style={{ color: C.text, fontSize: 11, fontWeight: 600, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', lineHeight: 1.35, whiteSpace:'pre-line' }}>{a.label}</span>
              </button>
            )
          })}
        </div>
      ) : (
        <div>
          <p style={{ color: C.muted, fontSize: 11, marginBottom: 10, lineHeight: 1.5 }}>Tap to toggle. Select up to 3 to show on Home.</p>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {QA_LIBRARY.map(a => {
              const active = qa.includes(a.id)
              return (
                <button key={a.id} onClick={() => toggleQA(a.id)} style={{
                  background: active ? `${C.gold}12` : '#fff',
                  border: `1.5px solid ${active ? C.gold : C.border}`, borderRadius: 12,
                  padding: 12, cursor: 'pointer', display:'flex', alignItems:'center', gap: 10, textAlign:'left'
                }}>
                  <div style={{ width: 32, height: 32, borderRadius: 10, background: `${a.col}20`, display:'flex', alignItems:'center', justifyContent:'center', fontSize: 16 }}>{a.icon}</div>
                  <span style={{ flex:1, color: C.text, fontSize: 12, fontWeight: 600, fontFamily:'DM Sans, sans-serif' }}>{a.label.replace('\n',' ')}</span>
                  {active && <span style={{ color: C.gold, fontWeight: 800 }}>✓</span>}
                </button>
              )
            })}
          </div>
        </div>
      )}
    </>
  )

  const renderEngagement = () => {
    // Metrics now come from the adherence-driven rewards engine (composite score
    // weighted heaviest on adherence, so score & adherence never visibly disagree).
    const RW = window.BHA_RW
    const m = RW ? RW.compute() : null
    const score = m ? m.score : 75
    const tier = m ? m.tier : { name: 'Advocate', color: C.green, emoji: '🌟' }
    const streak = m ? m.streak : 12
    const adherence = m ? m.adherence : 0
    const pending = m ? m.pending : 0
    const rewardsCount = m ? m.rewardsCount : 3
    return (
      <div style={{ background: `linear-gradient(135deg, #FFFFFF 0%, ${C.gold}08 100%)`, border: `1.5px solid ${C.gold}40`, borderRadius: 18, padding: 18, boxShadow: C.shadow }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom: 14 }}>
          <div>
            <p style={{ color: tier.color, fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: 'uppercase' }}>Health Engagement</p>
            <p style={{ fontFamily: 'DM Serif Display, serif', fontSize: 28, color: C.text, lineHeight: 1, marginTop: 4 }}>
              <span style={{ color: tier.color }}>{score}</span><span style={{ color: C.muted, fontSize: 18 }}>/100</span>
            </p>
          </div>
          <div style={{ background: `${tier.color}15`, color: tier.color, padding:'6px 12px', borderRadius: 100, fontSize: 11, fontWeight: 700, fontFamily:'DM Sans, sans-serif', display:'inline-flex', alignItems:'center', gap: 5 }}>
            <span>{tier.emoji}</span><span>{tier.name}</span>
          </div>
        </div>
        {/* Progress bar */}
        <div style={{ background: C.bg, borderRadius: 100, height: 8, overflow:'hidden', marginBottom: 12 }}>
          <div style={{ width: `${score}%`, height: '100%', background: `linear-gradient(90deg, ${C.green}, ${C.gold}, ${C.red})`, borderRadius: 100, transition:'width 0.5s' }}/>
        </div>
        {/* Pending points — loss-framed */}
        <div style={{ background: `${C.gold}10`, border: `1px solid ${C.gold}30`, borderRadius: 10, padding: '8px 11px', marginBottom: 12, display:'flex', alignItems:'center', gap: 8 }}>
          <span style={{ fontSize: 15 }}>⏳</span>
          <p style={{ color: C.goldDk, fontSize: 12, lineHeight: 1.4, fontFamily:'DM Sans, sans-serif', flex: 1 }}><strong>{pending} pending points</strong> — keep logging your meds to bank them.</p>
        </div>
        {/* Streak + adherence + rewards */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap: 8 }}>
          <div style={{ background: C.bg, borderRadius: 10, padding: 10, textAlign:'center' }}>
            <p style={{ fontSize: 18, marginBottom: 2 }}>{streak > 0 ? '🔥' : '💔'}</p>
            <p style={{ color: C.text, fontSize: 14, fontWeight: 700, fontFamily:'DM Sans, sans-serif' }}>{streak}</p>
            <p style={{ color: C.muted, fontSize: 9, letterSpacing: 0.8, textTransform:'uppercase', fontWeight:600 }}>Day Streak</p>
          </div>
          <div style={{ background: C.bg, borderRadius: 10, padding: 10, textAlign:'center' }}>
            <p style={{ fontSize: 18, marginBottom: 2 }}>💊</p>
            <p style={{ color: C.text, fontSize: 14, fontWeight: 700, fontFamily:'DM Sans, sans-serif' }}>{adherence}%</p>
            <p style={{ color: C.muted, fontSize: 9, letterSpacing: 0.8, textTransform:'uppercase', fontWeight:600 }}>Adherence</p>
          </div>
          <div style={{ background: C.bg, borderRadius: 10, padding: 10, textAlign:'center' }}>
            <p style={{ fontSize: 18, marginBottom: 2 }}>🎁</p>
            <p style={{ color: C.text, fontSize: 14, fontWeight: 700, fontFamily:'DM Sans, sans-serif' }}>{rewardsCount}</p>
            <p style={{ color: C.muted, fontSize: 9, letterSpacing: 0.8, textTransform:'uppercase', fontWeight:600 }}>Rewards</p>
          </div>
        </div>
        <button onClick={() => nav('rewards')} style={{
          marginTop: 12, width:'100%', background:'transparent', border:`1px solid ${C.gold}40`,
          borderRadius: 10, padding: 9, color: C.gold, fontSize: 12, fontWeight: 700,
          fontFamily:'DM Sans, sans-serif', cursor:'pointer'
        }}>View Rewards & Achievements →</button>
      </div>
    )
  }

  const renderInsight = () => (
    <div style={{ background: 'linear-gradient(135deg, #E8F5EC 0%, #D4EDD9 100%)', border: `1px solid ${C.green}50`, borderRadius: 18, padding: 18 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 8 }}>
        <p style={{ color: C.green, fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: 'uppercase' }}>Daily Insight · {member.role}</p>
        <span style={{ fontSize: 16 }}>💡</span>
      </div>
      <p style={{ color: '#1A3320', fontSize: 13, fontWeight: 700, marginBottom: 4 }}>{insight.title}</p>
      <p style={{ color: '#1A3320', fontSize: 13, lineHeight: 1.65 }}>{insight.body}</p>
      {insight.cta && (
        <button onClick={() => nav(insight.cta)} style={{ marginTop: 10, background: 'none', border: 'none', color: C.green, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12, cursor: 'pointer', padding: 0, textDecoration: 'underline' }}>Explore Research →</button>
      )}
    </div>
  )

  const renderNews = () => {
    const featured = BHA_NEWS[newsIdx]
    return (
      <>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 10, paddingLeft: 4 }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase' }}>Health News & Alerts</p>
          <div style={{ display:'flex', gap: 4 }}>
            {BHA_NEWS.map((_, i) => (
              <div key={i} style={{ width: i === newsIdx ? 16 : 5, height: 5, borderRadius: 3, background: i === newsIdx ? C.gold : C.border, transition:'all 0.2s' }}/>
            ))}
          </div>
        </div>

        {/* Featured hero card with swipe dots */}
        <button onClick={() => setOpenNews(featured)} style={{
          width:'100%', textAlign:'left', background: '#fff', border: `1px solid ${C.border}`,
          borderRadius: 18, padding: 0, overflow:'hidden', cursor:'pointer', marginBottom: 10,
          boxShadow: C.shadow
        }}>
          <div style={{ background: `linear-gradient(135deg, ${featured.color} 0%, ${featured.color}CC 100%)`, padding: '14px 16px' }}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <span style={{ color:'#fff', fontSize: 10, fontWeight: 800, letterSpacing: 1.5, background:'rgba(255,255,255,0.18)', padding:'3px 8px', borderRadius: 6 }}>
                {featured.tag}
              </span>
              <span style={{ color:'rgba(255,255,255,0.8)', fontSize: 11, fontFamily:'DM Sans, sans-serif' }}>{featured.source.split(' · ')[1]}</span>
            </div>
            <p style={{ color:'#fff', fontSize: 15, fontWeight: 700, fontFamily:'DM Sans, sans-serif', lineHeight: 1.35, marginTop: 10, textWrap:'pretty' }}>
              {featured.title}
            </p>
          </div>
          <div style={{ padding: '12px 16px 14px' }}>
            <p style={{ color: C.text, fontSize: 12, lineHeight: 1.6 }}>{featured.body.slice(0, 110)}…</p>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop: 10 }}>
              <p style={{ color: C.muted, fontSize: 10, fontFamily:'DM Sans, sans-serif' }}>{featured.source.split(' · ')[0]}</p>
              <span style={{ color: C.gold, fontSize: 11, fontWeight: 700, fontFamily:'DM Sans, sans-serif' }}>Read more →</span>
            </div>
          </div>
        </button>

        {/* Pager controls */}
        <div style={{ display:'flex', gap: 8, justifyContent:'center', marginBottom: 10 }}>
          <button onClick={() => setNewsIdx(i => (i - 1 + BHA_NEWS.length) % BHA_NEWS.length)} style={{
            background:'#fff', border:`1px solid ${C.border}`, borderRadius: 100, padding:'6px 14px',
            fontSize: 11, color: C.muted, cursor:'pointer', fontFamily:'DM Sans, sans-serif', fontWeight: 600
          }}>← Prev</button>
          <button onClick={() => setNewsIdx(i => (i + 1) % BHA_NEWS.length)} style={{
            background:'#fff', border:`1px solid ${C.border}`, borderRadius: 100, padding:'6px 14px',
            fontSize: 11, color: C.muted, cursor:'pointer', fontFamily:'DM Sans, sans-serif', fontWeight: 600
          }}>Next →</button>
        </div>

        {/* List of the rest */}
        <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius: 14, overflow:'hidden' }}>
          {BHA_NEWS.filter((_, i) => i !== newsIdx).slice(0, 3).map((n, i, arr) => (
            <button key={n.id} onClick={() => setOpenNews(n)} style={{
              width:'100%', textAlign:'left', background:'transparent',
              border:'none', borderBottom: i < arr.length - 1 ? `1px solid ${C.border}` : 'none',
              padding: '12px 14px', cursor:'pointer', display:'flex', alignItems:'center', gap: 12
            }}>
              <div style={{ width: 4, height: 38, borderRadius: 2, background: n.color, flexShrink: 0 }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ color: n.color, fontSize: 9, fontWeight: 800, letterSpacing: 1, marginBottom: 3 }}>{n.tag}</p>
                <p style={{ color: C.text, fontSize: 12, fontWeight: 600, fontFamily:'DM Sans, sans-serif', lineHeight: 1.35, overflow:'hidden', textOverflow:'ellipsis', display:'-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient:'vertical' }}>{n.title}</p>
              </div>
              <span style={{ color: C.dim, fontSize: 12 }}>›</span>
            </button>
          ))}
        </div>
      </>
    )
  }

  const renderFamily = () => {
    if (members.length <= 1) return null
    return (
      <>
        <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase', marginBottom: 10, paddingLeft: 4 }}>Family Health Overview</p>
        <div style={{ display:'flex', gap: 10, overflowX: 'auto', paddingBottom: 4 }}>
          {members.map(m => {
            const mMeds = meds[m.id] || []
            const done = mMeds.filter(x => x.taken).length
            return (
              <button key={m.id} onClick={() => setMember(m.id)} style={{
                flex:'0 0 130px', background: m.id === memberId ? `${C.gold}10` : '#fff',
                border: `1.5px solid ${m.id === memberId ? C.gold : C.border}`, borderRadius: 14,
                padding: 12, cursor:'pointer', display:'flex', flexDirection:'column', gap:6, textAlign:'left'
              }}>
                <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 14, background:`linear-gradient(135deg,${C.gold},${C.red})`, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:10, fontWeight:700 }}>{m.initials}</div>
                  <p style={{ color: C.text, fontSize: 12, fontWeight:700, fontFamily:'DM Sans, sans-serif' }}>{m.name.split(' ')[0]}</p>
                </div>
                <p style={{ color: C.muted, fontSize: 10 }}>{m.role}</p>
                {mMeds.length > 0 && (
                  <div style={{ marginTop: 2, background: C.bg, borderRadius: 6, height: 4, overflow:'hidden' }}>
                    <div style={{ width: `${(done/mMeds.length)*100}%`, height: '100%', background: C.green, transition:'width 0.3s' }}/>
                  </div>
                )}
                <p style={{ color: C.muted, fontSize: 10 }}>{mMeds.length > 0 ? `${done}/${mMeds.length} meds today` : 'No meds'}</p>
              </button>
            )
          })}
        </div>
      </>
    )
  }

  const renderers = {
    appointment: renderAppointment,
    engagement: renderEngagement,
    meds: renderMeds,
    insight: renderInsight,
    news: renderNews,
    family: renderFamily,
  }

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      {/* Header with member switcher */}
      <div style={{ padding: '56px 20px 20px', background: 'linear-gradient(160deg, #FDF6EC 0%, #FFFFFF 60%, #F6F2EC 100%)' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom: 8 }}>
          <div>
            <p style={{ color: C.gold, fontSize: 11, fontWeight: 700, letterSpacing: 2, textTransform: 'uppercase' }}>Welcome back</p>
            <h1 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 28, color: C.text, marginTop:2 }}>{member.name.split(' ')[0]}</h1>
          </div>
          <button onClick={() => setShowSwitcher(s => !s)} style={{
            background:'#fff', border:`1px solid ${C.border}`, borderRadius: 100, padding:'6px 10px 6px 6px',
            display:'flex', alignItems:'center', gap:8, cursor:'pointer', boxShadow: C.shadow
          }}>
            <div style={{ width:28, height:28, borderRadius:14, background:`linear-gradient(135deg,${C.gold},${C.red})`, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700 }}>{member.initials}</div>
            <span style={{ color: C.text, fontSize: 12, fontWeight:600, fontFamily:'DM Sans, sans-serif' }}>{member.role}</span>
            <span style={{ color: C.muted, fontSize: 10 }}>▼</span>
          </button>
        </div>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <p style={{ color: C.muted, fontSize: 13, marginTop: 4 }}>Family Plan · viewing {member.role.toLowerCase()}</p>
          <button onClick={() => setCustomizing(c => !c)} style={{
            background: customizing ? C.gold : 'transparent',
            border: `1px solid ${customizing ? C.gold : C.border}`, borderRadius: 100,
            padding:'5px 12px', cursor:'pointer', color: customizing ? '#fff' : C.gold,
            fontSize: 11, fontWeight: 700, fontFamily:'DM Sans, sans-serif', marginTop: 4,
            display:'inline-flex', alignItems:'center', gap: 5
          }}>
            {customizing ? '✓ Done' : '⇅ Customize'}
          </button>
        </div>
      </div>

      {/* Member Switcher Dropdown */}
      {showSwitcher && (
        <div style={{ position:'absolute', top: 110, right: 16, zIndex: 20, background:'#fff', border:`1px solid ${C.border}`, borderRadius: 14, boxShadow:'0 10px 30px rgba(0,0,0,0.15)', width: 240, overflow:'hidden' }}>
          <p style={{ padding:'12px 14px 8px', color: C.muted, fontSize: 10, fontWeight:700, letterSpacing: 1.2, textTransform:'uppercase' }}>Switch Member</p>
          {members.map(m => (
            <button key={m.id} onClick={() => setMember(m.id)} style={{
              width:'100%', background: m.id === memberId ? `${C.gold}12` : 'transparent',
              border:'none', padding:'10px 14px', display:'flex', alignItems:'center', gap:10, cursor:'pointer', textAlign:'left'
            }}>
              <div style={{ width:32, height:32, borderRadius:16, background:`linear-gradient(135deg,${C.gold},${C.red})`, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:12, fontWeight:700 }}>{m.initials}</div>
              <div style={{ flex:1 }}>
                <p style={{ color: C.text, fontSize:13, fontWeight:600, fontFamily:'DM Sans, sans-serif' }}>{m.name}</p>
                <p style={{ color: C.muted, fontSize:11 }}>{m.role}</p>
              </div>
              {m.id === memberId && <span style={{ color: C.gold, fontSize: 14 }}>✓</span>}
            </button>
          ))}
          <div style={{ borderTop:`1px solid ${C.border}`, padding:10 }}>
            <button onClick={() => { setShowSwitcher(false); nav('more') }} style={{ width:'100%', background:'none', border:'none', color: C.gold, fontSize:12, fontWeight:700, fontFamily:'DM Sans, sans-serif', cursor:'pointer', padding:6 }}>+ Add family member</button>
          </div>
        </div>
      )}

      {/* Customize banner */}
      {customizing && (
        <div style={{ margin:'12px 16px 0', background:`${C.gold}10`, border:`1px solid ${C.gold}40`, borderRadius: 12, padding: 12 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <div style={{ flex:1 }}>
              <p style={{ color: C.text, fontSize: 12, fontWeight: 700, fontFamily:'DM Sans, sans-serif' }}>Customize your Home Dashboard</p>
              <p style={{ color: C.muted, fontSize: 11, marginTop: 3, lineHeight: 1.5 }}>Drag sections, or use ↑↓ to reorder.</p>
            </div>
            <button onClick={resetOrder} style={{ background:'none', border:'none', color: C.gold, fontSize: 11, fontWeight: 700, fontFamily:'DM Sans, sans-serif', cursor:'pointer' }}>Reset</button>
          </div>
        </div>
      )}

      {/* Reorderable sections */}
      <div style={{ paddingTop: 16 }}>
        {sections.map((id, idx) => {
          const r = renderers[id]
          if (!r) return null
          const rendered = r()
          if (rendered === null) return null
          const isDragged = dragId === id
          const isDragOver = dragOverId === id && dragId !== id
          const meta = SECTION_META[id]
          return (
            <div
              key={id}
              draggable={customizing}
              onDragStart={(e) => { setDragId(id); e.dataTransfer.effectAllowed = 'move' }}
              onDragOver={(e) => { if (customizing) { e.preventDefault(); setDragOverId(id) } }}
              onDragLeave={() => setDragOverId(null)}
              onDrop={(e) => { e.preventDefault(); onDrop(id) }}
              onDragEnd={() => { setDragId(null); setDragOverId(null) }}
              style={{
                padding: '0 16px', marginBottom: 22,
                opacity: isDragged ? 0.4 : 1,
                transform: isDragOver ? 'translateY(4px)' : 'none',
                transition: 'opacity 0.15s, transform 0.15s',
                position: 'relative'
              }}
            >
              {customizing && (
                <div style={{
                  background: '#fff', border: `1.5px solid ${isDragOver ? C.gold : C.border}`, borderRadius: 14,
                  padding: '10px 12px', marginBottom: 8, display:'flex', alignItems:'center', gap: 10,
                  boxShadow: isDragOver ? `0 0 0 3px ${C.gold}30` : 'none',
                  cursor: 'grab'
                }}>
                  <span style={{ fontSize: 16, color: C.muted, cursor:'grab' }}>⋮⋮</span>
                  <span style={{ fontSize: 16 }}>{meta.icon}</span>
                  <span style={{ flex: 1, color: C.text, fontSize: 13, fontWeight: 700, fontFamily:'DM Sans, sans-serif' }}>{meta.name}</span>
                  <button onClick={(e) => { e.stopPropagation(); moveSection(id, -1) }} disabled={idx === 0} style={{
                    background: idx === 0 ? 'transparent' : `${C.gold}15`, border:'none',
                    width: 28, height: 28, borderRadius: 8, color: idx === 0 ? C.dim : C.gold,
                    fontSize: 14, fontWeight: 800, cursor: idx === 0 ? 'default' : 'pointer'
                  }}>↑</button>
                  <button onClick={(e) => { e.stopPropagation(); moveSection(id, 1) }} disabled={idx === sections.length - 1} style={{
                    background: idx === sections.length - 1 ? 'transparent' : `${C.gold}15`, border:'none',
                    width: 28, height: 28, borderRadius: 8, color: idx === sections.length - 1 ? C.dim : C.gold,
                    fontSize: 14, fontWeight: 800, cursor: idx === sections.length - 1 ? 'default' : 'pointer'
                  }}>↓</button>
                </div>
              )}
              {/* Preview mode when customizing — show collapsed summary only, full content when not */}
              {customizing ? (
                <div style={{ background:'#FAF7F2', border:`1px dashed ${C.border}`, borderRadius: 12, padding: '10px 14px' }}>
                  <p style={{ color: C.muted, fontSize: 11, fontStyle:'italic' }}>Preview hidden while reordering</p>
                </div>
              ) : rendered}
            </div>
          )
        })}
      </div>

      {/* News detail modal */}
      {openNews && (
        <div onClick={() => { setOpenNews(null); setShareOpen(false) }} style={{
          position:'absolute', inset: 0, background:'rgba(0,0,0,0.5)', zIndex: 40,
          display:'flex', alignItems:'flex-end', justifyContent:'center'
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            background:'#fff', width:'100%', maxHeight:'85%', overflowY:'auto',
            borderTopLeftRadius: 24, borderTopRightRadius: 24,
            animation:'slideUp 0.25s ease-out'
          }}>
            <div style={{ padding:'12px 0', display:'flex', justifyContent:'center' }}>
              <div style={{ width:44, height:4, borderRadius:2, background: C.border }}/>
            </div>
            <div style={{ padding:'0 22px 32px' }}>
              <span style={{ display:'inline-block', color:'#fff', fontSize: 10, fontWeight: 800, letterSpacing: 1.5, background: openNews.color, padding:'4px 10px', borderRadius: 6, marginBottom: 14 }}>
                {openNews.tag}
              </span>
              <h2 style={{ fontFamily:'DM Serif Display, serif', fontSize: 22, color: C.text, lineHeight: 1.25, marginBottom: 10 }}>
                {openNews.title}
              </h2>
              <p style={{ color: C.muted, fontSize: 12, marginBottom: 18 }}>{openNews.source}</p>
              <p style={{ color: C.text, fontSize: 14, lineHeight: 1.75 }}>{openNews.body}</p>
              <div style={{ marginTop: 24, padding: 14, background: `${openNews.color}10`, borderLeft: `3px solid ${openNews.color}`, borderRadius: 8 }}>
                <p style={{ color: openNews.color, fontSize: 11, fontWeight: 800, letterSpacing: 1, textTransform:'uppercase', marginBottom: 6 }}>Why this matters</p>
                <p style={{ color: C.text, fontSize: 13, lineHeight: 1.65 }}>This update directly impacts Black American health outcomes. Save to your library or share with your care team.</p>
              </div>
              {!shareOpen ? (
                <div style={{ marginTop: 20 }}>
                  <div style={{ display:'flex', gap: 10 }}>
                    <button onClick={() => { setOpenNews(null); setShareOpen(false) }} className="bha-tap" style={{
                      flex: 1.3, background: C.gold, color:'#fff', border:'none', borderRadius: 12,
                      padding: '12px', fontWeight: 700, fontSize: 13, fontFamily:'DM Sans, sans-serif', cursor:'pointer'
                    }}>Save to Library</button>
                    <button onClick={() => setShareOpen(true)} style={{
                      flex: 1, background: `${C.gold}12`, color: C.gold, border: `1.5px solid ${C.gold}`, borderRadius: 12,
                      padding: '12px', fontWeight: 700, fontSize: 13, fontFamily:'DM Sans, sans-serif', cursor:'pointer',
                      display:'flex', alignItems:'center', justifyContent:'center', gap: 6
                    }}>
                      <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><circle cx="18" cy="5" r="2.6" stroke={C.gold} strokeWidth="1.8"/><circle cx="6" cy="12" r="2.6" stroke={C.gold} strokeWidth="1.8"/><circle cx="18" cy="19" r="2.6" stroke={C.gold} strokeWidth="1.8"/><path d="M8.4 10.7l7.2-4.2M8.4 13.3l7.2 4.2" stroke={C.gold} strokeWidth="1.8"/></svg>
                      Share
                    </button>
                  </div>
                  <button onClick={() => { setOpenNews(null); setShareOpen(false) }} style={{
                    width:'100%', marginTop: 10, background: 'transparent', color: C.muted, border: `1.5px solid ${C.border}`, borderRadius: 12,
                    padding: '11px', fontWeight: 700, fontSize: 13, fontFamily:'DM Sans, sans-serif', cursor:'pointer'
                  }}>Close</button>
                </div>
              ) : (() => {
                const shareText = encodeURIComponent(`${openNews.title}\n\n${openNews.source}\n\nShared from Black Healthcare Advocate`)
                const subject = encodeURIComponent(openNews.title)
                const optStyle = { flex: 1, textDecoration:'none', borderRadius: 12, padding: '14px 10px', display:'flex', flexDirection:'column', alignItems:'center', gap: 6, fontFamily:'DM Sans, sans-serif', fontWeight: 700, fontSize: 13 }
                return (
                  <div style={{ marginTop: 20 }}>
                    <p style={{ color: C.muted, fontSize: 11, fontWeight: 800, textTransform:'uppercase', letterSpacing: 1, marginBottom: 12, fontFamily:'DM Sans, sans-serif' }}>Share this update</p>
                    <div style={{ display:'flex', gap: 10 }}>
                      <a href={`sms:&body=${shareText}`} style={{ ...optStyle, background: `${C.green}12`, color: C.green, border: `1.5px solid ${C.green}40` }}>
                        <span style={{ fontSize: 20 }}>💬</span>Text Message
                      </a>
                      <a href={`mailto:?subject=${subject}&body=${shareText}`} style={{ ...optStyle, background: `${C.blue}12`, color: C.blue, border: `1.5px solid ${C.blue}40` }}>
                        <span style={{ fontSize: 20 }}>✉️</span>Email
                      </a>
                    </div>
                    <button onClick={() => setShareOpen(false)} style={{
                      width:'100%', marginTop: 10, background: 'transparent', color: C.muted, border: `1.5px solid ${C.border}`, borderRadius: 12,
                      padding: '11px', fontWeight: 700, fontSize: 13, fontFamily:'DM Sans, sans-serif', cursor:'pointer'
                    }}>← Back</button>
                  </div>
                )
              })()}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// ── APPOINTMENT PREP ───────────────────────────────────────────

function PrepScreen({ nav }) {
  const [step, setStep] = React.useState('form')
  const [reason, setReason] = React.useState('')
  const [specialty, setSpecialty] = React.useState('Cardiology')
  const [questions, setQuestions] = React.useState([])
  const [recording, setRecording] = React.useState(false)
  const recogRef = React.useRef(null)

  const toggleVoice = () => {
    if (recording) {
      recogRef.current && recogRef.current.stop()
      setRecording(false)
      return
    }
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition
    if (!SR) {
      alert('Voice input is not supported in this browser. Please use Chrome or Safari.')
      return
    }
    const recog = new SR()
    recog.continuous = true
    recog.interimResults = true
    recog.lang = 'en-US'
    let finalText = reason ? reason + ' ' : ''
    recog.onresult = (e) => {
      let interim = ''
      for (let i = e.resultIndex; i < e.results.length; i++) {
        if (e.results[i].isFinal) finalText += e.results[i][0].transcript + ' '
        else interim += e.results[i][0].transcript
      }
      setReason((finalText + interim).trim())
    }
    recog.onerror = () => setRecording(false)
    recog.onend = () => setRecording(false)
    recog.start()
    recogRef.current = recog
    setRecording(true)
  }

  const generate = async () => {
    if (!reason.trim()) return
    setStep('loading')
    try {
      const res = await window.bhaAI.complete(`You are a Black healthcare advocate AI. Generate exactly 6 important questions a Black patient should ask their ${specialty} doctor about: "${reason}".
Consider health disparities that disproportionately affect the Black community, such as implicit bias, genetic variations, and underrepresentation in clinical trials.
Return ONLY a valid JSON array: [{"question": "...", "why": "one-sentence reason why this matters for Black patients, in VERY simple plain language an 8th grader could easily understand — everyday words, no medical jargon"}]`)
      setQuestions(JSON.parse(res.match(/\[[\s\S]*\]/)[0]))
    } catch {
      setQuestions([
        { question: "What are all my treatment options and their evidence base?", why: "Black patients are sometimes offered fewer options due to systemic bias." },
        { question: "Have clinical trials for this treatment included Black participants?", why: "Many drugs were tested on predominantly white populations." },
        { question: "Are there genetic or biological factors specific to my ancestry I should know about?", why: "Conditions like hypertension and kidney disease present differently in Black patients." },
        { question: "What are the full side effects, and how do they present in darker skin tones?", why: "Symptoms like rashes are often missed on darker complexions." },
        { question: "What lifestyle changes would complement or potentially reduce medication?", why: "Holistic approaches improve outcomes and patient agency." },
        { question: "What are the warning signs I should monitor at home?", why: "Self-advocacy between visits is critical." },
      ])
    }
    setStep('questions')
  }

  if (step === 'form') return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Appointment Prep" sub="AI-powered questions tailored to your profile" onBack={() => nav('home')} backLabel="Home" />
      <div style={{ padding: '0 16px' }}>
        {/* Profile Card */}
        <div style={{ background: C.card, borderRadius: 16, padding: 16, marginBottom: 12, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 12 }}>Patient Profile</p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <div style={{ width: 46, height: 46, borderRadius: 23, background: `linear-gradient(135deg, ${C.gold}, ${C.red})`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 17 }}>MJ</div>
            <div>
              <p style={{ color: C.text, fontWeight: 700, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>Marcus Johnson, 47</p>
              <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>Hypertension · Type 2 Diabetes · High Cholesterol</p>
            </div>
          </div>
          <button style={{ background: 'none', border: `1px solid ${C.border}`, borderRadius: 8, padding: '8px 12px', color: C.gold, fontFamily: 'DM Sans, sans-serif', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
            🏥 Connect Epic / MyChart
          </button>
        </div>

        {/* Specialty */}
        <div style={{ background: C.card, borderRadius: 16, padding: 16, marginBottom: 12, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10 }}>Specialty</p>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {['Cardiology', 'Primary Care', 'Endocrinology', 'Neurology', 'Oncology', 'OB-GYN'].map(s => (
              <button key={s} onClick={() => setSpecialty(s)} style={{
                padding: '7px 12px', borderRadius: 20,
                border: `1.5px solid ${specialty === s ? C.gold : C.border}`,
                background: specialty === s ? `${C.gold}12` : C.card,
                color: specialty === s ? C.gold : C.muted,
                fontFamily: 'DM Sans, sans-serif', fontSize: 13, cursor: 'pointer',
                fontWeight: specialty === s ? 700 : 500,
              }}>{s}</button>
            ))}
          </div>
        </div>

        {/* Reason */}
        <div style={{ background: C.card, borderRadius: 16, padding: 16, marginBottom: 18, border: `1px solid ${C.border}` }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 10 }}>
            <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1 }}>Reason for Visit</p>
            <button onClick={toggleVoice} style={{
              background: recording ? C.red : `${C.gold}15`,
              border: `1px solid ${recording ? C.red : C.gold}40`,
              borderRadius: 100, padding: '5px 11px', cursor: 'pointer',
              color: recording ? '#fff' : C.gold, fontSize: 11, fontWeight: 700,
              fontFamily: 'DM Sans, sans-serif', display:'inline-flex', alignItems:'center', gap: 5,
            }}>
              <span style={{ fontSize: 11 }}>{recording ? '⏹' : '🎤'}</span>
              {recording ? 'Stop' : 'Voice Input'}
            </button>
          </div>
          {recording && (
            <div style={{ background: '#FEF2F4', border: `1px solid ${C.red}40`, borderRadius: 8, padding: '8px 10px', marginBottom: 10, display:'flex', alignItems:'center', gap: 8 }}>
              <div style={{ width: 8, height: 8, borderRadius: 4, background: C.red, animation: 'pulse 1.2s ease-in-out infinite' }}/>
              <p style={{ color: C.red, fontSize: 12, fontWeight: 600, fontFamily:'DM Sans, sans-serif' }}>Listening… speak naturally</p>
            </div>
          )}
          <textarea value={reason} onChange={e => setReason(e.target.value)}
            placeholder="Describe your symptoms or the purpose of this visit, or tap 🎤 to dictate..."
            style={{ width: '100%', background: '#F6F2EC', border: `1.5px solid ${C.border}`, borderRadius: 10, padding: 12, color: C.text, fontFamily: 'DM Sans, sans-serif', fontSize: 14, resize: 'none', minHeight: 90, outline: 'none', lineHeight: 1.6, boxSizing: 'border-box' }}
          />
        </div>
        <GoldBtn label={reason.trim() ? "Generate My Questions →" : "Add a reason to continue"} onClick={generate} primary={!!reason.trim()} disabled={!reason.trim()} />
      </div>
    </div>
  )

  if (step === 'loading') return (
    <div style={{ height: '100%', background: C.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18 }}>
      <div style={{ width: 64, height: 64, borderRadius: 32, background: `${C.gold}15`, border: `2px solid ${C.gold}`, display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'pulse 1.6s ease-in-out infinite' }}><svg width="32" height="32" viewBox="0 0 24 24" fill="none"><path d="M12 2.5l2.3 6.2 6.2 2.3-6.2 2.3L12 19.5l-2.3-6.2L3.5 11l6.2-2.3z" fill={C.gold}/><circle cx="19" cy="5" r="1.6" fill={C.gold}/></svg></div>
      <p style={{ color: C.text, fontWeight: 700, fontSize: 17, fontFamily: 'DM Sans, sans-serif' }}>Analyzing Your Profile</p>
      <p style={{ color: C.muted, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>Generating personalized questions...</p>
    </div>
  )

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Your Questions" sub={`${specialty} · ${questions.length} questions generated by AI`} onBack={() => setStep('form')} backLabel="Prep" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {questions.map((q, i) => (
          <div key={i} style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <span style={{ background: C.gold, color: '#000', borderRadius: 20, width: 26, height: 26, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 12, flexShrink: 0 }}>{i + 1}</span>
              <div>
                <p style={{ color: C.text, fontWeight: 600, fontSize: 14, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>{q.question}</p>
                {q.why && <p style={{ color: C.muted, fontSize: 13, marginTop: 7, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>💡 {q.why}</p>}
              </div>
            </div>
          </div>
        ))}
        <GoldBtn label="Save to Appointment Notes" outline />
        <GoldBtn label="Schedule This Appointment →" onClick={() => nav('schedule')} />
      </div>
    </div>
  )
}

// ── TEST RESULTS ───────────────────────────────────────────────

function ResultValueCard({ v, expanded, onToggle }) {
  const accent = v.flag === 'H' ? C.red : v.flag === 'L' ? '#B05A00' : C.green
  return (
    <div style={{ background: C.card, borderRadius: 14, border: `1.5px solid ${v.flag ? accent + '50' : C.border}`, boxShadow: '0 1px 4px rgba(0,0,0,0.04)', overflow: 'hidden' }}>
      <button onClick={onToggle} style={{ width: '100%', background:'none', border:'none', cursor:'pointer', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left' }}>
        <div style={{ flex: 1 }}>
          <p style={{ color: C.text, fontWeight: 700, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>{v.marker}</p>
          <p style={{ color: C.muted, fontSize: 12, marginTop: 2, fontFamily: 'DM Sans, sans-serif' }}>Normal: {v.range} {v.unit}</p>
        </div>
        <div style={{ textAlign: 'right' }}>
          <p style={{ color: accent, fontWeight: 800, fontSize: 20, fontFamily: 'DM Sans, sans-serif' }}>{v.value}</p>
          <p style={{ color: C.muted, fontSize: 11, fontFamily: 'DM Sans, sans-serif' }}>{v.unit}{v.flag ? ` · ${v.flag === 'H' ? '▲ High' : '▼ Low'}` : ' · ✓ Normal'}</p>
        </div>
        <span style={{ color: C.dim, fontSize: 16, marginLeft: 4, transform: expanded ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s' }}>⌄</span>
      </button>
      {expanded && (
        <div style={{ padding: '0 16px 16px', borderTop: `1px solid ${C.border}`, background: C.bg + '60' }}>
          <p style={{ color: C.muted, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginTop: 12, marginBottom: 6, fontFamily: 'DM Sans, sans-serif' }}>What This Means</p>
          <p style={{ color: C.text, fontSize: 13, lineHeight: 1.65, fontFamily: 'DM Sans, sans-serif' }}>{v.explanation}</p>
          {v.nextSteps && v.nextSteps.length > 0 && (
            <>
              <p style={{ color: C.muted, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginTop: 14, marginBottom: 8, fontFamily: 'DM Sans, sans-serif' }}>Recommended Next Steps</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {v.nextSteps.map((step, j) => (
                  <div key={j} style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                    <span style={{ color: accent, fontSize: 14, lineHeight: 1.4, flexShrink: 0 }}>→</span>
                    <p style={{ color: C.text, fontSize: 13, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>{step}</p>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      )}
    </div>
  )
}

function ResultsScreen({ nav }) {
  const [selectedTest, setSelectedTest] = React.useState(null)
  const [view, setView] = React.useState('list')
  const [selected, setSelected] = React.useState(null)
  const [aiNote, setAiNote] = React.useState('')
  const [loading, setLoading] = React.useState(false)
  const [expanded, setExpanded] = React.useState(null)

  // Per-member lab results (defined in bha-data.jsx, keyed by active member).
  const labs = (window.__bhaLabs && window.__bhaLabs[window.__bhaActiveMember]) || []

  const openLab = async (lab) => {
    setSelected(lab)
    setView('detail')
    setAiNote('')
    if (lab.values.length === 0) return
    setLoading(true)
    try {
      const flagged = lab.values.filter(v => v.flag)
      const res = await window.bhaAI.complete(`You are a warm, caring Black healthcare advocate. Explain these lab results in VERY simple, plain language that an 8-year-old could easily understand.
Rules: Use short sentences. Use everyday words, not medical words. If you must use a medical word, explain it right away in simple terms (like "your blood pressure — how hard your blood pushes"). Use friendly comparisons a child would get. Keep it to 3-4 short sentences. Be encouraging, never scary.
Results:
${flagged.map(v => `${v.marker}: ${v.value}${v.unit} (normal: ${v.range}) — ${v.flag === 'H' ? 'High' : 'Low'}`).join('\n')}
Gently mention one thing that matters for Black patients in simple words, and end with one easy thing to ask the doctor.`)
      setAiNote(res)
    } catch {
      setAiNote("A few of your numbers are a little off, but don't worry — we can fix this together. Your blood (the red stuff that carries air around your body) is a bit low, so you might feel tired sometimes. Your sugar and fat numbers are higher than we'd like, which means your body needs a little extra help and healthy food. One thing to know: low Vitamin D is common for Black folks, so ask your doctor, 'Should I take Vitamin D, and what foods will help me feel better?'")
    }
    setLoading(false)
  }

  if (selectedTest) {
    const t = selectedTest
    const urgentColors = { overdue: C.critical, due: C.warning, recommended: C.muted }
    const urgentLabels = { overdue: 'Overdue', due: 'Due Now', recommended: 'Recommended' }
    const testInfo = {
      'Coronary Artery Calcium Scan': { what: 'A non-invasive CT scan that measures calcified plaque in your coronary arteries — a strong predictor of future heart attack risk.', prep: 'No prep needed. Avoid caffeine 4 hours before. Wear loose clothing.', duration: '10–15 minutes', cost: 'Often $100–$400 out-of-pocket; some insurance covers with risk factors.' },
      'Heart Disease Risk Panel': { what: 'A blood test panel measuring cholesterol (LDL, HDL, triglycerides), blood pressure, and inflammation markers like hs-CRP.', prep: 'Fast for 9–12 hours before (water only).', duration: '15 minutes', cost: 'Routinely covered as preventive care.' },
      'PSA (Prostate Cancer Screening)': { what: 'A simple blood test measuring prostate-specific antigen. Elevated levels can indicate prostate issues, including cancer.', prep: 'Avoid ejaculation, vigorous cycling, and prostate exams 48 hours before.', duration: '5 minutes (blood draw)', cost: 'Covered annually as preventive care for eligible ages.' },
      'Mammogram': { what: 'X-ray imaging of breast tissue used to detect early signs of breast cancer.', prep: 'Avoid deodorant, lotions, or powders on chest area day-of. Schedule the week after your period.', duration: '20–30 minutes', cost: 'Annual screening covered with no copay under ACA.' },
      'Pap Smear + HPV Test': { what: 'A cervical cell sample tested for abnormal cells and high-risk HPV strains that cause cervical cancer.', prep: 'Avoid intercourse, douching, and vaginal medications 48 hours before.', duration: '10–15 minutes', cost: 'Covered as preventive care.' },
      'Colonoscopy': { what: 'A flexible camera examination of the colon to detect and remove polyps before they become cancerous.', prep: 'Liquid diet day before; bowel prep solution evening prior.', duration: '30–60 minutes; arrange a ride home.', cost: 'Screening covered with no copay under ACA.' },
      'Skin Cancer Screening': { what: 'Full-body visual exam by a dermatologist looking for suspicious moles or lesions using the ABCDE method.', prep: 'Remove makeup, nail polish; come with hair down.', duration: '10–20 minutes', cost: 'Often covered with referral; cash price ~$100–$200.' },
      'Diabetic Retinal Eye Exam': { what: 'Dilated eye exam to detect early diabetic retinopathy — a leading cause of blindness in adults with diabetes.', prep: 'Bring sunglasses; vision blurry 4–6 hours after.', duration: '30 minutes', cost: 'Covered annually for patients with diabetes.' },
      'Diabetic Foot Exam': { what: 'A clinician checks your feet for nerve damage, circulation issues, and wounds that could lead to infection or amputation.', prep: 'Wear easy-to-remove shoes and socks.', duration: '10 minutes', cost: 'Covered with diabetes diagnosis.' },
      'A1C Diabetes Check': { what: 'Blood test measuring your average blood sugar over the past 3 months. Goal is typically under 7%.', prep: 'No fasting required.', duration: '5 minutes', cost: 'Covered as routine diabetes management.' },
      'Sickle Cell Trait Test': { what: 'Blood test that determines if you carry the sickle cell gene. Important for family planning and certain medical situations.', prep: 'None.', duration: '5 minutes', cost: 'Often free at community health programs; ~$50 cash.' },
      'Sleep Apnea Screening': { what: 'A questionnaire (STOP-BANG) followed by a take-home sleep study if indicated. Untreated apnea worsens BP, diabetes, and heart disease.', prep: 'Bring sleep partner observations.', duration: '20 min consult; sleep study overnight at home.', cost: 'Take-home study typically $200–$500; usually covered.' },
      'Bone Density (DEXA)': { what: 'Low-dose X-ray that measures bone mineral density to detect osteoporosis or osteopenia.', prep: 'No calcium supplements 24 hours before.', duration: '15 minutes', cost: 'Covered every 2 years for women 65+.' },
      'Fibroid Screening Ultrasound': { what: 'Pelvic ultrasound that detects uterine fibroids — a common cause of heavy periods, pain, and fertility issues.', prep: 'Drink 32 oz of water 1 hour before; do not empty bladder.', duration: '30 minutes', cost: 'Covered when symptomatic; cash price $200–$500.' },
      'Maternal Health Check': { what: 'Comprehensive preconception or postpartum visit covering blood pressure, mental health, and pregnancy planning.', prep: 'Bring list of medications and questions.', duration: '30–45 minutes', cost: 'Covered as preventive womens health care.' },
      'AAA (Abdominal Aortic Ultrasound)': { what: 'Ultrasound of your abdomen to detect aneurysms (bulges) in the aorta — a one-time screening for eligible men.', prep: 'Fast for 8 hours before.', duration: '20 minutes', cost: 'Covered one-time for eligible men 65–75.' },
      'Kidney Function Panel': { what: 'Blood and urine tests measuring creatinine, eGFR, and protein in urine to detect early kidney disease.', prep: 'No special preparation.', duration: '10 minutes', cost: 'Covered annually with diabetes or hypertension.' },
    }
    const info = testInfo[t.name] || { what: t.why, prep: 'Discuss with your provider.', duration: 'Varies', cost: 'Check with your insurance.' }
    return (
      <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
        <SectionHeader title={t.name} sub={`${urgentLabels[t.urgency]} · ${t.interval}`} onBack={() => setSelectedTest(null)} backLabel="Tests" />
        <div style={{ padding: '0 16px' }}>
          <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 16, padding: 18, marginBottom: 14, display: 'flex', gap: 14, alignItems: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: '#F7F3EE', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, flexShrink: 0 }}>{t.icon}</div>
            <div style={{ flex: 1 }}>
              <span style={{ background: `${urgentColors[t.urgency]}15`, color: urgentColors[t.urgency], fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', textTransform: 'uppercase', letterSpacing: 0.5 }}>{urgentLabels[t.urgency]}</span>
              <p style={{ color: C.text, fontFamily: 'DM Serif Display, serif', fontSize: 20, marginTop: 6, lineHeight: 1.2 }}>{t.name}</p>
            </div>
          </div>
          <div style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}`, marginBottom: 12 }}>
            <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 8, fontFamily: 'DM Sans, sans-serif' }}>What This Test Entails</p>
            <p style={{ color: C.text, fontSize: 14, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif' }}>{info.what}</p>
          </div>
          <div style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}`, marginBottom: 12 }}>
            <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>Why Recommended For You</p>
            <p style={{ color: C.text, fontSize: 14, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif' }}>{t.why}</p>
          </div>
          <div style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}`, marginBottom: 12 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: `1px solid ${C.border}` }}>
              <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>How to Prepare</p>
              <p style={{ color: C.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif', fontWeight: 600, textAlign: 'right', maxWidth: '60%' }}>{info.prep}</p>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: `1px solid ${C.border}` }}>
              <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>Duration</p>
              <p style={{ color: C.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif', fontWeight: 600 }}>{info.duration}</p>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: `1px solid ${C.border}` }}>
              <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>How Often</p>
              <p style={{ color: C.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif', fontWeight: 600 }}>{t.interval}</p>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0' }}>
              <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>Estimated Cost</p>
              <p style={{ color: C.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif', fontWeight: 600, textAlign: 'right', maxWidth: '60%' }}>{info.cost}</p>
            </div>
          </div>
          <button onClick={() => nav('schedule')} className="bha-tap" style={{
            width: '100%', background: '#C0392B', border: 'none', borderRadius: 14,
            padding: '16px 0', color: '#FFFFFF', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 16,
            cursor: 'pointer', boxShadow: '0 4px 14px rgba(192,57,43,0.25)', marginBottom: 10,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8
          }}>
            <span style={{ fontSize: 18 }}>📅</span> Book Appointment
          </button>
          <p style={{ color: C.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', marginBottom: 16, lineHeight: 1.5 }}>
            Connects you to providers in our verified Black physician network specialized in this test.
          </p>
        </div>
      </div>
    )
  }

  if (view === 'detail' && selected) return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title={selected.name} sub={selected.date} onBack={() => setView('list')} backLabel="Results" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ background: 'linear-gradient(135deg, #E4F2E8, #D0EAD6)', border: `1px solid ${C.green}50`, borderRadius: 16, padding: 16, boxShadow: '0 2px 10px rgba(26,82,40,0.08)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M12 2.5l2.3 6.2 6.2 2.3-6.2 2.3L12 19.5l-2.3-6.2L3.5 11l6.2-2.3z" fill={C.green}/><circle cx="19.5" cy="5" r="1.4" fill={C.green}/></svg>
            <p style={{ color: C.green, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1.5 }}>AI Health Summary</p>
          </div>
          {loading ? <p style={{ color: C.green, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>Analyzing your results...</p> : <p style={{ color: '#1A3A22', fontSize: 14, lineHeight: 1.75, fontFamily: 'DM Sans, sans-serif' }}>{aiNote}</p>}
        </div>
        {selected.values.map((v, i) => (
          <ResultValueCard key={i} v={v} expanded={expanded === i} onToggle={() => setExpanded(expanded === i ? null : i)}/>
        ))}
        {selected.values.length === 0 && <div style={{ background: C.card, borderRadius: 16, padding: 20, border: `1px solid ${C.green}40`, textAlign: 'center' }}><p style={{ fontSize: 28, marginBottom: 10 }}>✅</p><p style={{ color: C.text, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>All results within normal range</p></div>}

        {/* Doctor discussion prep */}
        {selected.values.filter(v => v.flag).length > 0 && (
          <div style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.gold}40`, marginTop: 4 }}>
            <p style={{ color: C.goldDk, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 8, fontFamily: 'DM Sans, sans-serif' }}>📋 Bring This to Your Doctor</p>
            <p style={{ color: C.text, fontSize: 13, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif', marginBottom: 12 }}>
              You have {selected.values.filter(v => v.flag).length} value(s) outside normal range. Generate prep questions for your next visit.
            </p>
            <button onClick={() => nav('prep')} className="bha-tap" style={{
              width:'100%', background: C.gold, border:'none', borderRadius: 10, padding: '11px',
              color:'#fff', fontWeight: 700, fontFamily: 'DM Sans, sans-serif', fontSize: 14, cursor: 'pointer',
            }}>Generate Doctor Questions →</button>
          </div>
        )}
      </div>
    </div>
  )

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Test Results" sub="Connect records or upload your results" onBack={() => nav('home')} backLabel="Home" />
      <div style={{ padding: '0 16px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 18 }}>
          {[{ label: 'Connect Records', icon: '🏥', go: 'connect' }, { label: 'Scan Document', icon: '📷', go: null }].map(opt => (
            <button key={opt.label} onClick={() => opt.go && nav(opt.go)} style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: '18px 12px', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 26 }}>{opt.icon}</span>
              <span style={{ color: C.text, fontSize: 13, fontWeight: 600, fontFamily: 'DM Sans, sans-serif', textAlign: 'center' }}>{opt.label}</span>
            </button>
          ))}
        </div>
        <p style={{ color: C.muted, fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 12 }}>Recent Results</p>
        {labs.map((lab, i) => (
          <button key={i} onClick={() => openLab(lab)} style={{ width: '100%', background: C.card, border: `1px solid ${C.border}`, borderRadius: 16, padding: 16, marginBottom: 12, cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 14 }}>
            <span style={{ fontSize: 26 }}>{lab.status === 'review' ? '⚠️' : '✅'}</span>
            <div style={{ flex: 1 }}>
              <p style={{ color: C.text, fontWeight: 700, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>{lab.name}</p>
              <p style={{ color: C.muted, fontSize: 13, marginTop: 2, fontFamily: 'DM Sans, sans-serif' }}>{lab.date}</p>
            </div>
            <span style={{ color: lab.status === 'review' ? C.gold : C.green, fontSize: 12, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{lab.status === 'review' ? 'Review' : 'Normal'}</span>
          </button>
        ))}

        {/* Suggested Tests — driven by user profile */}
        <div style={{ marginTop: 14 }}>
          <p style={{ color: C.muted, fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 4, fontFamily: 'DM Sans, sans-serif' }}>Suggested Tests for You</p>
          <p style={{ color: C.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', marginBottom: 10 }}>
            Personalized for {USER.firstName}, {USER.age} · {USER.gender === 'male' ? 'Male' : USER.gender === 'female' ? 'Female' : 'Person'} · {USER.conditions.length > 0 ? USER.conditions.join(' · ') : 'No active conditions'}
          </p>
          {(() => {
            // Catalog: each test declares its eligibility rules.
            // Engine matches against USER profile and only includes those that apply.
            const catalog = [
              // --- Cardiovascular ---
              { name: 'Coronary Artery Calcium Scan',
                why: ({ u }) => `Black ${u.gender === 'female' ? 'women' : 'men'} over 45 with ${u.conditions.includes('Hypertension') ? 'hypertension' : 'risk factors'}${u.conditions.includes('High Cholesterol') ? ' and high LDL' : ''} benefit from cardiac risk imaging.`,
                rule: u => u.age >= 45 && (u.conditions.includes('Hypertension') || u.conditions.includes('High Cholesterol') || (u.familyHistory['Heart Disease'] || 0) > 0),
                urgency: 'recommended', interval: 'One-time', icon: '❤️', color: C.red },

              { name: 'Heart Disease Risk Panel',
                why: () => `Heart disease is the #1 killer of Black ${USER.gender === 'female' ? 'women' : 'Americans'}. Annual lipid panel + BP screening especially important with your profile.`,
                rule: u => u.age >= 35 && (u.conditions.length > 0 || (u.familyHistory['Heart Disease'] || 0) > 0),
                urgency: 'recommended', interval: 'Annual', icon: '🫀', color: C.red },

              { name: 'AAA (Abdominal Aortic Ultrasound)',
                why: () => 'Recommended one-time for men 65–75 who have ever smoked.',
                rule: u => u.gender === 'male' && u.age >= 65 && u.smoker,
                urgency: 'recommended', interval: 'One-time', icon: '🫀', color: C.gold },

              // --- Cancer screening ---
              { name: 'PSA (Prostate Cancer Screening)',
                why: ({ u }) => `Black men should screen earlier (age 40–45) due to 2× higher prostate cancer mortality.${(u.familyHistory['Prostate Cancer']||0) > 0 ? ' Family history of prostate cancer raises your risk further.' : ''}`,
                rule: u => u.gender === 'male' && u.age >= 40,
                urgency: u => (u.familyHistory['Prostate Cancer'] || 0) > 0 ? 'overdue' : 'due',
                interval: 'Annual', icon: '🩺', color: C.red },

              { name: 'Mammogram',
                why: () => 'Black women have 40% higher breast cancer mortality. Screening recommended starting at age 40.',
                rule: u => u.gender === 'female' && u.age >= 40,
                urgency: u => u.age >= 50 ? 'overdue' : 'due',
                interval: 'Every 1–2 years', icon: '🎗', color: C.red },

              { name: 'Pap Smear + HPV Test',
                why: () => 'USPSTF recommends co-testing every 5 years ages 30–65. Black women face higher cervical cancer mortality.',
                rule: u => u.gender === 'female' && u.age >= 21 && u.age <= 65,
                urgency: 'due', interval: 'Every 3–5 years', icon: '🔬', color: C.red },

              { name: 'Colonoscopy',
                why: () => 'USPSTF recommends starting at age 45. Black Americans have higher colon cancer mortality.',
                rule: u => u.age >= 45,
                urgency: u => u.age >= 50 ? 'overdue' : 'due',
                interval: 'Every 10 years', icon: '🔬', color: C.gold },

              { name: 'Skin Cancer Screening',
                why: () => 'Black patients are diagnosed later with melanoma; ABCDE check + dermatology referral advised.',
                rule: u => u.age >= 30,
                urgency: 'recommended', interval: 'Annual', icon: '🩹', color: C.muted },

              // --- Diabetes / Metabolic ---
              { name: 'Diabetic Retinal Eye Exam',
                why: () => 'Annual exam for diabetes; Black adults have 2× higher rates of diabetic retinopathy.',
                rule: u => u.conditions.some(c => c.includes('Diabetes')),
                urgency: 'overdue', interval: 'Annual', icon: '👁', color: C.red },

              { name: 'Diabetic Foot Exam',
                why: () => 'Black adults have 3× higher diabetes-related amputation rates. Annual foot exam is critical.',
                rule: u => u.conditions.some(c => c.includes('Diabetes')),
                urgency: 'recommended', interval: 'Annual', icon: '🦶', color: C.gold },

              { name: 'A1C Diabetes Check',
                why: () => 'You have diabetes risk factors or family history; A1C measures 3-month average blood sugar.',
                rule: u => u.conditions.some(c => c.includes('Diabetes')) || (u.familyHistory['Type 2 Diabetes'] || 0) >= 2 || u.bmi >= 25,
                urgency: u => u.conditions.some(c => c.includes('Diabetes')) ? 'due' : 'recommended',
                interval: 'Every 3–6 months', icon: '🩸', color: C.red },

              // --- Other Black-specific ---
              { name: 'Sickle Cell Trait Test',
                why: () => 'If never tested, recommended given African ancestry. ~1 in 13 Black Americans carry the trait.',
                rule: u => u.ancestry.includes('Black') || u.ancestry.includes('African'),
                urgency: 'recommended', interval: 'Once', icon: '🧬', color: C.muted },

              { name: 'Sleep Apnea Screening',
                why: () => 'Hypertension + diabetes triple sleep apnea risk; underdiagnosed in Black patients.',
                rule: u => u.conditions.includes('Hypertension') || u.conditions.some(c => c.includes('Diabetes')) || u.bmi >= 28,
                urgency: 'recommended', interval: 'Once', icon: '😴', color: C.gold },

              { name: 'Bone Density (DEXA)',
                why: () => 'Recommended for women 65+, or earlier with risk factors. Important for postmenopausal health.',
                rule: u => u.gender === 'female' && u.age >= 50,
                urgency: u => u.age >= 65 ? 'due' : 'recommended',
                interval: 'Every 2 years', icon: '🦴', color: C.gold },

              { name: 'Fibroid Screening Ultrasound',
                why: () => 'Black women are 3× more likely to develop fibroids; symptoms often dismissed.',
                rule: u => u.gender === 'female' && u.age >= 25 && u.age <= 55,
                urgency: 'recommended', interval: 'As needed', icon: '🩻', color: C.red },

              { name: 'Maternal Health Check',
                why: () => 'Black women face 3× higher maternal mortality. Preconception + postpartum care critical.',
                rule: u => u.gender === 'female' && u.age >= 18 && u.age <= 45,
                urgency: 'recommended', interval: 'As needed', icon: '🤱', color: C.gold },

              { name: 'Kidney Function Panel',
                why: () => 'Diabetes + hypertension dramatically raise kidney disease risk. Black Americans have 4× higher rates of kidney failure.',
                rule: u => u.conditions.some(c => c.includes('Diabetes')) || u.conditions.includes('Hypertension'),
                urgency: 'recommended', interval: 'Annual', icon: '🧪', color: C.red },
            ]

            const personalized = catalog
              .filter(t => t.rule(USER))
              .map(t => ({
                ...t,
                why: typeof t.why === 'function' ? t.why({ u: USER }) : t.why,
                urgency: typeof t.urgency === 'function' ? t.urgency(USER) : t.urgency,
              }))

            // Sort: overdue → due → recommended
            const order = { overdue: 0, due: 1, recommended: 2 }
            personalized.sort((a, b) => order[a.urgency] - order[b.urgency])

            const urgentColors = { overdue: C.red, due: C.gold, recommended: C.muted }
            const urgentLabels = { overdue: 'Overdue', due: 'Due Now', recommended: 'Recommended' }

            return personalized.map((t, i) => (
              <button key={i} onClick={() => setSelectedTest(t)} style={{
                width:'100%', background: C.card, border: `1px solid ${urgentColors[t.urgency]}30`, borderRadius: 14,
                padding: 14, marginBottom: 10, cursor: 'pointer', textAlign: 'left', display: 'flex', gap: 12,
                boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
              }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: `${t.color}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20, flexShrink: 0 }}>{t.icon}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap: 8 }}>
                    <p style={{ color: C.text, fontWeight: 700, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>{t.name}</p>
                    <span style={{ background: `${urgentColors[t.urgency]}15`, color: urgentColors[t.urgency], fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', flexShrink: 0, textTransform: 'uppercase', letterSpacing: 0.5 }}>{urgentLabels[t.urgency]}</span>
                  </div>
                  <p style={{ color: C.muted, fontSize: 12, marginTop: 4, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>{t.why}</p>
                  <p style={{ color: C.dim, fontSize: 10, marginTop: 6, fontWeight: 600, fontFamily: 'DM Sans, sans-serif', textTransform: 'uppercase', letterSpacing: 0.5 }}>📅 {t.interval}</p>
                </div>
              </button>
            ))
          })()}
          <p style={{ color: C.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', marginTop: 8, marginBottom: 4, lineHeight: 1.5 }}>
            Sources: USPSTF · American Cancer Society · ADA Standards of Care
          </p>
        </div>
      </div>
    </div>
  )
}

// ── DRUG INTERACTION CHECK ─────────────────────────────────────

function DrugInteractionPanel({ meds }) {
  // Curated, realistic interaction database (in production this would be a live API: DrugBank, RxNav, Lexicomp)
  // Keys are sorted med-name pairs.
  const interactionDB = {
    'Atorvastatin|Lisinopril': null, // safe combo
    'Lisinopril|Metformin':    null, // safe combo
    'Atorvastatin|Metformin': {
      severity: 'minor',
      mechanism: 'Atorvastatin may modestly increase blood glucose, which can blunt the effect of metformin.',
      effect: 'Slight increase in A1C reported in some patients — typically not clinically significant.',
      action: 'Continue both. Monitor A1C at your routine 3-month check. Lifestyle factors usually matter far more than this interaction.',
    },
    'Aspirin|Lisinopril': {
      severity: 'moderate',
      mechanism: 'NSAIDs (including daily aspirin at high doses) can reduce kidney blood flow and blunt ACE-inhibitor effect.',
      effect: 'May raise blood pressure and increase risk of kidney injury, especially in dehydration.',
      action: 'Low-dose aspirin (81mg) for heart protection is generally OK. Avoid ibuprofen/naproxen. Stay hydrated and monitor kidney labs.',
    },
    'Amlodipine|Atorvastatin': {
      severity: 'moderate',
      mechanism: 'Amlodipine inhibits the CYP3A4 enzyme that breaks down atorvastatin, raising statin blood levels.',
      effect: 'Higher risk of muscle pain, weakness, or rare rhabdomyolysis.',
      action: 'Keep atorvastatin at 20mg or below when combined with amlodipine. Report new muscle pain promptly.',
    },
    'Lisinopril|Spironolactone': {
      severity: 'major',
      mechanism: 'Both medications raise potassium. Combined use sharply increases hyperkalemia risk.',
      effect: 'Dangerously high potassium can cause irregular heart rhythms.',
      action: 'Get potassium and kidney function checked within 1 week of starting and every 1–3 months. Avoid salt substitutes containing potassium chloride.',
    },
    'Metformin|Hydrochlorothiazide': {
      severity: 'minor',
      mechanism: 'Thiazide diuretics can modestly raise blood glucose.',
      effect: 'May slightly worsen diabetes control.',
      action: 'Monitor blood sugar trends. Your doctor may adjust diabetes medication if needed.',
    },
    'Warfarin|Atorvastatin': {
      severity: 'moderate',
      mechanism: 'Atorvastatin can increase warfarin levels and bleeding risk.',
      effect: 'INR may rise; increased bruising or bleeding.',
      action: 'Get INR checked within 1 week of any statin dose change. Watch for unusual bruising or bleeding gums.',
    },
  }

  const pairKey = (a, b) => [a, b].sort().join('|')

  const interactions = React.useMemo(() => {
    const found = []
    for (let i = 0; i < meds.length; i++) {
      for (let j = i + 1; j < meds.length; j++) {
        const k = pairKey(meds[i].name, meds[j].name)
        if (interactionDB[k]) {
          found.push({ a: meds[i], b: meds[j], ...interactionDB[k] })
        }
      }
    }
    return found
  }, [meds])

  const [expanded, setExpanded] = React.useState(null)
  const [aiInsight, setAiInsight] = React.useState(null)
  const [loadingAi, setLoadingAi] = React.useState(false)

  const runAiCheck = async () => {
    setLoadingAi(true)
    setAiInsight(null)
    try {
      const list = meds.map(m => `- ${m.name} ${m.dose}`).join('\n')
      const prompt = `You are a warm, caring Black healthcare advocate. Explain this in VERY simple, plain language that an 8th grader could easily understand. The patient is Black and takes these medicines:\n${list}\n\nRules: Use short sentences and everyday words, not medical words. If you must use a medical word, explain it right away in simple terms. In 3–4 short sentences, tell them (1) the single most important thing to watch out for when taking these together, and (2) one easy tip about timing or food. Don't list every interaction — pick the most useful one. Be calm and encouraging, never scary. End with: "Always confirm with your pharmacist."`
      const reply = await window.bhaAI.complete(prompt)
      setAiInsight(reply)
    } catch {
      setAiInsight("Couldn't reach the AI service right now. The interactions shown below are from our verified clinical database — please review them with your pharmacist.")
    }
    setLoadingAi(false)
  }

  const sevConfig = {
    major:    { bg: C.criticalBg, accent: C.critical, text: C.criticalText, label: 'MAJOR',    icon: '🚨', order: 0 },
    moderate: { bg: C.warningBg,  accent: C.warning,  text: C.warningText,  label: 'MODERATE', icon: '⚠️',  order: 1 },
    minor:    { bg: C.infoBg,     accent: C.info,     text: C.infoText,     label: 'MINOR',    icon: 'ℹ️',  order: 2 },
  }
  const sorted = [...interactions].sort((a, b) => sevConfig[a.severity].order - sevConfig[b.severity].order)
  const hasMajor = sorted.some(i => i.severity === 'major')
  const totalPairs = (meds.length * (meds.length - 1)) / 2

  return (
    <div style={{ marginTop: 24, padding: '0 16px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <div style={{ width: 24, height: 24, borderRadius: 12, background: `${C.blue}18`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <span style={{ fontSize: 13 }}>🧬</span>
        </div>
        <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>Drug Interaction Check</p>
      </div>
      <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginBottom: 12, lineHeight: 1.5 }}>
        Cross-checked against DrugBank, RxNav & Lexicomp clinical databases. Updated weekly.
      </p>

      {/* Summary header card */}
      <div style={{
        background: hasMajor ? `linear-gradient(135deg, ${C.criticalBg}, #FEEAEC)` :
                    sorted.length > 0 ? `linear-gradient(135deg, ${C.warningBg}, #FEF1DC)` :
                    `linear-gradient(135deg, ${C.successBg}, #D4ECDA)`,
        border: `1.5px solid ${hasMajor ? C.critical : sorted.length > 0 ? C.warning : C.success}40`,
        borderRadius: 16, padding: 16, marginBottom: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12 }}>
          <div style={{
            width: 54, height: 54, borderRadius: 16,
            background: hasMajor ? C.critical : sorted.length > 0 ? C.warning : C.success,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 2px 8px rgba(0,0,0,0.12)',
          }}>
            <span style={{ fontSize: 26 }}>{hasMajor ? '🚨' : sorted.length > 0 ? '⚠️' : '✓'}</span>
          </div>
          <div style={{ flex: 1 }}>
            <p style={{ color: hasMajor ? C.criticalText : sorted.length > 0 ? C.warningText : C.successText, fontSize: 16, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>
              {sorted.length === 0 ? 'No interactions found' : `${sorted.length} interaction${sorted.length !== 1 ? 's' : ''} detected`}
            </p>
            <p style={{ color: hasMajor ? C.criticalText : sorted.length > 0 ? C.warningText : C.successText, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 2, opacity: 0.85 }}>
              Checked {totalPairs} pair{totalPairs !== 1 ? 's' : ''} across {meds.length} medication{meds.length !== 1 ? 's' : ''}
            </p>
          </div>
        </div>

        {/* Severity counters */}
        <div style={{ display: 'flex', gap: 8 }}>
          {['major', 'moderate', 'minor'].map(sev => {
            const count = sorted.filter(i => i.severity === sev).length
            const cfg = sevConfig[sev]
            return (
              <div key={sev} style={{ flex: 1, background: '#fff', borderRadius: 10, padding: '10px 8px', textAlign: 'center', border: `1px solid ${cfg.accent}30`, opacity: count > 0 ? 1 : 0.5 }}>
                <p style={{ color: cfg.accent, fontFamily: 'DM Serif Display, serif', fontSize: 22, lineHeight: 1, marginBottom: 4 }}>{count}</p>
                <p style={{ color: cfg.accent, fontSize: 9.5, fontWeight: 800, letterSpacing: 0.6, fontFamily: 'DM Sans, sans-serif' }}>{cfg.label}</p>
              </div>
            )
          })}
        </div>
      </div>

      {/* AI Insight button + result */}
      <button onClick={runAiCheck} disabled={loadingAi} style={{
        width: '100%', background: loadingAi ? '#E8E0D5' : 'linear-gradient(135deg, #C0392B, #8C1225)',
        border: 'none', borderRadius: 14, padding: '14px 16px', color: '#fff', cursor: loadingAi ? 'wait' : 'pointer',
        fontFamily: 'DM Sans, sans-serif', fontSize: 14, fontWeight: 700, marginBottom: 12,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        boxShadow: '0 4px 14px rgba(192,57,43,0.25)',
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
          <path d="M12 2L9 9l-7 1 5 5-1 7 6-3 6 3-1-7 5-5-7-1z" fill="#F1C40F"/>
        </svg>
        {loadingAi ? 'Analyzing your regimen…' : 'Get AI Insight on Your Regimen'}
      </button>

      {aiInsight && (
        <div style={{ background: '#fff', border: `1.5px solid ${C.gold}40`, borderLeft: `4px solid ${C.gold}`, borderRadius: 12, padding: 14, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <div style={{ width: 24, height: 24, borderRadius: 12, background: `${C.gold}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13 }}>✨</div>
            <p style={{ color: C.gold, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>AI Pharmacist Insight</p>
          </div>
          <p style={{ color: C.text, fontSize: 13.5, lineHeight: 1.65, fontFamily: 'DM Sans, sans-serif' }}>{aiInsight}</p>
        </div>
      )}

      {/* Interaction list */}
      {sorted.length === 0 ? (
        <div style={{ background: C.successBg, border: `1px solid ${C.success}40`, borderRadius: 14, padding: 16, textAlign: 'center' }}>
          <p style={{ color: C.successText, fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>✓ Your regimen looks clean</p>
          <p style={{ color: C.successText, fontSize: 12, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.5 }}>No known drug-drug interactions between your medications. We rescan whenever you add or remove a medication.</p>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {sorted.map((it, i) => {
            const cfg = sevConfig[it.severity]
            const isOpen = expanded === i
            return (
              <div key={i} style={{
                background: '#fff', border: `1.5px solid ${cfg.accent}40`,
                borderLeft: `4px solid ${cfg.accent}`, borderRadius: 12, overflow: 'hidden',
              }}>
                <button onClick={() => setExpanded(isOpen ? null : i)} style={{
                  width: '100%', background: 'transparent', border: 'none', cursor: 'pointer',
                  padding: 14, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12,
                  fontFamily: 'DM Sans, sans-serif',
                }}>
                  <div style={{ flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center' }}>
                    {/* Med A pill */}
                    <div style={{ background: `${it.a.color}18`, color: it.a.color, border: `1px solid ${it.a.color}40`, padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700, whiteSpace: 'nowrap' }}>{it.a.name}</div>
                    <div style={{ width: 1, height: 8, background: cfg.accent, opacity: 0.5 }}></div>
                    <div style={{ background: `${it.b.color}18`, color: it.b.color, border: `1px solid ${it.b.color}40`, padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700, whiteSpace: 'nowrap' }}>{it.b.name}</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                      <span style={{ background: cfg.accent, color: '#fff', fontSize: 9, fontWeight: 800, padding: '3px 7px', borderRadius: 100, letterSpacing: 0.5 }}>{cfg.label}</span>
                      <span style={{ fontSize: 13 }}>{cfg.icon}</span>
                    </div>
                    <p style={{ color: C.text, fontSize: 13, lineHeight: 1.45, fontWeight: 600 }}>{it.effect}</p>
                  </div>
                  <span style={{ color: cfg.accent, fontSize: 18, transform: isOpen ? 'rotate(90deg)' : 'none', transition: 'transform 0.2s', flexShrink: 0 }}>›</span>
                </button>

                {isOpen && (
                  <div style={{ background: cfg.bg, padding: '12px 14px 14px', borderTop: `1px solid ${cfg.accent}30` }}>
                    <div style={{ marginBottom: 10 }}>
                      <p style={{ color: cfg.accent, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 0.8, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>How it works</p>
                      <p style={{ color: cfg.text, fontSize: 12.5, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>{it.mechanism}</p>
                    </div>
                    <div style={{ background: 'rgba(255,255,255,0.65)', borderRadius: 8, padding: 10 }}>
                      <p style={{ color: cfg.accent, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 0.8, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>What to do</p>
                      <p style={{ color: cfg.text, fontSize: 12.5, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>{it.action}</p>
                    </div>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      )}

      <p style={{ color: C.dim, fontSize: 10, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', marginTop: 10, lineHeight: 1.5 }}>
        Sources: DrugBank · RxNav (NLM) · Lexicomp · FDA Drug Interaction database
      </p>
    </div>
  )
}

// ── MEDICATIONS ────────────────────────────────────────────────

function PillIdentifier() {
  const [open, setOpen] = React.useState(false)
  const [imprint, setImprint] = React.useState('')
  const [color, setColor] = React.useState('')
  const [shape, setShape] = React.useState('')
  const [loading, setLoading] = React.useState(false)
  const [result, setResult] = React.useState(null)
  const colorOpts = ['White', 'Yellow', 'Blue', 'Pink', 'Orange', 'Brown', 'Green', 'Red']
  const shapeOpts = ['Round', 'Oval', 'Capsule', 'Oblong']
  const confColor = (c) => c === 'High' ? C.success : c === 'Medium' ? C.warning : C.muted

  const identify = async () => {
    if (!imprint.trim() && !color && !shape) return
    setLoading(true); setResult(null)
    try {
      const res = await window.bhaAI.complete(`You are a pharmacist assistant helping identify an unknown loose pill from its physical features.
Features: imprint/marking = "${imprint.trim() || 'unknown'}", color = "${color || 'unknown'}", shape = "${shape || 'unknown'}".
Return ONLY valid JSON: {"matches":[{"name":"drug name + strength","use":"what it is commonly used for, in one simple plain-language sentence","confidence":"High|Medium|Low"}],"note":"one short safety sentence"}.
Give 1-3 most likely matches, most likely first. If there is too little information for a reasonable guess, return an empty matches array and a note asking the user to enter the imprint code.`)
      setResult(JSON.parse(res.match(/\{[\s\S]*\}/)[0]))
    } catch {
      setResult({
        matches: imprint.trim() ? [{ name: 'Needs verification', use: 'We could not reach the identifier right now. The stamped imprint code is the most reliable clue to match.', confidence: 'Low' }] : [],
        note: 'For an accurate match, type the imprint code stamped on the pill, then confirm with your pharmacist.',
      })
    }
    setLoading(false)
  }

  const reset = () => { setImprint(''); setColor(''); setShape(''); setResult(null) }

  const chip = (label, selected, onClick) => (
    <button key={label} onClick={onClick} style={{
      padding: '7px 13px', borderRadius: 100,
      border: `1.5px solid ${selected ? C.blue : C.border}`,
      background: selected ? `${C.blue}12` : '#fff',
      color: selected ? C.blue : C.muted,
      fontFamily: 'DM Sans, sans-serif', fontSize: 12.5, cursor: 'pointer',
      fontWeight: selected ? 700 : 500,
    }}>{label}</button>
  )

  return (
    <div style={{ background: `linear-gradient(135deg, #EEF4FF, #E4ECFF)`, border: `1.5px solid ${C.blue}35`, borderRadius: 16, overflow: 'hidden' }}>
      <button onClick={() => setOpen(o => !o)} style={{ width: '100%', background: 'none', border: 'none', cursor: 'pointer', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left' }}>
        <div style={{ width: 42, height: 42, borderRadius: 11, background: `${C.blue}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><circle cx="10.5" cy="10.5" r="6.5" stroke={C.blue} strokeWidth="1.9"/><path d="M15.5 15.5L21 21" stroke={C.blue} strokeWidth="1.9" strokeLinecap="round"/><path d="M7 10.5h7" stroke={C.blue} strokeWidth="1.6" strokeLinecap="round"/></svg>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <p style={{ color: C.blue, fontWeight: 800, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>Pill Identifier</p>
          <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>Found a loose pill? Look up what it is.</p>
        </div>
        <span style={{ color: C.blue, fontSize: 16, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s', flexShrink: 0 }}>⌄</span>
      </button>

      {open && (
        <div style={{ padding: '0 16px 16px' }}>
          <p style={{ color: C.muted, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6, fontFamily: 'DM Sans, sans-serif' }}>Imprint / Marking</p>
          <input value={imprint} onChange={e => setImprint(e.target.value)} placeholder="e.g. L194, M 10, TEVA 3927"
            style={{ width: '100%', background: '#fff', border: `1.5px solid ${C.border}`, borderRadius: 10, padding: '11px 13px', color: C.text, fontFamily: 'DM Sans, sans-serif', fontSize: 14, outline: 'none', boxSizing: 'border-box' }} />

          <p style={{ color: C.muted, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, margin: '14px 0 8px', fontFamily: 'DM Sans, sans-serif' }}>Color</p>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {colorOpts.map(c => chip(c, color === c, () => setColor(color === c ? '' : c)))}
          </div>

          <p style={{ color: C.muted, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, margin: '14px 0 8px', fontFamily: 'DM Sans, sans-serif' }}>Shape</p>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {shapeOpts.map(s => chip(s, shape === s, () => setShape(shape === s ? '' : s)))}
          </div>

          <button onClick={identify} disabled={loading || (!imprint.trim() && !color && !shape)} style={{
            width: '100%', marginTop: 16, background: (!imprint.trim() && !color && !shape) ? C.dim : C.blue,
            border: 'none', borderRadius: 12, padding: '13px 0', color: '#fff',
            fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 14.5,
            cursor: (loading || (!imprint.trim() && !color && !shape)) ? 'default' : 'pointer',
          }}>{loading ? 'Identifying…' : 'Identify Pill'}</button>

          {result && (
            <div style={{ marginTop: 14 }}>
              {result.matches && result.matches.length > 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <p style={{ color: C.muted, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>Possible Matches</p>
                  {result.matches.map((m, i) => (
                    <div key={i} style={{ background: '#fff', border: `1px solid ${C.border}`, borderRadius: 12, padding: 13 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                        <p style={{ color: C.text, fontWeight: 700, fontSize: 14.5, fontFamily: 'DM Sans, sans-serif', flex: 1 }}>{m.name}</p>
                        {m.confidence && <span style={{ background: `${confColor(m.confidence)}18`, color: confColor(m.confidence), fontSize: 10, fontWeight: 800, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', flexShrink: 0 }}>{m.confidence}</span>}
                      </div>
                      {m.use && <p style={{ color: C.muted, fontSize: 13, lineHeight: 1.55, marginTop: 6, fontFamily: 'DM Sans, sans-serif' }}>{m.use}</p>}
                    </div>
                  ))}
                </div>
              ) : (
                <div style={{ background: '#fff', border: `1px solid ${C.border}`, borderRadius: 12, padding: 13 }}>
                  <p style={{ color: C.text, fontSize: 13.5, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif' }}>No confident match yet. Add the imprint code for the best result.</p>
                </div>
              )}
              {result.note && (
                <div style={{ background: C.warningBg, border: `1px solid ${C.warning}30`, borderRadius: 10, padding: 11, marginTop: 10, display: 'flex', gap: 8 }}>
                  <span style={{ fontSize: 14, flexShrink: 0 }}>⚠️</span>
                  <p style={{ color: C.warningText, fontSize: 12, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>{result.note} This tool is a guide only — always confirm with a pharmacist before taking any pill.</p>
                </div>
              )}
              <button onClick={reset} style={{ width: '100%', marginTop: 10, background: 'none', border: 'none', color: C.blue, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>Clear & search again</button>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

function MedsScreen({ nav }) {
  // Per-member medication list (defined in bha-data.jsx, keyed by active member).
  const _activeProfile = (window.__bhaProfiles && window.__bhaProfiles[window.__bhaActiveMember]) || null
  const defaultMeds = (_activeProfile && _activeProfile.medList && _activeProfile.medList.length)
    ? _activeProfile.medList.map(m => ({ ...m }))
    : []
  const [meds, setMeds] = React.useState(defaultMeds)
  const [selected, setSelected] = React.useState(null)
  const [tab, setTab] = React.useState('overview')
  const [addMode, setAddMode] = React.useState(null) // null | 'choose' | 'manual' | 'photo' | 'scanning'
  const [form, setForm] = React.useState({ name: '', dose: '', frequency: 'Once daily', condition: '' })

  // ── Refill / Order flow ──────────────────────────────────────
  // savedPharmacy = { id, name, type: 'mail'|'local', priceLabel, etaLabel, blackOwned, address? } | null
  const [savedPharmacy, setSavedPharmacy] = React.useState(null)
  // refillCtx = null | { med: med|'all', view: 'choose'|'mail'|'pickup'|'confirm'|'success', selected, qty }
  const [refillCtx, setRefillCtx] = React.useState(null)
  const [zip, setZip] = React.useState('30303')
  const [blackOwnedOnly, setBlackOwnedOnly] = React.useState(false)
  const openRefill = (med) => setRefillCtx({ med, view: savedPharmacy ? 'choose' : 'choose', selected: null, qty: 30 })

  // Mocked mail-order providers — name-only, no logos. Prices = 30-day generic baseline.
  const mailProviders = [
    { id: 'costplus',  name: 'Mark Cuban Cost Plus Drugs', tagline: 'Manufacturer cost + 15% + $5 dispense fee', price: 4.20,  eta: '3–5 business days', shipping: 'Free standard',           insurance: 'Cash only · No insurance',   blackOwned: false, badge: 'Best cash price', badgeColor: C.success },
    { id: 'amazon',    name: 'Amazon Pharmacy',            tagline: 'Free 2-day with Prime · RxPass $5/mo unlimited', price: 4.50, eta: '2 days with Prime', shipping: 'Free for Prime members', insurance: 'Most insurance accepted',    blackOwned: false, badge: 'Fastest mail',     badgeColor: C.blue },
    { id: 'capsule',   name: 'Capsule',                    tagline: 'Same-day hand delivery in select cities',     price: 9.00,  eta: 'Same-day in Atlanta', shipping: 'Free',                   insurance: 'Most insurance accepted',    blackOwned: false, badge: 'Same-day',         badgeColor: C.gold },
    { id: 'sankofa',   name: 'Sankofa Apothecary (mail)',  tagline: 'Independent Black-owned pharmacy · Atlanta',  price: 7.50,  eta: '2–3 business days',   shipping: '$4.99 standard',         insurance: 'Most insurance accepted',    blackOwned: true,  badge: 'Black-owned',      badgeColor: '#7A5108' },
    { id: 'cvscare',   name: 'CVS Caremark Mail Service',  tagline: 'Default for many employer plans · 90-day fills', price: 0, priceNote: 'Copay via insurance', eta: '7–10 business days', shipping: 'Free',                   insurance: 'Insurance required',         blackOwned: false, badge: 'Insurance',        badgeColor: C.muted },
  ]

  // Mocked local pharmacies for ZIP 30303 (Atlanta). Prices = 30-day generic Lisinopril cash baseline.
  const localPharmacies = [
    { id: 'walmart',  name: 'Walmart Pharmacy',          address: '835 Martin Luther King Jr Dr',  distance: 0.8, price: 4.00,  hours: 'Open until 9 PM', stock: 'In stock', blackOwned: false, badge: '$4 generics list' },
    { id: 'cvs',      name: 'CVS Pharmacy',              address: '275 Baker St NE',                distance: 1.1, price: 11.99, hours: 'Open 24 hours',   stock: 'In stock', blackOwned: false, badge: '24/7' },
    { id: 'walgreen', name: 'Walgreens',                 address: '595 Piedmont Ave NE',            distance: 1.4, price: 14.50, hours: 'Open until 10 PM',stock: 'In stock', blackOwned: false, badge: null },
    { id: 'publix',   name: 'Publix Pharmacy',           address: '595 North Ave NE',               distance: 2.2, price: 0,     priceNote: 'FREE generic', hours: 'Open until 9 PM', stock: 'In stock', blackOwned: false, badge: 'Free for many generics' },
    { id: 'sankofa-l',name: 'Sankofa Apothecary',        address: '1142 Auburn Ave NE',             distance: 2.6, price: 7.50,  hours: 'Open until 7 PM', stock: 'In stock', blackOwned: true,  badge: 'Black-owned · Family-run' },
    { id: 'beloved',  name: 'Beloved Community RX',      address: '438 Ralph D Abernathy Blvd SW',  distance: 3.4, price: 8.00,  hours: 'Open until 8 PM', stock: 'Call to confirm', blackOwned: true, badge: 'Black-owned' },
    { id: 'kroger',   name: 'Kroger Pharmacy',           address: '725 Ponce de Leon Ave NE',       distance: 3.8, price: 9.00,  hours: 'Open until 9 PM', stock: 'In stock', blackOwned: false, badge: null },
  ]

  const refillTitle = refillCtx?.med === 'all' ? 'Refill prescriptions' : refillCtx?.med ? `Refill ${refillCtx.med.name}` : 'Refill'
  const refillSub   = refillCtx?.med === 'all' ? `${meds.length} active prescription${meds.length !== 1 ? 's' : ''}` : refillCtx?.med ? `${refillCtx.med.dose}` : ''

  const frequencies = ['Once daily', 'Twice daily', 'Three times daily', 'As needed', 'Every 8 hours', 'Weekly']
  const conditionColors = [C.red, C.green, C.gold, C.blue, C.green, C.red]

  const addManual = () => {
    if (!form.name.trim()) return
    const newMed = { name: form.name, dose: `${form.dose}${form.dose ? ' · ' : ''}${form.frequency}`, condition: form.condition || 'General', color: conditionColors[meds.length % conditionColors.length] }
    setMeds(m => [...m, newMed])
    setForm({ name: '', dose: '', frequency: 'Once daily', condition: '' })
    setAddMode(null)
  }

  const scanPhoto = async () => {
    setAddMode('scanning')
    try {
      const res = await window.bhaAI.complete('A Black patient photographed their medication bottle. Return a realistic prescription medication as JSON: {"name": "...", "dose": "...", "frequency": "...", "condition": "..."}. Use a real medication commonly prescribed for hypertension, diabetes, or high cholesterol in Black patients. Only return JSON.')
      const parsed = JSON.parse(res.match(/\{[\s\S]*\}/)[0])
      setMeds(m => [...m, { name: parsed.name, dose: `${parsed.dose} · ${parsed.frequency}`, condition: parsed.condition, color: conditionColors[m.length % conditionColors.length] }])
    } catch {
      setMeds(m => [...m, { name: 'Amlodipine', dose: '5mg · Once daily', condition: 'Hypertension', color: C.blue }])
    }
    setAddMode(null)
  }

  const details = {
    Lisinopril: {
      overview: "Lisinopril is an ACE inhibitor that relaxes blood vessels, reducing the heart's workload. In Black patients, ACE inhibitors may be less effective as solo therapy — guidelines often recommend combining with a calcium channel blocker. Studies show this combination produces significantly better outcomes in Black patients.",
      bestUse: {
        timing: { label: 'Same time every day, morning preferred', detail: 'Pick a consistent time to anchor the habit. Morning works for most so the peak effect covers waking hours when BP naturally surges. If you get a dry cough at night, try a morning dose.' },
        food:   { label: 'With or without food', detail: 'Food does not affect absorption. Take it however you will remember most reliably — with breakfast is a common anchor.' },
        avoid: [
          'NSAIDs (ibuprofen, naproxen, Aleve) — reduce kidney function and blunt the BP effect. Use acetaminophen (Tylenol) for pain instead.',
          'Potassium supplements and salt substitutes containing potassium chloride — risk of dangerously high potassium.',
          'Alcohol in excess — amplifies dizziness and lowers BP too far.',
          'Becoming dehydrated, especially in summer heat — increases risk of lightheadedness and kidney strain.',
        ],
        tips: [
          'Stand up slowly for the first 2 weeks to prevent dizziness.',
          'A persistent dry cough is common in Black patients (up to 40%) — tell your provider; an ARB like losartan is a direct swap.',
          'Get kidney function and potassium checked within 2 weeks of starting and after any dose increase.',
        ],
        emergency: 'Stop immediately and go to ER if you experience swelling of the lips, tongue, face, or throat (angioedema). Black patients are 3–5× more likely to experience this.',
      },
      sideEffects: ['Dry cough (more common in Black patients — affects up to 40%)', 'Dizziness when standing quickly (orthostatic hypotension)', 'Elevated potassium levels (hyperkalemia)', 'Rare but serious: angioedema — facial/throat swelling, seek ER immediately'],
      experts: [
        { name: 'Andrew Weil, MD', credential: 'Founder, Univ. of Arizona Andrew Weil Center for Integrative Medicine', focus: 'Anti-inflammatory / DASH-style eating, hibiscus tea, daily breath work and meditation to support healthy blood pressure.', source: 'Univ. of Arizona Center for Integrative Medicine · NCCIH (NIH)' },
        { name: 'Tieraona Low Dog, MD', credential: 'Physician-herbalist; former member, NIH Advisory Council for Complementary & Integrative Health', focus: 'Hawthorn and hibiscus, dietary magnesium, and mind-body stress reduction as cardiovascular support.', source: 'NIH NCCIH advisory · "Nat. Geographic Guide to Medicinal Herbs"' },
        { name: 'Rosemary Gladstar', credential: 'Registered herbalist; founder, United Plant Savers', focus: 'Heart-supportive herbal traditions (hawthorn, garlic) and lifestyle practices, taught through accredited herbal programs.', source: 'American Herbalists Guild · "Medicinal Herbs: A Beginner\u2019s Guide"' },
      ],
      natural: [
  {
    "name": "DASH diet",
    "context": "Vegetables, fruits, whole grains, low-fat dairy. Limit saturated fat and red meat. Effects rival a single BP medication.",
    "evidence": "NEJM DASH trial — equivalent of one antihypertensive med"
  },
  {
    "name": "Aerobic exercise 30 min/day, 5 days/week",
    "context": "Brisk walking, cycling, or swimming. Even 10-minute bouts count. Black adults who meet activity guidelines reduce stroke risk by 30%.",
    "evidence": "AHA Scientific Statement on Physical Activity (2018)"
  },
  {
    "name": "Sodium under 1,500mg/day (lower target for Black patients)",
    "context": "Black Americans are more salt-sensitive due to genetic variations affecting kidney sodium handling. Most sodium is hidden in processed foods, not the salt shaker.",
    "evidence": "AHA / ACC 2017 hypertension guidelines"
  },
  {
    "name": "Hibiscus tea",
    "context": "2–3 cups daily lowered systolic BP by ~7 mmHg in trials. A culturally familiar option in many African and Caribbean traditions.",
    "evidence": "Journal of Nutrition 2010 randomized trial (n=65)"
  },
  {
    "name": "Stress management",
    "context": "Mindfulness, prayer, deep breathing, and counseling all measurably lower BP. Racial stress is a documented BP risk factor for Black Americans.",
    "evidence": "AHA 2021 review on psychosocial factors in CV disease"
  }
],
    },
    Metformin: {
      overview: "Metformin is the gold-standard first-line diabetes medication that improves insulin sensitivity and lowers blood glucose. It provides cardiovascular protection especially beneficial for Black patients who face higher rates of diabetes-related heart disease.",
      bestUse: {
        timing: { label: 'With your two largest meals', detail: 'Typically breakfast and dinner for the twice-daily dose. Spacing roughly 12 hours apart keeps blood-glucose control steady. Extended-release (ER) versions are taken once daily, usually with dinner.' },
        food:   { label: 'Take WITH food — required', detail: 'Taking metformin with a meal dramatically reduces nausea, diarrhea, and stomach upset. Never take on an empty stomach, especially when starting or increasing the dose.' },
        avoid: [
          'Heavy alcohol use — raises risk of lactic acidosis, a rare but serious complication.',
          'Skipping meals — if you miss a meal, skip that dose rather than taking it on an empty stomach.',
          'IV contrast dye for imaging scans — hold metformin for 48 hours before and after; tell the imaging team.',
          'Excessive caffeine on an empty stomach — compounds GI side effects.',
        ],
        tips: [
          'Start low and go slow — most providers titrate up over 2–4 weeks to minimize stomach upset.',
          'Get Vitamin B12 levels checked annually; long-term metformin can lower B12 absorption.',
          'Stay hydrated, especially when sick with vomiting or diarrhea — stop temporarily and call your provider.',
          'Pair with resistance training; muscle is your largest glucose sink and works synergistically.',
        ],
        emergency: 'Seek emergency care if you experience unusual muscle pain, trouble breathing, severe stomach pain, or feeling unusually cold — possible signs of lactic acidosis.',
      },
      sideEffects: ['Nausea, stomach upset (usually improves after a few weeks)', 'Diarrhea — especially when starting or increasing dose', 'Metallic taste in mouth', 'Long-term use can reduce Vitamin B12 absorption — monitor annually'],
      experts: [
        { name: 'Andrew Weil, MD', credential: 'Founder, Univ. of Arizona Andrew Weil Center for Integrative Medicine', focus: 'Low-glycemic, anti-inflammatory eating, soluble fiber, and Ceylon cinnamon to steady blood sugar.', source: 'Univ. of Arizona Center for Integrative Medicine · NCCIH (NIH)' },
        { name: 'Tieraona Low Dog, MD', credential: 'Physician-herbalist; integrative medicine educator', focus: 'Berberine, fenugreek, and gymnema for glucose support, with routine B12 monitoring alongside metformin.', source: 'NCCIH (NIH) · American Botanical Council (HerbalGram)' },
        { name: 'Aviva Romm, MD', credential: 'Physician, midwife, and herbalist (Yale-trained)', focus: 'Whole-food, fiber-forward diet and metabolic-support botanicals integrated with conventional diabetes care.', source: '"Botanical Medicine for Women\u2019s Health" · NCCIH' },
      ],
      natural: [
  {
    "name": "Berberine",
    "context": "A plant compound from goldenseal and barberry that activates the same AMPK pathway as metformin. Typical dose: 500 mg three times daily with meals.",
    "evidence": "Metabolism Journal 2008, head-to-head trial"
  },
  {
    "name": "Cinnamon extract (1–3g daily with meals)",
    "context": "Ceylon cinnamon (not Cassia) modestly lowers fasting blood glucose. Safe to add to oatmeal, coffee, or smoothies.",
    "evidence": "Diabetes Care 2003 meta-analysis"
  },
  {
    "name": "African bitter melon (Momordica charantia)",
    "context": "Long used in West African and Caribbean cuisine for blood sugar control. Steep as tea or eat as a vegetable.",
    "evidence": "Journal of Ethnopharmacology — multiple small trials"
  },
  {
    "name": "Resistance training",
    "context": "Two 30-min sessions/week using bands, bodyweight, or weights. Builds muscle — your bodys largest glucose sink. More effective than cardio alone for A1C reduction.",
    "evidence": "ADA Standards of Care 2024"
  }
],
    },
    Atorvastatin: {
      overview: "Atorvastatin is a statin that reduces LDL cholesterol by blocking its production in the liver. Black patients often have higher Lp(a) lipoprotein levels — a risk factor statins do not address. Ask your doctor about Lp(a) testing.",
      bestUse: {
        timing: { label: 'Evening or bedtime', detail: 'Your liver makes most of its cholesterol overnight. Atorvastatin has a long half-life so any time technically works, but evening dosing aligns with peak cholesterol synthesis and many patients find it easy to pair with brushing teeth.' },
        food:   { label: 'With or without food', detail: 'Food does not affect how well atorvastatin works. Take it consistently — whichever you choose, stick with it.' },
        avoid: [
          'Grapefruit and grapefruit juice — blocks the enzyme that breaks down the statin, leading to dangerously high blood levels and muscle damage. Limit to small amounts, or avoid entirely.',
          'Heavy alcohol use — strains the liver, which already processes the statin.',
          'Certain antibiotics (clarithromycin, erythromycin) and antifungals — interact strongly; always tell prescribers you are on a statin.',
          'Red yeast rice supplements — contain natural statin compounds; combining doubles the dose unknowingly.',
        ],
        tips: [
          'Report any new muscle aches, weakness, or dark-colored urine immediately — possible myopathy.',
          'Ask about a CoQ10 supplement (100–200mg) — many patients tolerate statins better with it.',
          'Get liver enzymes checked at 3 months, then annually.',
          'Ask your doctor about Lp(a) testing — a risk factor more common in Black patients that statins do not lower.',
        ],
        emergency: 'Seek immediate care for severe muscle pain with dark-brown or tea-colored urine — possible rhabdomyolysis (severe muscle breakdown).',
      },
      sideEffects: ['Muscle pain or weakness (myopathy) — report any unusual aches', 'Liver enzyme elevation (monitored with periodic blood tests)', 'Increased blood sugar — particularly relevant for those with diabetes', 'Rare: Rhabdomyolysis (severe muscle breakdown) — seek care immediately'],
      experts: [
        { name: 'Dean Ornish, MD', credential: 'Founder, Preventive Medicine Research Institute; Clinical Professor, UCSF', focus: 'Whole-food, plant-based diet clinically shown to lower LDL cholesterol and reverse coronary artery disease.', source: '"Reversing Heart Disease" · The Lancet (Ornish Lifestyle trial)' },
        { name: 'Andrew Weil, MD', credential: 'Founder, Univ. of Arizona Andrew Weil Center for Integrative Medicine', focus: 'Omega-3 fatty acids, plant sterols, and soluble fiber to complement cholesterol management.', source: 'Univ. of Arizona Center for Integrative Medicine · NCCIH (NIH)' },
        { name: 'Joel Kahn, MD', credential: 'Clinical Professor of Medicine; integrative/preventive cardiologist', focus: 'Plant-based nutrition and evidence-based supplements (red yeast rice, sterols) for lipid health.', source: '"The Whole Heart Solution" · American College of Lifestyle Medicine' },
      ],
      natural: [
  {
    "name": "Plant sterols/stanols (2g/day)",
    "context": "Natural compounds that block cholesterol absorption in the gut. Found in fortified spreads, orange juice, and supplements. Lowers LDL by ~10%.",
    "evidence": "AHA Lifestyle Recommendations"
  },
  {
    "name": "Soluble fiber: oats, beans, lentils, flaxseed",
    "context": "Aim for 5–10g daily. One cup oatmeal + half cup beans gets most of the way. Black-eyed peas and collards are excellent sources.",
    "evidence": "JAMA — Cochrane review of soluble fiber"
  },
  {
    "name": "Omega-3 fatty acids (2–4g EPA+DHA)",
    "context": "Fatty fish (salmon, sardines) twice weekly, or pharmaceutical-grade fish oil. Specifically targets triglycerides — statins do not.",
    "evidence": "AHA 2018 Scientific Advisory on Omega-3"
  },
  {
    "name": "CoQ10 supplementation (100–200mg daily)",
    "context": "Statins block CoQ10 production along with cholesterol. Supplementing helps many tolerate statins better. Not a statin substitute.",
    "evidence": "Mayo Clinic Proceedings 2014 review"
  }
],
    },
  }

  const getDetails = (med) => details[med.name] || {
    overview: `${med.name} has been added to your medication list. Tap the tabs below to learn about side effects and natural alternatives.`,
    bestUse: {
      timing: { label: 'Follow your prescription label', detail: 'Take this medication at the time and frequency your provider specified. Set a daily reminder to anchor the habit.' },
      food:   { label: 'Check with your pharmacist', detail: 'Some medications need food, others need an empty stomach. Confirm with your pharmacist or check the patient information leaflet.' },
      avoid: ['Alcohol may interact with many medications — ask your pharmacist.', 'Grapefruit interacts with many common drugs.', 'Other prescriptions and over-the-counter medications — always disclose your full list.'],
      tips: ['Use a pill organizer or app reminder for consistency.', 'Bring all medications (or a list) to every appointment.', 'Never stop a medication abruptly without your provider\u2019s guidance.'],
      emergency: 'Call 911 or go to the ER for severe rash, breathing trouble, facial swelling, or any reaction that feels life-threatening.',
    },
    sideEffects: ['Consult your doctor or pharmacist for a full list of side effects specific to this medication.'],
    experts: [
      { name: 'Find a Registered Herbalist — RH(AHG)', credential: 'American Herbalists Guild', focus: 'The AHG maintains a directory of professionally vetted herbalists who work alongside your medical care.', source: 'American Herbalists Guild (americanherbalistsguild.com)' },
      { name: 'Andrew Weil Center for Integrative Medicine', credential: 'University of Arizona', focus: 'Locate a board-certified integrative physician to discuss evidence-based complementary options for your condition.', source: 'Univ. of Arizona · NCCIH (NIH, nccih.nih.gov)' },
    ],
    natural: ['Ask your healthcare provider about complementary approaches that may support your treatment.'],
  }

  const tabLabels = [['overview', 'Overview', '📋'], ['best-use', 'How to Use', '🕐'], ['side-effects', 'Risks', '⚠️'], ['natural', 'Natural', '🌿']]
  const inputStyle = { width: '100%', background: '#F6F2EC', border: `1.5px solid ${C.border}`, borderRadius: 12, padding: '13px 16px', color: C.text, fontFamily: 'DM Sans, sans-serif', fontSize: 15, outline: 'none', boxSizing: 'border-box' }

  if (addMode === 'choose') return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Add Medication" sub="How would you like to add it?" onBack={() => setAddMode(null)} backLabel="Meds" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <button onClick={() => { setAddMode('photo'); setTimeout(scanPhoto, 800) }} style={{ background: 'linear-gradient(135deg, #EEF4FF, #DDE8FF)', border: `1.5px solid ${C.blue}40`, borderRadius: 18, padding: '24px 20px', cursor: 'pointer', textAlign: 'left', display: 'flex', gap: 16, alignItems: 'center', boxShadow: '0 2px 10px rgba(26,74,140,0.1)' }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: `${C.blue}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, flexShrink: 0 }}>📷</div>
          <div>
            <p style={{ color: C.blue, fontWeight: 700, fontSize: 17, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>Scan Prescription Label</p>
            <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.5 }}>Take a photo of your pill bottle. AI will extract the medication details automatically.</p>
          </div>
        </button>
        <button onClick={() => setAddMode('manual')} style={{ background: '#fff', border: `1.5px solid ${C.border}`, borderRadius: 18, padding: '24px 20px', cursor: 'pointer', textAlign: 'left', display: 'flex', gap: 16, alignItems: 'center', boxShadow: '0 1px 4px rgba(0,0,0,0.05)' }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: `${C.gold}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, flexShrink: 0 }}>✏️</div>
          <div>
            <p style={{ color: C.text, fontWeight: 700, fontSize: 17, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>Enter Manually</p>
            <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.5 }}>Type in the medication name, dosage, and schedule yourself.</p>
          </div>
        </button>
        <div style={{ background: '#F0F8F3', border: `1.5px solid ${C.green}30`, borderRadius: 14, padding: 14 }}>
          <p style={{ color: C.green, fontSize: 13, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.6 }}>🔒 Medications are stored securely on your device and never shared without your consent.</p>
        </div>
      </div>
    </div>
  )

  if (addMode === 'photo' || addMode === 'scanning') return (
    <div style={{ height: '100%', background: 'linear-gradient(160deg, #EEF4FF, #F6F2EC)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20, padding: 32 }}>
      <div style={{ width: 72, height: 72, borderRadius: 36, background: `${C.blue}15`, border: `2px solid ${C.blue}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 32 }}>🔍</div>
      <h2 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 24, color: C.text, textAlign: 'center' }}>Analyzing Label</h2>
      <p style={{ color: C.muted, fontSize: 14, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', lineHeight: 1.6 }}>AI is reading your prescription details…</p>
      <div style={{ display: 'flex', gap: 6 }}>{[0,1,2].map(i => <div key={i} style={{ width: 10, height: 10, borderRadius: 5, background: C.blue, opacity: 0.4 + i * 0.3 }} />)}</div>
    </div>
  )

  if (addMode === 'manual') return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Add Medication" sub="Enter your prescription details" onBack={() => setAddMode('choose')} backLabel="Add" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ background: '#fff', borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>Medication Name *</p>
          <input placeholder="e.g. Amlodipine" value={form.name} onChange={e => setForm(f => ({...f, name: e.target.value}))} style={inputStyle} />
        </div>
        <div style={{ background: '#fff', borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>Dosage</p>
          <input placeholder="e.g. 5mg" value={form.dose} onChange={e => setForm(f => ({...f, dose: e.target.value}))} style={inputStyle} />
        </div>
        <div style={{ background: '#fff', borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>Frequency</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {frequencies.map(f => (
              <button key={f} onClick={() => setForm(fm => ({...fm, frequency: f}))} style={{ padding: '8px 14px', borderRadius: 20, border: `1.5px solid ${form.frequency === f ? C.gold : C.border}`, background: form.frequency === f ? `${C.gold}15` : '#F6F2EC', color: form.frequency === f ? C.gold : C.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 13, fontWeight: form.frequency === f ? 700 : 500, cursor: 'pointer' }}>{f}</button>
            ))}
          </div>
        </div>
        <div style={{ background: '#fff', borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>Condition / Reason</p>
          <input placeholder="e.g. High Blood Pressure" value={form.condition} onChange={e => setForm(f => ({...f, condition: e.target.value}))} style={inputStyle} />
        </div>
        <button onClick={addManual} style={{ background: `linear-gradient(135deg, ${C.goldLt}, ${C.gold})`, border: 'none', borderRadius: 14, padding: '16px 0', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 16, cursor: 'pointer', boxShadow: '0 4px 14px rgba(122,81,8,0.25)' }}>
          Add to My Medications
        </button>
      </div>
    </div>
  )

  // ── Refill flow ──────────────────────────────────────────────
  if (refillCtx) {
    const closeRefill = () => setRefillCtx(null)
    const back = () => setRefillCtx(ctx => ({ ...ctx, view: 'choose', selected: null }))
    const fmtPrice = (p, note) => note ? note : (p === 0 ? 'FREE' : `$${p.toFixed(2)}`)
    const fillerList = blackOwnedOnly ? mailProviders.filter(p => p.blackOwned) : mailProviders
    const localList  = (blackOwnedOnly ? localPharmacies.filter(p => p.blackOwned) : localPharmacies).slice().sort((a,b) => a.distance - b.distance)

    // ── Success view ──
    if (refillCtx.view === 'success') {
      const p = refillCtx.selected
      return (
        <div style={{ height: '100%', background: C.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18, padding: 32, textAlign: 'center' }}>
          <div style={{ width: 88, height: 88, borderRadius: 44, background: C.successBg, border: `2px solid ${C.success}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 40, color: C.success, fontWeight: 800 }}>✓</div>
          <h2 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 26, color: C.text }}>Refill submitted</h2>
          <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: 16, width: '100%', maxWidth: 320, textAlign: 'left' }}>
            <p style={{ color: C.muted, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>Medication</p>
            <p style={{ color: C.text, fontSize: 15, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginBottom: 10 }}>{refillCtx.med === 'all' ? `${meds.length} prescriptions` : `${refillCtx.med.name} · ${refillCtx.med.dose.split(' · ')[0]}`}</p>
            <p style={{ color: C.muted, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>{p.type === 'mail' ? 'Shipping to' : 'Pickup at'}</p>
            <p style={{ color: C.text, fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{p.name}{p.blackOwned && <span style={{ marginLeft: 8, background: '#FFF1B8', color: '#7A5108', fontSize: 10, fontWeight: 800, padding: '2px 7px', borderRadius: 100 }}>BLACK-OWNED</span>}</p>
            <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 4 }}>{p.type === 'mail' ? p.eta : p.address}</p>
          </div>
          <p style={{ color: C.muted, fontSize: 13, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif', maxWidth: 320 }}>We've sent the request to your provider for authorization. You'll get a notification when it's filled.</p>
          <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
            {!savedPharmacy && (
              <button onClick={() => { setSavedPharmacy(p); closeRefill() }} style={{ background: '#fff', border: `1.5px solid ${C.gold}`, borderRadius: 12, padding: '12px 18px', color: C.gold, fontWeight: 700, fontSize: 13, fontFamily: 'DM Sans, sans-serif', cursor: 'pointer' }}>★ Save as default</button>
            )}
            <button onClick={closeRefill} style={{ background: `linear-gradient(135deg, ${C.goldLt}, ${C.gold})`, border: 'none', borderRadius: 12, padding: '12px 24px', color: '#fff', fontWeight: 700, fontSize: 14, fontFamily: 'DM Sans, sans-serif', cursor: 'pointer', boxShadow: '0 4px 14px rgba(122,81,8,0.25)' }}>Done</button>
          </div>
        </div>
      )
    }

    // ── Confirm view ──
    if (refillCtx.view === 'confirm' && refillCtx.selected) {
      const p = refillCtx.selected
      const isAll = refillCtx.med === 'all'
      return (
        <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 110 }}>
          <SectionHeader title="Confirm refill" sub="Review and submit" onBack={back} backLabel="Back" />
          <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
            {/* Medication */}
            <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14 }}>
              <p style={{ color: C.muted, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif', marginBottom: 8 }}>Refilling</p>
              {isAll ? meds.map((m, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, paddingTop: i ? 10 : 0, paddingBottom: 10, borderBottom: i < meds.length - 1 ? `1px solid ${C.border}` : 'none' }}>
                  <div style={{ width: 32, height: 32, borderRadius: 8, background: `${m.color}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>💊</div>
                  <div style={{ flex: 1 }}>
                    <p style={{ color: C.text, fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{m.name}</p>
                    <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>{m.dose}</p>
                  </div>
                </div>
              )) : (
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{ width: 44, height: 44, borderRadius: 12, background: `${refillCtx.med.color}18`, border: `1.5px solid ${refillCtx.med.color}30`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>💊</div>
                  <div style={{ flex: 1 }}>
                    <p style={{ color: C.text, fontSize: 15, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{refillCtx.med.name}</p>
                    <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>{refillCtx.med.dose}</p>
                  </div>
                </div>
              )}
            </div>

            {/* Quantity */}
            <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14 }}>
              <p style={{ color: C.muted, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif', marginBottom: 10 }}>Supply</p>
              <div style={{ display: 'flex', gap: 8 }}>
                {[30, 60, 90].map(q => (
                  <button key={q} onClick={() => setRefillCtx(ctx => ({ ...ctx, qty: q }))} style={{ flex: 1, padding: '11px 0', borderRadius: 10, border: `1.5px solid ${refillCtx.qty === q ? C.gold : C.border}`, background: refillCtx.qty === q ? `${C.gold}15` : '#F6F2EC', color: refillCtx.qty === q ? C.gold : C.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>{q}-day</button>
                ))}
              </div>
              <p style={{ color: C.muted, fontSize: 11, fontFamily: 'DM Sans, sans-serif', marginTop: 8, lineHeight: 1.5 }}>90-day supply often costs less per pill and reduces refill friction.</p>
            </div>

            {/* Pharmacy */}
            <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <p style={{ color: C.muted, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>{p.type === 'mail' ? 'Mail-order' : 'Pickup'}</p>
                <button onClick={back} style={{ background: 'none', border: 'none', color: C.gold, fontSize: 12, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', cursor: 'pointer' }}>Change</button>
              </div>
              <p style={{ color: C.text, fontSize: 15, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{p.name}{p.blackOwned && <span style={{ marginLeft: 8, background: '#FFF1B8', color: '#7A5108', fontSize: 10, fontWeight: 800, padding: '2px 7px', borderRadius: 100 }}>BLACK-OWNED</span>}</p>
              <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginTop: 3 }}>{p.type === 'mail' ? `${p.eta} · ${p.shipping}` : `${p.address} · ${p.distance} mi`}</p>
            </div>

            {/* Cost */}
            <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14 }}>
              <p style={{ color: C.muted, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif', marginBottom: 10 }}>Estimated cost</p>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <p style={{ color: C.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>{refillCtx.qty}-day cash price{isAll && ` × ${meds.length}`}</p>
                <p style={{ color: C.text, fontSize: 22, fontWeight: 800, fontFamily: 'DM Serif Display, serif' }}>{fmtPrice(p.price * (refillCtx.qty / 30) * (isAll ? meds.length : 1), p.priceNote && !isAll && refillCtx.qty === 30 ? p.priceNote : null)}</p>
              </div>
              <p style={{ color: C.muted, fontSize: 11, fontFamily: 'DM Sans, sans-serif', marginTop: 6, lineHeight: 1.5 }}>Final price may vary with insurance, coupons, or manufacturer assistance. We'll show the exact amount before charging.</p>
            </div>

            <button onClick={() => setRefillCtx(ctx => ({ ...ctx, view: 'success' }))} style={{ background: `linear-gradient(135deg, ${C.goldLt}, ${C.gold})`, border: 'none', borderRadius: 14, padding: '15px 0', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 16, cursor: 'pointer', boxShadow: '0 4px 14px rgba(122,81,8,0.25)', marginTop: 4 }}>
              Submit refill request
            </button>
            <p style={{ color: C.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', lineHeight: 1.5 }}>Your provider will be notified to authorize the refill if needed.</p>
          </div>
        </div>
      )
    }

    // ── Mail-order list ──
    if (refillCtx.view === 'mail') {
      return (
        <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
          <SectionHeader title="Mail-order" sub="Delivered to your door" onBack={back} backLabel="Back" />
          <div style={{ padding: '0 16px' }}>
            {/* Black-owned filter */}
            <button onClick={() => setBlackOwnedOnly(!blackOwnedOnly)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: 12, marginBottom: 12, background: blackOwnedOnly ? '#FFF1B8' : '#fff', border: `1.5px solid ${blackOwnedOnly ? '#7A5108' : C.border}`, borderRadius: 12, cursor: 'pointer', textAlign: 'left' }}>
              <div style={{ width: 22, height: 22, borderRadius: 6, border: `2px solid ${blackOwnedOnly ? '#7A5108' : C.muted}`, background: blackOwnedOnly ? '#7A5108' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 13, fontWeight: 800 }}>{blackOwnedOnly ? '✓' : ''}</div>
              <div style={{ flex: 1 }}>
                <p style={{ color: blackOwnedOnly ? '#7A5108' : C.text, fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>Only show Black-owned pharmacies</p>
                <p style={{ color: blackOwnedOnly ? '#7A5108' : C.muted, fontSize: 11.5, fontFamily: 'DM Sans, sans-serif', marginTop: 2, opacity: 0.85 }}>Support independent Black-owned pharmacies in your community</p>
              </div>
            </button>

            {fillerList.length === 0 ? (
              <div style={{ background: '#fff', border: `1px dashed ${C.border}`, borderRadius: 14, padding: 24, textAlign: 'center' }}>
                <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>No Black-owned mail-order pharmacies in this list yet. Try the Pickup option for local Black-owned pharmacies near you.</p>
              </div>
            ) : fillerList.map(p => (
              <button key={p.id} onClick={() => setRefillCtx(ctx => ({ ...ctx, view: 'confirm', selected: { ...p, type: 'mail' } }))} style={{ width: '100%', display: 'block', background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14, marginBottom: 10, cursor: 'pointer', textAlign: 'left' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10, marginBottom: 6 }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <p style={{ color: C.text, fontSize: 15, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{p.name}</p>
                    <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 2, lineHeight: 1.4 }}>{p.tagline}</p>
                  </div>
                  <div style={{ textAlign: 'right', flexShrink: 0, minWidth: 78 }}>
                    <p style={{ color: C.text, fontSize: p.priceNote ? 12 : 18, fontWeight: 800, fontFamily: p.priceNote ? 'DM Sans, sans-serif' : 'DM Serif Display, serif', lineHeight: 1.15, whiteSpace: 'nowrap' }}>{fmtPrice(p.price, p.priceNote)}</p>
                    <p style={{ color: C.muted, fontSize: 10, fontFamily: 'DM Sans, sans-serif', marginTop: 3, whiteSpace: 'nowrap' }}>30-day cash</p>
                  </div>
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
                  {p.badge && <span style={{ background: `${p.badgeColor}15`, color: p.badgeColor, fontSize: 10, fontWeight: 800, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', letterSpacing: 0.3, textTransform: 'uppercase', whiteSpace: 'nowrap' }}>{p.badge}</span>}
                  <span style={{ background: '#F6F2EC', color: C.muted, fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>🚚 {p.eta}</span>
                  <span style={{ background: '#F6F2EC', color: C.muted, fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>{p.insurance}</span>
                </div>
              </button>
            ))}

            <p style={{ color: C.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', lineHeight: 1.55, marginTop: 6 }}>Prices shown are cash baselines for generic Lisinopril 10mg. Your actual price may differ by medication, dose, and insurance.</p>
          </div>
        </div>
      )
    }

    // ── Local pickup list ──
    if (refillCtx.view === 'pickup') {
      return (
        <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
          <SectionHeader title="Pickup nearby" sub="Same-day at a local pharmacy" onBack={back} backLabel="Back" />
          <div style={{ padding: '0 16px' }}>
            {/* ZIP input */}
            <div style={{ background: '#fff', borderRadius: 14, padding: 12, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <span style={{ fontSize: 18 }}>📍</span>
              <input value={zip} onChange={e => setZip(e.target.value.replace(/[^0-9]/g, '').slice(0, 5))} placeholder="ZIP code" inputMode="numeric" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontFamily: 'DM Sans, sans-serif', fontSize: 15, color: C.text, fontWeight: 600 }} />
              <button style={{ background: C.gold, border: 'none', borderRadius: 8, padding: '7px 14px', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12, cursor: 'pointer' }}>Search</button>
            </div>

            {/* Black-owned filter */}
            <button onClick={() => setBlackOwnedOnly(!blackOwnedOnly)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: 12, marginBottom: 12, background: blackOwnedOnly ? '#FFF1B8' : '#fff', border: `1.5px solid ${blackOwnedOnly ? '#7A5108' : C.border}`, borderRadius: 12, cursor: 'pointer', textAlign: 'left' }}>
              <div style={{ width: 22, height: 22, borderRadius: 6, border: `2px solid ${blackOwnedOnly ? '#7A5108' : C.muted}`, background: blackOwnedOnly ? '#7A5108' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 13, fontWeight: 800 }}>{blackOwnedOnly ? '✓' : ''}</div>
              <div style={{ flex: 1 }}>
                <p style={{ color: blackOwnedOnly ? '#7A5108' : C.text, fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>Only show Black-owned pharmacies</p>
                <p style={{ color: blackOwnedOnly ? '#7A5108' : C.muted, fontSize: 11.5, fontFamily: 'DM Sans, sans-serif', marginTop: 2, opacity: 0.85 }}>{(blackOwnedOnly ? localPharmacies.filter(p => p.blackOwned) : localPharmacies).length} pharmac{(blackOwnedOnly ? localPharmacies.filter(p => p.blackOwned) : localPharmacies).length === 1 ? 'y' : 'ies'} within 5 mi</p>
              </div>
            </button>

            {/* Price comparison header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, padding: '4px 4px 8px', marginBottom: 2 }}>
              <p style={{ color: C.muted, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>Sorted by distance</p>
              <p style={{ color: C.dim, fontSize: 10, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>30-day cash price</p>
            </div>

            {localList.length === 0 ? (
              <div style={{ background: '#fff', border: `1px dashed ${C.border}`, borderRadius: 14, padding: 24, textAlign: 'center' }}>
                <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>No Black-owned pharmacies match in {zip}. Try a wider radius or check mail-order.</p>
              </div>
            ) : localList.map(p => {
              const cheapest = Math.min(...localList.filter(x => x.price > 0).map(x => x.price))
              const isCheapest = p.price > 0 && p.price === cheapest
              return (
                <button key={p.id} onClick={() => setRefillCtx(ctx => ({ ...ctx, view: 'confirm', selected: { ...p, type: 'local' } }))} style={{ width: '100%', display: 'block', background: C.card, border: `1px solid ${p.blackOwned ? '#7A5108' : C.border}`, borderRadius: 14, padding: 14, marginBottom: 10, cursor: 'pointer', textAlign: 'left', position: 'relative' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10, marginBottom: 8 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                        <p style={{ color: C.text, fontSize: 15, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{p.name}</p>
                        {p.blackOwned && <span style={{ background: '#FFF1B8', color: '#7A5108', fontSize: 9.5, fontWeight: 800, padding: '2px 7px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', letterSpacing: 0.3, whiteSpace: 'nowrap' }}>BLACK-OWNED</span>}
                      </div>
                      <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 3, lineHeight: 1.4 }}>{p.address}</p>
                    </div>
                    <div style={{ textAlign: 'right', flexShrink: 0, minWidth: 70 }}>
                      <p style={{ color: isCheapest ? C.success : C.text, fontSize: p.priceNote ? 13 : 20, fontWeight: 800, fontFamily: p.priceNote ? 'DM Sans, sans-serif' : 'DM Serif Display, serif', lineHeight: 1.15, whiteSpace: 'nowrap' }}>{fmtPrice(p.price, p.priceNote)}</p>
                      {isCheapest && <p style={{ color: C.success, fontSize: 9.5, fontWeight: 800, fontFamily: 'DM Sans, sans-serif', marginTop: 3, letterSpacing: 0.5, whiteSpace: 'nowrap' }}>LOWEST</p>}
                    </div>
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    <span style={{ background: '#F6F2EC', color: C.muted, fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>📍 {p.distance} mi</span>
                    <span style={{ background: '#F6F2EC', color: C.muted, fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>🕐 {p.hours}</span>
                    <span style={{ background: p.stock === 'In stock' ? `${C.success}15` : `${C.warning}15`, color: p.stock === 'In stock' ? C.success : C.warning, fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>● {p.stock}</span>
                    {p.badge && <span style={{ background: '#F6F2EC', color: C.text, fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>{p.badge}</span>}
                  </div>
                </button>
              )
            })}

            <p style={{ color: C.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', lineHeight: 1.55, marginTop: 6 }}>Prices shown are cash baselines for generic Lisinopril 10mg. Insurance copay shown at confirmation if applicable.</p>
          </div>
        </div>
      )
    }

    // ── Choose view (entry point) ──
    return (
      <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
        <SectionHeader title={refillTitle} sub={refillSub} onBack={closeRefill} backLabel="Meds" />
        <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Quick refill — saved pharmacy */}
          {savedPharmacy && (
            <button onClick={() => setRefillCtx(ctx => ({ ...ctx, view: 'confirm', selected: savedPharmacy }))} style={{ background: `linear-gradient(135deg, #FFF8E1, #FEF1CD)`, border: `2px solid ${C.gold}`, borderRadius: 18, padding: '18px 18px', cursor: 'pointer', textAlign: 'left', boxShadow: '0 3px 14px rgba(122,81,8,0.18)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <span style={{ background: C.gold, color: '#fff', fontSize: 10, fontWeight: 800, padding: '3px 8px', borderRadius: 100, letterSpacing: 0.5, fontFamily: 'DM Sans, sans-serif' }}>★ DEFAULT</span>
                <p style={{ color: C.gold, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>One-tap refill</p>
              </div>
              <p style={{ color: C.text, fontSize: 18, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{savedPharmacy.name}{savedPharmacy.blackOwned && <span style={{ marginLeft: 8, background: '#fff', color: '#7A5108', fontSize: 10, fontWeight: 800, padding: '2px 7px', borderRadius: 100 }}>BLACK-OWNED</span>}</p>
              <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginTop: 3 }}>{savedPharmacy.type === 'mail' ? `Ships in ${savedPharmacy.eta}` : `${savedPharmacy.address} · ${savedPharmacy.distance} mi`} · {fmtPrice(savedPharmacy.price, savedPharmacy.priceNote)}</p>
              <div style={{ marginTop: 12, background: '#fff', borderRadius: 10, padding: '10px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ color: C.text, fontWeight: 700, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>Refill now →</span>
                <button onClick={(e) => { e.stopPropagation(); setSavedPharmacy(null) }} style={{ background: 'none', border: 'none', color: C.muted, fontSize: 11, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', cursor: 'pointer', textDecoration: 'underline' }}>Remove default</button>
              </div>
            </button>
          )}

          {savedPharmacy && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 4px' }}>
              <div style={{ flex: 1, height: 1, background: C.border }}></div>
              <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1.2, fontFamily: 'DM Sans, sans-serif' }}>Or choose a different option</p>
              <div style={{ flex: 1, height: 1, background: C.border }}></div>
            </div>
          )}

          {/* Two big paths */}
          <div style={{ display: 'flex', gap: 12 }}>
            <button onClick={() => { setBlackOwnedOnly(false); setRefillCtx(ctx => ({ ...ctx, view: 'mail' })) }} style={{ flex: 1, background: `linear-gradient(160deg, #EEF4FF, #DDE8FF)`, border: `1.5px solid ${C.blue}40`, borderRadius: 18, padding: '20px 14px', cursor: 'pointer', textAlign: 'left', boxShadow: '0 2px 10px rgba(26,74,140,0.1)' }}>
              <div style={{ width: 44, height: 44, borderRadius: 12, background: `${C.blue}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, marginBottom: 10 }}>🚚</div>
              <p style={{ color: C.blue, fontSize: 15, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>Mail-order</p>
              <p style={{ color: C.muted, fontSize: 11.5, fontFamily: 'DM Sans, sans-serif', marginTop: 4, lineHeight: 1.4 }}>Delivered to your door · From $4.20</p>
              <p style={{ color: C.blue, fontSize: 10, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginTop: 8, opacity: 0.75 }}>5 providers ›</p>
            </button>
            <button onClick={() => { setBlackOwnedOnly(false); setRefillCtx(ctx => ({ ...ctx, view: 'pickup' })) }} style={{ flex: 1, background: `linear-gradient(160deg, #F0F8F3, #DCEFE3)`, border: `1.5px solid ${C.success}40`, borderRadius: 18, padding: '20px 14px', cursor: 'pointer', textAlign: 'left', boxShadow: '0 2px 10px rgba(22,163,74,0.08)' }}>
              <div style={{ width: 44, height: 44, borderRadius: 12, background: `${C.success}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, marginBottom: 10 }}>📍</div>
              <p style={{ color: C.success, fontSize: 15, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>Pickup nearby</p>
              <p style={{ color: C.muted, fontSize: 11.5, fontFamily: 'DM Sans, sans-serif', marginTop: 4, lineHeight: 1.4 }}>Same-day at a local pharmacy · From FREE</p>
              <p style={{ color: C.success, fontSize: 10, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginTop: 8, opacity: 0.75 }}>{localPharmacies.length} in {zip} ›</p>
            </button>
          </div>

          {/* Find Black-owned shortcut */}
          <button onClick={() => { setBlackOwnedOnly(true); setRefillCtx(ctx => ({ ...ctx, view: 'pickup' })) }} style={{ background: '#fff', border: `1.5px solid #7A5108`, borderRadius: 14, padding: '14px 16px', cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: '#FFF1B8', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20, flexShrink: 0 }}>✊🏾</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <p style={{ color: '#7A5108', fontSize: 14, fontWeight: 800, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.3 }}>Find Black-owned pharmacies near you</p>
              <p style={{ color: C.muted, fontSize: 11.5, fontFamily: 'DM Sans, sans-serif', marginTop: 4, lineHeight: 1.4 }}>{localPharmacies.filter(p => p.blackOwned).length} within 5 mi of {zip}</p>
            </div>
            <span style={{ color: '#7A5108', fontSize: 20, flexShrink: 0 }}>›</span>
          </button>

          {/* Insurance note */}
          <div style={{ background: C.infoBg, border: `1px solid ${C.info}30`, borderRadius: 12, padding: 12, display: 'flex', gap: 10 }}>
            <span style={{ fontSize: 16 }}>💳</span>
            <p style={{ color: C.infoText, fontSize: 12, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>Insurance copay info will show on the next screen. If you're uninsured, cash prices vary 3× across pharmacies — we always show the cheapest first.</p>
          </div>
        </div>
      </div>
    )
  }

  if (selected) {
    const d = getDetails(selected)
    return (
      <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
        <SectionHeader title={selected.name} sub={`${selected.dose} · ${selected.condition}`} onBack={() => setSelected(null)} backLabel="List" />
        <div style={{ padding: '0 16px' }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 14 }}>
            {tabLabels.map(([key, label, icon]) => {
              const on = tab === key
              return (
                <button key={key} onClick={() => setTab(key)} style={{
                  flex: '1 1 calc(50% - 4px)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
                  padding: '12px 6px', borderRadius: 100, cursor: 'pointer',
                  background: on ? selected.color : '#fff',
                  border: `1.5px solid ${on ? selected.color : C.border}`,
                  color: on ? '#fff' : C.muted,
                  fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 13.5,
                  boxShadow: on ? `0 4px 14px ${selected.color}33` : '0 1px 3px rgba(0,0,0,0.04)',
                  transition: 'box-shadow 0.18s ease',
                }}>
                  <span style={{ fontSize: 15, lineHeight: 1 }}>{icon}</span>{label}
                </button>
              )
            })}
          </div>
          {tab === 'overview' && <div style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}><p style={{ color: C.text, fontSize: 14, lineHeight: 1.8, fontFamily: 'DM Sans, sans-serif' }}>{d.overview}</p></div>}
          {tab === 'best-use' && d.bestUse && (() => {
            const bu = d.bestUse
            const accent = selected.color
            return (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {/* Quick-glance row: Timing + Food */}
                <div style={{ display: 'flex', gap: 10 }}>
                  <div style={{ flex: 1, background: C.card, border: `1px solid ${C.border}`, borderTop: `3px solid ${accent}`, borderRadius: 14, padding: 12 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                      <span style={{ fontSize: 16 }}>🕐</span>
                      <p style={{ color: C.muted, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 0.8, fontFamily: 'DM Sans, sans-serif' }}>When</p>
                    </div>
                    <p style={{ color: C.text, fontSize: 13, fontWeight: 700, lineHeight: 1.35, fontFamily: 'DM Sans, sans-serif' }}>{bu.timing.label}</p>
                  </div>
                  <div style={{ flex: 1, background: C.card, border: `1px solid ${C.border}`, borderTop: `3px solid ${accent}`, borderRadius: 14, padding: 12 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                      <span style={{ fontSize: 16 }}>🍽️</span>
                      <p style={{ color: C.muted, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 0.8, fontFamily: 'DM Sans, sans-serif' }}>Food</p>
                    </div>
                    <p style={{ color: C.text, fontSize: 13, fontWeight: 700, lineHeight: 1.35, fontFamily: 'DM Sans, sans-serif' }}>{bu.food.label}</p>
                  </div>
                </div>

                {/* Timing detail */}
                <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14 }}>
                  <p style={{ color: accent, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif', marginBottom: 8 }}>Time of day</p>
                  <p style={{ color: C.text, fontSize: 13.5, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif' }}>{bu.timing.detail}</p>
                </div>

                {/* Food detail */}
                <div style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14 }}>
                  <p style={{ color: accent, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif', marginBottom: 8 }}>With or without food</p>
                  <p style={{ color: C.text, fontSize: 13.5, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif' }}>{bu.food.detail}</p>
                </div>

                {/* Avoid list */}
                {bu.avoid && bu.avoid.length > 0 && (
                  <div style={{ background: '#FEF6E6', border: `1.5px solid ${C.gold}40`, borderRadius: 14, padding: 14 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                      <span style={{ fontSize: 16 }}>🚫</span>
                      <p style={{ color: C.gold, fontSize: 12, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>Avoid · Interactions</p>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {bu.avoid.map((a, i) => (
                        <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
                          <span style={{ width: 5, height: 5, borderRadius: 3, background: C.gold, marginTop: 8, flexShrink: 0 }}></span>
                          <p style={{ color: C.text, fontSize: 13, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>{a}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Tips list */}
                {bu.tips && bu.tips.length > 0 && (
                  <div style={{ background: C.successBg, border: `1.5px solid ${C.success}40`, borderRadius: 14, padding: 14 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                      <span style={{ fontSize: 16 }}>✓</span>
                      <p style={{ color: C.successText, fontSize: 12, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>Best Practices</p>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {bu.tips.map((t, i) => (
                        <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
                          <span style={{ width: 18, height: 18, borderRadius: 9, background: `${C.success}25`, color: C.success, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, fontFamily: 'DM Sans, sans-serif', flexShrink: 0, marginTop: 1 }}>{i + 1}</span>
                          <p style={{ color: C.successText, fontSize: 13, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>{t}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Emergency */}
                {bu.emergency && (
                  <div style={{ background: C.criticalBg, border: `1.5px solid ${C.critical}50`, borderLeft: `4px solid ${C.critical}`, borderRadius: 12, padding: 14 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                      <span style={{ fontSize: 16 }}>🚨</span>
                      <p style={{ color: C.critical, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>When to seek emergency care</p>
                    </div>
                    <p style={{ color: C.criticalText, fontSize: 13.5, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>{bu.emergency}</p>
                  </div>
                )}
              </div>
            )
          })()}
          {tab === 'side-effects' && d.sideEffects.map((s, i) => (
            <div key={i} style={{ background: '#FEF2F4', borderRadius: 12, padding: 14, marginBottom: 10, border: `1.5px solid ${C.red}30`, display: 'flex', gap: 10 }}>
              <span>⚠️</span><p style={{ color: C.text, fontSize: 14, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif' }}>{s}</p>
            </div>
          ))}
          {tab === 'natural' && <>
            <div style={{ background: C.successBg, border: `1.5px solid ${C.success}50`, borderRadius: 12, padding: 12, marginBottom: 12 }}>
              <p style={{ color: C.successText, fontSize: 13, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif', fontWeight: 500 }}>⚕️ Always consult your doctor before stopping medications or combining with herbs/supplements. These are complementary, not replacements.</p>
            </div>

            {/* Recognized practitioners & well-sourced authorities (medication-specific) */}
            {d.experts && d.experts.length > 0 && (
              <div style={{ background: 'linear-gradient(135deg, #EAF5EC, #DDEFE0)', border: `1.5px solid ${C.success}40`, borderRadius: 16, padding: 16, marginBottom: 12 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <span style={{ fontSize: 18 }}>🌿</span>
                  <p style={{ color: C.successText, fontSize: 12, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>Recognized Practitioners & Sources</p>
                </div>
                <p style={{ color: '#1A3A22', fontSize: 12.5, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif', marginBottom: 12 }}>
                  Credentialed herbalists, integrative physicians, and alternative-medicine authorities whose work on {selected.condition.toLowerCase()} is well documented.
                </p>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {d.experts.map((ex, i) => (
                    <div key={i} style={{ background: 'rgba(255,255,255,0.7)', border: `1px solid ${C.success}25`, borderRadius: 12, padding: 13 }}>
                      <p style={{ color: C.text, fontWeight: 800, fontSize: 14.5, fontFamily: 'DM Sans, sans-serif' }}>{ex.name}</p>
                      <p style={{ color: C.successText, fontWeight: 700, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>{ex.credential}</p>
                      <p style={{ color: '#2A5035', fontSize: 13, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif', marginTop: 6 }}>{ex.focus}</p>
                      <p style={{ color: C.muted, fontSize: 11, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif', marginTop: 6, fontStyle: 'italic' }}>📚 {ex.source}</p>
                    </div>
                  ))}
                </div>
                <div style={{ background: C.warningBg, border: `1px solid ${C.warning}30`, borderRadius: 10, padding: 11, marginTop: 12, display: 'flex', gap: 8 }}>
                  <span style={{ fontSize: 14, flexShrink: 0 }}>⚠️</span>
                  <p style={{ color: C.warningText, fontSize: 12, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>These practitioners offer complementary approaches — not a substitute for your prescribed medication. Some herbs interact with drugs; talk with your doctor or pharmacist before starting.</p>
                </div>
              </div>
            )}

            {d.natural.map((s, i) => {
              const item = typeof s === 'string' ? { name: s, context: '', evidence: null } : s
              return (
                <div key={i} style={{ background: C.card, borderRadius: 14, padding: 14, marginBottom: 10, border: `1px solid ${C.border}` }}>
                  <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 8 }}>
                    <div style={{ width: 28, height: 28, borderRadius: 14, background: `${C.success}18`, color: C.success, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 13, fontFamily: 'DM Sans, sans-serif', flexShrink: 0 }}>{i + 1}</div>
                    <p style={{ color: C.text, fontSize: 14, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, flex: 1 }}>{item.name}</p>
                  </div>
                  {item.context && <p style={{ color: C.muted, fontSize: 13, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif', paddingLeft: 38 }}>{item.context}</p>}
                  {item.evidence && <p style={{ color: C.dim, fontSize: 11, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif', paddingLeft: 38, marginTop: 6, fontStyle: 'italic' }}>📚 {item.evidence}</p>}
                </div>
              )
            })}
          </>}
          <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <button onClick={() => openRefill(selected)} style={{ width: '100%', background: `linear-gradient(135deg, ${C.goldLt}, ${C.gold})`, border: 'none', borderRadius: 12, padding: '15px 0', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 15, cursor: 'pointer', boxShadow: '0 4px 14px rgba(122,81,8,0.25)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              <span style={{ fontSize: 16 }}>🔄</span>
              {savedPharmacy ? `Refill at ${savedPharmacy.name.split(' ').slice(0, 2).join(' ')}…` : 'Refill or order this medication'}
            </button>
            <button onClick={() => { setMeds(m => m.filter(x => x.name !== selected.name)); setSelected(null) }} style={{ width: '100%', background: '#FEF2F4', border: `1.5px solid ${C.red}30`, borderRadius: 12, padding: '13px 0', color: C.red, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 14, cursor: 'pointer' }}>
              Remove from My Medications
            </button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Medications" sub={`${meds.length} active prescription${meds.length !== 1 ? 's' : ''}`} onBack={() => nav('home')} backLabel="Home" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {meds.map((med, i) => (
          <div key={i} style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 16, padding: 14, boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
            <div onClick={() => { setSelected(med); setTab('overview') }} style={{ display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer' }}>
              <div style={{ width: 50, height: 50, borderRadius: 14, background: `${med.color}18`, border: `1.5px solid ${med.color}30`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, flexShrink: 0 }}>💊</div>
              <div style={{ flex: 1 }}>
                <p style={{ color: C.text, fontWeight: 700, fontSize: 16, fontFamily: 'DM Sans, sans-serif' }}>{med.name}</p>
                <p style={{ color: C.muted, fontSize: 13, marginTop: 2, fontFamily: 'DM Sans, sans-serif' }}>{med.dose}</p>
                <Tag label={med.condition} color={med.color} />
              </div>
              <span style={{ color: C.muted, fontSize: 22 }}>›</span>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 12, paddingTop: 12, borderTop: `1px solid ${C.border}` }}>
              <button onClick={(e) => { e.stopPropagation(); setSelected(med); setTab('overview') }} style={{ flex: 1, background: '#fff', border: `1px solid ${C.border}`, borderRadius: 10, padding: '9px 0', color: C.muted, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12.5, cursor: 'pointer' }}>
                Details
              </button>
              <button onClick={(e) => { e.stopPropagation(); openRefill(med) }} style={{ flex: 1, background: `${C.gold}12`, border: `1px solid ${C.gold}40`, borderRadius: 10, padding: '9px 0', color: C.gold, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12.5, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
                <span style={{ fontSize: 13 }}>🔄</span> Refill
              </button>
            </div>
          </div>
        ))}
        <button onClick={() => setAddMode('choose')} style={{ background: `linear-gradient(135deg, ${C.goldLt}15, ${C.gold}08)`, border: `1.5px dashed ${C.gold}60`, borderRadius: 16, padding: '18px 20px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: `${C.gold}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, color: C.gold, fontWeight: 700 }}>+</div>
          <div style={{ textAlign: 'left' }}>
            <p style={{ color: C.gold, fontWeight: 700, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>Add Medication</p>
            <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>Scan label or enter manually</p>
          </div>
        </button>

        {/* Refill entry */}
        {meds.length > 0 && (
          <button onClick={() => setRefillCtx({ med: 'all', view: 'choose', selected: null, qty: 30 })} style={{ width: '100%', background: savedPharmacy ? `linear-gradient(135deg, #FFF8E1, #FEF1CD)` : `linear-gradient(135deg, #EEF4FF, #DDE8FF)`, border: `1.5px solid ${savedPharmacy ? C.gold : C.blue}40`, borderRadius: 14, padding: '14px 16px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left' }}>
            <div style={{ width: 42, height: 42, borderRadius: 11, background: savedPharmacy ? `${C.gold}20` : `${C.blue}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>{savedPharmacy ? '⚡' : '🔄'}</div>
            <div style={{ flex: 1 }}>
              <p style={{ color: savedPharmacy ? C.gold : C.blue, fontWeight: 800, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>{savedPharmacy ? `One-tap refill all (${meds.length})` : 'Refill or order medications'}</p>
              <p style={{ color: C.muted, fontSize: 11.5, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>{savedPharmacy ? `Via ${savedPharmacy.name}` : 'Mail-order or pickup nearby · compare prices'}</p>
            </div>
            <span style={{ color: savedPharmacy ? C.gold : C.blue, fontSize: 22 }}>›</span>
          </button>
        )}

        <PillIdentifier />
      </div>
    
        {/* Drug Interaction Check */}
        <DrugInteractionPanel meds={meds} />

        {/* Recalls & Safety Alerts */}
        <div style={{ marginTop: 24, padding: '0 16px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <div style={{ width: 24, height: 24, borderRadius: 12, background: C.criticalBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <span style={{ fontSize: 13 }}>⚠️</span>
            </div>
            <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif' }}>Recalls & Safety Alerts</p>
          </div>
          <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginBottom: 10, lineHeight: 1.5 }}>
            Active FDA recalls and safety alerts affecting your medications. Updated daily.
          </p>

          {(() => {
            // FDA-style recall feed — filter for medications matching user's list
            const allAlerts = [
              { severity: 'critical', medName: 'Lisinopril', title: 'Class I Recall — Lisinopril 10mg', issuer: 'FDA / Lupin Pharmaceuticals', date: 'May 12, 2026', summary: 'Specific lot numbers may contain trace nitrosamine impurities (NDMA) above acceptable daily intake limits. Long-term exposure may increase cancer risk.', action: 'Check your prescription bottle for lot numbers L-2024-1187 through L-2024-1203. Do NOT stop your medication abruptly. Contact your pharmacy for a replacement at no cost.', lots: 'L-2024-1187 to L-2024-1203' },
              { severity: 'warning', medName: 'Metformin', title: 'Voluntary Recall — Extended-Release Metformin', issuer: 'FDA / Marksans Pharma', date: 'April 28, 2026', summary: 'Limited recall of select extended-release lots. Standard immediate-release formulations are not affected.', action: 'If you take ER (extended-release) metformin, verify with your pharmacist that your specific lot is not affected.', lots: 'XR-23-441, XR-23-447' },
              { severity: 'info', medName: 'Atorvastatin', title: 'FDA Safety Communication — Statin & Diabetes Risk', issuer: 'FDA Drug Safety', date: 'March 15, 2026', summary: 'Updated labeling clarifies the small increased risk of new-onset diabetes with statins, particularly for patients already at risk. Benefits still outweigh risks for most cardiovascular patients.', action: 'No action required. Discuss with your provider at your next visit if you have concerns.', lots: null },
            ]
            const userMedNames = meds.map(m => m.name)
            const relevant = allAlerts.filter(a => userMedNames.includes(a.medName))
            const sevColors = { critical: { bg: C.criticalBg, text: C.criticalText, accent: C.critical, label: 'CRITICAL' }, warning: { bg: C.warningBg, text: C.warningText, accent: C.warning, label: 'WARNING' }, info: { bg: C.infoBg, text: C.infoText, accent: C.info, label: 'INFO' } }

            if (relevant.length === 0) {
              return (
                <div style={{ background: C.successBg, border: `1px solid ${C.success}40`, borderRadius: 14, padding: 16, textAlign: 'center' }}>
                  <p style={{ color: C.successText, fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>✓ All Clear</p>
                  <p style={{ color: C.successText, fontSize: 12, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.5 }}>No active recalls or safety alerts for your current medications.</p>
                </div>
              )
            }

            return relevant.map((a, i) => {
              const sc = sevColors[a.severity]
              return (
                <div key={i} style={{ background: sc.bg, border: `1.5px solid ${sc.accent}40`, borderLeft: `4px solid ${sc.accent}`, borderRadius: 12, padding: 14, marginBottom: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8, marginBottom: 8 }}>
                    <div style={{ flex: 1 }}>
                      <span style={{ background: sc.accent, color: '#fff', fontSize: 9, fontWeight: 800, padding: '3px 7px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', letterSpacing: 0.5 }}>{sc.label}</span>
                      <p style={{ color: sc.text, fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginTop: 6 }}>{a.title}</p>
                      <p style={{ color: sc.text, fontSize: 11, fontFamily: 'DM Sans, sans-serif', marginTop: 2, opacity: 0.8 }}>{a.issuer} · {a.date}</p>
                    </div>
                    <span style={{ background: '#fff', color: sc.text, fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 6, fontFamily: 'DM Sans, sans-serif', flexShrink: 0 }}>{a.medName}</span>
                  </div>
                  <p style={{ color: sc.text, fontSize: 13, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif', marginBottom: 8 }}>{a.summary}</p>
                  <div style={{ background: 'rgba(255,255,255,0.6)', borderRadius: 8, padding: 10, marginBottom: a.lots ? 8 : 0 }}>
                    <p style={{ color: sc.text, fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 4, fontFamily: 'DM Sans, sans-serif' }}>What to do</p>
                    <p style={{ color: sc.text, fontSize: 12, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>{a.action}</p>
                  </div>
                  {a.lots && (
                    <div style={{ marginTop: 6, display: 'flex', gap: 6, alignItems: 'center' }}>
                      <span style={{ color: sc.text, fontSize: 10, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>AFFECTED LOTS:</span>
                      <span style={{ color: sc.text, fontSize: 11, fontFamily: 'DM Mono, monospace', fontWeight: 600 }}>{a.lots}</span>
                    </div>
                  )}
                </div>
              )
            })
          })()}

          <p style={{ color: C.dim, fontSize: 10, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', marginTop: 8, lineHeight: 1.5 }}>
            Source: FDA Recalls, Market Withdrawals & Safety Alerts feed
          </p>
        </div>
</div>
  )
}


// ── SCHEDULE APPOINTMENT ───────────────────────────────────────

function DoctorAvatar({ size = 60, grad, seed = 0 }) {
  // Variations of stylized portrait silhouettes (4 variants)
  const variant = seed % 4
  const hairStyles = [
    // 0: short close-cut
    <path d="M50 28 Q35 28 32 38 Q31 44 35 48 L65 48 Q69 44 68 38 Q65 28 50 28 Z" fill="#1A0F08"/>,
    // 1: locs / longer hair
    <g><path d="M50 26 Q33 26 30 40 Q29 50 32 56 L36 50 Q38 56 40 50 Q42 56 44 50 L46 56 Q48 50 50 56 Q52 50 54 56 L56 50 Q58 56 60 50 Q62 56 64 50 L68 56 Q71 50 70 40 Q67 26 50 26 Z" fill="#1A0F08"/></g>,
    // 2: head wrap / scarf
    <g><path d="M50 26 Q34 26 30 38 Q28 44 30 50 L70 50 Q72 44 70 38 Q66 26 50 26 Z" fill="#C8102E"/><path d="M30 38 Q40 35 50 36 Q60 35 70 38" stroke="#8C1225" strokeWidth="1.5" fill="none"/></g>,
    // 3: afro
    <g><circle cx="50" cy="38" r="22" fill="#1A0F08"/><circle cx="38" cy="34" r="6" fill="#1A0F08"/><circle cx="62" cy="34" r="6" fill="#1A0F08"/><circle cx="32" cy="44" r="5" fill="#1A0F08"/><circle cx="68" cy="44" r="5" fill="#1A0F08"/></g>,
  ]
  const skinTones = ['#5C3A1F', '#6E4B2C', '#8B5E3C', '#7A4A28']
  const skin = skinTones[seed % skinTones.length]
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ flexShrink: 0, borderRadius: size/2, overflow: 'hidden', display: 'block' }}>
      <defs>
        <linearGradient id={`bg${seed}`} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor={grad[0]} stopOpacity="0.25"/>
          <stop offset="100%" stopColor={grad[1]} stopOpacity="0.35"/>
        </linearGradient>
      </defs>
      <rect width="100" height="100" fill={`url(#bg${seed})`}/>
      {/* Body / shoulders - white coat */}
      <path d="M20 100 Q20 78 35 72 L65 72 Q80 78 80 100 Z" fill="#FFFFFF"/>
      <path d="M50 72 L46 100 M50 72 L54 100" stroke="#E5E5E5" strokeWidth="1"/>
      {/* Stethoscope hint */}
      <circle cx="42" cy="84" r="3" fill="none" stroke="#1A4A8C" strokeWidth="1.2"/>
      {/* Neck */}
      <rect x="44" y="58" width="12" height="18" fill={skin}/>
      {/* Face */}
      <ellipse cx="50" cy="45" rx="16" ry="19" fill={skin}/>
      {/* Hair */}
      {hairStyles[variant]}
      {/* Eyes */}
      <ellipse cx="44" cy="46" rx="1.3" ry="1.6" fill="#1A0F08"/>
      <ellipse cx="56" cy="46" rx="1.3" ry="1.6" fill="#1A0F08"/>
      {/* Smile */}
      <path d="M45 54 Q50 57 55 54" stroke="#3A2410" strokeWidth="1.3" fill="none" strokeLinecap="round"/>
    </svg>
  )
}

function ScheduleScreen({ nav }) {
  const [specialty, setSpecialty] = React.useState('Cardiology')
  const [selected, setSelected] = React.useState(null)
  const [booked, setBooked] = React.useState(false)

  const doctors = [
    { name: 'Dr. Amara Osei',    specialty: 'Cardiologist',     rating: 4.9, reviews: 312, location: 'Atlanta Medical Center',  insurance: 'in-network',     distance: '2.1 mi', init: 'AO', grad: [C.gold, C.red],     next: 'Tomorrow, 10:30 AM',    seed: 2 },
    { name: 'Dr. Marcus Webb',   specialty: 'Cardiologist',     rating: 4.7, reviews: 187, location: 'Grady Memorial Hospital',  insurance: 'in-network',     distance: '3.4 mi', init: 'MW', grad: [C.red,  '#8C1225'],   next: 'Mon Apr 22, 2:00 PM',  seed: 0 },
    { name: 'Dr. Keisha Thomas', specialty: 'Cardiologist',     rating: 4.8, reviews: 256, location: 'Emory Heart Center',       insurance: 'out-of-network', distance: '4.8 mi', init: 'KT', grad: [C.green, '#1A5228'],  next: 'Wed Apr 24, 9:00 AM',  seed: 1 },
    { name: 'Dr. Jelani Ford',   specialty: 'Cardiologist',     rating: 4.6, reviews: 142, location: 'Piedmont Atlanta Hospital', insurance: 'in-network',     distance: '5.6 mi', init: 'JF', grad: [C.blue, '#0E2D55'],   next: 'Fri Apr 26, 11:00 AM', seed: 3 },
  ]

  if (booked) return (
    <div style={{ height: '100%', background: C.bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18, padding: 32 }}>
      <div style={{ width: 80, height: 80, borderRadius: 40, background: '#E4F2E8', border: `2px solid ${C.green}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 36 }}>✓</div>
      <h2 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 26, color: C.text, textAlign: 'center' }}>Appointment Confirmed</h2>
      <p style={{ color: C.muted, fontSize: 15, textAlign: 'center', lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif' }}>{selected?.name}<br />Tomorrow · 10:30 AM<br />Atlanta Medical Center</p>
      <button onClick={() => { setBooked(false); setSelected(null) }} style={{ marginTop: 16, background: `linear-gradient(135deg, ${C.goldLt}, ${C.gold})`, border: 'none', borderRadius: 14, padding: '14px 32px', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 15, cursor: 'pointer' }}>Done</button>
    </div>
  )

  if (selected) return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title={selected.name} sub={`${selected.specialty} · ${selected.location}`} onBack={() => setSelected(null)} backLabel="List" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ background: C.card, borderRadius: 16, padding: 18, border: `1px solid ${C.border}`, display: 'flex', gap: 16, alignItems: 'center' }}>
          <DoctorAvatar size={64} grad={selected.grad} seed={selected.seed}/>
          <div>
            <p style={{ color: C.text, fontWeight: 700, fontSize: 18, fontFamily: 'DM Sans, sans-serif' }}>{selected.name}</p>
            <p style={{ color: C.muted, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>{selected.specialty}</p>
            <p style={{ color: C.gold, fontSize: 13, marginTop: 3, fontFamily: 'DM Sans, sans-serif' }}>⭐ {selected.rating} · {selected.reviews} reviews · {selected.distance}</p>
          </div>
        </div>

        <div style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 12 }}>Insurance Coverage</p>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: 14, background: selected.insurance === 'in-network' ? '#E6EEF8' : '#FEF6E6', borderRadius: 12, border: `1.5px solid ${selected.insurance === 'in-network' ? C.blue : C.gold}50` }}>
            <span style={{ fontSize: 20, marginTop: 1 }}>{selected.insurance === 'in-network' ? '✅' : '⚠️'}</span>
            <div>
              <p style={{ color: selected.insurance === 'in-network' ? C.blue : C.gold, fontWeight: 700, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>{selected.insurance === 'in-network' ? 'In-Network' : 'Out-of-Network'}</p>
              <p style={{ color: C.muted, fontSize: 13, marginTop: 3, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>
                {selected.insurance === 'in-network' ? 'BlueCross BlueShield · $35 copay · Covered 100% after deductible met' : 'Est. cost: $285–$340 · Submit for partial reimbursement at out-of-network rate'}
              </p>
            </div>
          </div>
        </div>

        <div style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 12 }}>Select a Time</p>
          {[selected.next, 'Fri Apr 25, 1:00 PM', 'Mon Apr 28, 3:30 PM'].map((slot, i) => (
            <button key={i} style={{ width: '100%', background: i === 0 ? `${C.gold}15` : C.bg, border: `1.5px solid ${i === 0 ? C.gold : C.border}`, borderRadius: 10, padding: '12px 14px', marginBottom: 8, cursor: 'pointer', textAlign: 'left', color: i === 0 ? C.gold : C.text, fontFamily: 'DM Sans, sans-serif', fontWeight: i === 0 ? 700 : 500, fontSize: 14 }}>
              {i === 0 ? '⭐ ' : ''}{slot}
            </button>
          ))}
        </div>

        <GoldBtn label="Confirm Appointment" onClick={() => setBooked(true)} />
      </div>
    </div>
  )

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Find a Black Doctor" sub="Culturally-competent care in your area" onBack={() => nav('more')} backLabel="More" />
      <div style={{ padding: '0 16px' }}>
        <div style={{ display: 'flex', gap: 8, marginBottom: 16, overflowX: 'auto', paddingBottom: 4 }}>
          {['Cardiology', 'Primary Care', 'OB-GYN', 'Psychiatry', 'Dermatology', 'Oncology', 'Endocrinology', 'Pediatrics', 'Neurology', 'Orthopedics', 'Gastroenterology', 'Urology'].map(s => (
            <button key={s} onClick={() => setSpecialty(s)} style={{ padding: '8px 14px', borderRadius: 20, border: `1.5px solid ${specialty === s ? C.gold : C.border}`, background: specialty === s ? `${C.gold}12` : C.card, color: specialty === s ? C.gold : C.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 13, cursor: 'pointer', fontWeight: specialty === s ? 700 : 500, whiteSpace: 'nowrap', flexShrink: 0 }}>{s}</button>
          ))}
        </div>
        {doctors.map((doc, i) => (
          <button key={i} onClick={() => setSelected(doc)} style={{ width: '100%', background: C.card, border: `1px solid ${C.border}`, borderRadius: 16, padding: 16, marginBottom: 12, cursor: 'pointer', textAlign: 'left' }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <DoctorAvatar size={56} grad={doc.grad} seed={doc.seed}/>
              <div style={{ flex: 1 }}>
                <p style={{ color: C.text, fontWeight: 700, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>{doc.name}</p>
                <p style={{ color: C.muted, fontSize: 12, marginTop: 2, fontFamily: 'DM Sans, sans-serif' }}>{doc.location}</p>
                <p style={{ color: C.gold, fontSize: 12, marginTop: 3, fontFamily: 'DM Sans, sans-serif' }}>⭐ {doc.rating} · {doc.distance}</p>
              </div>
              <span style={{ background: doc.insurance === 'in-network' ? '#E6EEF8' : '#FEF6E6', color: doc.insurance === 'in-network' ? C.blue : '#7A5108', borderRadius: 8, padding: '5px 8px', fontSize: 11, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', lineHeight: 1.3, border: `1px solid ${doc.insurance === 'in-network' ? C.blue : '#7A5108'}30` }}>
                {doc.insurance === 'in-network' ? 'In\nNetwork' : 'Out of\nNetwork'}
              </span>
            </div>
            <div style={{ marginTop: 10, padding: '8px 12px', background: '#F6F2EC', borderRadius: 10, border: `1px solid ${C.border}` }}>
              <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>Next available: <span style={{ color: C.text, fontWeight: 600 }}>{doc.next}</span></p>
            </div>
          </button>
        ))}
      </div>
    </div>
  )
}

// ── RESEARCH ───────────────────────────────────────────────────

function ResearchScreen({ nav }) {
  const [search, setSearch] = React.useState('')
  const papers = [
    { title: 'Racial Disparities in Hypertension Outcomes: A 10-Year Longitudinal Study', journal: 'JAMA Internal Medicine', date: 'Mar 2026', tags: ['Hypertension', 'Cardiovascular'], reads: '4.2K' },
    { title: 'APOL1 Gene Variants and Chronic Kidney Disease in African Americans', journal: 'New England Journal of Medicine', date: 'Jan 2026', tags: ['Kidney', 'Genetics'], reads: '8.7K' },
    { title: 'Triple-Negative Breast Cancer: Immunotherapy Outcomes in Black Women', journal: 'Lancet Oncology', date: 'Feb 2026', tags: ['Cancer', "Women's Health"], reads: '6.1K' },
    { title: 'Sickle Cell Disease: Community-Centered Treatment Models and Outcomes', journal: 'Blood Journal', date: 'Apr 2026', tags: ['Sickle Cell', 'Treatment'], reads: '3.4K' },
    { title: 'Implicit Bias in Pain Management: Disparities in Emergency Care Settings', journal: 'Annals of Emergency Medicine', date: 'Mar 2026', tags: ['Pain', 'Bias', 'ER'], reads: '11.2K' },
  ]
  const filtered = papers.filter(p => !search || p.title.toLowerCase().includes(search.toLowerCase()) || p.tags.some(t => t.toLowerCase().includes(search.toLowerCase())))

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Research" sub="World literature on Black health" onBack={() => nav('more')} backLabel="More" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search topics, conditions, journals..." style={{ width: '100%', background: C.card, border: `1.5px solid ${C.border}`, borderRadius: 12, padding: '12px 16px', color: C.text, fontFamily: 'DM Sans, sans-serif', fontSize: 14, outline: 'none', boxSizing: 'border-box', boxShadow: '0 1px 4px rgba(0,0,0,0.05)' }} />
        {filtered.map((p, i) => (
          <div key={i} style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}`, cursor: 'pointer' }}>
            <div style={{ display: 'flex', gap: 6, marginBottom: 10, flexWrap: 'wrap' }}>
              {p.tags.map(t => <Tag key={t} label={t} />)}
            </div>
            <p style={{ color: C.text, fontWeight: 700, fontSize: 14, lineHeight: 1.5, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>{p.title}</p>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>{p.journal} · {p.date}</p>
              <p style={{ color: C.dim, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>👁 {p.reads}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

// ── HEALTH FORUM ───────────────────────────────────────────────

function ForumScreen({ nav, userConditions }) {
  const [aiRecs, setAiRecs] = React.useState([])
  const [recsLoading, setRecsLoading] = React.useState(true)
  const [search, setSearch] = React.useState('')

  React.useEffect(() => {
    const conditions = userConditions || ['Hypertension', 'Type 2 Diabetes']
    window.bhaAI.complete(`A Black patient has these conditions: ${conditions.join(', ')}. From these health forum topic areas: Hypertension, Sickle Cell, Mental Health, Genetics, Cardiology, Diabetes, Cancer, Kidney Disease — list the 2 most relevant ones for this patient with a one-sentence reason each. Write the reason in VERY simple, plain language that an 8th grader could easily understand — short sentence, everyday words, no medical jargon. Return JSON: [{"topic": "...", "reason": "..."}]`)
      .then(res => { const m = res.match(/\[[\s\S]*\]/); if (m) setAiRecs(JSON.parse(m[0])) })
      .catch(() => setAiRecs([{topic: 'Hypertension', reason: 'Directly relevant to your current condition and medications.'},{topic: 'Cardiology', reason: 'Important given your cardiovascular risk profile.'}]))
      .finally(() => setRecsLoading(false))
  }, [])
  const posts = [
    { user: 'TyroneMD', title: 'Managing Hypertension Naturally — My 6-Month Journey', body: 'After my diagnosis at 44, I was put on 3 medications. Over 6 months working closely with my doctor, I have reduced to 1. Here is what actually worked for me...', tags: ['Hypertension', 'Success Story'], likes: 142, replies: 38, time: '2h ago', init: 'T', col: C.red },
    { user: 'NatalieBrooks', title: 'Questions About APOL1 Gene Testing — Has Anyone Done This?', body: 'My nephrologist mentioned genetic testing for kidney disease risk. Has anyone in the community gone through this? I am curious about what to expect from the process...', tags: ['Genetics', 'Kidney'], likes: 67, replies: 24, time: '5h ago', init: 'N', col: C.gold },
    { user: 'DrAmandaK', title: 'As a Black Cardiologist: What I Want My Patients to Know', body: 'After 15 years in practice, I want to share truths about heart disease in our community that do not get enough attention in mainstream cardiology...', tags: ['Expert', 'Cardiology'], likes: 328, replies: 91, time: '1d ago', init: 'A', col: C.green, verified: true },
    { user: 'MarcusW', title: 'Sickle Cell & Mental Health: Breaking the Silence', body: 'Living with sickle cell has taken a toll not just on my body but my mind. I want to start a conversation about the psychological burden we carry that doctors rarely address...', tags: ['Sickle Cell', 'Mental Health'], likes: 201, replies: 54, time: '2d ago', init: 'M', col: C.red },
  ]

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Community Health Forum" sub="Community stories, questions & shared wisdom" onBack={() => nav('more')} backLabel="More" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ background: 'linear-gradient(135deg, #E4F2E8, #D0EAD6)', border: `1px solid ${C.green}50`, borderRadius: 16, padding: 16, boxShadow: '0 2px 10px rgba(26,82,40,0.08)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M12 2.5l2.3 6.2 6.2 2.3-6.2 2.3L12 19.5l-2.3-6.2L3.5 11l6.2-2.3z" fill={C.green}/><circle cx="19.5" cy="5" r="1.4" fill={C.green}/></svg>
            <p style={{ color: C.green, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1.5 }}>Recommended For You</p>
          </div>
          {recsLoading
            ? <p style={{ color: '#1A3320', fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>Finding relevant discussions...</p>
            : aiRecs.map((r, i) => (
              <div key={i} style={{ marginBottom: i < aiRecs.length-1 ? 10 : 0, paddingBottom: i < aiRecs.length-1 ? 10 : 0, borderBottom: i < aiRecs.length-1 ? `1px solid ${C.green}30` : 'none' }}>
                <p style={{ color: '#1A3320', fontWeight: 700, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>{r.topic}</p>
                <p style={{ color: '#2A5035', fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginTop: 3, lineHeight: 1.5 }}>{r.reason}</p>
              </div>
            ))
          }
        </div>
        <div style={{ position: 'relative', marginBottom: 2 }}>
          <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', fontSize: 16, color: C.dim, pointerEvents: 'none' }}>🔍</span>
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search stories, conditions, topics…"
            style={{
              width: '100%', background: C.card, border: `1.5px solid ${C.border}`, borderRadius: 14,
              padding: '13px 14px 13px 40px', color: C.text, fontSize: 14, fontFamily: 'DM Sans, sans-serif',
              outline: 'none', boxSizing: 'border-box',
            }}
            onFocus={(e) => e.target.style.borderColor = C.gold}
            onBlur={(e) => e.target.style.borderColor = C.border}
          />
        </div>
        <button style={{ background: `linear-gradient(135deg, ${C.red}, #6A0A18)`, border: 'none', borderRadius: 14, padding: '15px 24px', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 15, cursor: 'pointer', boxShadow: '0 4px 14px rgba(140,18,37,0.25)' }}>
          + Share Your Story
        </button>
        {posts.filter(p => !search || p.title.toLowerCase().includes(search.toLowerCase()) || p.body.toLowerCase().includes(search.toLowerCase()) || p.user.toLowerCase().includes(search.toLowerCase())).map((p, i) => (
          <div key={i} style={{ background: C.card, borderRadius: 16, padding: 16, border: `1px solid ${C.border}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <div style={{ width: 38, height: 38, borderRadius: 19, background: `linear-gradient(135deg, ${p.col}, ${p.col}80)`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 800, fontSize: 15 }}>{p.init}</div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <p style={{ color: C.text, fontWeight: 700, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>{p.user}</p>
                  {p.verified && <span style={{ background: C.green, borderRadius: 4, padding: '2px 5px', fontSize: 10, color: '#fff', fontWeight: 700 }}>MD</span>}
                </div>
                <p style={{ color: C.dim, fontSize: 12, marginTop: 1, fontFamily: 'DM Sans, sans-serif' }}>{p.time}</p>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6, marginBottom: 8, flexWrap: 'wrap' }}>
              {p.tags.map(t => <span key={t} style={{ background: C.bg, color: C.muted, borderRadius: 6, padding: '3px 8px', fontSize: 11, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', border: `1px solid ${C.border}` }}>{t}</span>)}
            </div>
            <p style={{ color: C.text, fontWeight: 700, fontSize: 15, marginBottom: 6, lineHeight: 1.4, fontFamily: 'DM Sans, sans-serif' }}>{p.title}</p>
            <p style={{ color: C.muted, fontSize: 13, lineHeight: 1.65, fontFamily: 'DM Sans, sans-serif' }}>{p.body.length > 130 ? p.body.slice(0, 130) + '...' : p.body}</p>
            <div style={{ display: 'flex', gap: 16, marginTop: 12, paddingTop: 12, borderTop: `1px solid ${C.border}` }}>
              <button style={{ background: 'none', border: 'none', color: C.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 13, cursor: 'pointer' }}>❤️ {p.likes}</button>
              <button style={{ background: 'none', border: 'none', color: C.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 13, cursor: 'pointer' }}>💬 {p.replies} replies</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

// ── ABOUT ──────────────────────────────────────────────────────

function AboutScreen({ nav }) {
  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <div style={{ background: 'linear-gradient(160deg, #FDF6EC 0%, #F6F0E4 100%)', padding: '70px 20px 32px', textAlign: 'center', borderBottom: `1px solid ${C.border}` }}>
        <img src="logo-mark.png" style={{ width: 110, height: 110, marginBottom: 16 }} alt="Black Healthcare Advocate logo: Sankofa bird with caduceus, symbolizing reclaiming health knowledge" role="img"/>
        <h1 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 28, color: C.text, lineHeight: 1.2 }}>Black Healthcare<br/>Advocate</h1>
        <p style={{ color: C.gold, fontSize: 13, marginTop: 10, letterSpacing: 0.5, fontFamily: 'DM Sans, sans-serif' }}>Reclaim Your Health. Rebuild Your Trust.</p>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginTop: 20 }}>
          {[C.red, C.gold, C.green, C.text].map((col, i) => <div key={i} style={{ width: 20, height: 4, borderRadius: 2, background: col }} />)}
        </div>
      </div>

      <div style={{ padding: '20px 16px 0', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ background: C.card, borderRadius: 16, padding: 20, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.gold, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1.5, marginBottom: 12 }}>Our Mission</p>
          <p style={{ color: C.text, fontSize: 14, lineHeight: 1.8, fontFamily: 'DM Sans, sans-serif' }}>Black Healthcare Advocate was born from a personal truth: that Black Americans have historically been underserved, misdiagnosed, and undertreated by a system not built with us in mind.</p>
          <p style={{ color: C.text, fontSize: 14, lineHeight: 1.8, marginTop: 12, fontFamily: 'DM Sans, sans-serif' }}>We believe knowledge is the first step to power. By combining AI-driven tools with culturally-competent care, we give our community the resources to walk into any medical setting informed, prepared, and fully advocating for themselves.</p>
        </div>

        <div style={{ background: C.card, borderRadius: 16, padding: 20, border: `1px solid ${C.border}` }}>
          <p style={{ color: C.gold, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1.5, marginBottom: 16 }}>Founder's Story</p>
          <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 14 }}>
            <div style={{ width: 54, height: 54, borderRadius: 27, background: `linear-gradient(135deg, ${C.gold}, ${C.red})`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 800, fontSize: 22, flexShrink: 0 }}>F</div>
            <div>
              <p style={{ color: C.text, fontWeight: 700, fontSize: 16, fontFamily: 'DM Sans, sans-serif' }}>The Founder</p>
              <p style={{ color: C.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>Patient Advocate & Health Equity Champion</p>
            </div>
          </div>
          <p style={{ color: C.text, fontSize: 14, lineHeight: 1.8, fontFamily: 'DM Sans, sans-serif' }}>After watching a family member receive a delayed diagnosis due to systemic bias in healthcare, the vision for BHA became undeniable: build a platform where the Black community can understand their health on their own terms, with an AI advocate by their side at every step.</p>
        </div>

        <div style={{ background: 'linear-gradient(135deg, #FEF6E4, #FDE8EC)', border: `1px solid ${C.gold}40`, borderRadius: 16, padding: 20 }}>
          <p style={{ color: C.gold, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1.5, marginBottom: 10 }}>The Sankofa Symbol</p>
          <p style={{ color: C.text, fontSize: 14, lineHeight: 1.8, fontFamily: 'DM Sans, sans-serif', fontStyle: 'italic' }}>"Se wo were fi na wosankofa a yenkyi" — It is not wrong to go back for what you forgot.</p>
          <p style={{ color: C.muted, fontSize: 13, lineHeight: 1.7, marginTop: 10, fontFamily: 'DM Sans, sans-serif' }}>Our logo's Sankofa bird looks backward to move forward — just as we reclaim our healthcare history and cultural wisdom to forge a healthier, more equitable future.</p>
        </div>
      </div>
    </div>
  )
}

// ── CONNECT HEALTH RECORDS (EHR API) ───────────────────────────

function ConnectRecordsScreen({ nav }) {
  const [providers, setProviders] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('bha_ehr') || '{}') } catch { return {} }
  })
  const [connecting, setConnecting] = React.useState(null) // provider id mid-flow
  const [authStep, setAuthStep] = React.useState(null) // null | 'redirect' | 'auth' | 'consent' | 'syncing'
  const [showInfo, setShowInfo] = React.useState(false)

  const persist = (next) => {
    setProviders(next)
    localStorage.setItem('bha_ehr', JSON.stringify(next))
  }

  // EHR integrations — these mirror the real FHIR/SMART-on-FHIR partners apps connect through
  const integrations = [
    { id: 'epic',      name: 'Epic / MyChart',      sub: 'Used by ~250M U.S. patients · 70%+ of major hospitals',         color: '#A21D2A', logo: 'E', records: ['Visit summaries', 'Lab results', 'Prescriptions', 'Imaging reports', 'Immunizations'] },
    { id: 'cerner',    name: 'Oracle Cerner',       sub: 'PowerChart / HealtheLife · 27%+ of U.S. hospitals',             color: '#0072CE', logo: 'C', records: ['Visit summaries', 'Lab results', 'Prescriptions', 'Vitals'] },
    { id: 'athena',    name: 'Athenahealth',        sub: 'athenaPatient · 160K+ providers',                                color: '#7B2CBF', logo: 'A', records: ['Appointments', 'Lab results', 'Prescriptions'] },
    { id: 'allscripts',name: 'Veradigm (Allscripts)', sub: 'FollowMyHealth · 180K+ physicians',                            color: '#1B7A3E', logo: 'V', records: ['Visit summaries', 'Lab results', 'Prescriptions'] },
    { id: 'meditech',  name: 'MEDITECH Expanse',    sub: 'Community hospitals · ~17% U.S. hospital market',                color: '#005EB8', logo: 'M', records: ['Visit summaries', 'Lab results', 'Imaging reports'] },
    { id: 'va',        name: 'VA Health (Veterans Affairs)', sub: 'My HealtheVet · For veterans',                           color: '#112E51', logo: 'V', records: ['Visit summaries', 'Lab results', 'Prescriptions', 'Service-connected conditions'] },
    { id: 'kaiser',    name: 'Kaiser Permanente',   sub: 'KP.org · Integrated provider + insurer',                          color: '#006BA6', logo: 'K', records: ['Visit summaries', 'Lab results', 'Prescriptions', 'Imaging reports'] },
    { id: 'apple',     name: 'Apple Health',        sub: 'Wearable & device data · iPhone & Apple Watch',                  color: '#1A1A1A', logo: '', records: ['Heart rate', 'Blood pressure', 'Steps', 'Sleep', 'ECG'] },
  ]

  const beginConnect = (provider) => {
    setConnecting(provider.id)
    setAuthStep('redirect')
    setTimeout(() => setAuthStep('auth'),    700)
    setTimeout(() => setAuthStep('consent'), 1800)
  }

  const completeConnect = (provider) => {
    setAuthStep('syncing')
    setTimeout(() => {
      persist({ ...providers, [provider.id]: { connectedAt: new Date().toISOString(), recordCount: 8 + Math.floor(Math.random() * 40) } })
      setConnecting(null)
      setAuthStep(null)
    }, 1600)
  }

  const disconnect = (id) => {
    const { [id]: _, ...rest } = providers
    persist(rest)
  }

  const connectedCount = Object.keys(providers).length
  const totalRecords = Object.values(providers).reduce((s, p) => s + (p.recordCount || 0), 0)

  // ── In-flow auth modal ───────────────────────────────────────
  if (connecting) {
    const provider = integrations.find(p => p.id === connecting)
    return (
      <div style={{ height: '100%', background: C.bg, display: 'flex', flexDirection: 'column' }}>
        <SectionHeader title="Connecting…" sub={provider.name} onBack={() => { setConnecting(null); setAuthStep(null) }} backLabel="Cancel" />
        <div style={{ flex: 1, padding: '8px 16px', overflowY: 'auto' }}>
          {/* OAuth-style window */}
          <div style={{ background: '#fff', borderRadius: 18, border: `1px solid ${C.border}`, overflow: 'hidden', boxShadow: '0 6px 24px rgba(0,0,0,0.08)' }}>
            <div style={{ background: provider.color, padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: '#fff', color: provider.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 16, fontFamily: 'DM Sans, sans-serif' }}>{provider.logo || '◆'}</div>
              <div style={{ flex: 1 }}>
                <p style={{ color: '#fff', fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{provider.name}</p>
                <p style={{ color: 'rgba(255,255,255,0.85)', fontSize: 11, fontFamily: 'DM Sans, sans-serif', display: 'flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ fontSize: 9 }}>🔒</span> Secure FHIR / SMART-on-FHIR
                </p>
              </div>
            </div>

            {authStep === 'redirect' && (
              <div style={{ padding: '28px 20px', textAlign: 'center' }}>
                <div style={{ width: 44, height: 44, borderRadius: 22, border: `3px solid ${provider.color}30`, borderTopColor: provider.color, animation: 'bhaPulse 1s linear infinite', margin: '0 auto 14px' }}></div>
                <p style={{ color: C.text, fontSize: 14, fontWeight: 600, fontFamily: 'DM Sans, sans-serif' }}>Redirecting to {provider.name}…</p>
              </div>
            )}

            {authStep === 'auth' && (
              <div style={{ padding: '22px 20px' }}>
                <p style={{ color: C.text, fontSize: 17, fontFamily: 'DM Serif Display, serif', marginBottom: 4 }}>Sign in</p>
                <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginBottom: 14 }}>Use your {provider.name.split(' ')[0]} credentials.</p>
                <input placeholder="Username or email" defaultValue="marcus.johnson@email.com" style={{ width: '100%', background: '#F6F2EC', border: `1.5px solid ${C.border}`, borderRadius: 10, padding: '11px 14px', fontFamily: 'DM Sans, sans-serif', fontSize: 13.5, color: C.text, marginBottom: 10, boxSizing: 'border-box' }} />
                <input type="password" placeholder="Password" defaultValue="••••••••••" style={{ width: '100%', background: '#F6F2EC', border: `1.5px solid ${C.border}`, borderRadius: 10, padding: '11px 14px', fontFamily: 'DM Sans, sans-serif', fontSize: 13.5, color: C.text, marginBottom: 14, boxSizing: 'border-box' }} />
                <button onClick={() => setAuthStep('consent')} style={{ width: '100%', background: provider.color, border: 'none', borderRadius: 10, padding: '12px 0', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 14, cursor: 'pointer' }}>Sign in</button>
              </div>
            )}

            {authStep === 'consent' && (
              <div style={{ padding: '20px' }}>
                <p style={{ color: C.text, fontSize: 16, fontFamily: 'DM Serif Display, serif', marginBottom: 6 }}>Authorize access</p>
                <p style={{ color: C.muted, fontSize: 12.5, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.5, marginBottom: 14 }}>
                  <strong>Black Healthcare Advocate</strong> is requesting read-only access to the following from your {provider.name} record:
                </p>
                <div style={{ background: '#F6F2EC', borderRadius: 10, padding: 12, marginBottom: 14 }}>
                  {provider.records.map((r, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: i === provider.records.length - 1 ? 0 : 8 }}>
                      <span style={{ width: 16, height: 16, borderRadius: 8, background: C.success, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 800 }}>✓</span>
                      <span style={{ color: C.text, fontSize: 12.5, fontFamily: 'DM Sans, sans-serif' }}>{r}</span>
                    </div>
                  ))}
                </div>
                <p style={{ color: C.muted, fontSize: 10.5, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.5, marginBottom: 14 }}>
                  You can revoke access anytime in Black Healthcare Advocate settings or at {provider.name}.com. Black Healthcare Advocate cannot write to or change your medical record.
                </p>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button onClick={() => { setConnecting(null); setAuthStep(null) }} style={{ flex: 1, background: '#F6F2EC', border: `1.5px solid ${C.border}`, borderRadius: 10, padding: '12px 0', color: C.muted, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>Deny</button>
                  <button onClick={() => completeConnect(provider)} style={{ flex: 2, background: provider.color, border: 'none', borderRadius: 10, padding: '12px 0', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>Allow access</button>
                </div>
              </div>
            )}

            {authStep === 'syncing' && (
              <div style={{ padding: '28px 20px', textAlign: 'center' }}>
                <div style={{ width: 60, height: 60, borderRadius: 30, background: `${C.success}18`, border: `2px solid ${C.success}`, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, marginBottom: 12 }}>↓</div>
                <p style={{ color: C.text, fontSize: 15, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>Syncing your records</p>
                <p style={{ color: C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>Pulling visit history, labs, and prescriptions…</p>
              </div>
            )}
          </div>
        </div>
      </div>
    )
  }

  // ── Main list view ───────────────────────────────────────────
  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Connect Records" sub="Pull your real medical history into Black Healthcare Advocate" onBack={() => nav('more')} backLabel="More" />

      <div style={{ padding: '0 16px' }}>
        {/* Summary card */}
        <div style={{
          background: connectedCount > 0 ? `linear-gradient(135deg, #E4F2E8, #D0EAD6)` : `linear-gradient(135deg, #EEF4FF, #DDE8FF)`,
          border: `1px solid ${connectedCount > 0 ? C.success : C.blue}40`,
          borderRadius: 16, padding: 16, marginBottom: 16, boxShadow: '0 2px 10px rgba(0,0,0,0.04)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 54, height: 54, borderRadius: 16, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 26, boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>🏥</div>
            <div style={{ flex: 1 }}>
              <p style={{ color: C.text, fontSize: 17, fontWeight: 800, fontFamily: 'DM Serif Display, serif' }}>
                {connectedCount === 0 ? 'No records connected yet' : `${connectedCount} provider${connectedCount !== 1 ? 's' : ''} connected`}
              </p>
              <p style={{ color: C.muted, fontSize: 12.5, fontFamily: 'DM Sans, sans-serif', marginTop: 2, lineHeight: 1.5 }}>
                {connectedCount === 0 ? 'Sign in once to pull lifetime records — labs, prescriptions, imaging, vaccinations.' : `${totalRecords} records synced across your providers`}
              </p>
            </div>
          </div>
        </div>

        {/* Trust info */}
        <button onClick={() => setShowInfo(!showInfo)} style={{
          width: '100%', background: '#fff', border: `1px solid ${C.border}`, borderRadius: 12, padding: '12px 14px',
          cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16,
          fontFamily: 'DM Sans, sans-serif', textAlign: 'left',
        }}>
          <div style={{ width: 32, height: 32, borderRadius: 16, background: `${C.green}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, flexShrink: 0 }}>🔒</div>
          <div style={{ flex: 1 }}>
            <p style={{ color: C.text, fontSize: 13, fontWeight: 700 }}>How your data is protected</p>
            <p style={{ color: C.muted, fontSize: 11, marginTop: 2 }}>HIPAA-compliant · SMART-on-FHIR · You control access</p>
          </div>
          <span style={{ color: C.muted, fontSize: 18, transform: showInfo ? 'rotate(90deg)' : 'none', transition: 'transform 0.2s' }}>›</span>
        </button>

        {showInfo && (
          <div style={{ background: '#F0F8F3', border: `1px solid ${C.green}30`, borderRadius: 12, padding: 14, marginBottom: 16, fontFamily: 'DM Sans, sans-serif' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                ['Read-only access', 'Black Healthcare Advocate can pull your records but cannot change them at your provider.'],
                ['Industry standards', 'Uses HL7 FHIR R4 + SMART-on-FHIR OAuth 2.0 — the same standards every major hospital app uses.'],
                ['HIPAA-compliant', 'Records are encrypted in transit (TLS 1.3) and at rest (AES-256). End-to-end audit logs.'],
                ['You own access', 'Revoke any provider in one tap. Disconnecting deletes synced records from Black Healthcare Advocate within 24 hours.'],
                ['Never sold', 'We do not sell, share, or use your data for advertising. Ever.'],
              ].map(([t, d], i) => (
                <div key={i}>
                  <p style={{ color: C.successText, fontSize: 12.5, fontWeight: 700 }}>✓ {t}</p>
                  <p style={{ color: C.successText, fontSize: 11.5, lineHeight: 1.5, marginTop: 2, opacity: 0.85 }}>{d}</p>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Providers list */}
        <p style={{ color: C.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, fontFamily: 'DM Sans, sans-serif', marginBottom: 10 }}>Available Integrations</p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {integrations.map(p => {
            const conn = providers[p.id]
            return (
              <div key={p.id} style={{
                background: '#fff', border: conn ? `1.5px solid ${C.success}50` : `1px solid ${C.border}`,
                borderRadius: 14, overflow: 'hidden',
              }}>
                <div style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{
                    width: 48, height: 48, borderRadius: 12, background: p.color,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: '#fff', fontSize: 22, fontWeight: 800, fontFamily: 'DM Sans, sans-serif',
                    flexShrink: 0,
                  }}>{p.logo || '◆'}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <p style={{ color: C.text, fontSize: 14.5, fontWeight: 700, fontFamily: 'DM Sans, sans-serif' }}>{p.name}</p>
                      {conn && (
                        <span style={{ background: C.success, color: '#fff', fontSize: 9, fontWeight: 800, padding: '2px 6px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', letterSpacing: 0.4 }}>CONNECTED</span>
                      )}
                    </div>
                    <p style={{ color: C.muted, fontSize: 11.5, fontFamily: 'DM Sans, sans-serif', marginTop: 2, lineHeight: 1.4 }}>{p.sub}</p>
                  </div>
                  {conn ? (
                    <button onClick={() => disconnect(p.id)} style={{ background: '#FEF2F4', border: `1px solid ${C.red}30`, borderRadius: 8, padding: '7px 12px', color: C.red, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12, cursor: 'pointer', flexShrink: 0 }}>Disconnect</button>
                  ) : (
                    <button onClick={() => beginConnect(p)} style={{ background: p.color, border: 'none', borderRadius: 8, padding: '8px 14px', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12, cursor: 'pointer', flexShrink: 0 }}>Connect</button>
                  )}
                </div>
                {conn && (
                  <div style={{ background: C.successBg, borderTop: `1px solid ${C.success}30`, padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 12, fontFamily: 'DM Sans, sans-serif' }}>
                    <div style={{ flex: 1 }}>
                      <p style={{ color: C.successText, fontSize: 11.5, fontWeight: 600 }}>{conn.recordCount} records synced · Last updated just now</p>
                    </div>
                    <button style={{ background: '#fff', border: `1px solid ${C.success}40`, borderRadius: 6, padding: '5px 10px', color: C.successText, fontSize: 11, fontWeight: 700, cursor: 'pointer' }}>Sync now</button>
                  </div>
                )}
              </div>
            )
          })}
        </div>

        {/* Footer credits */}
        <p style={{ color: C.dim, fontSize: 10, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', marginTop: 18, lineHeight: 1.6 }}>
          Powered by HL7 FHIR R4 · SMART-on-FHIR OAuth 2.0<br/>
          Certified Health IT — ONC 2015 Edition Cures Update
        </p>
      </div>
    </div>
  )
}

// ── MORE ───────────────────────────────────────────────────────

function MoreScreen({ nav }) {
  const items = [
    { label: 'My Profile', sub: 'Health summary, insurance, settings', icon: '👤', screen: 'profile', col: C.gold },
    { label: 'Connect Health Records', sub: 'Epic · Cerner · MyChart · Athena · Veterans Affairs', icon: '🏥', screen: 'connect', col: C.blue },
    { label: 'Notifications', sub: 'Reminders & alerts', icon: '🔔', screen: 'notifications', col: C.blue },
    { label: 'Schedule Appointment', sub: 'Find Black doctors near you', icon: '🗓', screen: 'schedule', col: C.green },
    { label: 'Plans & Pricing', sub: 'Free · Plus · Family · ', icon: '⭐', screen: 'pricing', col: C.gold },
    { label: 'About Us', sub: 'Our story & mission', icon: '✊🏾', screen: 'about', col: C.red },
  ]
  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C.bg, paddingBottom: 90 }}>
      <SectionHeader title="More" sub="Settings, integrations & more tools" onBack={() => nav('home')} backLabel="Home" />
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {items.map((item, i) => (
          <button key={i} onClick={() => nav(item.screen)} style={{ background: C.card, border: `1px solid ${C.border}`, borderRadius: 16, padding: 18, cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 50, height: 50, borderRadius: 14, background: `${item.col}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24 }}>{item.icon}</div>
            <div style={{ flex: 1 }}>
              <p style={{ color: C.text, fontWeight: 700, fontSize: 16, fontFamily: 'DM Sans, sans-serif' }}>{item.label}</p>
              <p style={{ color: C.muted, fontSize: 13, marginTop: 3, fontFamily: 'DM Sans, sans-serif' }}>{item.sub}</p>
            </div>
            <span style={{ color: C.muted, fontSize: 22 }}>›</span>
          </button>
        ))}
      </div>
    </div>
  )
}

Object.assign(window, {
  BHA_COLORS, SplashScreen, HomeScreen, PrepScreen, ResultsScreen,
  MedsScreen, ScheduleScreen, ResearchScreen, ForumScreen, AboutScreen, MoreScreen,
  ConnectRecordsScreen,
})
