// Application flow: 5 steps + review + post-submit confirmation.

const STEPS = [
  { n: '01', title: 'Intention',  fields: [
      { id: 'building', label: 'What are you constructing that will outlast you?', kind: 'textarea', rows: 4 },
      { id: 'why',      label: 'What brought you here?',                           kind: 'textarea', rows: 3 },
  ] },
  { n: '02', title: 'Practice',   fields: [
      { id: 'physical', label: 'Describe your current physical practice. Frequency, modality, recent milestones.', kind: 'textarea', rows: 4 },
      { id: 'source',   label: 'Describe your Source or spiritual practice, if any.', kind: 'textarea', rows: 3 },
  ] },
  { n: '03', title: 'Relationships', fields: [
      { id: 'rel', label: 'What are you building in your closest relationships? Where are you strong? Where are you growing?', kind: 'textarea', rows: 5 },
  ] },
  { n: '04', title: 'Capacity',   fields: [
      { id: 'firearms', label: 'Describe your experience with firearms and hunting. (None required. Growth mindset essential.)', kind: 'textarea', rows: 4 },
      { id: 'bring',    label: 'What do you bring to a team of men doing the work?',  kind: 'textarea', rows: 3 },
  ] },
  { n: '05', title: 'Logistics',  fields: [
      { id: 'name',     label: 'Name',              kind: 'text', placeholder: 'First Last' },
      { id: 'age',      label: 'Age',               kind: 'number', placeholder: '28–50' },
      { id: 'location', label: 'Location',          kind: 'text', placeholder: 'City, State' },
      { id: 'job',      label: 'Occupation',        kind: 'text', placeholder: 'What do you do?' },
      { id: 'email',    label: 'Email',             kind: 'email', placeholder: 'you@domain.com' },
      { id: 'phone',    label: 'Phone',             kind: 'tel', placeholder: '+1 …' },
      { id: 'emergency',label: 'Emergency Contact', kind: 'text', placeholder: 'Name + phone' },
      { id: 'referral', label: 'Referral Source',   kind: 'text', placeholder: 'Who sent you?' },
  ] },
];

