// Church onboarding flow — for pastors/elders/members to apply on behalf of their church

const Church = ({ tweaks, navigate, onBack }) => {
  const { Nav, Footer, Btn, Field, SectionLabel, Badge, inputStyle } = window;
  const [submitted, setSubmitted] = React.useState(false);
  const [submitterIsPrimary, setSubmitterIsPrimary] = React.useState(true);
  const [data, setData] = React.useState({
    submitterName: '', submitterRole: 'pastor', submitterEmail: '',
    churchName: '', churchCity: '', churchState: '', presbytery: '',
    pastorName: '', pastorTitle: 'Senior Pastor', pastorEmail: '', pastorPhone: '',
    sessionSize: '', singlesEstimate: '', notes: ''
  });
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));

  // When submitterIsPrimary changes, sync data
  React.useEffect(() => {
    if (submitterIsPrimary) {
      set('pastorName', data.submitterName);
      set('pastorEmail', data.submitterEmail);
    }
  }, [submitterIsPrimary]);

  const isPastorOrElder = data.submitterRole === 'pastor' || data.submitterRole === 'elder';

  if (submitted) return <ChurchSubmitted tweaks={tweaks} navigate={navigate} data={data} />;

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

      {/* Header */}
      <section style={{ borderBottom: '1px solid var(--line)' }}>
        <div style={{ maxWidth: 1100, margin: '0 auto', padding: '72px 56px 56px' }}>
          {onBack &&
          <button onClick={onBack} style={{
            background: 'none', border: 'none', padding: 0, cursor: 'pointer',
            fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
            color: 'var(--ink-3)', marginBottom: 24
          }}>← Change path</button>
          }
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 64, alignItems: 'end' }}>
            <h1 className="serif" style={{ fontSize: 64, lineHeight: 1.04, fontWeight: 500, margin: 0, textWrap: 'balance' }}>
              Onboard your church <em>to the Network.</em>
            </h1>
            <p style={{ fontSize: 16, lineHeight: 1.65, color: 'var(--ink-2)', margin: 0, textWrap: 'pretty' }}>Anyone can submit this form — a pastor, elder, or member. We'll then schedule a 30-minute video call with a pastor or elder to walk through the mission and answer questions before approving the church.

            </p>
          </div>
        </div>
      </section>

      {/* Form + sidebar */}
      <section>
        <div style={{ maxWidth: 1100, margin: '0 auto', padding: '64px 56px 96px', display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 64 }}>

          <main style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: '48px 56px' }}>

            <FormSection title="About you">
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                <Field label="Your name" required><input style={inputStyle} value={data.submitterName} onChange={(e) => set('submitterName', e.target.value)} placeholder="John Marshall" /></Field>
                <Field label="Your email" required><input style={inputStyle} type="email" value={data.submitterEmail} onChange={(e) => set('submitterEmail', e.target.value)} placeholder="john@example.com" /></Field>
              </div>
              <Field label="Your role at the church" required>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
                  {[['pastor', 'Pastor'], ['elder', 'Elder'], ['deacon', 'Deacon'], ['member', 'Member']].map(([v, l]) =>
                  <button key={v} onClick={() => set('submitterRole', v)} style={{
                    padding: '11px 12px', background: data.submitterRole === v ? 'var(--ink)' : 'var(--paper)',
                    color: data.submitterRole === v ? 'var(--paper)' : 'var(--ink)',
                    border: '1px solid ' + (data.submitterRole === v ? 'var(--ink)' : 'var(--line-2)'),
                    fontFamily: 'var(--sans)', fontSize: 13, borderRadius: 2
                  }}>{l}</button>
                  )}
                </div>
              </Field>
            </FormSection>

            <FormSection title="The church">
              <Field label="Church name" required><input style={inputStyle} value={data.churchName} onChange={(e) => set('churchName', e.target.value)} placeholder="Second Presbyterian Church" /></Field>
              <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 20 }}>
                <Field label="City" required><input style={inputStyle} value={data.churchCity} onChange={(e) => set('churchCity', e.target.value)} placeholder="Greenville" /></Field>
                <Field label="State" required><input style={inputStyle} value={data.churchState} onChange={(e) => set('churchState', e.target.value)} placeholder="SC" /></Field>
                <Field label="Denomination" required><input style={inputStyle} value={data.presbytery} onChange={(e) => set('presbytery', e.target.value)} placeholder="PCA, OPC, URCNA…" /></Field>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                <Field label="Approx. leadership size"><input style={inputStyle} value={data.sessionSize} onChange={(e) => set('sessionSize', e.target.value)} placeholder="12 elders" data-comment-anchor="2aa948d540-input-85-56" /></Field>
                <Field label="Approx. singles 18+"><input style={inputStyle} value={data.singlesEstimate} onChange={(e) => set('singlesEstimate', e.target.value)} placeholder="40" /></Field>
              </div>
            </FormSection>

            <FormSection title="Primary pastor or elder">
              {isPastorOrElder &&
              <Field label="Are you the primary contact for this call?" required>
                  <div style={{ display: 'flex', gap: 8 }}>
                    {[['yes', 'Yes, contact me'], ['no', 'No, contact someone else']].map(([v, l]) =>
                  <button key={v} onClick={() => setSubmitterIsPrimary(v === 'yes')} style={{
                    flex: 1, padding: '11px 14px', background: submitterIsPrimary && v === 'yes' || !submitterIsPrimary && v === 'no' ? 'var(--ink)' : 'var(--paper)',
                    color: submitterIsPrimary && v === 'yes' || !submitterIsPrimary && v === 'no' ? 'var(--paper)' : 'var(--ink)',
                    border: '1px solid ' + (submitterIsPrimary && v === 'yes' || !submitterIsPrimary && v === 'no' ? 'var(--ink)' : 'var(--line-2)'),
                    fontFamily: 'var(--sans)', fontSize: 14, borderRadius: 2
                  }}>{l}</button>
                  )}
                  </div>
                </Field>
              }

              {(!isPastorOrElder || !submitterIsPrimary) &&
              <>
                  <p style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: isPastorOrElder ? 20 : -8, marginBottom: 20, fontStyle: 'italic', lineHeight: 1.5 }}>
                    We'll email this person to schedule a brief video call. Other leaders who haven't been informed yet — that's fine. We'll loop them in gently.
                  </p>
                  <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20 }}>
                    <Field label="Name" required><input style={inputStyle} value={data.pastorName} onChange={(e) => set('pastorName', e.target.value)} placeholder="Rev. Daniel M. Carrick" /></Field>
                    <Field label="Title" required>
                      <select style={inputStyle} value={data.pastorTitle} onChange={(e) => set('pastorTitle', e.target.value)}>
                        <option>Senior Pastor</option><option>Associate Pastor</option><option>Assistant Pastor</option><option>Elder (Board Chair)</option><option>Elder</option>
                      </select>
                    </Field>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                    <Field label="Email" required><input style={inputStyle} type="email" value={data.pastorEmail} onChange={(e) => set('pastorEmail', e.target.value)} placeholder="dcarrick@2ndpres.org" /></Field>
                    <Field label="Phone (optional)"><input style={inputStyle} value={data.pastorPhone} onChange={(e) => set('pastorPhone', e.target.value)} placeholder="(864) 555-0182" /></Field>
                  </div>
                </>
              }

              {isPastorOrElder && submitterIsPrimary &&
              <p style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 20, fontStyle: 'italic', lineHeight: 1.6, background: 'var(--bg-2)', padding: 20 }}>
                  Great — we'll email <strong style={{ color: 'var(--ink)' }}>{data.submitterEmail || 'you'}</strong> to schedule the call.
                </p>
              }
            </FormSection>

            <FormSection title="Anything we should know?" last>
              <Field label="Notes for our team">
                <textarea style={{ ...inputStyle, minHeight: 110, resize: 'vertical', fontFamily: 'var(--serif)', fontSize: 16, lineHeight: 1.5 }}
                value={data.notes} onChange={(e) => set('notes', e.target.value)}
                placeholder="Our elders have discussed this and are enthusiastic. Three of us have read the FAQ already..." />
              </Field>
            </FormSection>

            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 32 }}>
              <Btn kind="ghost" onClick={() => onBack ? onBack() : navigate('landing')}>← Cancel</Btn>
              <Btn kind="accent" onClick={() => setSubmitted(true)}>Submit application</Btn>
            </div>
          </main>

          <aside style={{ position: 'sticky', top: 100, alignSelf: 'flex-start' }}>
            <div style={{ background: 'var(--bg-2)', padding: 28, borderTop: '2px solid var(--ink)' }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 16 }}>What happens next</div>
              {[
              ["Within 48 hours", "We email your pastor or elder to introduce ourselves and propose times for a call."],
              ["The call (≈30 min)", "Two of the Magnalia team — one of whom is an ordained pastor — meet with the elder. We answer doctrinal questions and confirm mission alignment."],
              ["Approval", "If your leadership affirms, we activate the church. Members can then request to join."],
              ["No cost", "There is no fee to onboard, ever. We are funded by donors."]].
              map(([t, d]) =>
              <div key={t} style={{ marginBottom: 18 }}>
                  <div className="serif" style={{ fontSize: 17, fontWeight: 600, marginBottom: 4 }}>{t}</div>
                  <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55 }}>{d}</div>
                </div>
              )}
            </div>
          </aside>
        </div>
      </section>

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

};

