// Browse / directory + algorithmic intro

const Browse = ({ tweaks, navigate }) => {
  const { Nav, Footer, Btn, Badge, Portrait, SectionLabel } = window;
  const [mode, setMode] = React.useState('directory'); // directory | introduction | suggestions
  const [filters, setFilters] = React.useState({ sex: 'any', ageMin: 22, ageMax: 35, region: 'any', presbytery: 'any', relocate: 'any' });
  const [sort, setSort] = React.useState('recent');

  const members = window.HMN_DATA.MEMBERS;

  return (
    <div>
      <Nav tweaks={tweaks} navigate={navigate} active="browse" />

      {/* Sub-header with mode toggle */}
      <section style={{ borderBottom: '1px solid var(--line)', background: 'var(--paper)' }}>
        <div style={{ maxWidth: 1240, margin: '0 auto', padding: '40px 56px 0' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <SectionLabel num="">The Network</SectionLabel>
              <h1 className="serif" style={{ fontSize: 44, lineHeight: 1.05, fontWeight: 500, margin: 0 }}>
                Browse, search, or receive an <em>introduction.</em>
              </h1>
            </div>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', color: 'var(--ink-3)', marginTop: 12 }}>
              Signed in as <span style={{ color: 'var(--ink)' }}>Caleb R.</span> · Commended
            </div>
          </div>

          <div style={{ display: 'flex', gap: 0, marginTop: 32, marginBottom: -1 }}>
            {[
              ['directory', 'Directory', `${members.length} members`],
              ['introduction', 'This week’s introduction', 'A curated match'],
              ['suggestions', 'Suggested for you', '14 candidates'],
            ].map(([id, label, sub]) => (
              <button key={id} onClick={() => setMode(id)} style={{
                background: mode === id ? 'var(--bg)' : 'transparent',
                border: '1px solid ' + (mode === id ? 'var(--line)' : 'transparent'),
                borderBottom: mode === id ? '1px solid var(--bg)' : '1px solid var(--line)',
                padding: '14px 24px', cursor: 'pointer', fontFamily: 'var(--sans)',
                textAlign: 'left', minWidth: 240, whiteSpace: 'nowrap'
              }}>
                <div className="serif" style={{ fontSize: 19, fontWeight: 500, color: mode === id ? 'var(--ink)' : 'var(--ink-3)' }}>{label}</div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-3)', marginTop: 2, textTransform: 'uppercase' }}>{sub}</div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {mode === 'directory' && <Directory members={members} filters={filters} setFilters={setFilters} sort={sort} setSort={setSort} navigate={navigate} />}
      {mode === 'introduction' && <Introduction member={members[0]} navigate={navigate} />}
      {mode === 'suggestions' && <Suggestions members={members} navigate={navigate} />}

      <Footer tweaks={tweaks} navigate={navigate} />
    </div>
  );
};

const Directory = ({ members, filters, setFilters, sort, setSort, navigate }) => {
  const { Btn, Badge, Portrait } = window;
  const set = (k, v) => setFilters({ ...filters, [k]: v });

  return (
    <section>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '48px 56px 96px', display: 'grid', gridTemplateColumns: '260px 1fr', gap: 56 }}>
        {/* Filters */}
        <aside style={{ position: 'sticky', top: 90, alignSelf: 'flex-start' }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 16 }}>Filter</div>

          <FilterGroup title={`Age · ${filters.ageMin}–${filters.ageMax}`}>
            <div style={{ display: 'flex', gap: 8 }}>
              <input type="number" value={filters.ageMin} onChange={e => set('ageMin', +e.target.value)}
                style={{ width: '100%', padding: '8px 10px', background: 'var(--paper)', border: '1px solid var(--line-2)', fontFamily: 'var(--mono)', fontSize: 13 }}/>
              <input type="number" value={filters.ageMax} onChange={e => set('ageMax', +e.target.value)}
                style={{ width: '100%', padding: '8px 10px', background: 'var(--paper)', border: '1px solid var(--line-2)', fontFamily: 'var(--mono)', fontSize: 13 }}/>
            </div>
          </FilterGroup>

          <FilterGroup title="Region">
            <Pills options={[['any','Any'],['se','SE'],['ne','NE'],['mw','MW'],['sw','SW'],['w','W']]} value={filters.region} onChange={v => set('region', v)} small/>
          </FilterGroup>

          <FilterGroup title="Open to relocate">
            <Pills options={[['any','Any'],['open','Open'],['regional','Regional'],['local','Local']]} value={filters.relocate} onChange={v => set('relocate', v)} />
          </FilterGroup>

          <FilterGroup title="Denomination">
            <select style={{ width: '100%', padding: '8px 10px', background: 'var(--paper)', border: '1px solid var(--line-2)', fontFamily: 'var(--sans)', fontSize: 13, borderRadius: 2 }}>
              <option>Any denomination</option>
              <optgroup label="Reformed / Presbyterian">
                <option>PCA — Presbyterian Church in America</option>
                <option>OPC — Orthodox Presbyterian Church</option>
                <option>URCNA — United Reformed Churches</option>
                <option>RPCNA — Reformed Presbyterian (Covenanter)</option>
                <option>ARP — Associate Reformed Presbyterian</option>
                <option>EPC — Evangelical Presbyterian</option>
                <option>CREC — Communion of Reformed Evangelical</option>
                <option>RCUS — Reformed Church in the U.S.</option>
                <option>HRC — Heritage Reformed</option>
              </optgroup>
              <optgroup label="Baptist">
                <option>SBC — Southern Baptist Convention</option>
                <option>ARBCA / Reformed Baptist (1689)</option>
                <option>FIRE Fellowship</option>
                <option>Independent Baptist (confessional)</option>
              </optgroup>
              <optgroup label="Anglican">
                <option>ACNA — Anglican Church in North America</option>
                <option>REC — Reformed Episcopal</option>
                <option>APA — Anglican Province of America</option>
              </optgroup>
              <optgroup label="Lutheran">
                <option>LCMS — Lutheran Church—Missouri Synod</option>
                <option>WELS — Wisconsin Evangelical Lutheran</option>
                <option>ELS — Evangelical Lutheran Synod</option>
              </optgroup>
              <optgroup label="Other confessional">
                <option>EFCA — Evangelical Free</option>
                <option>Bible Presbyterian</option>
                <option>Independent / non-denominational (confessional)</option>
              </optgroup>
            </select>
          </FilterGroup>

          <button onClick={() => setFilters({ sex: 'any', ageMin: 22, ageMax: 35, region: 'any', presbytery: 'any', relocate: 'any' })}
            style={{ background: 'none', border: 'none', padding: 0, fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--taupe)', cursor: 'pointer', marginTop: 16 }}>
            Reset filters
          </button>
        </aside>

        {/* Results */}
        <main>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 24 }}>
            <div className="serif" style={{ fontSize: 22, fontWeight: 500 }}>
              <span style={{ fontStyle: 'italic' }}>{members.length}</span> commended members
            </div>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--ink-3)', textTransform: 'uppercase' }}>Sort</span>
              <select value={sort} onChange={e => setSort(e.target.value)}
                style={{ background: 'var(--paper)', border: '1px solid var(--line-2)', padding: '6px 10px', fontFamily: 'var(--sans)', fontSize: 13, borderRadius: 2 }}>
                <option value="recent">Recently active</option>
                <option value="new">Newly joined</option>
                <option value="alpha">Alphabetical</option>
              </select>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 24 }}>
            {members.map(m => (
              <article key={m.id} onClick={() => navigate('profile', m.id)} style={{
                background: 'var(--paper)', border: '1px solid var(--line)', cursor: 'pointer',
                display: 'grid', gridTemplateColumns: '160px 1fr', transition: 'all 0.15s'
              }} onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--ink)'} onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--line)'}>
                <div style={{ width: 160, height: 200 }}>
                  <Portrait seed={m.img} size={160} name={m.name} />
                </div>
                <div style={{ padding: '18px 20px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                      <h3 className="serif" style={{ fontSize: 22, fontWeight: 500, margin: 0, lineHeight: 1.1 }}>{m.name}, {m.age}</h3>
                    </div>
                    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)', textTransform: 'uppercase', marginTop: 6 }}>
                      {m.location.split(',')[0]} · {m.presbytery.replace(' Presbytery', '')}
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5, marginTop: 12 }}>
                      {m.vocation}.
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, marginTop: 16, alignItems: 'center' }}>
                    <Badge tone="vouched">Commended</Badge>
                    <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.08em' }}>· {m.lastActive}</span>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </main>
      </div>
    </section>
  );
};

