// Careers page — owner-operator packet form (primary goal)
const { useState: useCState } = React;

function CareersPage() {
  const [step, setStep] = useCState(0);
  const [submitted, setSubmitted] = useCState(false);
  const [form, setForm] = useCState({
    // Step 1 — personal
    firstName: '', lastName: '', email: '', phone: '', dob: '',
    city: '', state: '', zip: '',
    // Step 2 — authority & equipment
    authority: 'lease-on', mc: '', dot: '', ein: '',
    equipmentType: '', year: '', make: '', model: '', vin: '',
    boxLength: '', liftgate: 'no', hazmat: 'no', twic: 'no',
    // Step 3 — experience
    cdl: 'none', cdlState: '', yearsExperience: '', preferredLanes: '',
    otrAvailable: 'yes', startDate: '',
    // Step 4 — consent
    referral: '', notes: '', consent: false,
  });

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const steps = [
    { id: 0, label: 'Personal', icon: '01' },
    { id: 1, label: 'Equipment', icon: '02' },
    { id: 2, label: 'Experience', icon: '03' },
    { id: 3, label: 'Review', icon: '04' },
  ];

  const canNext = () => {
    if (step === 0) return form.firstName && form.lastName && form.email && form.phone;
    if (step === 1) return form.equipmentType && form.year && form.make;
    if (step === 2) return form.yearsExperience;
    if (step === 3) return form.consent;
    return true;
  };

  const [submitting, setSubmitting] = useCState(false);
  const [submitError, setSubmitError] = useCState('');

  const submit = async () => {
    setSubmitting(true);
    setSubmitError('');
    try {
      const res = await fetch('https://formspree.io/f/xjgjaool', {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({
          _subject: `New Owner-Operator Application — ${form.firstName} ${form.lastName}`,
          form_type: 'Owner-Operator Packet',
          ...form,
        }),
      });
      if (!res.ok) throw new Error('submit failed');
      setSubmitted(true);
    } catch (e) {
      setSubmitError('Something went wrong. Please try again or call +1 484 235 5888.');
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <div className="page">
        <div className="apply-success">
          <div className="success-check big">
            <svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 6L9 17l-5-5"/></svg>
          </div>
          <h1>Application received.</h1>
          <p className="apply-success-sub">Thanks, {form.firstName}. Your owner-operator packet is on the way to our recruiting team — expect a call or email within 24 hours at <strong>{form.phone}</strong> or <strong>{form.email}</strong>.</p>
          <div className="apply-next">
            <h3>What happens next</h3>
            <ol>
              <li>Recruiting reviews your equipment and authority</li>
              <li>We send you a short video call link to meet your dispatcher</li>
              <li>Onboarding docs + first load dispatched within 3–5 days</li>
            </ol>
          </div>
          <a href="tel:+14842355888" className="btn btn-primary btn-lg">Call us now: +1 484 235 5888</a>
        </div>
      </div>
    );
  }

  return (
    <div className="page careers-page">
      <div className="careers-hero">
        <div className="careers-hero-left">
          <span className="section-kicker">CAREERS · OWNER-OPERATORS</span>
          <h1 className="page-title">Your truck.<br/>Your lanes.<br/><span className="italic-accent">Our loads.</span></h1>
          <p className="page-lede">Lease onto Babiline and keep control of where you go. Personal dispatcher, high-paying loads, weekly pay + same-day Quick Pay, and zero forced dispatch.</p>
          <div className="perk-grid">
            {[
              ['No forced dispatch', 'You pick your lanes. Every load.'],
              ['Personal dispatcher', 'One name. One number. Not a call center.'],
              ['Weekly + Quick Pay', 'Settlements every Friday. Same-day QP available.'],
              ['Consistent freight', 'Custom load-board automation keeps the truck loaded.'],
              ['Local or OTR', 'Whatever fits your life. Your call.'],
              ['High-paying lanes', 'We don\'t chase cheap freight.'],
            ].map(([t, d]) => (
              <div key={t} className="perk">
                <div className="perk-mark">+</div>
                <h4>{t}</h4>
                <p>{d}</p>
              </div>
            ))}
          </div>
        </div>
        <div className="careers-hero-right">
          <div className="form-card">
            <div className="form-header">
              <h2>Owner-Operator Packet</h2>
              <p>Takes about 5 minutes. We email you within 24 hrs.</p>
            </div>

            <div className="stepper">
              {steps.map(s => (
                <div key={s.id} className={`step-dot ${step === s.id ? 'active' : ''} ${step > s.id ? 'done' : ''}`}>
                  <div className="step-num">{s.icon}</div>
                  <div className="step-label">{s.label}</div>
                </div>
              ))}
            </div>

            <div className="form-body">
              {step === 0 && <Step1 form={form} update={update} />}
              {step === 1 && <Step2 form={form} update={update} />}
              {step === 2 && <Step3 form={form} update={update} />}
              {step === 3 && <Step4 form={form} update={update} />}
            </div>

            <div className="form-nav">
              {step > 0 && <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>← Back</button>}
              <div style={{ flex: 1 }}></div>
              {step < 3 && (
                <button className="btn btn-primary" disabled={!canNext()} onClick={() => setStep(step + 1)}>
                  Continue →
                </button>
              )}
              {step === 3 && (
                <button className="btn btn-primary btn-lg" disabled={!canNext() || submitting} onClick={submit}>
                  {submitting ? 'Submitting…' : 'Submit packet'}
                </button>
              )}
            </div>
            {submitError && <div className="form-error-msg">{submitError}</div>}
          </div>
        </div>
      </div>

      <section className="pay-breakdown">
        <div className="section-head">
          <span className="section-kicker">04 — THE PAY</span>
          <h2 className="section-title">Straight talk on earnings.</h2>
        </div>
        <div className="pay-grid pay-grid-3">
          {[
            ['Cargo Van / Sprinter', '$2,500 – $3,500', 'weekly gross'],
            ['Box Truck', '$4,500 – $6,500', 'weekly gross'],
            ['Straight Truck', '$8,000 – $12,000', 'weekly gross'],
          ].map(([t, r, m]) => (
            <div key={t} className="pay-card">
              <div className="pay-type">{t}</div>
              <div className="pay-rate">{r}</div>
              <div className="pay-meta">{m}</div>
            </div>
          ))}
        </div>
        <p className="pay-note">Ranges reflect typical weekly gross for consistent, lease-on owner-operators. Actual earnings depend on lanes, hours worked, and load mix.</p>
      </section>
    </div>
  );
}