const FormSection = ({ title, children, last }) =>
<div style={{ marginBottom: last ? 0 : 36, paddingBottom: last ? 0 : 36, borderBottom: last ? 'none' : '1px solid var(--line)' }}>
    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 22 }}>{title}</div>
    {children}
  </div>;


const ChurchSubmitted = ({ tweaks, navigate, data }) => {
  const { Nav, Footer, Btn } = window;
  return (
    <div>
      <Nav tweaks={tweaks} navigate={navigate} active="" />
      <div style={{ maxWidth: 720, margin: '0 auto', padding: '120px 56px 80px', textAlign: 'center' }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 24 }}>Application received</div>
        <h1 className="serif" style={{ fontSize: 56, lineHeight: 1.08, fontWeight: 500, margin: 0, textWrap: 'balance' }}>
          Thank you. We'll be in touch <em>soon</em>.
        </h1>
        <p style={{ fontSize: 17, lineHeight: 1.65, color: 'var(--ink-2)', marginTop: 28 }}>
          We've logged the application for <strong style={{ color: 'var(--ink)' }}>{data.churchName || 'your church'}</strong>. Within 48 hours, our team will email <strong style={{ color: 'var(--ink)' }}>{data.pastorName || 'your primary pastor'}</strong> to introduce ourselves and propose times for a 30-minute video call.
        </p>
        <div style={{ marginTop: 44, textAlign: 'left', padding: 28, background: 'var(--paper)', border: '1px solid var(--line)' }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 16 }}>Receipt</div>
          {[
          ['Submitted by', `${data.submitterName} (${data.submitterRole})`],
          ['Church', `${data.churchName} — ${data.churchCity}, ${data.churchState}`],
          ['Denomination', data.presbytery],
          ['Primary contact', `${data.pastorName} (${data.pastorTitle})`],
          ['Reference #', 'HMN-2026-0287']].
          map(([l, v]) =>
          <div key={l} style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 16, padding: '8px 0', borderBottom: '1px solid var(--line)', fontSize: 14 }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>{l}</span>
              <span>{v}</span>
            </div>
          )}
        </div>
        <div style={{ marginTop: 32, display: 'flex', gap: 12, justifyContent: 'center' }}>
          <Btn kind="secondary" onClick={() => navigate('landing')}>Return home</Btn>
          <Btn kind="primary" onClick={() => navigate('browse')}>See sample profiles</Btn>
        </div>
      </div>
      <Footer tweaks={tweaks} navigate={navigate} />
    </div>);

};

Object.assign(window, { Church, FormSection });