// Signup / Request to join — used when applicant's church is already a partner

const Signup = ({ tweaks, navigate, onBack }) => {
  const { Nav, Footer, Btn, Field, SectionLabel, inputStyle } = window;
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({
    firstName: '', lastName: '', age: '', sex: 'male', email: '',
    church: '', presbytery: '', elderName: '', elderEmail: '', elderRole: 'pastor',
    catechism: 'wsc', readiness: '', relocate: 'open', testimony: '',
    ref1Name: '', ref1Email: '', ref2Name: '', ref2Email: ''
  });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

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

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

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 80 }}>
          {/* Left rail: progress */}
          <aside style={{ position: 'sticky', top: 100, alignSelf: 'flex-start' }}>
            <SectionLabel num="">Membership Request</SectionLabel>
            <h1 className="serif" style={{ fontSize: 44, lineHeight: 1.05, fontWeight: 500, margin: 0, textWrap: 'balance' }}>
              Tell us who you are <em>and</em> who can commend you.
            </h1>
            <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-3)', marginTop: 20 }}>
              Five short steps. We'll save your progress and email your pastor or elder once you finish.
            </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: '12px 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, letterSpacing: '0.04em'
                    }}>{done ? '✓' : n}</span>
                    <span style={{
                      fontFamily: 'var(--serif)', fontSize: 19, fontStyle: active ? 'italic' : 'normal',
                      fontWeight: active ? 600 : 500
                    }}>{s}</span>
                  </div>
                );
              })}
            </div>
          </aside>

          {/* Right: form panel */}
          <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 && <StepYou data={data} set={set} />}
            {step === 2 && <StepChurch data={data} set={set} />}
            {step === 3 && <StepElder data={data} set={set} />}
            {step === 4 && <StepWitness data={data} set={set} />}
            {step === 5 && <StepReview data={data} navigate={navigate} />}

            <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 ? onBack() : navigate('landing'))}>
                ← {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 & request commendation</Btn>}
            </div>
          </main>
        </div>
      </div>
      <Footer tweaks={tweaks} navigate={navigate} />
    </div>
  );
};

const StepYou = ({ data, set }) => {
  const { Field, inputStyle } = window;
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        <Field label="First name" required><input style={inputStyle} value={data.firstName} onChange={e => set('firstName', e.target.value)} placeholder="James"/></Field>
        <Field label="Last name" required><input style={inputStyle} value={data.lastName} onChange={e => set('lastName', e.target.value)} placeholder="Marshall"/></Field>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        <Field label="Age" required><input style={inputStyle} type="number" value={data.age} onChange={e => set('age', e.target.value)} placeholder="26"/></Field>
        <Field label="Sex" required>
          <div style={{ display: 'flex', gap: 8 }}>
            {['male', 'female'].map(s => (
              <button key={s} onClick={() => set('sex', s)} style={{
                flex: 1, padding: '11px 14px', background: data.sex === s ? 'var(--ink)' : 'var(--paper)',
                color: data.sex === s ? 'var(--paper)' : 'var(--ink)',
                border: '1px solid ' + (data.sex === s ? 'var(--ink)' : 'var(--line-2)'),
                fontFamily: 'var(--sans)', fontSize: 14, textTransform: 'capitalize', borderRadius: 2
              }}>{s}</button>
            ))}
          </div>
        </Field>
      </div>
      <Field label="Email" required hint="We'll send all correspondence here."><input style={inputStyle} type="email" value={data.email} onChange={e => set('email', e.target.value)} placeholder="james.marshall@example.com"/></Field>
      <div style={{ background: 'var(--bg-2)', padding: 20, borderLeft: '2px solid var(--taupe)', marginTop: 24 }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--taupe)', marginBottom: 8 }}>Note</div>
        <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-2)' }}>
          The Help Meet Network is for unmarried members 18 or older from approved confessional Christian churches who are actively desiring marriage in the next few years and are open to children.
        </div>
      </div>
    </div>
  );
};