function Field({ label, children, half, third }) {
  const cls = 'field' + (half ? ' field-half' : '') + (third ? ' field-third' : '');
  return <div className={cls}><label>{label}</label>{children}</div>;
}

function Step1({ form, update }) {
  return (
    <div className="form-step">
      <h3>Tell us about you</h3>
      <div className="field-row">
        <Field label="First name" half><input value={form.firstName} onChange={e => update('firstName', e.target.value)} /></Field>
        <Field label="Last name" half><input value={form.lastName} onChange={e => update('lastName', e.target.value)} /></Field>
      </div>
      <div className="field-row">
        <Field label="Email" half><input type="email" value={form.email} onChange={e => update('email', e.target.value)} /></Field>
        <Field label="Phone" half><input type="tel" value={form.phone} onChange={e => update('phone', e.target.value)} placeholder="+1 " /></Field>
      </div>
      <div className="field-row">
        <Field label="City" half><input value={form.city} onChange={e => update('city', e.target.value)} /></Field>
        <Field label="State" third><input value={form.state} onChange={e => update('state', e.target.value)} maxLength={2} /></Field>
        <Field label="ZIP" third><input value={form.zip} onChange={e => update('zip', e.target.value)} /></Field>
      </div>
    </div>
  );
}

function Step2({ form, update }) {
  const equipTypes = ['Cargo Van / Sprinter', 'Box Truck', 'Straight Truck'];
  return (
    <div className="form-step">
      <h3>Equipment & authority</h3>
      <Field label="Equipment type">
        <div className="chip-group">
          {equipTypes.map(t => (
            <button key={t} type="button" className={`chip ${form.equipmentType === t ? 'active' : ''}`}
              onClick={() => update('equipmentType', t)}>{t}</button>
          ))}
        </div>
      </Field>
      <div className="field-row">
        <Field label="Year" third><input value={form.year} onChange={e => update('year', e.target.value)} placeholder="2022" /></Field>
        <Field label="Make" third><input value={form.make} onChange={e => update('make', e.target.value)} /></Field>
        <Field label="Model" third><input value={form.model} onChange={e => update('model', e.target.value)} /></Field>
      </div>
      <Field label="VIN (optional)"><input value={form.vin} onChange={e => update('vin', e.target.value)} /></Field>
      <div className="field-row">
        <Field label="Liftgate?" third>
          <div className="seg">
            {['yes', 'no'].map(v => <button key={v} type="button" className={form.liftgate === v ? 'active' : ''} onClick={() => update('liftgate', v)}>{v}</button>)}
          </div>
        </Field>
        <Field label="Hazmat endorsement?" third>
          <div className="seg">
            {['yes', 'no'].map(v => <button key={v} type="button" className={form.hazmat === v ? 'active' : ''} onClick={() => update('hazmat', v)}>{v}</button>)}
          </div>
        </Field>
        <Field label="TWIC card?" third>
          <div className="seg">
            {['yes', 'no'].map(v => <button key={v} type="button" className={form.twic === v ? 'active' : ''} onClick={() => update('twic', v)}>{v}</button>)}
          </div>
        </Field>
      </div>
    </div>
  );
}

