// Logged-in member screens: home (Sunday Letter), inbox, conversation,
// edit profile, settings, notifications, pause, mutual matches.

// ─── Shared bits ────────────────────────────────────────────────────────
const MemberShell = ({ tweaks, navigate, active, children }) => {
  const { Nav, Footer } = window;
  return (
    <div>
      <Nav tweaks={tweaks} navigate={navigate} active={active} />
      <main style={{ minHeight: 'calc(100vh - 220px)' }}>{children}</main>
      <Footer tweaks={tweaks} navigate={navigate} />
    </div>
  );
};

const SubNav = ({ items, active, navigate }) => (
  <div style={{ borderBottom: '1px solid var(--line)', background: 'var(--bg)' }}>
    <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 56px', display: 'flex', gap: 24 }}>
      {items.map(([id, label, count]) => (
        <button key={id} onClick={() => navigate(id)} style={{
          background: 'none', border: 'none', padding: '18px 0', cursor: 'pointer',
          fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 500,
          color: active === id ? 'var(--ink)' : 'var(--ink-3)',
          borderBottom: active === id ? '2px solid var(--ink)' : '2px solid transparent',
          marginBottom: -1, display: 'flex', alignItems: 'center', gap: 8
        }}>
          {label}
          {count !== undefined && <span style={{
            fontSize: 11, fontFamily: 'var(--mono)', padding: '2px 7px', borderRadius: 10,
            background: active === id ? 'var(--ink)' : 'var(--bg-2)',
            color: active === id ? 'var(--paper)' : 'var(--ink-3)'
          }}>{count}</span>}
        </button>
      ))}
    </div>
  </div>
);

const PageHeader = ({ eyebrow, title, sub, right }) => (
  <div style={{ borderBottom: '1px solid var(--line)' }}>
    <div style={{ maxWidth: 1240, margin: '0 auto', padding: '56px 56px 40px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 32, flexWrap: 'wrap' }}>
      <div style={{ maxWidth: 720 }}>
        {eyebrow && <div className="mono" style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 14 }}>{eyebrow}</div>}
        <h1 className="serif" style={{ fontSize: 52, fontWeight: 500, lineHeight: 1.05, margin: 0, letterSpacing: '-0.01em', textWrap: 'balance' }}>{title}</h1>
        {sub && <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink-2)', marginTop: 16, marginBottom: 0, textWrap: 'pretty' }}>{sub}</p>}
      </div>
      {right}
    </div>
  </div>
);

