// Unified application entry point — branches between member application and church onboarding

const Apply = ({ tweaks, navigate }) => {
  const { Nav, Footer, Btn, SectionLabel } = window;
  // mode: null | 'self-has-church' | 'self-no-church' | 'church'
  // step:
  //   null               → choice 1: for yourself or for your church
  //   'has-church?'      → choice 2: does your church already have an account
  //   then renders the appropriate sub-flow
  const [stage, setStage] = React.useState('who'); // 'who' | 'has-church' | 'flow'
  const [path, setPath] = React.useState(null); // 'member-existing' | 'member-new-church' | 'church-only'

  const choose = (p) => {setPath(p);setStage('flow');window.scrollTo(0, 0);};
  const restart = () => {setStage('who');setPath(null);window.scrollTo(0, 0);};

  if (stage === 'flow' && path === 'member-existing') {
    return <window.Signup tweaks={tweaks} navigate={navigate} onBack={restart} />;
  }
  if (stage === 'flow' && path === 'member-new-church') {
    return <window.SignupWithChurch tweaks={tweaks} navigate={navigate} onBack={restart} />;
  }
  if (stage === 'flow' && path === 'church-only') {
    return <window.Church tweaks={tweaks} navigate={navigate} onBack={restart} />;
  }

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

      {/* Forks */}
      <section>
        <div style={{ maxWidth: 1100, margin: '0 auto', padding: '96px 56px' }}>

          {stage === 'who' &&
          <ForkScreen
            eyebrow="Request to join"
            title="Who are you applying for?"
            subtitle=""
            options={[
            {
              k: 'self',
              label: "For myself",
              blurb: "I'm an unmarried Christian seeking marriage, and I'd like to join the network as a member.",
              cta: "I'm applying as a member",
              onClick: () => {setStage('has-church');window.scrollTo(0, 0);}
            },
            {
              k: 'church',
              label: "For my church",
              blurb: "I'm a pastor, elder, or member helping our congregation become an approved partner church.",
              cta: "Onboard my church",
              onClick: () => choose('church-only')
            }]
            } />

          }

          {stage === 'has-church' &&
          <ForkScreen
            eyebrow=""
            title="Is your church already a partner?"
            subtitle="Members must be commended by a pastor or elder at an approved partner church — confirmed as members in good standing, and known to be mature and godly. If yours isn't yet on our list, you can submit it for review as part of your application — we review each church against our doctrinal basis before approving."
            backTo={() => setStage('who')}
            options={[
            {
              k: 'yes',
              label: "Yes, my church is already a partner",
              blurb: "I'll search for it by name on the next step. My pastor or elder will be emailed a short commendation form.",
              cta: "Continue as a member",
              onClick: () => choose('member-existing')
            },
            {
              k: 'no',
              label: "No — or I'm not sure",
              blurb: "We'll take your application and request a 30-minute call with your pastor to consider your church for the network. Both reviews run in parallel.",
              cta: "Apply & submit my church for review",
              onClick: () => choose('member-new-church')
            },
            {
              k: 'check',
              label: "Let me check first",
              blurb: "Browse the list of currently approved partner churches before deciding.",
              cta: "See partner churches →",
              onClick: () => navigate('churches'),
              ghost: true
            }]
            } />

          }
        </div>
      </section>

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

};

const ForkScreen = ({ eyebrow, title, subtitle, options, backTo }) => {
  const { Btn } = window;
  return (
    <div>
      {backTo &&
      <button onClick={backTo} 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
      }}>← Back</button>
      }
      {eyebrow && <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 14 }}>{eyebrow}</div>}
      <h2 className="serif" style={{ fontSize: 44, lineHeight: 1.08, fontWeight: 500, margin: 0, textWrap: 'balance' }}>{title}</h2>
      {subtitle && <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--ink-2)', maxWidth: 680, marginTop: 18, textWrap: 'pretty' }} data-comment-anchor="32afe4eee3-p-111-20">{subtitle}</p>}

      <div style={{
        display: 'grid',
        gridTemplateColumns: options.length === 3 ? 'repeat(3, 1fr)' : 'repeat(2, 1fr)',
        gap: 20,
        marginTop: 48
      }}>
        {options.map((o) =>
        <button key={o.k} onClick={o.onClick} style={{
          textAlign: 'left',
          background: o.ghost ? 'transparent' : 'var(--paper)',
          border: '1px solid ' + (o.ghost ? 'var(--line)' : 'var(--line-2)'),
          padding: '36px 32px 32px',
          cursor: 'pointer',
          fontFamily: 'inherit',
          transition: 'border-color 120ms, transform 120ms',
          display: 'flex', flexDirection: 'column', minHeight: 240
        }}
        onMouseEnter={(e) => {e.currentTarget.style.borderColor = 'var(--ink)';e.currentTarget.style.transform = 'translateY(-2px)';}}
        onMouseLeave={(e) => {e.currentTarget.style.borderColor = o.ghost ? 'var(--line)' : 'var(--line-2)';e.currentTarget.style.transform = 'translateY(0)';}}>
          
            <div className="serif" style={{ fontSize: 26, fontWeight: 500, lineHeight: 1.2, marginBottom: 14, textWrap: 'balance' }}>{o.label}</div>
            <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-2)', flex: 1, textWrap: 'pretty' }}>{o.blurb}</div>
            <div style={{ marginTop: 24, paddingTop: 18, borderTop: '1px solid var(--line)',
            fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase',
            color: 'var(--ink)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span>{o.cta}</span>
              <span style={{ fontFamily: 'var(--serif)', fontSize: 22, fontStyle: 'italic' }}>→</span>
            </div>
          </button>
        )}
      </div>
    </div>);

};

