// bha-screens2.jsx — Login, Onboarding, Pricing, Profile, Notifications

const C2 = window.BHA_COLORS;

// ── LOGIN ──────────────────────────────────────────────────────

function LoginScreen({ onLogin }) {
  const [email, setEmail] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [showPass, setShowPass] = React.useState(false);
  const [mode, setMode] = React.useState('signin'); // signin | signup
  const [error, setError] = React.useState('');

  const inputStyle = {
    width: '100%', background: '#F6F2EC', border: `1.5px solid ${C2.border}`,
    borderRadius: 12, padding: '14px 16px', color: C2.text,
    fontFamily: 'DM Sans, sans-serif', fontSize: 15, outline: 'none',
    boxSizing: 'border-box', transition: 'border-color 0.2s'
  };

  const submit = () => {
    if (!email.trim() || !pass.trim()) {setError('Please fill in all fields.');return;}
    if (pass.length < 6) {setError('Password must be at least 6 characters.');return;}
    onLogin({ email, isNew: mode === 'signup' });
  };

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: 'linear-gradient(160deg, #FDF8F0 0%, #F0EAE0 100%)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '70px 28px 32px', textAlign: 'center' }}>
        <img src="logo-mark.png" style={{ width: 86, height: 86, marginBottom: 14 }} alt="Black Healthcare Advocate logo" role="img" />
        <h1 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 26, color: C2.text, marginBottom: 4 }}>
          {mode === 'signin' ? 'Welcome Back' : 'Create Account'}
        </h1>
        <p style={{ color: C2.muted, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>
          {mode === 'signin' ? 'Sign in to your BHA account' : 'Join the Black Healthcare Advocate community'}
        </p>
      </div>

      <div style={{ flex: 1, padding: '0 24px 40px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {mode === 'signup' &&
        <input placeholder="Full Name" style={inputStyle} />
        }
        <input
          type="email" placeholder="Email address" value={email}
          onChange={(e) => {setEmail(e.target.value);setError('');}}
          style={inputStyle} />
        
        <div style={{ position: 'relative' }}>
          <input
            type={showPass ? 'text' : 'password'} placeholder="Password" value={pass}
            onChange={(e) => {setPass(e.target.value);setError('');}}
            style={{ ...inputStyle, paddingRight: 48 }} />
          
          <button onClick={() => setShowPass(!showPass)} style={{ position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: C2.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>
            {showPass ? 'Hide' : 'Show'}
          </button>
        </div>

        {error && <p style={{ color: C2.red, fontSize: 13, fontFamily: 'DM Sans, sans-serif', fontWeight: 500 }}>⚠ {error}</p>}

        {mode === 'signin' &&
        <button style={{ background: 'none', border: 'none', color: C2.gold, fontFamily: 'DM Sans, sans-serif', fontSize: 13, fontWeight: 600, cursor: 'pointer', textAlign: 'right', padding: 0 }}>
            Forgot password?
          </button>
        }

        <button onClick={submit} style={{
          marginTop: 4, width: '100%', background: `linear-gradient(135deg, ${C2.goldLt}, ${C2.gold})`,
          border: 'none', borderRadius: 14, padding: '16px 24px', color: '#fff',
          fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 16, cursor: 'pointer',
          boxShadow: '0 4px 14px rgba(122,81,8,0.28)'
        }}>{mode === 'signin' ? 'Sign In' : 'Create Account'}</button>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '4px 0' }}>
          <div style={{ flex: 1, height: 1, background: C2.border }} />
          <span style={{ color: C2.dim, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>or</span>
          <div style={{ flex: 1, height: 1, background: C2.border }} />
        </div>

        {['Continue with Google', 'Continue with Apple'].map((label, i) =>
        <button key={i} style={{ width: '100%', background: '#fff', border: `1.5px solid ${C2.border}`, borderRadius: 14, padding: '14px 24px', color: C2.text, fontFamily: 'DM Sans, sans-serif', fontWeight: 600, fontSize: 14, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, boxShadow: '0 1px 4px rgba(0,0,0,0.06)' }}>
            <span style={{ fontSize: 18 }}>{i === 0 ? 'G' : ''}{i === 1 ? '🍎' : ''}</span> {label}
          </button>
        )}

        <p style={{ textAlign: 'center', color: C2.muted, fontSize: 14, fontFamily: 'DM Sans, sans-serif', marginTop: 8 }}>
          {mode === 'signin' ? "Don't have an account? " : 'Already have an account? '}
          <button onClick={() => {setMode(mode === 'signin' ? 'signup' : 'signin');setError('');}} style={{ background: 'none', border: 'none', color: C2.gold, fontWeight: 700, cursor: 'pointer', fontFamily: 'DM Sans, sans-serif', fontSize: 14 }}>
            {mode === 'signin' ? 'Create Account' : 'Sign In'}
          </button>
        </p>

        <p style={{ textAlign: 'center', color: C2.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.6, marginTop: 8 }}>
          By continuing, you agree to our Terms of Service and Privacy Policy. Your health data is encrypted and never sold.
        </p>
      </div>
    </div>);

}

// ── ONBOARDING ─────────────────────────────────────────────────

function OnboardingScreen({ onComplete }) {
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({
    firstName: '', lastName: '', dob: '', sex: '',
    conditions: [], otherCondition: '',
    insurance: '', memberId: '', connected: false
  });

  const conditions = ['Hypertension', 'Type 2 Diabetes', 'High Cholesterol', 'Heart Disease', 'Sickle Cell', 'Asthma', 'Obesity', 'Kidney Disease', 'Depression/Anxiety', 'Cancer', 'Lupus', 'HIV/AIDS'];
  const insurers = ['BlueCross BlueShield', 'Aetna', 'UnitedHealthcare', 'Cigna', 'Humana', 'Medicaid', 'Medicare', 'No Insurance', 'Other'];

  const toggleCondition = (c) => {
    setData((d) => ({ ...d, conditions: d.conditions.includes(c) ? d.conditions.filter((x) => x !== c) : [...d.conditions, c] }));
  };

  const pillStyle = (active, col) => ({
    padding: '9px 14px', borderRadius: 20, cursor: 'pointer',
    border: `1.5px solid ${active ? col || C2.gold : C2.border}`,
    background: active ? `${col || C2.gold}15` : '#fff',
    color: active ? col || C2.gold : C2.muted,
    fontFamily: 'DM Sans, sans-serif', fontSize: 13, fontWeight: active ? 700 : 500
  });

  const inputStyle = {
    width: '100%', background: '#F6F2EC', border: `1.5px solid ${C2.border}`,
    borderRadius: 12, padding: '13px 16px', color: C2.text,
    fontFamily: 'DM Sans, sans-serif', fontSize: 15, outline: 'none', boxSizing: 'border-box'
  };

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: 'linear-gradient(160deg, #FDF8F0, #F0EAE0)', paddingBottom: 40 }}>
      {/* Progress */}
      <div style={{ padding: '60px 24px 0' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 24 }}>
          {[1, 2, 3].map((n) =>
          <div key={n} style={{ flex: 1, height: 4, borderRadius: 2, background: n <= step ? C2.gold : C2.border, transition: 'background 0.3s' }} />
          )}
        </div>
        <p style={{ color: C2.muted, fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6, fontFamily: 'DM Sans, sans-serif' }}>Step {step} of 3</p>
      </div>

      {step === 1 &&
      <div style={{ padding: '0 24px' }}>
          <h2 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 26, color: C2.text, marginBottom: 6 }}>Tell us about you</h2>
          <p style={{ color: C2.muted, fontSize: 14, marginBottom: 24, fontFamily: 'DM Sans, sans-serif' }}>Your information helps us personalize your health guidance.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <input placeholder="First name" value={data.firstName} onChange={(e) => setData((d) => ({ ...d, firstName: e.target.value }))} style={inputStyle} />
              <input placeholder="Last name" value={data.lastName} onChange={(e) => setData((d) => ({ ...d, lastName: e.target.value }))} style={inputStyle} />
            </div>
            <input placeholder="Date of birth (MM/DD/YYYY)" value={data.dob} onChange={(e) => setData((d) => ({ ...d, dob: e.target.value }))} style={inputStyle} />
            <div>
              <p style={{ color: C2.muted, fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>Biological Sex</p>
              <div style={{ display: 'flex', gap: 8 }}>
                {['Male', 'Female', 'Intersex'].map((s) =>
              <button key={s} onClick={() => setData((d) => ({ ...d, sex: s }))} style={pillStyle(data.sex === s)}>{s}</button>
              )}
              </div>
            </div>
          </div>
        </div>
      }

      {step === 2 &&
      <div style={{ padding: '0 24px' }}>
          <h2 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 26, color: C2.text, marginBottom: 6 }}>Your health profile</h2>
          <p style={{ color: C2.muted, fontSize: 14, marginBottom: 20, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.5 }}>Select any current conditions. This helps the AI give you relevant guidance.</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 16 }}>
            {conditions.map((c) =>
          <button key={c} onClick={() => toggleCondition(c)} style={pillStyle(data.conditions.includes(c), data.conditions.includes(c) ? C2.red : null)}>{c}</button>
          )}
          </div>
          <input placeholder="Other condition (optional)" value={data.otherCondition} onChange={(e) => setData((d) => ({ ...d, otherCondition: e.target.value }))} style={inputStyle} />
          <p style={{ color: C2.dim, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 10, lineHeight: 1.5 }}>🔒 This data is encrypted and only used to personalize your experience. It is never shared without your consent.</p>
        </div>
      }

      {step === 3 &&
      <div style={{ padding: '0 24px' }}>
          <h2 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 26, color: C2.text, marginBottom: 6 }}>Your coverage</h2>
          <p style={{ color: C2.muted, fontSize: 14, marginBottom: 20, fontFamily: 'DM Sans, sans-serif' }}>Helps us check if Black doctors in your area are in-network.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 20 }}>
            <div>
              <p style={{ color: C2.muted, fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>Insurance Provider</p>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {insurers.map((ins) =>
              <button key={ins} onClick={() => setData((d) => ({ ...d, insurance: ins }))} style={pillStyle(data.insurance === ins, C2.blue)}>{ins}</button>
              )}
              </div>
            </div>
            <input placeholder="Member ID (optional)" value={data.memberId} onChange={(e) => setData((d) => ({ ...d, memberId: e.target.value }))} style={inputStyle} />
          </div>
          <button onClick={() => setData((d) => ({ ...d, connected: !d.connected }))} style={{
          width: '100%', background: data.connected ? '#E4F2E8' : '#fff',
          border: `1.5px solid ${data.connected ? C2.green : C2.border}`,
          borderRadius: 14, padding: '16px 20px', cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left'
        }}>
            <span style={{ fontSize: 28 }}>🏥</span>
            <div style={{ flex: 1 }}>
              <p style={{ color: C2.text, fontWeight: 700, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>{data.connected ? '✓ MyChart Connected' : 'Connect MyChart / Epic'}</p>
              <p style={{ color: C2.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>Auto-import records, lab results & appointments</p>
            </div>
          </button>
        </div>
      }

      {/* Navigation buttons */}
      <div style={{ padding: '24px 24px 0', display: 'flex', gap: 10 }}>
        {step > 1 &&
        <button onClick={() => setStep((s) => s - 1)} style={{ flex: 1, background: '#fff', border: `1.5px solid ${C2.border}`, borderRadius: 14, padding: '15px 0', color: C2.muted, fontFamily: 'DM Sans, sans-serif', fontWeight: 600, fontSize: 15, cursor: 'pointer' }}>← Back</button>
        }
        <button onClick={() => step < 3 ? setStep((s) => s + 1) : onComplete(data)} style={{
          flex: 2, background: `linear-gradient(135deg, ${C2.goldLt}, ${C2.gold})`,
          border: 'none', borderRadius: 14, 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.28)'
        }}>{step < 3 ? 'Continue →' : 'Get Started →'}</button>
      </div>
      {step === 1 &&
      <button onClick={() => onComplete({})} style={{ width: '100%', background: 'none', border: 'none', color: C2.dim, fontFamily: 'DM Sans, sans-serif', fontSize: 13, cursor: 'pointer', marginTop: 14, padding: '0 24px' }}>Skip for now</button>
      }
    </div>);

}

// ── PRICING ────────────────────────────────────────────────────

function PricingScreen({ nav, currentPlan, onUpgrade }) {
  const [billing, setBilling] = React.useState('monthly');
  const disc = billing === 'annual' ? 0.8 : 1;

  const plans = [
  {
    id: 'free', label: 'Free', price: 0, color: C2.muted,
    desc: 'Build trust. Start learning.',
    features: ['Community Health Forum', 'Educational content library', 'Daily health insights', '3 AI interactions/month', 'Basic medication info']
  },
  {
    id: 'plus', label: 'Plus', price: 19, color: C2.gold, recommended: true,
    desc: 'Full AI advocacy for one person.',
    features: ['Everything in Free', 'Unlimited AI guidance', 'Appointment prep (unlimited)', 'Lab result breakdowns', 'Medication deep-dives + alternatives', 'Find Black doctors + insurance check', 'Research library access']
  },
  {
    id: 'family', label: 'Family', price: 39, color: C2.green,
    desc: 'Coordinated care for up to 5 members.',
    features: ['Everything in Plus', 'Up to 5 family members', 'Shared caregiver dashboard', 'Coordinated appointment tracking', 'Family medication management', 'Priority AI support']
  }];


  const payPerUse = [
  { label: 'Appointment Prep Session', price: '$7', icon: '📋' },
  { label: 'Post-Visit Explanation', price: '$9', icon: '🩺' },
  { label: 'Lab Result Breakdown', price: '$6', icon: '🔬' },
  { label: 'Care Plan Summary', price: '$4', icon: '📝' }];


  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C2.bg, paddingBottom: 90 }}>
      <SectionHeader title="Choose Your Plan" sub="Upgrade anytime. Cancel anytime." onBack={() => nav('profile')} />
      <div style={{ padding: '0 16px' }}>
        {/* Billing toggle */}
        <div style={{ display: 'flex', background: '#fff', borderRadius: 12, padding: 4, border: `1px solid ${C2.border}`, marginBottom: 20 }}>
          {['monthly', 'annual'].map((b) =>
          <button key={b} onClick={() => setBilling(b)} style={{
            flex: 1, padding: '9px', borderRadius: 8, border: 'none', cursor: 'pointer',
            background: billing === b ? C2.gold : 'transparent',
            color: billing === b ? '#fff' : C2.muted,
            fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 13
          }}>
              {b === 'monthly' ? 'Monthly' : 'Annual (Save 20%)'}
            </button>
          )}
        </div>

        {plans.map((plan) =>
        <div key={plan.id} style={{
          background: plan.recommended ? `linear-gradient(135deg, #FEF6E4, #FDF0D8)` : '#fff',
          borderRadius: 18, padding: 20, marginBottom: 14,
          border: `2px solid ${plan.recommended ? C2.gold : C2.border}`,
          boxShadow: plan.recommended ? `0 4px 20px rgba(122,81,8,0.15)` : '0 1px 4px rgba(0,0,0,0.05)',
          position: 'relative'
        }}>
            {plan.recommended &&
          <div style={{ position: 'absolute', top: -12, left: '50%', transform: 'translateX(-50%)', background: C2.gold, color: '#fff', borderRadius: 20, padding: '4px 14px', fontSize: 11, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', whiteSpace: 'nowrap' }}>
                ⭐ Most Popular
              </div>
          }
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
              <div>
                <p style={{ color: plan.color, fontWeight: 800, fontSize: 18, fontFamily: 'DM Sans, sans-serif' }}>{plan.label}</p>
                <p style={{ color: C2.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>{plan.desc}</p>
              </div>
              <div style={{ textAlign: 'right' }}>
                {plan.price === 0 ?
              <p style={{ color: C2.text, fontWeight: 800, fontSize: 22, fontFamily: 'DM Sans, sans-serif' }}>Free</p> :

              <>
                    <p style={{ color: C2.text, fontWeight: 800, fontSize: 22, fontFamily: 'DM Sans, sans-serif' }}>${Math.round(plan.price * disc)}<span style={{ fontSize: 13, fontWeight: 500 }}>/mo</span></p>
                    {billing === 'annual' && <p style={{ color: C2.green, fontSize: 11, fontWeight: 600, fontFamily: 'DM Sans, sans-serif' }}>Save ${Math.round(plan.price * 12 * 0.2)}/yr</p>}
                  </>
              }
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginBottom: 16 }}>
              {plan.features.map((f, i) =>
            <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                  <span style={{ color: plan.color, fontWeight: 700, flexShrink: 0, marginTop: 1 }}>✓</span>
                  <p style={{ color: C2.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.4 }}>{f}</p>
                </div>
            )}
            </div>
            {currentPlan === plan.id ?
          <div style={{ background: `${plan.color}15`, border: `1px solid ${plan.color}40`, borderRadius: 10, padding: '10px 16px', textAlign: 'center' }}>
                <p style={{ color: plan.color, fontWeight: 700, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>✓ Your current plan</p>
              </div> :

          <button onClick={() => onUpgrade(plan.id)} style={{
            width: '100%', background: plan.price === 0 ? 'transparent' : `linear-gradient(135deg, ${plan.color === C2.gold ? C2.goldLt : plan.color}, ${plan.color})`,
            border: plan.price === 0 ? `1.5px solid ${C2.border}` : 'none',
            borderRadius: 12, padding: '13px 0', color: plan.price === 0 ? C2.muted : '#fff',
            fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 14, cursor: 'pointer',
            boxShadow: plan.price === 0 ? 'none' : '0 3px 10px rgba(0,0,0,0.15)'
          }}>
                {plan.price === 0 ? 'Downgrade to Free' : `Upgrade to ${plan.label}`}
              </button>
          }
          </div>
        )}

        {/* Pay-Per-Use */}
        <div style={{ background: '#fff', borderRadius: 18, padding: 20, border: `1px solid ${C2.border}`, marginBottom: 16 }}>
          <p style={{ color: C2.text, fontWeight: 800, fontSize: 16, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>FREE Plan (Add-On Services)</p>
          <p style={{ color: C2.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginBottom: 16 }}>Pay only for what you need, when you need it.</p>
          {payPerUse.map((item, i) =>
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: i < payPerUse.length - 1 ? `1px solid ${C2.border}` : 'none' }}>
              <span style={{ fontSize: 22 }}>{item.icon}</span>
              <p style={{ flex: 1, color: C2.text, fontSize: 14, fontFamily: 'DM Sans, sans-serif', fontWeight: 500 }}>{item.label}</p>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <p style={{ color: C2.gold, fontWeight: 800, fontSize: 16, fontFamily: 'DM Sans, sans-serif' }}>{item.price}</p>
                <button style={{ background: C2.gold, border: 'none', borderRadius: 8, padding: '6px 12px', color: '#fff', fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12, cursor: 'pointer' }}>Buy</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>);

}

// ── PROFILE ────────────────────────────────────────────────────

function ProfileScreen({ nav, user, plan, onLogout }) {
  const [language, setLanguage] = React.useState('English')
  const [accessibility, setAccessibility] = React.useState({ on: false, largeText: false, highContrast: false, reducedMotion: false, screenReader: false })
  const [openModal, setOpenModal] = React.useState(null)
  const languages = [
    { code: 'en', name: 'English', native: 'English' },
    { code: 'es', name: 'Spanish', native: 'Español' },
    { code: 'fr', name: 'French', native: 'Français' },
    { code: 'pt', name: 'Portuguese', native: 'Português' },
    { code: 'ht', name: 'Haitian Creole', native: 'Kreyòl Ayisyen' },
    { code: 'sw', name: 'Swahili', native: 'Kiswahili' },
    { code: 'am', name: 'Amharic', native: 'አማርኛ' },
    { code: 'yo', name: 'Yoruba', native: 'Yorùbá' },
    { code: 'ig', name: 'Igbo', native: 'Igbo' },
    { code: 'ar', name: 'Arabic', native: 'العربية' },
    { code: 'zh', name: 'Mandarin', native: '中文' },
  ]
  const planColors = { free: C2.muted, plus: C2.gold, family: C2.green };
  const planLabels = { free: 'Free Plan', plus: 'Plus — $19/mo', family: 'Family — $39/mo' };

  // Active member profile (per-member; defined in bha-data.jsx)
  const AP = (window.__bhaProfiles && window.__bhaProfiles[window.__bhaActiveMember]) || {}
  const apConditions = (AP.conditions && AP.conditions.length) ? AP.conditions.join(' · ') : 'No active conditions'
  const apMedCount = (AP.medList && AP.medList.length) || 0
  const apIns = AP.insurance || { provider: '—', memberId: '—', planType: '—' }
  const apApptVal = AP.appt ? `${AP.appt.when.split('·')[0].trim()} · ${AP.appt.doctor}` : 'None scheduled'
  const apEmail = AP.firstName ? `${AP.firstName.toLowerCase()}.${AP.lastName.toLowerCase()}@email.com` : 'member@email.com'

  const sections = [
  {
    header: 'Health Profile',
    items: [
    { label: 'Conditions', value: apConditions, icon: '🩺' },
    { label: 'Medications', value: `${apMedCount} active prescription${apMedCount !== 1 ? 's' : ''}`, icon: '💊', screen: 'meds' },
    { label: 'Family Health History', value: '8 of 12 sections complete · 67%', icon: 'tree-img', screen: 'familyhistory' },
    { label: 'Health Engagement', value: 'Advocate tier · rewards & streak', icon: '🌟', screen: 'rewards' },
    { label: 'Upcoming Appointment', value: apApptVal, icon: '🗓', screen: 'schedule' }]

  },
  {
    header: 'Insurance & Coverage',
    items: [
    { label: 'Provider', value: apIns.provider, icon: '🛡' },
    { label: 'Member ID', value: apIns.memberId, icon: '#' },
    { label: 'Plan Type', value: apIns.planType, icon: '📄' }]

  },
  {
    header: 'Connected Accounts',
    items: [
    { label: 'MyChart / Epic', value: '✓ Connected', icon: '🏥', connected: true },
    { label: 'Apple Health', value: 'Tap to connect', icon: '❤️', connected: false },
    { label: 'Fitbit / Wearable', value: 'Tap to connect', icon: '⌚', connected: false }]

  },
  {
    header: 'App Settings',
    items: [
    { label: 'Notifications', value: 'Medication & appointment alerts on', icon: '🔔', screen: 'notifications' },
    { label: 'Privacy & Security', value: 'Data encrypted · 2FA enabled', icon: '🔒' },
    { label: 'Language', value: language, icon: '🌐', onClick: () => setOpenModal('language') },
    { label: 'Accessibility', value: accessibility.on ? 'On · Customize options' : 'Off', icon: '♿', onClick: () => setOpenModal('accessibility') }]

  }];

  const minors = (window.__bhaMembers || []).filter(m => m.age != null && m.age <= 18)
  if (minors.length) {
    sections.splice(1, 0, {
      header: "Children's Immunizations",
      items: minors.map(m => ({
        label: `${m.name}'s Immunizations`,
        value: `Age ${m.age} · CDC + ${m.state || 'state'} school requirements`,
        icon: '💉',
        screen: 'immunizations',
        onClick: () => { window.__bhaImmunFocusId = m.id; nav('immunizations') },
      })),
    })
  }

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C2.bg, paddingBottom: 90 }}>
      {openModal === 'language' && (
        <div onClick={() => setOpenModal(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(26,26,46,0.55)', zIndex: 100, display: 'flex', alignItems: 'flex-end', backdropFilter: 'blur(4px)' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ width: '100%', maxHeight: '75%', background: '#fff', borderRadius: '20px 20px 0 0', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '14px 20px', borderBottom: `1px solid ${C2.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0 }}>
              <p style={{ fontFamily: 'DM Serif Display, serif', fontSize: 20, color: C2.text }}>Choose Language</p>
              <button onClick={() => setOpenModal(null)} style={{ background: 'none', border: 'none', fontSize: 22, color: C2.muted, cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ overflowY: 'auto', padding: 12 }}>
              {languages.map(l => (
                <button key={l.code} onClick={() => { setLanguage(l.name); setOpenModal(null) }} style={{ width: '100%', background: language === l.name ? 'rgba(192,57,43,0.08)' : 'none', border: `1.5px solid ${language === l.name ? '#C0392B' : 'transparent'}`, borderRadius: 12, padding: '12px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer', textAlign: 'left', marginBottom: 4 }}>
                  <div>
                    <p style={{ color: C2.text, fontFamily: 'DM Sans, sans-serif', fontSize: 15, fontWeight: 600 }}>{l.native}</p>
                    <p style={{ color: C2.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 12, marginTop: 2 }}>{l.name}</p>
                  </div>
                  {language === l.name && <span style={{ color: '#C0392B', fontSize: 18, fontWeight: 700 }}>✓</span>}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {openModal === 'accessibility' && (
        <div onClick={() => setOpenModal(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(26,26,46,0.55)', zIndex: 100, display: 'flex', alignItems: 'flex-end', backdropFilter: 'blur(4px)' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ width: '100%', maxHeight: '80%', background: '#fff', borderRadius: '20px 20px 0 0', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '14px 20px', borderBottom: `1px solid ${C2.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0 }}>
              <p style={{ fontFamily: 'DM Serif Display, serif', fontSize: 20, color: C2.text }}>Accessibility</p>
              <button onClick={() => setOpenModal(null)} style={{ background: 'none', border: 'none', fontSize: 22, color: C2.muted, cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ overflowY: 'auto', padding: 16 }}>
              <button onClick={() => setAccessibility(a => ({ ...a, on: !a.on }))} style={{ width: '100%', background: accessibility.on ? 'rgba(22,163,74,0.08)' : '#F7F3EE', border: `1.5px solid ${accessibility.on ? '#16A34A' : C2.border}`, borderRadius: 14, padding: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer', textAlign: 'left', marginBottom: 16 }}>
                <div>
                  <p style={{ color: C2.text, fontFamily: 'DM Sans, sans-serif', fontSize: 16, fontWeight: 700 }}>Accessibility Mode</p>
                  <p style={{ color: C2.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 12, marginTop: 4, lineHeight: 1.5 }}>Master toggle for all accessibility features</p>
                </div>
                <div style={{ width: 48, height: 28, background: accessibility.on ? '#16A34A' : '#D8D2C4', borderRadius: 14, padding: 3, flexShrink: 0, transition: 'background 200ms' }}>
                  <div style={{ width: 22, height: 22, background: '#fff', borderRadius: 11, transform: accessibility.on ? 'translateX(20px)' : 'translateX(0)', transition: 'transform 200ms', boxShadow: '0 1px 3px rgba(0,0,0,0.2)' }} />
                </div>
              </button>
              {accessibility.on && (
                <>
                  <p style={{ color: C2.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>Customize</p>
                  {[
                    { key: 'largeText', label: 'Large Text', desc: 'Increase font size across the app' },
                    { key: 'highContrast', label: 'High Contrast', desc: 'Stronger color contrast for low vision' },
                    { key: 'reducedMotion', label: 'Reduce Motion', desc: 'Minimize animations and transitions' },
                    { key: 'screenReader', label: 'Screen Reader Optimization', desc: 'Enhanced labels for VoiceOver/TalkBack' },
                  ].map(opt => (
                    <button key={opt.key} onClick={() => setAccessibility(a => ({ ...a, [opt.key]: !a[opt.key] }))} style={{ width: '100%', background: '#fff', border: `1px solid ${C2.border}`, borderRadius: 12, padding: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer', textAlign: 'left', marginBottom: 8 }}>
                      <div style={{ flex: 1, paddingRight: 12 }}>
                        <p style={{ color: C2.text, fontFamily: 'DM Sans, sans-serif', fontSize: 14, fontWeight: 600 }}>{opt.label}</p>
                        <p style={{ color: C2.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 12, marginTop: 2, lineHeight: 1.5 }}>{opt.desc}</p>
                      </div>
                      <div style={{ width: 40, height: 24, background: accessibility[opt.key] ? '#16A34A' : '#D8D2C4', borderRadius: 12, padding: 2, flexShrink: 0, transition: 'background 200ms' }}>
                        <div style={{ width: 20, height: 20, background: '#fff', borderRadius: 10, transform: accessibility[opt.key] ? 'translateX(16px)' : 'translateX(0)', transition: 'transform 200ms', boxShadow: '0 1px 3px rgba(0,0,0,0.2)' }} />
                      </div>
                    </button>
                  ))}
                </>
              )}
              <p style={{ color: C2.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', textAlign: 'center', marginTop: 14, lineHeight: 1.5 }}>
                These settings are honored by VoiceOver, TalkBack, and our app's adaptive UI.
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Header */}
      <div style={{ background: 'linear-gradient(160deg, #FDF6EC 0%, #FFFFFF 60%, #F6F2EC 100%)', padding: '64px 20px 24px', borderBottom: `1px solid ${C2.border}` }}>
        <button onClick={() => nav('more')} 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>
          More
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 64, height: 64, borderRadius: 32, background: `linear-gradient(135deg, ${C2.goldLt}, ${C2.red})`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 800, fontSize: 24, flexShrink: 0 }}>{AP.initials || 'MJ'}</div>
          <div style={{ flex: 1 }}>
            <h1 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 24, color: C2.text }}>{AP.name || 'Marcus Johnson'}</h1>
            <p style={{ color: C2.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>{apEmail}</p>
            <button onClick={() => nav('pricing')} style={{
              marginTop: 8, background: `${planColors[plan]}15`, border: `1px solid ${planColors[plan]}50`,
              borderRadius: 20, padding: '4px 12px', color: planColors[plan],
              fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12, cursor: 'pointer'
            }}>
              {planLabels[plan]} ›
            </button>
          </div>
        </div>
      </div>

      {/* Sections */}
      <div style={{ padding: '16px 16px 0', display: 'flex', flexDirection: 'column', gap: 20 }}>
        {sections.map((sec, si) =>
        <div key={si}>
            <p style={{ color: C2.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif', paddingLeft: 4 }}>{sec.header}</p>
            <div style={{ background: '#fff', borderRadius: 16, border: `1px solid ${C2.border}`, overflow: 'hidden', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
              {sec.items.map((item, ii) =>
            <button key={ii} onClick={() => item.onClick ? item.onClick() : item.screen && nav(item.screen)} style={{
              width: '100%', background: 'none', border: 'none', borderBottom: ii < sec.items.length - 1 ? `1px solid ${C2.border}` : 'none',
              padding: '14px 16px', cursor: (item.screen || item.onClick) ? 'pointer' : 'default',
              display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left'
            }}>
                  {item.icon === 'tree-img' ? <img src="family-tree.png" alt="Family tree" style={{ width: 28, height: 28, objectFit: 'contain', filter: 'invert(36%) sepia(38%) saturate(670%) hue-rotate(86deg) brightness(95%) contrast(85%)' }} /> : <span style={{ fontSize: 18, width: 28, textAlign: 'center' }}>{item.icon}</span>}
                  <div style={{ flex: 1 }}>
                    <p style={{ color: C2.text, fontWeight: 600, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>{item.label}</p>
                    <p style={{ color: item.connected === true ? C2.green : item.connected === false ? C2.gold : C2.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>{item.value}</p>
                  </div>
                  {item.screen && <span style={{ color: C2.dim, fontSize: 18 }}>›</span>}
                </button>
            )}
            </div>
          </div>
        )}

        <button onClick={onLogout} style={{ width: '100%', background: '#FEF2F4', border: `1.5px solid ${C2.red}30`, borderRadius: 14, padding: '15px 24px', color: C2.red, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 15, cursor: 'pointer', marginTop: 4 }}>
          Sign Out
        </button>
        <p style={{ textAlign: 'center', color: C2.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif' }}>BHA v1.0.0 · Your data is encrypted and secure</p>
      </div>
    </div>);

}

// ── NOTIFICATIONS ──────────────────────────────────────────────

function NotificationsScreen({ nav }) {
  const [read, setRead] = React.useState([]);

  const notifications = [
  {
    id: 1, time: '8:00 AM', group: 'Today', icon: '💊', color: C2.gold,
    title: 'Medication Reminder', body: 'Time to take Lisinopril 10mg', screen: 'meds', urgent: false
  },
  {
    id: 2, time: '9:15 AM', group: 'Today', icon: '📋', color: C2.red,
    title: 'Appointment Tomorrow', body: 'Cardiology with Dr. Amara Osei · 10:30 AM. Prep your questions now.', screen: 'prep', urgent: true
  },
  {
    id: 3, time: '2:30 PM', group: 'Today', icon: '🔬', color: C2.blue,
    title: 'Lab Results Ready', body: 'Your Complete Blood Panel from Apr 17 has been analyzed by AI.', screen: 'results', urgent: false
  },
  {
    id: 4, time: 'Yesterday', group: 'This Week', icon: '💬', color: C2.green,
    title: 'Forum Reply', body: 'DrAmandaK replied to your post about hypertension management.', screen: 'forum', urgent: false
  },
  {
    id: 5, time: 'Apr 17', group: 'This Week', icon: '💊', color: C2.gold,
    title: 'Medication Reminder', body: 'Time to take Metformin 500mg (evening dose)', screen: 'meds', urgent: false
  },
  {
    id: 6, time: 'Apr 16', group: 'This Week', icon: '📚', color: C2.red,
    title: 'New Research', body: 'A new study on hypertension in Black patients matches your profile.', screen: 'research', urgent: false
  }];


  const groups = [...new Set(notifications.map((n) => n.group))];
  const markRead = (id) => setRead((r) => [...r, id]);

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: C2.bg, paddingBottom: 90 }}>
      <SectionHeader title="Notifications" sub="Medication reminders, alerts & updates" onBack={() => nav('profile')} />
      <div style={{ padding: '0 16px' }}>
        {groups.map((group) =>
        <div key={group} style={{ marginBottom: 20 }}>
            <p style={{ color: C2.muted, fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10, fontFamily: 'DM Sans, sans-serif' }}>{group}</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {notifications.filter((n) => n.group === group).map((n) =>
            <button key={n.id} onClick={() => {markRead(n.id);nav(n.screen);}} style={{
              background: read.includes(n.id) ? '#fff' : n.urgent ? '#FEF6EE' : '#fff',
              border: `1.5px solid ${read.includes(n.id) ? C2.border : n.urgent ? C2.gold + '60' : C2.border}`,
              borderRadius: 14, padding: '14px 14px', cursor: 'pointer', textAlign: 'left',
              display: 'flex', alignItems: 'flex-start', gap: 12,
              boxShadow: '0 1px 4px rgba(0,0,0,0.04)'
            }}>
                  <div style={{ width: 40, height: 40, borderRadius: 12, background: `${n.color}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20, flexShrink: 0 }}>{n.icon}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                      <p style={{ color: C2.text, fontWeight: 700, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>{n.title}</p>
                      <p style={{ color: C2.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif', flexShrink: 0, marginLeft: 8 }}>{n.time}</p>
                    </div>
                    <p style={{ color: C2.muted, fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginTop: 3, lineHeight: 1.5 }}>{n.body}</p>
                  </div>
                  {!read.includes(n.id) && <div style={{ width: 8, height: 8, borderRadius: 4, background: n.color, flexShrink: 0, marginTop: 4 }} />}
                </button>
            )}
            </div>
          </div>
        )}

        {/* Notification Settings */}
        <div style={{ background: '#fff', borderRadius: 16, padding: 16, border: `1px solid ${C2.border}`, marginBottom: 12 }}>
          <p style={{ color: C2.muted, fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 12, fontFamily: 'DM Sans, sans-serif' }}>Notification Settings</p>
          {[
          { label: 'Medication Reminders', on: true },
          { label: 'Appointment Alerts', on: true },
          { label: 'Lab Result Updates', on: true },
          { label: 'Forum Replies', on: false },
          { label: 'Health Research', on: false }].
          map((s, i, arr) =>
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: i < arr.length - 1 ? `1px solid ${C2.border}` : 'none' }}>
              <p style={{ color: C2.text, fontSize: 14, fontFamily: 'DM Sans, sans-serif', fontWeight: 500 }}>{s.label}</p>
              <div style={{ width: 44, height: 26, borderRadius: 13, background: s.on ? C2.green : '#DDD', position: 'relative', cursor: 'pointer' }}>
                <div style={{ width: 20, height: 20, borderRadius: 10, background: '#fff', position: 'absolute', top: 3, left: s.on ? 21 : 3, transition: 'left 0.2s', boxShadow: '0 1px 3px rgba(0,0,0,0.2)' }} />
              </div>
            </div>
          )}
        </div>
      </div>
    </div>);

}

Object.assign(window, {
  LoginScreen, OnboardingScreen, PricingScreen, ProfileScreen, NotificationsScreen
});