const StepChurch = ({ data, set }) => {
  const { Field, inputStyle } = window;
  const churches = window.HMN_DATA.CHURCHES_VOUCHED;
  const [query, setQuery] = React.useState(data.church);
  const filtered = churches.filter(c => c.name.toLowerCase().includes(query.toLowerCase())).slice(0, 5);
  return (
    <div>
      <Field label="Your home church" required hint="Type to search our list of partner churches.">
        <input style={inputStyle} value={query} onChange={e => { setQuery(e.target.value); set('church', e.target.value); }} placeholder="Second Presbyterian Church"/>
        {query && filtered.length > 0 && data.church !== filtered[0].name && (
          <div style={{ background: 'var(--paper)', border: '1px solid var(--line-2)', borderTop: 'none', marginTop: -1 }}>
            {filtered.map(c => (
              <button key={c.name} onClick={() => { set('church', c.name); set('presbytery', c.presbytery); setQuery(c.name); }}
                style={{ display: 'block', width: '100%', textAlign: 'left', padding: '10px 14px', background: 'none', border: 'none', borderBottom: '1px solid var(--line)', cursor: 'pointer', fontFamily: 'var(--sans)' }}>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{c.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{c.city} · {c.presbytery}</div>
              </button>
            ))}
          </div>
        )}
      </Field>
      <div style={{ background: 'var(--bg-2)', padding: 20, marginTop: 8, fontSize: 13, lineHeight: 1.6, color: 'var(--ink-2)' }}>
        Don't see your church? <button onClick={() => window.scrollTo(0,0)} style={{ background: 'none', border: 'none', padding: 0, color: 'var(--ink)', textDecoration: 'underline', cursor: 'pointer', font: 'inherit' }}>Ask your church leadership to onboard</button> — we'll schedule a call with your pastor and add the church within ~2 weeks.
      </div>
    </div>
  );
};

const StepElder = ({ data, set }) => {
  const { Field, inputStyle } = window;
  return (
    <div>
      <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, marginTop: -16, marginBottom: 28, fontStyle: 'italic' }}>
        Name one pastor or elder who knows you well. We'll email them a short form asking them to commend you — to confirm you're a member in good standing, and that they know you to be mature and godly, ready to pursue marriage.
      </p>
      <Field label="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 hint="We'll send the commendation form here, BCC'd to you."><input style={inputStyle} type="email" value={data.elderEmail} onChange={e => set('elderEmail', e.target.value)} placeholder="dcarrick@2ndpresgvl.org"/></Field>
    </div>
  );
};

const StepWitness = ({ data, set }) => {
  const { Field, inputStyle } = window;
  return (
    <div>
      <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, marginTop: -16, marginBottom: 28, fontStyle: 'italic' }}>
        These answers begin your profile draft. You can edit them later before publishing.
      </p>
      <Field label="Confessional familiarity" required>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {[['fluent','Confession & catechism — fluent'], ['working','Working through them'], ['familiar','Generally familiar'], ['learning','Still learning']].map(([v,l]) => (
            <button key={v} onClick={() => set('catechism', v)} style={{
              padding: '11px 12px', background: data.catechism === v ? 'var(--ink)' : 'var(--paper)',
              color: data.catechism === v ? 'var(--paper)' : 'var(--ink)',
              border: '1px solid ' + (data.catechism === v ? 'var(--ink)' : 'var(--line-2)'),
              fontFamily: 'var(--sans)', fontSize: 13, borderRadius: 2, textAlign: 'left'
            }}>{l}</button>
          ))}
        </div>
      </Field>
      <Field label="Openness to relocation" required>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          {[['open','Open anywhere'], ['regional','Regional only'], ['local','Local-only']].map(([v,l]) => (
            <button key={v} onClick={() => set('relocate', v)} style={{
              padding: '11px 12px', background: data.relocate === v ? 'var(--ink)' : 'var(--paper)',
              color: data.relocate === v ? 'var(--paper)' : 'var(--ink)',
              border: '1px solid ' + (data.relocate === v ? 'var(--ink)' : 'var(--line-2)'),
              fontFamily: 'var(--sans)', fontSize: 13, borderRadius: 2
            }}>{l}</button>
          ))}
        </div>
      </Field>
      <Field label="A short testimony of your faith" hint="2–4 sentences. Plain prose — no need to dazzle.">
        <textarea style={{ ...inputStyle, minHeight: 110, resize: 'vertical', fontFamily: 'var(--serif)', fontSize: 16, lineHeight: 1.5 }}
          value={data.testimony} onChange={e => set('testimony', e.target.value)}
          placeholder="Raised in the covenant. Came to a settled faith at 16 through a study of Romans..."/>
      </Field>
      <Field label="Why now?" hint="Why are you joining the network at this point in your life?">
        <textarea style={{ ...inputStyle, minHeight: 80, resize: 'vertical' }}
          value={data.readiness} onChange={e => set('readiness', e.target.value)}
          placeholder="I'm 26, finished with school, established in vocation, and ready to be a wife and mother."/>
      </Field>

      <div style={{ background: 'var(--bg-2)', padding: 20, borderLeft: '2px solid var(--navy)', marginTop: 8 }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--navy)', marginBottom: 8 }}>Character references — optional</div>
        <div style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--ink-2)', marginBottom: 20 }}>
          Friends, family, or mentors who know you well and can speak to your character. They needn't be from your church — each will be asked to write a short reference, and their own membership will be confirmed before it's published. You can add or change these anytime.
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <Field label="Reference 1 — name"><input style={inputStyle} value={data.ref1Name} onChange={e => set('ref1Name', e.target.value)} placeholder="Rachel Donovan"/></Field>
          <Field label="Reference 1 — email"><input style={inputStyle} type="email" value={data.ref1Email} onChange={e => set('ref1Email', e.target.value)} placeholder="rachel@example.com"/></Field>
          <Field label="Reference 2 — name"><input style={inputStyle} value={data.ref2Name} onChange={e => set('ref2Name', e.target.value)} placeholder="(optional)"/></Field>
          <Field label="Reference 2 — email"><input style={inputStyle} type="email" value={data.ref2Email} onChange={e => set('ref2Email', e.target.value)} placeholder="(optional)"/></Field>
        </div>
      </div>
    </div>
  );
};