// ─── HOME — Sunday Letter ──────────────────────────────────────────────
const MemberHome = ({ tweaks, navigate }) => {
  const { Btn, Badge, Portrait, SectionLabel } = window;
  const introMember = window.HMN_DATA.MEMBERS[1]; // Caleb R.
  const others = window.HMN_DATA.MEMBERS.slice(2, 5);

  return (
    <MemberShell tweaks={tweaks} navigate={navigate} active="member-home">
      {/* Sunday letter */}
      <section style={{ background: 'var(--paper)', borderBottom: '1px solid var(--line)' }}>
        <div style={{ maxWidth: 1100, margin: '0 auto', padding: '72px 56px 96px' }}>
          <div style={{ textAlign: 'center', marginBottom: 56 }}>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.24em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 16 }}>The Sunday Letter · No. 9 · Lord's Day, 8 March</div>
            <h1 className="serif" style={{ fontSize: 56, fontWeight: 500, lineHeight: 1.05, margin: 0, fontStyle: 'italic', textWrap: 'balance' }}>
              Dear Hannah,
            </h1>
          </div>

          <div className="serif" style={{ fontSize: 19, lineHeight: 1.7, color: 'var(--ink-2)', maxWidth: 680, margin: '0 auto', textWrap: 'pretty' }}>
            <p style={{ marginTop: 0 }}>
              This week we'd like you to consider <strong style={{ color: 'var(--ink)' }}>Caleb R.</strong>, a 29-year-old mechanical engineer in Birmingham, AL.
              He is a member of Briarwood Presbyterian (PCA), where his pastor, Rev. Jonathan H. Pace, has commended him as a member in good standing.
            </p>
            <p>
              He converted at 19 through a college RUF retreat. He subscribes the Westminster Confession,
              teaches the Shorter Catechism to his small group, and is eager for children. We thought of you because
              you both come from PCA churches, share a love of Bach, and have written about wanting a household
              shaped by hymnody and family worship.
            </p>
            <p>
              Take your time with his profile. There is no rush, and there is no obligation either way.
              If something stirs, write to us — or better, write to him directly.
            </p>
            <p style={{ fontStyle: 'italic', color: 'var(--ink-3)', fontSize: 17 }}>
              Soli Deo gloria,<br/>
              <span style={{ fontFamily: 'var(--mono)', fontStyle: 'normal', fontSize: 12, letterSpacing: '0.08em' }}>— THE HELP MEET NETWORK</span>
            </p>
          </div>

          {/* Featured profile card */}
          <div style={{ marginTop: 56, background: 'var(--bg)', border: '1px solid var(--line)', display: 'grid', gridTemplateColumns: '320px 1fr', maxWidth: 900, margin: '56px auto 0' }} className="hmn-card-row">
            <div style={{ aspectRatio: '4/5' }} className="hmn-card-row-img">
              <Portrait seed={introMember.img} size={400} name={introMember.name} />
            </div>
            <div style={{ padding: '32px 36px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                  <h2 className="serif" style={{ fontSize: 36, fontWeight: 500, margin: 0 }}>{introMember.name}, {introMember.age}</h2>
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-3)', fontFamily: 'var(--mono)', letterSpacing: '0.04em' }}>
                  {introMember.location} · {introMember.presbytery}
                </div>
                <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--ink-2)', marginTop: 18 }}>
                  {introMember.vocation} · {introMember.education}.<br/>
                  <em>{introMember.testimony}</em>
                </p>
              </div>
              <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
                <Btn kind="primary" onClick={() => navigate('profile', introMember.id)}>Read full profile →</Btn>
                <Btn kind="secondary">Pass kindly</Btn>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Also consider */}
      <section style={{ background: 'var(--bg)' }}>
        <div style={{ maxWidth: 1240, margin: '0 auto', padding: '72px 56px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 40 }}>
            <div>
              <SectionLabel>Also consider</SectionLabel>
              <h2 className="serif" style={{ fontSize: 36, fontWeight: 500, lineHeight: 1.1, margin: 0 }}>
                Three more, drawn from the directory.
              </h2>
            </div>
            <Btn kind="secondary" onClick={() => navigate('member-browse')}>Open the directory →</Btn>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28 }}>
            {others.map(m => (
              <div key={m.id} onClick={() => navigate('profile', m.id)} style={{
                background: 'var(--paper)', border: '1px solid var(--line)', cursor: 'pointer'
              }}>
                <div style={{ aspectRatio: '4/5' }}>
                  <Portrait seed={m.img} size={320} name={m.name} />
                </div>
                <div style={{ padding: '20px 22px 24px' }}>
                  <h3 className="serif" style={{ fontSize: 22, fontWeight: 500, margin: 0 }}>{m.name}, {m.age}</h3>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4, fontFamily: 'var(--mono)', letterSpacing: '0.04em' }}>
                    {m.location.split(',')[0].toUpperCase()} · {m.presbytery.split(' · ')[0]}
                  </div>
                  <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--ink-2)', marginTop: 12, marginBottom: 0 }}>
                    {m.vocation}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Activity bar */}
      <section style={{ background: 'var(--paper)', borderTop: '1px solid var(--line)' }}>
        <div style={{ maxWidth: 1240, margin: '0 auto', padding: '48px 56px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0 }}>
          {[
            { label: "Inbox", value: "3 new", note: "Unread messages", view: 'member-inbox' },
            { label: "Mutual interests", value: "1", note: "Awaiting your reply", view: 'member-matches' },
            { label: "Profile", value: "92%", note: "Add a second photo to reach 100%", view: 'member-profile-edit' },
          ].map((s, i) => (
            <button key={s.label} onClick={() => navigate(s.view)} style={{
              padding: '8px 32px', textAlign: 'left', background: 'none', cursor: 'pointer',
              border: 'none', borderLeft: i > 0 ? '1px solid var(--line)' : 'none', fontFamily: 'inherit'
            }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>{s.label}</div>
              <div className="serif" style={{ fontSize: 32, fontWeight: 500, color: 'var(--ink)', lineHeight: 1 }}>{s.value}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 8 }}>{s.note}</div>
            </button>
          ))}
        </div>
      </section>
    </MemberShell>
  );
};

