// Credit Application — multi-step wizard

const { useState, useEffect } = React;

const STEPS = [
  { key: "personal", title: "Personal" },
  { key: "employment", title: "Employment" },
  { key: "vehicle", title: "Vehicle" },
  { key: "review", title: "Review & Submit" },
];

function Aside({ current }) {
  return (
    <aside className="app-aside">
      <a href="index.html" className="nav__logo" style={{ alignSelf: 'flex-start', height: 56 }}>
        <img src="logo.png" alt="123 Auto Group NYC" style={{ height: '100%', width: 'auto', display: 'block' }} />
      </a>
      <div>
        <div className="section__eyebrow">Credit Application</div>
        <h1 className="app-aside__lede">
          Let's see what <em>terms you qualify for.</em>
        </h1>
        <p className="app-aside__sub" style={{ marginTop: 16 }}>
          Takes about 4 minutes. No hard pull until you tell us to proceed. We'll get back within one business day with options.
        </p>
      </div>
      <div className="steps">
        {STEPS.map((s, i) => (
          <div
            key={s.key}
            className={
              "steps__item" +
              (i === current ? " is-active" : "") +
              (i < current ? " is-done" : "")
            }
          >
            <div className="steps__num">{i < current ? "✓" : i + 1}</div>
            <div className="steps__title">{s.title}</div>
          </div>
        ))}
      </div>
      <div className="app-aside__trust">
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.3">
          <rect x="2.5" y="6" width="9" height="6" rx="1" />
          <path d="M4.5 6V4a2.5 2.5 0 015 0v2" />
        </svg>
        <div>
          <strong>Bank-level encryption</strong>
          Your information is encrypted in transit and at rest. We never share with third parties without your written consent.
        </div>
      </div>
    </aside>
  );
}

function Field({ label, children, full, hint, error }) {
  return (
    <div className={"app-field" + (full ? " app-field--full" : "") + (error ? " is-error" : "")}>
      <label>{label}<span className="app-field__req" aria-hidden="true">*</span></label>
      {children}
      {error
        ? <span className="app-field__error">This field is required.</span>
        : hint && <span className="app-field__hint">{hint}</span>}
    </div>
  );
}

function Radios({ value, onChange, options, error }) {
  return (
    <div className={"app-radio-group" + (error ? " is-error" : "")}>
      {options.map(o => (
        <button
          type="button"
          key={o.value}
          className={"app-radio" + (value === o.value ? " is-active" : "")}
          onClick={() => onChange(o.value)}
        >
          {o.label}
        </button>
      ))}
    </div>
  );
}