function Step3({ form, update }) {
  return (
    <div className="form-step">
      <h3>Driving experience</h3>
      <Field label="CDL class">
        <div className="chip-group">
          {['None', 'Class A', 'Class B', 'Class C'].map(c => (
            <button key={c} type="button" className={`chip ${form.cdl === c ? 'active' : ''}`}
              onClick={() => update('cdl', c)}>{c}</button>
          ))}
        </div>
      </Field>
      <div className="field-row">
        <Field label="CDL state" half><input value={form.cdlState} onChange={e => update('cdlState', e.target.value)} maxLength={2} /></Field>
        <Field label="Years driving" half><input value={form.yearsExperience} onChange={e => update('yearsExperience', e.target.value)} placeholder="e.g. 5" /></Field>
      </div>
      <Field label="Preferred lanes / regions"><input value={form.preferredLanes} onChange={e => update('preferredLanes', e.target.value)} placeholder="e.g. Northeast, PA ↔ IL, anywhere OTR" /></Field>
      <div className="field-row">
        <Field label="Available for OTR?" half>
          <div className="seg">
            {[['yes', 'Yes'], ['regional', 'Regional only'], ['local', 'Local only']].map(([v, l]) => (
              <button key={v} type="button" className={form.otrAvailable === v ? 'active' : ''} onClick={() => update('otrAvailable', v)}>{l}</button>
            ))}
          </div>
        </Field>
        <Field label="When can you start?" half><input type="date" value={form.startDate} onChange={e => update('startDate', e.target.value)} /></Field>
      </div>
    </div>
  );
}

function Step4({ form, update }) {
  return (
    <div className="form-step">
      <h3>Almost done</h3>
      <Field label="How did you hear about us?">
        <div className="chip-group">
          {['Facebook', 'Google', 'Referral', 'Another driver', 'Load board', 'Other'].map(r => (
            <button key={r} type="button" className={`chip ${form.referral === r ? 'active' : ''}`}
              onClick={() => update('referral', r)}>{r}</button>
          ))}
        </div>
      </Field>
      <Field label="Anything else we should know? (optional)">
        <textarea rows={3} value={form.notes} onChange={e => update('notes', e.target.value)} placeholder="Preferred pay schedule, questions, availability notes…" />
      </Field>

      <div className="review-summary">
        <h4>Quick review</h4>
        <div className="review-grid">
          <div><span>Name</span><strong>{form.firstName} {form.lastName}</strong></div>
          <div><span>Contact</span><strong>{form.phone} · {form.email}</strong></div>
          <div><span>Location</span><strong>{form.city}{form.state ? ', ' + form.state : ''}</strong></div>
          <div><span>Equipment</span><strong>{form.year} {form.make} {form.model} — {form.equipmentType}</strong></div>
          <div><span>Endorsements</span><strong>{[form.hazmat === 'yes' && 'Hazmat', form.twic === 'yes' && 'TWIC', form.liftgate === 'yes' && 'Liftgate'].filter(Boolean).join(' · ') || '—'}</strong></div>
          <div><span>Experience</span><strong>{form.yearsExperience || '—'} years · CDL {form.cdl}</strong></div>
          <div><span>Availability</span><strong>{form.otrAvailable} · starts {form.startDate || '—'}</strong></div>
        </div>
      </div>

      <label className="consent">
        <input type="checkbox" checked={form.consent} onChange={e => update('consent', e.target.checked)} />
        <span>I confirm the above information is accurate and authorize Babiline LLC to contact me regarding this application.</span>
      </label>
    </div>
  );
}

window.CareersPage = CareersPage;