function ApplicationFlow({ onClose }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({});
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  const setField = (id, v) => setData(d => ({ ...d, [id]: v }));

  const validate = (idx) => {
    const cfg = STEPS[idx];
    const newErr = {};
    cfg.fields.forEach(f => {
      const v = (data[f.id] || '').toString().trim();
      if (!v) newErr[f.id] = 'Required.';
      else if (f.kind === 'email' && !/^\S+@\S+\.\S+$/.test(v)) newErr[f.id] = 'Email needed.';
      else if (f.kind === 'number' && isNaN(Number(v))) newErr[f.id] = 'Number needed.';
    });
    return newErr;
  };

  const next = () => {
    const e = validate(step);
    setErrors(e);
    if (Object.keys(e).length === 0) setStep(s => Math.min(STEPS.length, s + 1));
  };
  const back = () => setStep(s => Math.max(0, s - 1));
  const submit = () => {
    setSubmitted(true);
  };

  if (submitted) return <ApplicationConfirmed onClose={onClose} data={data} />;
  if (step >= STEPS.length) return <ApplicationReview data={data} onBack={() => setStep(STEPS.length - 1)} onSubmit={submit} onEdit={(i) => setStep(i)} onClose={onClose} />;

  const cfg = STEPS[step];
  const totalProgress = ((step) / STEPS.length) * 100;

  return (
    <div className="app-flow">
      <header className="app-hd">
        <div className="app-hd-l">
          <span className="app-hd-mark">◣</span>
          <span className="app-hd-word">SFMENS</span>
          <span className="app-hd-sep">/</span>
          <span className="app-hd-meta">APPLICATION</span>
        </div>
        <button className="app-hd-x" onClick={onClose}>← Return</button>
      </header>

      <div className="app-prog">
        <div className="app-prog-bar"><div className="app-prog-fill" style={{ width: `${totalProgress}%` }} /></div>
        <div className="app-prog-steps">
          {STEPS.map((s, i) => (
            <button key={s.n} className={`app-prog-step ${i === step ? 'on' : ''} ${i < step ? 'done' : ''}`}
                    onClick={() => i <= step && setStep(i)}>
              <span className="app-prog-n">{s.n}</span>
              <span className="app-prog-t">{s.title}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="app-stage">
        <div className="app-stage-l">
          <div className="app-step-marker">
            <span className="app-step-n">{cfg.n}</span>
            <span className="app-step-of">/ 05</span>
          </div>
          <h1 className="app-step-h">Begin.</h1>
          <p className="app-step-sub">
            {step === 0 && 'Tell us why you are here. The work is the answer; the question still matters.'}
            {step === 1 && 'Practice is the proof. Describe what you do, not what you intend.'}
            {step === 2 && 'Strength is also relational. Where you build, and where you bend.'}
            {step === 3 && 'Capacity is built. Tell us what you bring; we will train the rest.'}
            {step === 4 && 'Logistics. The plain facts that move us from prose to plans.'}
          </p>
          <div className="app-step-meta">
            <span>STEP {cfg.n} OF 05</span>
            <span className="rule-h-line" />
            <span>{cfg.title.toUpperCase()}</span>
          </div>
        </div>

        <form className="app-form" onSubmit={(e) => { e.preventDefault(); next(); }}>
          {cfg.fields.map(f => (
            <Field key={f.id} f={f} value={data[f.id] || ''}
                   onChange={(v) => setField(f.id, v)} error={errors[f.id]} />
          ))}

          <div className="app-form-nav">
            <button type="button" className="app-back" onClick={back} disabled={step === 0}>← Back</button>
            <div className="app-form-nav-r">
              <span className="app-form-nav-meta">{cfg.fields.length} fields</span>
              <button type="submit" className="app-next">
                {step === STEPS.length - 1 ? 'Review' : 'Continue'} <span aria-hidden="true">→</span>
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}

function Field({ f, value, onChange, error }) {
  const [focused, setFocused] = React.useState(false);
  const cls = `app-field ${focused ? 'on' : ''} ${error ? 'err' : ''} ${value ? 'filled' : ''}`;
  const longLabel = f.kind === 'textarea';
  return (
    <label className={cls}>
      <div className="app-field-lbl">
        <span>{f.label}</span>
        {error && <span className="app-field-err">{error}</span>}
      </div>
      {f.kind === 'textarea' ? (
        <textarea
          rows={f.rows || 4}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
        />
      ) : (
        <input
          type={f.kind}
          value={value}
          placeholder={f.placeholder || ''}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
        />
      )}
    </label>
  );
}

function ApplicationReview({ data, onBack, onSubmit, onEdit, onClose }) {
  return (
    <div className="app-flow">
      <header className="app-hd">
        <div className="app-hd-l">
          <span className="app-hd-mark">◣</span>
          <span className="app-hd-word">SFMENS</span>
          <span className="app-hd-sep">/</span>
          <span className="app-hd-meta">REVIEW</span>
        </div>
        <button className="app-hd-x" onClick={onClose}>← Return</button>
      </header>

      <div className="app-review">
        <div className="app-review-hd">
          <span className="app-step-n">06</span>
          <h1 className="app-step-h">Review.<br/>Submit.</h1>
          <p className="app-step-sub">A final pass before the work begins.</p>
        </div>

        <div className="app-review-list">
          {STEPS.map((s, i) => (
            <section key={s.n} className="app-review-sec">
              <header>
                <span className="app-review-n">{s.n}</span>
                <span className="app-review-t">{s.title}</span>
                <button className="app-review-edit" onClick={() => onEdit(i)}>Edit</button>
              </header>
              <dl>
                {s.fields.map(f => (
                  <div key={f.id} className="app-review-row">
                    <dt>{f.label}</dt>
                    <dd>{(data[f.id] && data[f.id].toString().trim()) || <span className="app-review-empty">— blank —</span>}</dd>
                  </div>
                ))}
              </dl>
            </section>
          ))}
        </div>

        <div className="app-form-nav">
          <button type="button" className="app-back" onClick={onBack}>← Back</button>
          <button type="button" className="app-next app-next--final" onClick={onSubmit}>
            Submit application <span aria-hidden="true">→</span>
          </button>
        </div>
      </div>
    </div>
  );
}

function ApplicationConfirmed({ onClose, data }) {
  const name = (data.name || '').trim().split(' ')[0] || 'Builder';
  const ref = 'SFM-' + Math.random().toString(36).slice(2, 8).toUpperCase();
  return (
    <div className="app-flow app-flow--confirmed">
      <header className="app-hd">
        <div className="app-hd-l">
          <span className="app-hd-mark">◣</span>
          <span className="app-hd-word">SFMENS</span>
          <span className="app-hd-sep">/</span>
          <span className="app-hd-meta">RECEIVED</span>
        </div>
        <button className="app-hd-x" onClick={onClose}>← Return to site</button>
      </header>

      <div className="app-confirm">
        <VideoPlate label="POST-SUBMIT · STILL · 0:00" tone="dark">
          <div className="app-confirm-overlay">
            <div className="app-confirm-tag">
              <span className="dot" />
              <span>RECEIVED</span>
            </div>
            <h1 className="app-confirm-h">Received.</h1>
            <p className="app-confirm-sub">
              {name}, your application is logged. Applications reviewed quarterly.
              You will hear from us within 14 days.
            </p>
            <div className="app-confirm-card">
              <div className="app-confirm-row">
                <span>REFERENCE</span>
                <span className="mono">{ref}</span>
              </div>
              <div className="app-confirm-row">
                <span>SUBMITTED</span>
                <span className="mono">{new Date().toISOString().slice(0, 16).replace('T', ' ')}</span>
              </div>
              <div className="app-confirm-row">
                <span>NEXT WINDOW</span>
                <span className="mono">≤ 14 DAYS</span>
              </div>
            </div>
            <button className="app-back-to-site" onClick={onClose}>Return to site →</button>
          </div>
        </VideoPlate>
      </div>
    </div>
  );
}

Object.assign(window, { ApplicationFlow });