function StepPersonal({ data, set, errors }) {
  return (
    <>
      <div className="app-step__head">
        <div className="app-step__num">Step 01 / 04</div>
        <h2 className="app-step__title">Tell us about you.</h2>
        <p className="app-step__sub">Standard intake — name, contact, where you live. We'll collect your SSN by phone when you're ready to authorize a credit pull.</p>
      </div>
      <div className="app-fields">
        <Field label="First name" error={errors.firstName}><input value={data.firstName} onChange={e => set("firstName", e.target.value)} placeholder="Jane" /></Field>
        <Field label="Last name" error={errors.lastName}><input value={data.lastName} onChange={e => set("lastName", e.target.value)} placeholder="Doe" /></Field>
        <Field label="Email" error={errors.email}><input type="email" value={data.email} onChange={e => set("email", e.target.value)} placeholder="jane@email.com" /></Field>
        <Field label="Phone" error={errors.phone}><input type="tel" value={data.phone} onChange={e => set("phone", e.target.value)} placeholder="(212) 555-0100" /></Field>
        <Field label="Date of birth" error={errors.dob}><input type="date" value={data.dob} onChange={e => set("dob", e.target.value)} /></Field>
        <Field label="Street address" full error={errors.address}><input value={data.address} onChange={e => set("address", e.target.value)} placeholder="123 Park Ave, Apt 4B" /></Field>
        <Field label="City" error={errors.city}><input value={data.city} onChange={e => set("city", e.target.value)} placeholder="New York" /></Field>
        <Field label="State" error={errors.state}>
          <select value={data.state} onChange={e => set("state", e.target.value)}>
            <option value="">Select…</option>
            <option value="NY">New York</option>
            <option value="NJ">New Jersey</option>
            <option value="CT">Connecticut</option>
            <option value="PA">Pennsylvania</option>
            <option value="other">Other</option>
          </select>
        </Field>
        <Field label="ZIP" error={errors.zip}><input value={data.zip} onChange={e => set("zip", e.target.value)} placeholder="10001" /></Field>
        <Field label="Time at residence" error={errors.timeAtResidence}>
          <select value={data.timeAtResidence} onChange={e => set("timeAtResidence", e.target.value)}>
            <option value="">Select…</option>
            <option>Less than 1 year</option>
            <option>1–2 years</option>
            <option>3–5 years</option>
            <option>5+ years</option>
          </select>
        </Field>
        <Field label="Housing status" full error={errors.housing}>
          <Radios
            value={data.housing}
            onChange={(v) => set("housing", v)}
            error={errors.housing}
            options={[
              { value: "rent", label: "Rent" },
              { value: "own", label: "Own" },
              { value: "family", label: "With family" },
              { value: "other", label: "Other" },
            ]}
          />
        </Field>
        {data.housing === "rent" && (
          <Field label="Monthly rent" full hint="Used by lenders to calculate debt-to-income." error={errors.monthlyRent}>
            <input value={data.monthlyRent} onChange={e => set("monthlyRent", e.target.value)} placeholder="$2,800" />
          </Field>
        )}
        {data.housing === "own" && (
          <Field label="Monthly mortgage payment" full hint="Include taxes & insurance if escrowed." error={errors.monthlyRent}>
            <input value={data.monthlyRent} onChange={e => set("monthlyRent", e.target.value)} placeholder="$3,400" />
          </Field>
        )}
      </div>
    </>
  );
}

function StepEmployment({ data, set, errors }) {
  return (
    <>
      <div className="app-step__head">
        <div className="app-step__num">Step 02 / 04</div>
        <h2 className="app-step__title">Income & employment.</h2>
        <p className="app-step__sub">Lenders need to see income consistency. Self-employed and 1099 are fine — we work with banks that understand both.</p>
      </div>
      <div className="app-fields">
        <Field label="Employment status" full error={errors.empStatus}>
          <Radios
            value={data.empStatus}
            onChange={(v) => set("empStatus", v)}
            error={errors.empStatus}
            options={[
              { value: "ft", label: "Full-time" },
              { value: "pt", label: "Part-time" },
              { value: "self", label: "Self-employed" },
              { value: "retired", label: "Retired" },
              { value: "other", label: "Other" },
            ]}
          />
        </Field>
        <Field label="Employer / Business name" error={errors.employer}><input value={data.employer} onChange={e => set("employer", e.target.value)} placeholder="Acme Co." /></Field>
        <Field label="Job title" error={errors.title}><input value={data.title} onChange={e => set("title", e.target.value)} placeholder="Director of Marketing" /></Field>
        <Field label="Time with employer" error={errors.timeAtJob}>
          <select value={data.timeAtJob} onChange={e => set("timeAtJob", e.target.value)}>
            <option value="">Select…</option>
            <option>Less than 1 year</option>
            <option>1–2 years</option>
            <option>3–5 years</option>
            <option>5+ years</option>
          </select>
        </Field>
        <Field label="Annual gross income" error={errors.income}><input value={data.income} onChange={e => set("income", e.target.value)} placeholder="$120,000" /></Field>
        <Field label="Other monthly income" hint="Bonuses, rental, alimony, etc. Enter $0 if none." error={errors.otherIncome}><input value={data.otherIncome} onChange={e => set("otherIncome", e.target.value)} placeholder="$0" /></Field>
      </div>
    </>
  );
}