const FilterGroup = ({ title, children }) => (
  <div style={{ marginBottom: 24, paddingBottom: 24, borderBottom: '1px solid var(--line)' }}>
    <div style={{ fontFamily: 'var(--serif)', fontSize: 16, fontWeight: 500, marginBottom: 12 }}>{title}</div>
    {children}
  </div>
);

const Pills = ({ options, value, onChange, small }) => (
  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
    {options.map(([v, l]) => (
      <button key={v} onClick={() => onChange(v)} style={{
        padding: small ? '5px 10px' : '6px 12px',
        background: value === v ? 'var(--ink)' : 'transparent',
        color: value === v ? 'var(--paper)' : 'var(--ink-2)',
        border: '1px solid ' + (value === v ? 'var(--ink)' : 'var(--line-2)'),
        fontFamily: 'var(--sans)', fontSize: 12, borderRadius: 2, cursor: 'pointer'
      }}>{l}</button>
    ))}
  </div>
);

const Introduction = ({ member, navigate }) => {
  const { Btn, Badge, Portrait } = window;
  return (
    <section>
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '64px 56px 96px' }}>
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: 48, position: 'relative' }}>
          <div style={{ position: 'absolute', top: -1, left: 48, background: 'var(--paper)', padding: '0 16px' }}>
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)' }}>Week 18 · 2026</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 56, alignItems: 'start' }}>
            <div>
              <Portrait seed={member.img} size={320} name={member.name} />
              <Badge tone="vouched"><span style={{ marginRight: 4 }}>✓</span> Commended by {member.elder.split(' ').slice(-1)[0]}</Badge>
            </div>
            <div>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 12 }}>This week, we'd like you to consider</div>
              <h2 className="serif" style={{ fontSize: 56, lineHeight: 1.05, fontWeight: 500, margin: 0, textWrap: 'balance' }}>
                {member.name}, {member.age}<br/><em style={{ color: 'var(--taupe)' }}>{member.location.split(',')[0]}</em>
              </h2>
              <p className="serif" style={{ fontSize: 22, fontStyle: 'italic', lineHeight: 1.4, color: 'var(--ink-2)', marginTop: 24, textWrap: 'pretty' }}>
                {member.testimony}
              </p>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 32, fontSize: 14 }}>
                {[
                  ['Vocation', member.vocation],
                  ['Catechism', member.catechism],
                  ['Family vision', member.family],
                  ['Open to', member.relocate],
                ].map(([l, v]) => (
                  <div key={l} style={{ borderTop: '1px solid var(--line)', paddingTop: 12 }}>
                    <div className="mono" style={{ fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 4 }}>{l}</div>
                    <div style={{ color: 'var(--ink-2)' }}>{v}</div>
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', gap: 12, marginTop: 36 }}>
                <Btn kind="primary" onClick={() => navigate('profile', member.id)}>Read full profile →</Btn>
                <Btn kind="secondary">Express interest</Btn>
                <Btn kind="ghost">Not the right season</Btn>
              </div>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 32, padding: 24, background: 'var(--bg-2)', fontSize: 14, lineHeight: 1.6, color: 'var(--ink-2)', textWrap: 'pretty' }}>
          <strong style={{ color: 'var(--ink)' }}>Why we're suggesting Hannah:</strong> she is open to relocation, your presbyteries are theologically aligned, your family visions overlap, and her elder is willing to speak with yours. The introduction is a suggestion — not a verdict. Pray on it.
        </div>
      </div>
    </section>
  );
};