// ─── INBOX ──────────────────────────────────────────────────────────────
const THREADS = [
  { id: 1, with: "Caleb R.", img: 2, location: "Birmingham, AL", lastMsg: "Yes — would Saturday morning work for a call? My elder is fine looping in if either of us want.", lastAt: "2 h ago", unread: true, mutual: true },
  { id: 2, with: "Andrew P.", img: 4, location: "Pittsburgh, PA", lastMsg: "Thank you for writing back. I'd love to hear more about your work at the hospital.", lastAt: "Yesterday", unread: true, mutual: false },
  { id: 3, with: "Samuel B.", img: 6, location: "Boise, ID", lastMsg: "Sent a longer note about the ranch — no rush at all on a reply.", lastAt: "3 days ago", unread: true, mutual: false },
  { id: 4, with: "Daniel T.", img: 4, location: "Nashville, TN", lastMsg: "(closed) Thank you, kindly. Wishing you well.", lastAt: "2 weeks ago", unread: false, mutual: false, closed: true },
];

const MemberInbox = ({ tweaks, navigate }) => {
  const { Btn, Portrait, Badge } = window;
  const unread = THREADS.filter(t => t.unread).length;

  return (
    <MemberShell tweaks={tweaks} navigate={navigate} active="member-inbox">
      <PageHeader eyebrow="Inbox" title="Your conversations." sub="Open exchanges with members in good standing. Either of you can invite an elder into a conversation at any time." />
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '40px 56px 96px' }}>
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)' }}>
          {THREADS.map((t, i) => (
            <button key={t.id} onClick={() => navigate('member-thread', t.id)} style={{
              display: 'grid', gridTemplateColumns: '64px 1fr auto', gap: 24, alignItems: 'center',
              width: '100%', textAlign: 'left', padding: '20px 28px', background: 'none', cursor: 'pointer',
              border: 'none', borderTop: i === 0 ? 'none' : '1px solid var(--line)', fontFamily: 'inherit',
              opacity: t.closed ? 0.55 : 1
            }}>
              <div style={{ width: 64, height: 64 }}><Portrait seed={t.img} size={64} name={t.with} /></div>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 4, flexWrap: 'wrap' }}>
                  <h3 className="serif" style={{ fontSize: 20, fontWeight: 500, margin: 0 }}>{t.with}</h3>
                  <span style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)' }}>{t.location}</span>
                  {t.mutual && <Badge tone="vouched">Mutual interest</Badge>}
                  {t.closed && <Badge tone="default">Closed</Badge>}
                </div>
                <div style={{ fontSize: 14, color: t.unread ? 'var(--ink)' : 'var(--ink-3)', fontWeight: t.unread ? 500 : 400, lineHeight: 1.5,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.lastMsg}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.04em' }}>{t.lastAt}</div>
                {t.unread && <div style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--accent)', marginTop: 8, marginLeft: 'auto' }}></div>}
              </div>
            </button>
          ))}
        </div>
      </div>
    </MemberShell>
  );
};