function StepVehicle({ data, set, errors }) {
  return (
    <>
      <div className="app-step__head">
        <div className="app-step__num">Step 03 / 04</div>
        <h2 className="app-step__title">The car.</h2>
        <p className="app-step__sub">Tell us what you're after. Specific is great — VIN, trim, color. Vague is fine too. We'll work it out together.</p>
      </div>
      <div className="app-fields">
        <Field label="Structure" full error={errors.structure}>
          <Radios
            value={data.structure}
            onChange={(v) => set("structure", v)}
            error={errors.structure}
            options={[
              { value: "lease", label: "Lease" },
              { value: "finance", label: "Finance" },
              { value: "cash", label: "Cash" },
              { value: "open", label: "Open to either" },
            ]}
          />
        </Field>
        <Field label="Year" error={errors.year}><input value={data.year} onChange={e => set("year", e.target.value)} placeholder="2026" /></Field>
        <Field label="Make" error={errors.make}><input value={data.make} onChange={e => set("make", e.target.value)} placeholder="BMW" /></Field>
        <Field label="Model" error={errors.model}><input value={data.model} onChange={e => set("model", e.target.value)} placeholder="M3 Competition xDrive" /></Field>
        <Field label="Trim / color" error={errors.trim}><input value={data.trim} onChange={e => set("trim", e.target.value)} placeholder="Frozen Black, Black/Silverstone interior" /></Field>
        <Field label="Target monthly payment" error={errors.targetPayment}><input value={data.targetPayment} onChange={e => set("targetPayment", e.target.value)} placeholder="$1,100/mo" /></Field>
        <Field label="Down payment" error={errors.down}><input value={data.down} onChange={e => set("down", e.target.value)} placeholder="$5,000" /></Field>
        <Field label="Lease term (mo)" error={errors.term}>
          <select value={data.term} onChange={e => set("term", e.target.value)}>
            <option value="">Select…</option>
            <option>24 months</option>
            <option>36 months</option>
            <option>39 months</option>
            <option>48 months</option>
            <option>N/A — financing</option>
          </select>
        </Field>
        <Field label="Annual mileage" error={errors.miles}>
          <select value={data.miles} onChange={e => set("miles", e.target.value)}>
            <option value="">Select…</option>
            <option>7,500 / yr</option>
            <option>10,000 / yr</option>
            <option>12,000 / yr</option>
            <option>15,000 / yr</option>
            <option>N/A — financing</option>
          </select>
        </Field>
        <Field label="Trade-in?" full error={errors.tradeIn}>
          <Radios
            value={data.tradeIn}
            onChange={(v) => set("tradeIn", v)}
            error={errors.tradeIn}
            options={[
              { value: "no", label: "No trade" },
              { value: "yes", label: "Yes — have one" },
              { value: "lease-end", label: "Coming off lease" },
            ]}
          />
        </Field>
        <Field label="Anything else we should know?" full error={errors.notes}>
          <textarea rows="3" value={data.notes} onChange={e => set("notes", e.target.value)} placeholder="Special requirements, deadlines, must-have specs, dealer quotes you've already received…" />
        </Field>
      </div>
    </>
  );
}

function StepReview({ data, onEdit, set, errors }) {
  const sections = [
    {
      title: "Personal",
      step: 0,
      rows: [
        ["Name", `${data.firstName} ${data.lastName}`.trim() || "—"],
        ["Email", data.email || "—"],
        ["Phone", data.phone || "—"],
        ["Address", [data.address, data.city, data.state, data.zip].filter(Boolean).join(", ") || "—"],
        ["Housing", data.housing ? `${data.housing}${data.monthlyRent ? ` · ${data.monthlyRent}/mo` : ""}` : "—"],
      ],
    },
    {
      title: "Employment",
      step: 1,
      rows: [
        ["Status", data.empStatus || "—"],
        ["Employer", data.employer || "—"],
        ["Title", data.title || "—"],
        ["Time at job", data.timeAtJob || "—"],
        ["Annual income", data.income || "—"],
      ],
    },
    {
      title: "Vehicle",
      step: 2,
      rows: [
        ["Structure", data.structure || "—"],
        ["Vehicle", [data.year, data.make, data.model, data.trim].filter(Boolean).join(" ") || "—"],
        ["Target payment", data.targetPayment || "—"],
        ["Down payment", data.down || "—"],
        ["Term / Miles", [data.term, data.miles].filter(Boolean).join(" · ") || "—"],
        ["Trade-in", data.tradeIn || "—"],
      ],
    },
  ];

  return (
    <>
      <div className="app-step__head">
        <div className="app-step__num">Step 04 / 04</div>
        <h2 className="app-step__title">One last look.</h2>
        <p className="app-step__sub">Confirm everything's right. By submitting, you authorize 123 Auto Group to obtain a soft credit pull and contact you about your application.</p>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 32 }}>
        {sections.map(s => (
          <div key={s.title} style={{ borderTop: "1px solid var(--line)", paddingTop: 24 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16 }}>
              <h3 style={{ fontFamily: "var(--serif)", fontSize: 28, fontWeight: 400, letterSpacing: "-0.01em" }}>{s.title}</h3>
              <button type="button" onClick={() => onEdit(s.step)} style={{
                fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.12em",
                textTransform: "uppercase", color: "var(--fg-dim)",
              }}>Edit →</button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "180px 1fr", rowGap: 12, fontSize: 15 }}>
              {s.rows.map(([k, v]) => (
                <React.Fragment key={k}>
                  <div style={{ color: "var(--fg-mute)", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", paddingTop: 4 }}>{k}</div>
                  <div style={{ color: "var(--fg)" }}>{v}</div>
                </React.Fragment>
              ))}
            </div>
          </div>
        ))}
      </div>

      <label style={{ display: "flex", gap: 12, alignItems: "flex-start", marginTop: 40, cursor: "pointer", fontSize: 13, color: errors.authorize ? "var(--accent)" : "var(--fg-dim)", lineHeight: 1.5 }}>
        <input type="checkbox" checked={!!data.authorize} onChange={e => set("authorize", e.target.checked)} style={{ marginTop: 4, accentColor: "var(--accent)" }} />
        <span>I authorize 123 Auto Group NYC to obtain a soft credit inquiry and contact me regarding my application via phone, email, or SMS.{errors.authorize && <em style={{ display: "block", fontStyle: "normal", marginTop: 4, fontSize: 12 }}>Authorization is required to submit.</em>}</span>
      </label>
    </>
  );
}