// Combined member + church onboarding flow (used when applicant's church is not yet a partner)
const SignupWithChurch = ({ tweaks, navigate, onBack }) => {
  const { Nav, Footer, Btn, Field, SectionLabel, inputStyle } = window;
  const [step, setStep] = React.useState(1);
  const [elderSameAsPastor, setElderSameAsPastor] = React.useState(true);
  const [data, setData] = React.useState({
    // about you
    firstName: '', lastName: '', age: '', sex: 'male', email: '',
    // your church (to be onboarded)
    churchName: '', churchCity: '', churchState: '', presbytery: '',
    pastorName: '', pastorTitle: 'Senior Pastor', pastorEmail: '', pastorPhone: '',
    // your elder/vouching
    elderName: '', elderEmail: '', elderRelation: '',
    // witness
    catechism: 'wsc', readiness: '', relocate: 'open', testimony: ''
  });
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const STEPS = ["You", "Your Church", "Primary Pastor", "Commendation", "Your Witness", "Review"];

  return (
    <div>
      <Nav tweaks={tweaks} navigate={navigate} active="apply" />
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '64px 56px 96px' }}>
        <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: 32
        }}>← Change path</button>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 80 }}>
          <aside style={{ position: 'sticky', top: 100, alignSelf: 'flex-start' }}>
            <SectionLabel num="">Member + Church Application</SectionLabel>
            <h1 className="serif" style={{ fontSize: 40, lineHeight: 1.08, fontWeight: 500, margin: 0, textWrap: 'balance' }}>
              Two requests, <em>one form.</em>
            </h1>
            <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-3)', marginTop: 20, textWrap: 'pretty' }}>
              We'll process your member application and reach out to your pastor to begin reviewing your church for the network. The two move in parallel — though your membership depends on your church being approved.
            </p>
            <div style={{ marginTop: 40 }}>
              {STEPS.map((s, i) => {
                const n = i + 1;
                const done = n < step;
                const active = n === step;
                return (
                  <div key={s} style={{ display: 'flex', gap: 16, alignItems: 'center', padding: '10px 0', opacity: done || active ? 1 : 0.5 }}>
                    <span style={{
                      width: 26, height: 26, borderRadius: '50%',
                      border: '1px solid ' + (active || done ? 'var(--ink)' : 'var(--line-2)'),
                      background: done ? 'var(--ink)' : 'transparent',
                      color: done ? 'var(--paper)' : active ? 'var(--ink)' : 'var(--ink-3)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'var(--mono)', fontSize: 11
                    }}>{done ? '✓' : n}</span>
                    <span style={{
                      fontFamily: 'var(--serif)', fontSize: 17, fontStyle: active ? 'italic' : 'normal',
                      fontWeight: active ? 600 : 500
                    }}>{s}</span>
                  </div>);

              })}
            </div>
          </aside>

          <main style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: '48px 56px' }}>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 6 }}>
              Step {step} of {STEPS.length}
            </div>
            <h2 className="serif" style={{ fontSize: 32, fontWeight: 500, margin: '0 0 32px' }}>{STEPS[step - 1]}</h2>

            {step === 1 && <window.StepYou data={data} set={set} />}

            {step === 2 &&
            <div>
                <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, marginTop: -16, marginBottom: 28, fontStyle: 'italic' }}>
                  Tell us a little about your home congregation. Our team will follow up with your pastor to schedule a 30-minute call before formally approving the church.
                </p>
                <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>
            }

            {step === 3 &&
            <div>
                <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, marginTop: -16, marginBottom: 28, fontStyle: 'italic' }}>
                  We'll email this person to introduce ourselves and propose times for a video call. They don't need to know about your application yet — we'll explain the network first.
                </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>
              </div>
            }

            {step === 4 &&
            <div>
                <Field label="Is the pastor or elder who will commend you the same as the primary pastor above?" required>
                  <div style={{ display: 'flex', gap: 8 }}>
                    {[['yes', 'Yes, same person'], ['no', 'No, someone else']].map(([v, l]) =>
                  <button key={v} onClick={() => setElderSameAsPastor(v === 'yes')} style={{
                    flex: 1, padding: '11px 14px', background: elderSameAsPastor && v === 'yes' || !elderSameAsPastor && v === 'no' ? 'var(--ink)' : 'var(--paper)',
                    color: elderSameAsPastor && v === 'yes' || !elderSameAsPastor && v === 'no' ? 'var(--paper)' : 'var(--ink)',
                    border: '1px solid ' + (elderSameAsPastor && v === 'yes' || !elderSameAsPastor && v === 'no' ? 'var(--ink)' : 'var(--line-2)'),
                    fontFamily: 'var(--sans)', fontSize: 14, borderRadius: 2
                  }}>{l}</button>
                  )}
                  </div>
                </Field>

                {elderSameAsPastor &&
              <p style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 20, fontStyle: 'italic', lineHeight: 1.6, background: 'var(--bg-2)', padding: 20 }}>
                    Great — once your church is approved, we'll send the commendation form to <strong style={{ color: 'var(--ink)' }}>{data.pastorName || 'the primary pastor'}</strong>.
                  </p>
              }

                {!elderSameAsPastor &&
              <>
                    <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, marginTop: 20, marginBottom: 28, fontStyle: 'italic' }}>
                      This could be another pastor or elder who knows you personally. Once your church is approved, we'll send them the commendation form for your application.
                    </p>
                    <Field label="Confirming pastor or elder's name" required><input style={inputStyle} value={data.elderName} onChange={(e) => set('elderName', e.target.value)} placeholder="Rev. Daniel M. Carrick" /></Field>
                    <Field label="Their email" required><input style={inputStyle} type="email" value={data.elderEmail} onChange={(e) => set('elderEmail', e.target.value)} placeholder="dcarrick@2ndpres.org" /></Field>
                  </>
              }
              </div>
            }

            {step === 5 && <window.StepWitness data={data} set={set} />}

            {step === 6 &&
            <div>
                <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, marginTop: -16, marginBottom: 28, fontStyle: 'italic' }}>
                  When you submit, two things happen in parallel: our team emails <strong style={{ color: 'var(--ink)' }}>{data.pastorName || 'your pastor'}</strong> to begin reviewing the church for the network, and once the church is approved we send the commendation form to <strong style={{ color: 'var(--ink)' }}>{data.elderName || 'your elder'}</strong>.
                </p>
                <div style={{ borderTop: '1px solid var(--line)' }}>
                  {[
                ["Name", `${data.firstName} ${data.lastName}`],
                ["Age / Sex", [data.age, data.sex].filter(Boolean).join(' · ')],
                ["Email", data.email],
                ["Church", `${data.churchName}${data.churchCity ? ' — ' + data.churchCity + ', ' + data.churchState : ''}`],
                ["Denomination", data.presbytery],
                ["Primary pastor", `${data.pastorName} (${data.pastorTitle})`],
                ["Commended by", data.elderName],
                ["Catechism", data.catechism],
                ["Relocation", data.relocate]].
                map(([l, v]) =>
                <div key={l} style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 24, padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
                      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{l}</div>
                      <div style={{ fontSize: 15, color: 'var(--ink)' }}>{v || <em style={{ color: 'var(--ink-3)' }}>—</em>}</div>
                    </div>
                )}
                </div>
              </div>
            }

            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 48, paddingTop: 28, borderTop: '1px solid var(--line)' }}>
              <Btn kind="ghost" onClick={() => step > 1 ? setStep(step - 1) : onBack()}>
                ← {step > 1 ? "Back" : "Cancel"}
              </Btn>
              {step < STEPS.length && <Btn kind="primary" onClick={() => setStep(step + 1)}>Continue →</Btn>}
              {step === STEPS.length && <Btn kind="accent" onClick={() => navigate('signup-done')}>Submit application</Btn>}
            </div>
          </main>
        </div>
      </div>
      <Footer tweaks={tweaks} navigate={navigate} />
    </div>);

};

Object.assign(window, { Apply, SignupWithChurch });