const Suggestions = ({ members, navigate }) => {
  const { Btn, Badge, Portrait } = window;
  return (
    <section>
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '48px 56px 96px' }}>
        <p className="serif" style={{ fontSize: 20, fontStyle: 'italic', color: 'var(--ink-2)', maxWidth: 720, lineHeight: 1.5 }}>
          Members whose answers align with what you've told us you're seeking. Updated weekly. We don't rank them — we present them.
        </p>
        <div style={{ marginTop: 40 }}>
          {members.map((m, i) => (
            <article key={m.id} onClick={() => navigate('profile', m.id)} style={{
              padding: '28px 0', borderTop: '1px solid var(--line)',
              borderBottom: i === members.length - 1 ? '1px solid var(--line)' : 'none',
              display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: 28, alignItems: 'center', cursor: 'pointer'
            }}>
              <div style={{ width: 80, height: 80 }}><Portrait seed={m.img} size={80} name={m.name} /></div>
              <div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
                  <h3 className="serif" style={{ fontSize: 26, fontWeight: 500, margin: 0 }}>{m.name}, {m.age}</h3>
                  <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-3)', textTransform: 'uppercase' }}>{m.location} · {m.presbytery.replace(' Presbytery', '')}</span>
                </div>
                <p style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55, margin: '8px 0 0', maxWidth: 640 }}>
                  {m.vocation}. {m.family.split('.')[0]}.
                </p>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--taupe)', textTransform: 'uppercase', marginBottom: 8 }}>Match note</div>
                <div className="serif" style={{ fontSize: 17, fontStyle: 'italic', color: 'var(--ink-2)' }}>{["Open to relocation", "Family vision aligns", "Same presbytery network", "Strong confessional fit", "Both pre-vocational", "Shares interests"][i % 6]}</div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Browse });
