/* global React, ArrowRight */
const { useState: useStateA, useEffect: useEffectA } = React;

// ============================================================
// APPLY PAGE — Multi-step form
// ============================================================
function ApplyPage() {
  const [step, setStep] = useStateA(1);
  const [data, setData] = useStateA({
    amount: 100000,
    use: '',
    industry: '',
    timeInBiz: '',
    revenue: '',
    creditTier: '',
    legalName: '',
    contactName: '',
    email: '',
    phone: '',
    state: '',
    consent: false,
  });
  const [errors, setErrors] = useStateA({});
  const [ref, setRef] = useStateA(null);
  const [submitting, setSubmitting] = useStateA(false);

  // Google Apps Script endpoint — delivers submissions to schneur@kbfundinggroup.com
  const FORM_ENDPOINT = 'https://script.google.com/macros/s/AKfycbxeyarB9KpwKLjVSbUoAqGvcV4ivo5mUvASuMkb0Hj0oIaUmmhSHHpUYwROSHOAWJFr/exec';

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

  const validateStep = (s) => {
    const e = {};
    if (s === 1) {
      if (!data.use) e.use = 'Select a use of funds';
      if (!data.industry) e.industry = 'Pick your industry';
    }
    if (s === 2) {
      if (!data.timeInBiz) e.timeInBiz = 'Select time in business';
      if (!data.revenue) e.revenue = 'Select monthly revenue';
      if (!data.creditTier) e.creditTier = 'Select a credit tier';
    }
    if (s === 3) {
      if (!data.legalName.trim()) e.legalName = 'Required';
      if (!data.contactName.trim()) e.contactName = 'Required';
      if (!data.email.match(/^\S+@\S+\.\S+$/)) e.email = 'Valid email required';
      if (!data.phone.match(/^[0-9\-\s\(\)]{10,}$/)) e.phone = 'Valid phone required';
      if (!data.state) e.state = 'Required';
      if (!data.consent) e.consent = 'You must agree to continue';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (submitting) return;
    if (!validateStep(step)) return;
    if (step === 3) {
      const r = 'KB-' + Math.random().toString(36).slice(2, 7).toUpperCase() + '-' + Math.random().toString(36).slice(2, 5).toUpperCase();
      const payload = { ...data, ref: r, formType: 'application' };

      // Fire-and-forget POST to Apps Script. Using `no-cors` + text/plain avoids
      // a CORS preflight (Apps Script doesn't respond to OPTIONS), so the request
      // goes through cleanly. We won't be able to read the response body, but the
      // script still runs and the email still sends.
      setSubmitting(true);
      fetch(FORM_ENDPOINT, {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        body: JSON.stringify(payload),
      }).catch((err) => {
        console.error('Form submit failed:', err);
      }).finally(() => {
        setSubmitting(false);
      });

      setRef(r);
      setStep(4);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      setStep(step + 1);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };
  const back = () => setStep(Math.max(1, step - 1));

  return (
    <div className="page-fade">
      <PageBanner
        crumb="Apply"
        title={<>Get pre-qualified in <em>under 4 minutes.</em></>}
        lead="Soft inquiry only — no impact on your credit. A KB advisor will reach out within one business hour with your matched offers."
      />
      <section>
        <div className="container">
          <div className="apply-grid">
            <div>
              {ref ? (
                <SuccessCard ref_={ref} data={data} />
              ) : (
                <div className="form-card">
                  <Stepper step={step} />
                  {step === 1 && <Step1 data={data} update={update} errors={errors} />}
                  {step === 2 && <Step2 data={data} update={update} errors={errors} />}
                  {step === 3 && <Step3 data={data} update={update} errors={errors} />}
                  <div className="form-actions">
                    {step > 1 ? (
                      <button className="btn btn-outline" onClick={back}>← Back</button>
                    ) : <span></span>}
                    <button className="btn btn-primary" onClick={next} disabled={submitting}>
                      {submitting ? 'Submitting…' : (step === 3 ? 'Submit application' : 'Continue')} <ArrowRight />
                    </button>
                  </div>
                </div>
              )}
            </div>

            <aside className="form-side">
              <h3 style={{ fontSize: 28 }}>What you'll get.</h3>
              <ul className="side-list">
                <li>
                  <span className="ck">✓</span>
                  <div>
                    <span className="t">Real offers, not estimates</span>
                    <span className="d">Side-by-side from up to 75 vetted lenders.</span>
                  </div>
                </li>
                <li>
                  <span className="ck">✓</span>
                  <div>
                    <span className="t">A named advisor</span>
                    <span className="d">One person from application through funding.</span>
                  </div>
                </li>
                <li>
                  <span className="ck">✓</span>
                  <div>
                    <span className="t">No credit impact today</span>
                    <span className="d">Soft inquiry only until you accept an offer.</span>
                  </div>
                </li>
                <li>
                  <span className="ck">✓</span>
                  <div>
                    <span className="t">Funded in 24–48 hours</span>
                    <span className="d">Most working-capital products wire within 2 business days.</span>
                  </div>
                </li>
              </ul>
              <div style={{
                background: 'var(--cream)', border: '1px solid var(--line)', padding: 24,
              }}>
                <div style={{ fontSize: 11.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--gold-deep)', fontWeight: 600, marginBottom: 8 }}>
                  Need to talk first?
                </div>
                <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 28, color: 'var(--navy)', lineHeight: 1.1 }}>
                  (347) 881-4260
                </div>
                <div style={{ fontSize: 13, color: 'var(--slate)', marginTop: 6 }}>
                  Mon–Fri · 8a–7p ET · An advisor, not a phone tree.
                </div>
              </div>
            </aside>
          </div>
        </div>
      </section>
    </div>
  );
}

function Stepper({ step }) {
  const steps = ['Funding', 'Business', 'Contact'];
  return (
    <div className="stepper">
      {steps.map((s, i) => {
        const idx = i + 1;
        const status = idx < step ? 'done' : idx === step ? 'active' : '';
        return (
          <React.Fragment key={s}>
            <div className={`step-pill ${status}`}>
              <div className="dot">{idx < step ? '✓' : idx}</div>
              <div className="lbl">{s}</div>
            </div>
            {i < steps.length - 1 && <div className={`step-bar ${idx < step ? 'done' : ''}`} />}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function Step1({ data, update, errors }) {
  const fmt = (n) => '$' + n.toLocaleString();
  const uses = ['Working capital', 'Equipment', 'Expansion', 'Inventory', 'Refinance', 'Other'];
  const industries = ['Construction', 'Restaurants', 'Retail / E-comm', 'Trucking', 'Healthcare', 'Manufacturing', 'Auto', 'Pro Services', 'Other'];
  return (
    <div>
      <h3 style={{ marginBottom: 6 }}>How much do you need?</h3>
      <p style={{ color: 'var(--slate)', fontSize: 14.5, marginBottom: 28 }}>Slide to your target amount. We'll match offers within ~10% of this.</p>

      <div className="form-group">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
          <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 48, color: 'var(--navy)', lineHeight: 1, fontWeight: 500 }}>
            {fmt(data.amount)}
          </div>
          <div style={{ fontSize: 12, color: 'var(--slate)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>$10K – $2M</div>
        </div>
        <input
          type="range" min="10000" max="2000000" step="5000"
          value={data.amount}
          onChange={(e) => update('amount', Number(e.target.value))}
          style={{ background: 'var(--line)' }}
        />
      </div>

      <div className="form-group">
        <label className="field-label">Use of funds</label>
        <div className="option-grid">
          {uses.map(u => (
            <button key={u} className={`option ${data.use === u ? 'selected' : ''}`} onClick={() => update('use', u)}>{u}</button>
          ))}
        </div>
        {errors.use && <div className="error-msg">{errors.use}</div>}
      </div>

      <div className="form-group">
        <label className="field-label">Industry</label>
        <select className="select" value={data.industry} onChange={(e) => update('industry', e.target.value)}>
          <option value="">Select your industry…</option>
          {industries.map(i => <option key={i} value={i}>{i}</option>)}
        </select>
        {errors.industry && <div className="error-msg">{errors.industry}</div>}
      </div>
    </div>
  );
}

function Step2({ data, update, errors }) {
  const tibs = ['Under 6 mo', '6–12 mo', '1–2 yrs', '2–5 yrs', '5+ yrs'];
  const revs = ['Under $10K', '$10K–$25K', '$25K–$50K', '$50K–$100K', '$100K–$250K', '$250K+'];
  const credits = ['Under 550', '550–599', '600–649', '650–699', '700–749', '750+'];
  return (
    <div>
      <h3 style={{ marginBottom: 6 }}>Tell us about the business.</h3>
      <p style={{ color: 'var(--slate)', fontSize: 14.5, marginBottom: 28 }}>This helps your advisor match you to the right products.</p>

      <div className="form-group">
        <label className="field-label">Time in business</label>
        <div className="option-grid">
          {tibs.map(o => (
            <button key={o} className={`option ${data.timeInBiz === o ? 'selected' : ''}`} onClick={() => update('timeInBiz', o)}>{o}</button>
          ))}
        </div>
        {errors.timeInBiz && <div className="error-msg">{errors.timeInBiz}</div>}
      </div>

      <div className="form-group">
        <label className="field-label">Average monthly revenue</label>
        <div className="option-grid">
          {revs.map(o => (
            <button key={o} className={`option ${data.revenue === o ? 'selected' : ''}`} onClick={() => update('revenue', o)}>{o}</button>
          ))}
        </div>
        {errors.revenue && <div className="error-msg">{errors.revenue}</div>}
      </div>

      <div className="form-group">
        <label className="field-label">Personal credit score (estimate)</label>
        <div className="option-grid">
          {credits.map(o => (
            <button key={o} className={`option ${data.creditTier === o ? 'selected' : ''}`} onClick={() => update('creditTier', o)}>{o}</button>
          ))}
        </div>
        {errors.creditTier && <div className="error-msg">{errors.creditTier}</div>}
        <div className="help">Soft check only — won't impact your score.</div>
      </div>
    </div>
  );
}

const STATES = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];

function Step3({ data, update, errors }) {
  return (
    <div>
      <h3 style={{ marginBottom: 6 }}>How can we reach you?</h3>
      <p style={{ color: 'var(--slate)', fontSize: 14.5, marginBottom: 28 }}>An advisor will follow up within one business hour with matched offers.</p>

      <div className="form-group">
        <label className="field-label">Legal business name</label>
        <input className={`input ${errors.legalName ? 'error' : ''}`} value={data.legalName} onChange={(e) => update('legalName', e.target.value)} placeholder="e.g. Hale Construction Group, LLC" />
        {errors.legalName && <div className="error-msg">{errors.legalName}</div>}
      </div>

      <div className="form-group">
        <label className="field-label">Your name</label>
        <input className={`input ${errors.contactName ? 'error' : ''}`} value={data.contactName} onChange={(e) => update('contactName', e.target.value)} placeholder="First and last" />
        {errors.contactName && <div className="error-msg">{errors.contactName}</div>}
      </div>

      <div className="form-row">
        <div className="form-group">
          <label className="field-label">Email</label>
          <input className={`input ${errors.email ? 'error' : ''}`} type="email" value={data.email} onChange={(e) => update('email', e.target.value)} placeholder="you@business.com" />
          {errors.email && <div className="error-msg">{errors.email}</div>}
        </div>
        <div className="form-group">
          <label className="field-label">Phone</label>
          <input className={`input ${errors.phone ? 'error' : ''}`} value={data.phone} onChange={(e) => update('phone', e.target.value)} placeholder="(555) 123-4567" />
          {errors.phone && <div className="error-msg">{errors.phone}</div>}
        </div>
      </div>

      <div className="form-group">
        <label className="field-label">State of operation</label>
        <select className={`select ${errors.state ? 'error' : ''}`} value={data.state} onChange={(e) => update('state', e.target.value)}>
          <option value="">Select…</option>
          {STATES.map(s => <option key={s} value={s}>{s}</option>)}
        </select>
        {errors.state && <div className="error-msg">{errors.state}</div>}
      </div>

      <div className="form-group" style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginTop: 6 }}>
        <input id="cs" type="checkbox" checked={data.consent} onChange={(e) => update('consent', e.target.checked)}
               style={{ marginTop: 4, accentColor: 'var(--gold-deep)' }} />
        <label htmlFor="cs" style={{ fontSize: 13, color: 'var(--slate)', lineHeight: 1.5 }}>
          I agree to be contacted by KB Funding Group by phone, email, and SMS regarding
          my application. I understand pre-qualification involves a soft credit inquiry only.
        </label>
      </div>
      {errors.consent && <div className="error-msg">{errors.consent}</div>}
    </div>
  );
}

function SuccessCard({ ref_, data }) {
  return (
    <div className="form-card success-card">
      <div className="seal">✓</div>
      <span className="eyebrow" style={{ justifyContent: 'center' }}>Application Received</span>
      <h2 style={{ marginTop: 14 }}>Thanks, {data.contactName.split(' ')[0]}.</h2>
      <p style={{ fontSize: 16.5, color: 'var(--slate)', maxWidth: 480, margin: '14px auto 0' }}>
        A KB advisor will reach out within one business hour to {data.email} or {data.phone}. Save your reference number — you'll need it when we connect.
      </p>
      <div className="ref">REF · {ref_}</div>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
        <a href="#/" className="btn btn-outline" onClick={(e) => { e.preventDefault(); window.location.hash = '/'; }}>Back to home</a>
        <a href="tel:13478814260" className="btn btn-primary">Call us now <ArrowRight /></a>
      </div>
    </div>
  );
}

Object.assign(window, { ApplyPage });