// ─── CONVERSATION THREAD ───────────────────────────────────────────────
const MemberThread = ({ tweaks, navigate, threadId = 1 }) => {
  const { Btn, Portrait, Badge } = window;
  const t = THREADS.find(x => x.id === threadId) || THREADS[0];
  const member = window.HMN_DATA.MEMBERS.find(m => m.name === t.with) || window.HMN_DATA.MEMBERS[1];
  const [draft, setDraft] = React.useState('');
  const [showElderModal, setShowElderModal] = React.useState(false);

  const messages = [
    { from: 'them', at: 'Mar 4 · 9:14 am', body: "Hannah — thank you for expressing interest. Your profile spoke deeply to me, especially how you wrote about hymnody. Would you be open to writing back? I'd love to know what called you to nursing." },
    { from: 'me', at: 'Mar 4 · 7:32 pm', body: "Caleb, thank you for the kind note. I went into nursing after a summer working in a hospice; I came home convinced that nothing else would feel as worth my time. I'd love to know more about your church and how you came to subscribe the Confession." },
    { from: 'them', at: 'Mar 6 · 11:08 am', body: "That's beautiful. Briarwood is a large but warm church — I came to it as a new convert and Rev. Pace personally walked me through the WCF over a year of breakfasts. I still meet with him monthly. May I ask: what does your family worship look like, or what would you want it to look like?" },
    { from: 'me', at: 'Yesterday · 8:12 pm', body: "Right now I read Scripture and a hymn before bed alone, but I would love a household where it's the rhythm of every evening. My parents did this when we were small and I miss it. What does it look like for you?" },
    { from: 'them', at: '2 hours ago', body: "Yes — would Saturday morning work for a call? My elder is fine looping in if either of us want." }
  ];

  return (
    <MemberShell tweaks={tweaks} navigate={navigate} active="member-inbox">
      <div style={{ maxWidth: 880, margin: '0 auto', padding: '40px 56px 0' }}>
        <button onClick={() => navigate('member-inbox')} style={{
          background: 'none', border: 'none', padding: 0, cursor: 'pointer',
          fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.08em', color: 'var(--ink-3)', marginBottom: 24
        }}>← BACK TO INBOX</button>

        <div style={{ borderBottom: '1px solid var(--line)', paddingBottom: 28, marginBottom: 32, display: 'grid', gridTemplateColumns: '64px 1fr auto', gap: 20, alignItems: 'center' }}>
          <div style={{ width: 64, height: 64 }}><Portrait seed={t.img} size={64} name={t.with} /></div>
          <div>
            <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: 0 }}>{t.with}</h1>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', fontFamily: 'var(--mono)', marginTop: 4 }}>
              {member.presbytery} · commended by {member.elder.split(' ').slice(-2).join(' ')}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn kind="ghost" size="sm" onClick={() => navigate('profile', member.id)}>View profile</Btn>
            <Btn kind="secondary" size="sm" onClick={() => setShowElderModal(true)}>Loop in elder</Btn>
          </div>
        </div>

        {/* Mutual interest banner */}
        {t.mutual && (
          <div style={{ background: 'var(--paper)', border: '1px solid var(--accent)', borderLeft: '4px solid var(--accent)', padding: '16px 20px', marginBottom: 32, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
            <div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 4 }}>Mutual interest</div>
              <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>You both expressed interest. This conversation is private; loop in either elder when you're ready.</div>
            </div>
          </div>
        )}

        {/* Messages */}
        <div style={{ marginBottom: 32 }}>
          {messages.map((m, i) => (
            <div key={i} style={{ marginBottom: 24, display: 'flex', flexDirection: m.from === 'me' ? 'row-reverse' : 'row', gap: 12 }}>
              <div style={{ maxWidth: '75%' }}>
                <div className="mono" style={{
                  fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)', marginBottom: 6,
                  textAlign: m.from === 'me' ? 'right' : 'left'
                }}>{m.from === 'me' ? 'YOU' : t.with.toUpperCase()} · {m.at}</div>
                <div style={{
                  background: m.from === 'me' ? 'var(--ink)' : 'var(--paper)',
                  color: m.from === 'me' ? 'var(--paper)' : 'var(--ink-2)',
                  border: m.from === 'me' ? 'none' : '1px solid var(--line)',
                  padding: '16px 20px',
                  fontFamily: 'var(--serif)', fontSize: 17, lineHeight: 1.55, textWrap: 'pretty'
                }}>{m.body}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Compose */}
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: 20, marginBottom: 64 }}>
          <textarea value={draft} onChange={e => setDraft(e.target.value)} placeholder="Write to Caleb…"
            style={{
              width: '100%', minHeight: 110, resize: 'vertical', border: 'none', outline: 'none',
              fontFamily: 'var(--serif)', fontSize: 17, lineHeight: 1.55, color: 'var(--ink)',
              background: 'transparent'
            }}/>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.06em' }}>Plain text · no attachments · saved to both inboxes</div>
            <Btn kind="primary" size="sm">Send</Btn>
          </div>
        </div>
      </div>

      {showElderModal && (
        <div onClick={() => setShowElderModal(false)} style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.35)', zIndex: 100,
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            background: 'var(--bg)', border: '1px solid var(--line)', maxWidth: 520, padding: 36
          }}>
            <h2 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: '0 0 12px' }}>Loop in your elder?</h2>
            <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--ink-2)', marginTop: 0 }}>
              We'll grant <strong>Rev. Daniel M. Carrick</strong> read-access to this conversation and notify him by email. {t.with} will be told their elder may also be invited. Either of you may end the loop-in later.
            </p>
            <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
              <Btn kind="primary" onClick={() => setShowElderModal(false)}>Yes, loop in Rev. Carrick</Btn>
              <Btn kind="ghost" onClick={() => setShowElderModal(false)}>Not yet</Btn>
            </div>
          </div>
        </div>
      )}
    </MemberShell>
  );
};