function validateStep(step, data) {
  const e = {};
  if (step === 0) {
    ["firstName", "lastName", "email", "phone", "dob", "address", "city", "state", "zip", "timeAtResidence", "housing"]
      .forEach(k => { if (!data[k]) e[k] = true; });
    if ((data.housing === "rent" || data.housing === "own") && !data.monthlyRent) e.monthlyRent = true;
  }
  if (step === 1) {
    ["empStatus", "employer", "title", "timeAtJob", "income", "otherIncome"]
      .forEach(k => { if (!data[k]) e[k] = true; });
  }
  if (step === 2) {
    ["structure", "year", "make", "model", "trim", "targetPayment", "down", "term", "miles", "tradeIn", "notes"]
      .forEach(k => { if (!data[k]) e[k] = true; });
  }
  if (step === 3) {
    if (!data.authorize) e.authorize = true;
  }
  return e;
}

function CreditApp() {
  const [step, setStep] = useState(0);
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [errors, setErrors] = useState({});
  const [data, setData] = useState({
    firstName: "", lastName: "", email: "", phone: "", dob: "",
    address: "", city: "", state: "", zip: "", timeAtResidence: "", housing: "", monthlyRent: "",
    empStatus: "", employer: "", title: "", timeAtJob: "", income: "", otherIncome: "",
    structure: "", year: "", make: "", model: "", trim: "", targetPayment: "", down: "", term: "", miles: "", tradeIn: "", notes: "",
    authorize: false,
  });
  const set = (k, v) => {
    setData(prev => ({ ...prev, [k]: v }));
    setErrors(prev => {
      if (!prev[k]) return prev;
      const next = { ...prev };
      delete next[k];
      return next;
    });
  };

  useEffect(() => {
    document.documentElement.style.scrollBehavior = "auto";
    window.scrollTo(0, 0);
    document.documentElement.style.scrollBehavior = "smooth";
  }, [step, submitted]);

  if (submitted) {
    return (
      <div className="app-shell">
        <Aside current={STEPS.length} />
        <main className="app-main">
          <div className="app-success">
            <div className="app-success__mark">
              <svg width="32" height="32" viewBox="0 0 32 32" fill="none" stroke="#fff" strokeWidth="2">
                <path d="M8 16l5 5 11-11" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <h2 className="app-success__title">Thanks, {data.firstName || "friend"}.<br /><em>We're on it.</em></h2>
            <p className="app-success__copy">
              Your application is in. A broker will review and reach out within one business day with the structure and terms you qualify for. Check your email — we sent a confirmation.
            </p>
            <div style={{ display: "flex", gap: 12, marginTop: 24 }}>
              <a href="index.html" className="btn btn--ghost">Back to home</a>
              <a href="tel:+17188802418" className="btn btn--primary">Call us instead</a>
            </div>
          </div>
        </main>
      </div>
    );
  }

  return (
    <div className="app-shell">
      <Aside current={step} />
      <main className="app-main">
        <a href="index.html" className="app-back">
          <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 2L3 5l3 3" /></svg>
          Back to site
        </a>
        {step === 0 && <StepPersonal data={data} set={set} errors={errors} />}
        {step === 1 && <StepEmployment data={data} set={set} errors={errors} />}
        {step === 2 && <StepVehicle data={data} set={set} errors={errors} />}
        {step === 3 && <StepReview data={data} onEdit={(i) => setStep(i)} set={set} errors={errors} />}

        {Object.keys(errors).length > 0 && (
          <p className="app-form-error">Please complete every field before continuing.</p>
        )}

        <div className="app-actions">
          {step > 0 ? (
            <button type="button" className="btn btn--ghost" onClick={() => { setErrors({}); setStep(step - 1); }}>
              <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M10 3l-5 5 5 5" /></svg>
              Back
            </button>
          ) : <span />}
          <span className="app-actions__progress">{String(step + 1).padStart(2, "0")} / 0{STEPS.length}</span>
          {step < STEPS.length - 1 ? (
            <button type="button" className="btn btn--primary" onClick={() => {
              const e = validateStep(step, data);
              if (Object.keys(e).length > 0) { setErrors(e); return; }
              setErrors({});
              setStep(step + 1);
            }}>
              Continue
              <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 3l5 5-5 5" /></svg>
            </button>
          ) : (
            <button type="button" disabled={submitting} className="btn btn--primary" style={submitting ? { opacity: 0.6, cursor: 'wait' } : {}} onClick={async () => {
              const finalErrors = { ...validateStep(0, data), ...validateStep(1, data), ...validateStep(2, data), ...validateStep(3, data) };
              if (Object.keys(finalErrors).length > 0) {
                setErrors(finalErrors);
                for (let s = 0; s < 4; s++) {
                  if (Object.keys(validateStep(s, data)).length > 0) { setStep(s); break; }
                }
                return;
              }
              setSubmitting(true);
              setSubmitError("");
              try {
                const res = await fetch("https://api.web3forms.com/submit", {
                  method: "POST",
                  headers: { "Content-Type": "application/json", "Accept": "application/json" },
                  body: JSON.stringify({
                    access_key: "54e7cb7f-fa6c-40d0-96fc-a326fa54a49c",
                    subject: `Credit Application — ${data.firstName} ${data.lastName}`,
                    from_name: "123 Auto Group Credit App",
                    name: `${data.firstName} ${data.lastName}`,
                    email: data.email,
                    phone: data.phone,
                    date_of_birth: data.dob,
                    address: `${data.address}, ${data.city}, ${data.state} ${data.zip}`,
                    time_at_residence: data.timeAtResidence,
                    housing: data.housing,
                    monthly_rent_or_mortgage: data.monthlyRent,
                    employment_status: data.empStatus,
                    employer: data.employer,
                    title: data.title,
                    time_at_job: data.timeAtJob,
                    annual_income: data.income,
                    other_income: data.otherIncome,
                    structure: data.structure,
                    vehicle: `${data.year} ${data.make} ${data.model} ${data.trim}`,
                    target_payment: data.targetPayment,
                    down_payment: data.down,
                    term: data.term,
                    miles: data.miles,
                    trade_in: data.tradeIn,
                    notes: data.notes,
                  }),
                });
                const r = await res.json();
                if (r.success) {
                  setSubmitted(true);
                } else {
                  setSubmitError(r.message || "Submission failed. Please call us directly.");
                }
              } catch (err) {
                setSubmitError("Network error. Please try again or call (718) 880-2418.");
              } finally {
                setSubmitting(false);
              }
            }}>
              {submitting ? "Submitting…" : "Submit application"}
              <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 3l5 5-5 5" /></svg>
            </button>
          )}
        </div>
        {submitError && <p style={{ color: 'var(--accent)', fontSize: 13, marginTop: 16, textAlign: 'right' }}>{submitError}</p>}
      </main>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<CreditApp />);