const StepReview = ({ data, navigate }) => {
  const row = (l, v) => (
    <div 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>
  );
  return (
    <div>
      <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, marginTop: -16, marginBottom: 28, fontStyle: 'italic' }}>
        Review your submission. When you click submit, we'll email <strong style={{ color: 'var(--ink)' }}>{data.elderName || 'your pastor or elder'}</strong> a short commendation form.
      </p>
      <div style={{ borderTop: '1px solid var(--line)' }}>
        {row("Name", `${data.firstName} ${data.lastName}`)}
        {row("Age / Sex", [data.age, data.sex].filter(Boolean).join(' · '))}
        {row("Email", data.email)}
        {row("Church", data.church)}
        {row("Denomination", data.presbytery)}
        {row("Commended by", data.elderName)}
        {row("Their email", data.elderEmail)}
        {row("Catechism", data.catechism)}
        {row("Relocation", data.relocate)}
        {row("Character references", [data.ref1Name, data.ref2Name].filter(Boolean).join(' · '))}
      </div>
      <div style={{ marginTop: 28, background: 'var(--bg-2)', padding: 20, fontSize: 14, lineHeight: 1.6, color: 'var(--ink-2)' }}>
        <strong>What happens next:</strong> your pastor or elder receives an email today. Once they commend you (typically within a week), we'll guide you through publishing your profile. Any references you named are contacted separately. There is no membership fee.
      </div>
    </div>
  );
};

const SignupDone = ({ tweaks, navigate }) => {
  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 style={{ width: 64, height: 64, borderRadius: '50%', border: '1.5px solid var(--ink)', margin: '0 auto 32px', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--serif)', fontSize: 32, fontStyle: 'italic' }}>✓</div>
        <h1 className="serif" style={{ fontSize: 56, lineHeight: 1.1, fontWeight: 500, margin: 0, textWrap: 'balance' }}>
          Your request is in.
        </h1>
        <p style={{ fontSize: 17, lineHeight: 1.65, color: 'var(--ink-2)', marginTop: 28, textWrap: 'pretty' }}>
          We've sent a commendation request to your pastor or elder. You'll receive a copy by email so you can follow up if needed. Most respond within a week. We'll let you know the moment they commend you — and then walk you through publishing your profile.
        </p>
        <div style={{ marginTop: 44, padding: 28, background: 'var(--paper)', border: '1px solid var(--line)', textAlign: 'left' }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 14 }}>While you wait</div>
          <div style={{ fontFamily: 'var(--serif)', fontSize: 22, fontStyle: 'italic', lineHeight: 1.4, color: 'var(--ink)' }}>
            “Commit thy way unto the LORD; trust also in him; and he shall bring it to pass.”
          </div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', color: 'var(--ink-3)', marginTop: 12 }}>Psalm 37:5</div>
        </div>
        <div style={{ marginTop: 32 }}>
          <Btn kind="secondary" onClick={() => navigate('landing')}>Return to home</Btn>
        </div>
      </div>
      <Footer tweaks={tweaks} navigate={navigate} />
    </div>
  );
};

Object.assign(window, { Signup, SignupDone, StepYou, StepChurch, StepElder, StepWitness, StepReview });