// ─── EDIT PROFILE ──────────────────────────────────────────────────────
const MemberProfileEdit = ({ tweaks, navigate }) => {
  const { Btn, Field, inputStyle, Portrait, Badge } = window;
  const me = window.HMN_DATA.MEMBERS[0]; // Hannah K.

  const sections = [
    ['About', [
      ['Name', me.name],
      ['Age', me.age],
      ['Vocation', me.vocation],
      ['Education', me.education],
      ['Location', me.location],
    ]],
    ['Faith', [
      ['Church', me.church],
      ['Presbytery / denomination', me.presbytery],
      ['Catechism', me.catechism],
      ['Commended by', me.elder + ' (' + me.elderRole + ')'],
    ]],
    ['Family vision', [
      ['Hopes', me.family],
      ['Open to relocation', me.relocate],
    ]],
  ];

  return (
    <MemberShell tweaks={tweaks} navigate={navigate} active="member-profile-edit">
      <SubNav active="member-profile-edit" navigate={navigate} items={[
        ['member-profile-edit', 'Edit profile'],
        ['member-settings', 'Account'],
        ['member-notifications', 'Notifications'],
        ['member-pause', 'Pause'],
      ]}/>

      <PageHeader title="Your profile." sub="Every change is reviewed for Spirit and tone — but lightly. The goal is your voice, not ours." right={
        <div style={{ display: 'flex', gap: 8 }}>
          <Btn kind="ghost" onClick={() => navigate('profile', me.id)}>Preview as others see it →</Btn>
          <Btn kind="primary">Save changes</Btn>
        </div>
      } />

      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '40px 56px 96px', display: 'grid', gridTemplateColumns: '300px 1fr', gap: 56 }}>
        {/* Left rail — photos */}
        <aside>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 16 }}>Photos</div>
          <div style={{ aspectRatio: '4/5', overflow: 'hidden', marginBottom: 10 }}>
            <Portrait seed={me.img} size={300} name={me.name} />
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            {[1, 2, 3].map(i => (
              <div key={i} style={{ flex: 1, aspectRatio: '1/1', background: 'var(--bg-2)', border: '1px dashed var(--line-2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.1em' }}>+ ADD</div>
            ))}
          </div>
          <Btn kind="secondary" size="sm" style={{ width: '100%', justifyContent: 'center', marginTop: 14 }}>Replace primary photo</Btn>
          <div style={{ marginTop: 28, padding: 16, background: 'var(--bg-2)', fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.55 }}>
            <strong style={{ color: 'var(--ink)' }}>Profile completeness: 92%</strong><br/>
            Add a second photo to reach 100%. Members with 2+ photos receive 3× more interest.
          </div>
        </aside>

        <div>
          {/* Testimony */}
          <div style={{ marginBottom: 40 }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 16 }}>Testimony</div>
            <textarea defaultValue={me.testimony} style={{
              ...inputStyle, minHeight: 120, fontFamily: 'var(--serif)', fontSize: 17, lineHeight: 1.55, resize: 'vertical'
            }}/>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>2–4 paragraphs is ideal. Tell the story of how you came to faith.</div>
          </div>

          {sections.map(([title, fields]) => (
            <div key={title} style={{ marginBottom: 40 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 16 }}>{title}</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                {fields.map(([label, value]) => (
                  <Field key={label} label={label}><input style={inputStyle} defaultValue={value}/></Field>
                ))}
              </div>
            </div>
          ))}

          <div style={{ marginBottom: 40 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)' }}>Character references</div>
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Optional</span>
            </div>
            <p style={{ fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.6, margin: '0 0 16px', fontStyle: 'italic' }}>
              People who know you well and have agreed to speak for your character. They don't have to be from your church — each is confirmed as a member in good standing before their words appear.
            </p>
            <div style={{ display: 'grid', gap: 10 }}>
              {me.references.map((r, i) => (
                <div key={i} style={{ background: 'var(--bg-2)', border: '1px solid var(--line)', padding: '14px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
                  <div>
                    <div className="serif" style={{ fontSize: 17, fontWeight: 600 }}>{r.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{r.relationship} · {r.church}</div>
                  </div>
                  <span className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--navy)', border: '1px solid var(--navy)', padding: '3px 8px', whiteSpace: 'nowrap' }}>✓ Confirmed</span>
                </div>
              ))}
              <button style={{ padding: '12px 18px', border: '1px dashed var(--line-2)', background: 'transparent', textAlign: 'left', fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)', cursor: 'pointer' }}>+ Invite a character reference</button>
            </div>
          </div>

          <div style={{ marginBottom: 40 }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 16 }}>Interests</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {me.interests.map(t => (
                <span key={t} style={{ padding: '6px 12px', background: 'var(--bg-2)', border: '1px solid var(--line)', fontSize: 13, fontFamily: 'var(--serif)' }}>
                  {t} <span style={{ color: 'var(--ink-3)', marginLeft: 6, cursor: 'pointer' }}>×</span>
                </span>
              ))}
              <span style={{ padding: '6px 12px', border: '1px dashed var(--line-2)', fontSize: 13, fontFamily: 'var(--mono)', color: 'var(--ink-3)', cursor: 'pointer' }}>+ ADD</span>
            </div>
          </div>
        </div>
      </div>
    </MemberShell>
  );
};

// ─── ACCOUNT SETTINGS ──────────────────────────────────────────────────
const MemberSettings = ({ tweaks, navigate }) => {
  const { Btn, Field, inputStyle } = window;
  return (
    <MemberShell tweaks={tweaks} navigate={navigate} active="member-settings">
      <SubNav active="member-settings" navigate={navigate} items={[
        ['member-profile-edit', 'Edit profile'],
        ['member-settings', 'Account'],
        ['member-notifications', 'Notifications'],
        ['member-pause', 'Pause'],
      ]}/>
      <PageHeader title="Account." sub="Sign-in details, your church, and the pastor or elder who confirms your membership." />

      <div style={{ maxWidth: 760, margin: '0 auto', padding: '40px 56px 96px' }}>
        <SettingsBlock title="Sign in">
          <Field label="Email"><input style={inputStyle} defaultValue="hannah.kemp@gmail.com" /></Field>
          <div style={{ height: 16 }}></div>
          <Field label="Password"><input style={inputStyle} type="password" defaultValue="••••••••••" /></Field>
          <div style={{ marginTop: 14 }}><Btn kind="secondary" size="sm">Change password</Btn></div>
        </SettingsBlock>

        <SettingsBlock title="Your church">
          <div style={{ background: 'var(--bg-2)', padding: 18, fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6 }}>
            <div className="serif" style={{ fontSize: 18, color: 'var(--ink)', fontWeight: 500 }}>Second Presbyterian Church</div>
            <div style={{ color: 'var(--ink-3)', fontSize: 13, fontFamily: 'var(--mono)', marginTop: 4 }}>Greenville, SC · PCA · Calvary Presbytery</div>
            <div style={{ marginTop: 12, fontSize: 13 }}>
              Commended by: <strong>Rev. Daniel M. Carrick</strong> (Senior Pastor)
            </div>
          </div>
          <div style={{ marginTop: 14, fontSize: 13, color: 'var(--ink-3)', fontStyle: 'italic' }}>
            Changed churches? <a href="#" style={{ color: 'var(--ink)' }}>Request a transfer</a> — we'll need a new commendation from your new church's leadership.
          </div>
        </SettingsBlock>

        <SettingsBlock title="Privacy">
          <Toggle label="Hide my last name from non-mutual conversations" on />
          <Toggle label="Allow elders of members in good standing to view my profile" on />
          <Toggle label="Show me to members outside my preferred regions" off />
        </SettingsBlock>

        <SettingsBlock title="Danger zone" tone="danger">
          <Btn kind="ghost" style={{ color: '#7a2727', borderColor: '#7a2727' }}>Delete my account</Btn>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 10 }}>This removes your profile and all conversations. Your church and elder will be notified.</div>
        </SettingsBlock>
      </div>
    </MemberShell>
  );
};

// ─── NOTIFICATIONS ─────────────────────────────────────────────────────
const MemberNotifications = ({ tweaks, navigate }) => (
  <MemberShell tweaks={tweaks} navigate={navigate} active="member-notifications">
    <SubNav active="member-notifications" navigate={navigate} items={[
      ['member-profile-edit', 'Edit profile'],
      ['member-settings', 'Account'],
      ['member-notifications', 'Notifications'],
      ['member-pause', 'Pause'],
    ]}/>
    <PageHeader title="Notifications." sub="Email-first by design. We'll never send you push notifications or marketing." />
    <div style={{ maxWidth: 760, margin: '0 auto', padding: '40px 56px 96px' }}>
      <SettingsBlock title="Email">
        <Toggle label="The Sunday Letter (weekly introduction)" on locked />
        <Toggle label="Someone expresses interest in you" on />
        <Toggle label="A new message arrives" on />
        <Toggle label="Mutual interest with a member" on />
        <Toggle label="Your elder writes a note about a conversation" on />
        <Toggle label="Quiet digest — daily summary at 7 am rather than per-event" off />
      </SettingsBlock>
      <SettingsBlock title="Quiet hours">
        <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-2)', marginTop: 0 }}>
          We'll hold non-urgent emails until your selected window each morning.
        </p>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 14, fontFamily: 'var(--mono)', fontSize: 13 }}>
          From <input style={{ width: 80, padding: '6px 10px', border: '1px solid var(--line-2)', background: 'var(--paper)', fontFamily: 'inherit' }} defaultValue="9:00 pm"/>
          to <input style={{ width: 80, padding: '6px 10px', border: '1px solid var(--line-2)', background: 'var(--paper)', fontFamily: 'inherit' }} defaultValue="7:00 am"/>
        </div>
      </SettingsBlock>
    </div>
  </MemberShell>
);

// ─── PAUSE / HIDE ──────────────────────────────────────────────────────
const MemberPause = ({ tweaks, navigate }) => {
  const { Btn } = window;
  return (
    <MemberShell tweaks={tweaks} navigate={navigate} active="member-pause">
      <SubNav active="member-pause" navigate={navigate} items={[
        ['member-profile-edit', 'Edit profile'],
        ['member-settings', 'Account'],
        ['member-notifications', 'Notifications'],
        ['member-pause', 'Pause'],
      ]}/>
      <PageHeader title="Pause your profile." sub="Step away for a season — for a courtship, a hard providence, or simply rest. Your conversations resume when you do." />
      <div style={{ maxWidth: 760, margin: '0 auto', padding: '40px 56px 96px' }}>
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: 32 }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 16 }}>While paused</div>
          <ul style={{ paddingLeft: 18, fontSize: 15, lineHeight: 1.7, color: 'var(--ink-2)', marginTop: 0 }}>
            <li>Your profile is hidden from the directory and from Sunday Letters.</li>
            <li>Existing mutual-interest conversations remain open if you wish.</li>
            <li>You can return any time. Your elder is not notified unless you ask.</li>
          </ul>

          <div style={{ marginTop: 32 }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 12 }}>Reason (optional, never shown)</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {["I'm in a courtship", "Taking a break", "Health / family", "Just a rest", "Other"].map(r => (
                <button key={r} style={{
                  padding: '8px 14px', border: '1px solid var(--line-2)', background: 'transparent',
                  fontFamily: 'var(--serif)', fontSize: 14, cursor: 'pointer', color: 'var(--ink-2)'
                }}>{r}</button>
              ))}
            </div>
          </div>

          <div style={{ marginTop: 32, display: 'flex', gap: 10 }}>
            <Btn kind="primary">Pause my profile</Btn>
            <Btn kind="ghost" onClick={() => navigate('member-home')}>Cancel</Btn>
          </div>
        </div>
      </div>
    </MemberShell>
  );
};

// ─── MUTUAL MATCHES ────────────────────────────────────────────────────
const MemberMatches = ({ tweaks, navigate }) => {
  const { Btn, Portrait, Badge } = window;
  const mutual = [window.HMN_DATA.MEMBERS[1]]; // Caleb
  const youInterested = [window.HMN_DATA.MEMBERS[3], window.HMN_DATA.MEMBERS[5]]; // Andrew, Samuel
  const interestedInYou = [window.HMN_DATA.MEMBERS[2]]; // Margaret (cross-sex unrealistic, but it's mock)

  const Block = ({ title, sub, items, cta }) => (
    <div style={{ marginBottom: 56 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 20, paddingBottom: 12, borderBottom: '1px solid var(--line)' }}>
        <div>
          <h2 className="serif" style={{ fontSize: 26, fontWeight: 500, margin: 0 }}>{title}</h2>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>{sub}</div>
        </div>
        <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', letterSpacing: '0.1em' }}>{items.length}</span>
      </div>
      {items.length === 0
        ? <div style={{ padding: '32px 0', fontSize: 14, color: 'var(--ink-3)', fontStyle: 'italic' }}>None yet.</div>
        : <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {items.map(m => (
              <div key={m.id} onClick={() => navigate('profile', m.id)} style={{
                background: 'var(--paper)', border: '1px solid var(--line)', cursor: 'pointer',
                display: 'grid', gridTemplateColumns: '90px 1fr', gap: 0
              }}>
                <div style={{ width: 90, height: 110 }}><Portrait seed={m.img} size={90} name={m.name} /></div>
                <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                  <div>
                    <h3 className="serif" style={{ fontSize: 18, fontWeight: 500, margin: 0 }}>{m.name}, {m.age}</h3>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)', marginTop: 2 }}>{m.location.split(',')[0]}</div>
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>{cta}</div>
                </div>
              </div>
            ))}
          </div>
      }
    </div>
  );

  return (
    <MemberShell tweaks={tweaks} navigate={navigate} active="member-matches">
      <PageHeader eyebrow="Mutual & open" title="Where things stand." sub="A quiet record of who you've expressed interest in, and who has expressed interest in you." />
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '40px 56px 96px' }}>
        <Block title="Mutual interest" sub="Both of you said yes. Conversations are open." items={mutual} cta="Continue conversation →" />
        <Block title="You expressed interest" sub="Awaiting their reply. We'll let you know either way." items={youInterested} cta="Pending" />
        <Block title="Expressed interest in you" sub="Read the profile, then decide." items={interestedInYou} cta="Open profile →" />
      </div>
    </MemberShell>
  );
};

// ─── helpers ───────────────────────────────────────────────────────────
const SettingsBlock = ({ title, children, tone }) => (
  <div style={{ marginBottom: 36, paddingBottom: 36, borderBottom: '1px solid var(--line)' }}>
    <h2 className="serif" style={{ fontSize: 22, fontWeight: 500, margin: '0 0 18px', color: tone === 'danger' ? '#7a2727' : 'var(--ink)' }}>{title}</h2>
    {children}
  </div>
);

const Toggle = ({ label, on, locked }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderTop: '1px solid var(--line)' }}>
    <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{label}</div>
    <div style={{
      width: 36, height: 20, borderRadius: 10, padding: 2,
      background: on ? 'var(--ink)' : 'var(--line-2)', cursor: locked ? 'not-allowed' : 'pointer',
      opacity: locked ? 0.6 : 1, position: 'relative'
    }}>
      <div style={{
        width: 16, height: 16, borderRadius: 8, background: 'var(--paper)',
        transform: on ? 'translateX(16px)' : 'translateX(0)', transition: 'transform 150ms'
      }}></div>
    </div>
  </div>
);

Object.assign(window, { MemberHome, MemberInbox, MemberThread, MemberProfileEdit, MemberSettings, MemberNotifications, MemberPause, MemberMatches });
