// contact.jsx — consultation intake (no calendar)
// Customer reaches out first with vehicle + goals + contact; we consult, then schedule.
// ─────────────────────────────────────────────────────────────

const { useState: useStateC, useMemo: useMemoC } = React;

// ─────────────────────────────────────── INTAKE FORM ──────────
function BookingFlow() {
  const [step, setStep] = useStateC(0);
  const [data, setData] = useStateC({
    vehicle: "", year: "", color: "",
    notes: "", goal: "", address: "",
    name: "", contact: "", refer: "",
  });
  const [submitted, setSubmitted] = useStateC(false);
  const [sending, setSending] = useStateC(false);
  const [error, setError] = useStateC("");
  const [ref, setRef] = useStateC("");
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  // Submit to Netlify Forms. Encodes the intake as url-encoded form data and
  // POSTs to the site root, where Netlify intercepts the "booking" form.
  async function submitBooking() {
    setSending(true);
    setError("");
    const refCode = Math.random().toString(36).slice(2, 8).toUpperCase();
    const payload = {
      "form-name": "booking",
      "company": "", // honeypot, must stay empty
      vehicle: data.vehicle, year: data.year, color: data.color,
      address: data.address, notes: data.notes, goal: data.goal,
      name: data.name, contact: data.contact, refer: data.refer,
      ref: refCode,
    };
    const body = new URLSearchParams(payload).toString();
    try {
      const res = await fetch("/", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body,
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      setRef(refCode);
      setSubmitted(true);
    } catch (e) {
      // Only a live Netlify deploy has the form backend. Anywhere else — local
      // dev, the file:// protocol, or the editor preview sandbox — the POST 404s,
      // so show a graceful demo confirmation. Real production failures (a genuine
      // network drop on the live site) still surface the contact fallback.
      const h = location.hostname;
      const isDemoHost =
        h === "localhost" || h === "127.0.0.1" ||
        location.protocol === "file:" ||
        h.endsWith(".claudeusercontent.com") ||
        h.endsWith(".webcontainer.io") ||
        h === "";
      if (isDemoHost) {
        setRef(refCode);
        setSubmitted(true);
      } else {
        setError("Something went wrong sending your brief. Please email jewelthepaint@gmail.com or call (408) 987-5587.");
      }
    } finally {
      setSending(false);
    }
  }

  const steps = [
    { label: "Vehicle",  key: "vehicle" },
    { label: "Goal",     key: "goal" },
    { label: "Contact",  key: "contact" },
    { label: "Review",   key: "confirm" },
  ];

  return (
    <section id="book" className="section" style={{
      paddingTop: "var(--pad-section)", paddingBottom: "var(--pad-section)",
      borderTop: "1px solid var(--rule)", background: "var(--bg-2)",
    }}>
      <div className="wrap responsive-grid-2" style={{
        display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 64,
      }}>
        <div className="col gap-16">
          <div className="spec">§ 02 · START A CONSULTATION</div>
          <h2 className="h-display" style={{ fontSize: "clamp(36px, 5vw, 64px)", margin: 0 }}>
            Start a<br /><em>conversation</em>.
          </h2>
          <p style={{
            fontFamily: "var(--serif)", fontWeight: 300, fontSize: 18,
            color: "var(--ink-2)", lineHeight: 1.55, margin: 0, maxWidth: 460,
          }}>
            Every car is different, so we begin with a conversation — not a
            calendar. Tell us about the vehicle and what you're hoping for, and
            we'll respond within two business days with a written brief. If we're
            a good fit, we'll schedule an in-person inspection from there.
          </p>
          <div className="col gap-12" style={{
            marginTop: 16, paddingTop: 24, borderTop: "1px solid var(--rule)",
          }}>
            <div className="spec">HOW IT WORKS</div>
            <ol style={{
              margin: 0, padding: 0, listStyle: "none",
              display: "flex", flexDirection: "column", gap: 10,
            }}>
              {[
                ["01", "You send the brief below"],
                ["02", "We reply within two business days"],
                ["03", "In-person inspection & quote"],
                ["04", "We schedule the correction"],
              ].map(([n, t]) => (
                <li key={n} className="row gap-12" style={{ alignItems: "baseline" }}>
                  <span className="num" style={{ color: "var(--accent)", fontSize: 12 }}>{n}</span>
                  <span style={{ fontFamily: "var(--serif)", fontSize: 17, fontWeight: 300, color: "var(--ink-2)" }}>{t}</span>
                </li>
              ))}
            </ol>
          </div>
          <div className="col gap-8" style={{
            marginTop: 16, paddingTop: 24, borderTop: "1px solid var(--rule)",
          }}>
            <div className="spec">OR REACH US DIRECTLY</div>
            <a href="tel:+14089875587" style={{
              fontFamily: "var(--serif)", fontSize: 22, fontWeight: 300,
              color: "var(--ink)",
            }}>(408) 987-5587</a>
            <a href="mailto:jewelthepaint@gmail.com" style={{
              fontFamily: "var(--serif)", fontSize: 22, fontWeight: 300,
              color: "var(--ink)",
            }}>jewelthepaint@gmail.com</a>
          </div>
        </div>

        <div style={{
          background: "var(--bg)", border: "1px solid var(--rule)",
          padding: "32px 36px",
          display: "flex", flexDirection: "column", gap: 24, minHeight: 600,
        }}>
          {/* progress */}
          <div className="row" style={{ gap: 0, alignItems: "center", flexWrap: "wrap" }}>
            {steps.map((s, i) => (
              <React.Fragment key={s.key}>
                <div className="row gap-8" style={{ alignItems: "center" }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: "50%",
                    background: i <= step ? "var(--ink)" : "var(--bg-3)",
                    color: i <= step ? "var(--bg)" : "var(--ink-3)",
                    fontFamily: "var(--mono)", fontSize: 11,
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>{i + 1}</div>
                  <div className="spec" style={{
                    color: i <= step ? "var(--ink)" : "var(--ink-3)",
                    fontWeight: i === step ? 500 : 400,
                  }}>{s.label}</div>
                </div>
                {i < steps.length - 1 && (
                  <div style={{
                    flex: 1, minWidth: 12, height: 1,
                    background: "var(--rule)", margin: "0 10px",
                  }} />
                )}
              </React.Fragment>
            ))}
          </div>

          <div style={{ height: 1, background: "var(--rule)" }} />

          {/* steps */}
          {step === 0 && (
            <div className="col gap-16">
              <Field label="Make & model" placeholder="e.g. 2022 911 GT3 Touring"
                     value={data.vehicle} onChange={v => set("vehicle", v)} />
              <div className="row gap-16">
                <Field label="Year" placeholder="2022"
                       value={data.year} onChange={v => set("year", v)}
                       style={{ flex: 1 }} />
                <Field label="Colour" placeholder="Aventurine Green Metallic"
                       value={data.color} onChange={v => set("color", v)}
                       style={{ flex: 2 }} />
              </div>
              <Field label="Driveway / address" placeholder="City, neighborhood — exact address shared after intake"
                     value={data.address} onChange={v => set("address", v)} />
              <Field label="Notes for the studio" multiline rows={4}
                     placeholder={"Anything we should know — known swirls, prior\ncorrection, deadlines, paint history, sentimental\nconcerns. The more, the better."}
                     value={data.notes} onChange={v => set("notes", v)} />
            </div>
          )}

          {step === 1 && (
            <div className="col gap-16">
              <div className="spec">WHAT BRINGS YOU IN?</div>
              <div className="col gap-8">
                {[
                  "Multi-stage paint correction",
                  "Concours / show-prep finish",
                  "Single-stage refinement (sale prep, light enhancement)",
                  "Ceramic coating after correction",
                  "Headlight restoration",
                  "Maintenance visit (existing client)",
                  "Not sure yet — would like a consultation",
                ].map(opt => (
                  <label key={opt} style={{
                    display: "flex", gap: 12, alignItems: "center",
                    padding: "12px 14px", border: "1px solid var(--rule)",
                    cursor: "pointer",
                    background: data.goal === opt ? "var(--bg-2)" : "var(--bg)",
                  }}>
                    <input type="radio" name="goal" checked={data.goal === opt}
                           onChange={() => set("goal", opt)}
                           style={{ accentColor: "var(--ink)" }} />
                    <span style={{ fontSize: 14 }}>{opt}</span>
                  </label>
                ))}
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="col gap-16">
              <Field label="Your name" placeholder="Jane Driver"
                     value={data.name} onChange={v => set("name", v)} />
              <Field label="Email or phone" placeholder="jane@domain.com  /  (415) 555-0182"
                     value={data.contact} onChange={v => set("contact", v)} />
              <Field label="How did you hear about us?" placeholder="Referral, search, instagram…"
                     value={data.refer} onChange={v => set("refer", v)} />
            </div>
          )}

          {step === 3 && !submitted && (
            <div className="col gap-12">
              <div className="spec">REVIEW & SEND</div>
              <Row k="Vehicle" v={`${data.year || "—"} ${data.vehicle || "—"}`} />
              <Row k="Colour" v={data.color || "—"} />
              <Row k="Driveway" v={data.address || "—"} />
              <Row k="Notes" v={data.notes || "—"} />
              <Row k="Goal" v={data.goal || "—"} />
              <Row k="Name" v={data.name || "—"} />
              <Row k="Contact" v={data.contact || "—"} />
              <p style={{
                fontFamily: "var(--serif)", fontStyle: "italic", fontWeight: 300,
                color: "var(--ink-3)", fontSize: 16, marginTop: 16,
              }}>
                "We'll respond within two business days with a written brief.
                If we're a good fit, we'll arrive in person for an inspection."
              </p>
              {error && (
                <div style={{
                  background: "var(--bg-2)", border: "1px solid var(--accent)",
                  padding: "12px 16px", marginTop: 8,
                  fontFamily: "var(--serif)", fontSize: 15, color: "var(--ink-2)",
                  lineHeight: 1.5,
                }}>{error}</div>
              )}
            </div>
          )}

          {step === 3 && submitted && (
            <div className="col gap-16" style={{
              alignItems: "center", textAlign: "center", padding: "32px 0",
            }}>
              <div className="spec" style={{ color: "var(--accent)" }}>RECEIVED</div>
              <h3 style={{
                fontFamily: "var(--serif)", fontSize: 36, fontWeight: 300,
                margin: 0, letterSpacing: "-0.02em",
              }}>
                We have your <em>brief</em>.
              </h3>
              <p style={{
                fontFamily: "var(--serif)", fontStyle: "italic", fontWeight: 300,
                fontSize: 18, color: "var(--ink-2)", maxWidth: 420, margin: 0,
              }}>
                We'll reply within two business days to set up a consultation —
                either confirming next steps or asking a few more questions first.
              </p>
              <div className="spec" style={{ color: "var(--ink-4)" }}>
                REF · {ref}
              </div>
            </div>
          )}

          {/* nav */}
          {!submitted && (
            <div className="row" style={{
              justifyContent: "space-between", alignItems: "center",
              marginTop: "auto", paddingTop: 16,
              borderTop: "1px solid var(--rule)",
            }}>
              <button onClick={() => setStep(s => Math.max(0, s - 1))}
                      disabled={step === 0}
                      className="btn btn-ghost" style={{
                        opacity: step === 0 ? 0.3 : 1,
                        pointerEvents: step === 0 ? "none" : "auto",
                      }}>
                ← Back
              </button>
              <div className="num" style={{ color: "var(--ink-3)", fontSize: 12 }}>
                STEP {step + 1} / {steps.length}
              </div>
              {step < steps.length - 1 ? (
                <button onClick={() => setStep(s => Math.min(steps.length - 1, s + 1))}
                        className="btn">
                  Continue <span className="arr">→</span>
                </button>
              ) : (
                <button onClick={submitBooking} disabled={sending} className="btn"
                        style={{ opacity: sending ? 0.5 : 1 }}>
                  {sending ? "Sending…" : <>Send brief <span className="arr">→</span></>}
                </button>
              )}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function Field({ label, value, onChange, placeholder, style, multiline, rows = 3 }) {
  const sharedStyle = {
    border: 0, borderBottom: "1px solid var(--rule)",
    background: "transparent", padding: "10px 2px",
    fontFamily: "var(--serif)", fontSize: 18, fontWeight: 300,
    color: "var(--ink)", outline: "none",
    width: "100%", resize: "vertical", lineHeight: 1.45,
  };
  return (
    <label className="col gap-8" style={style}>
      <span className="spec">{label.toUpperCase()}</span>
      {multiline ? (
        <textarea value={value} onChange={e => onChange(e.target.value)}
                  placeholder={placeholder} rows={rows} style={sharedStyle}
                  onFocus={e => { e.target.style.borderBottomColor = "var(--ink)"; }}
                  onBlur={e => { e.target.style.borderBottomColor = "var(--rule)"; }} />
      ) : (
        <input value={value} onChange={e => onChange(e.target.value)}
               placeholder={placeholder} style={sharedStyle}
               onFocus={e => { e.target.style.borderBottomColor = "var(--ink)"; }}
               onBlur={e => { e.target.style.borderBottomColor = "var(--rule)"; }} />
      )}
    </label>
  );
}

function Row({ k, v }) {
  return (
    <div className="row" style={{
      justifyContent: "space-between", padding: "10px 0",
      borderBottom: "1px dashed var(--rule)", gap: 16,
    }}>
      <div className="spec" style={{ color: "var(--ink-3)" }}>{k}</div>
      <div style={{
        fontFamily: "var(--serif)", fontSize: 16, fontWeight: 300,
        textAlign: "right", maxWidth: "65%",
      }}>{v}</div>
    </div>
  );
}

Object.assign(window, { BookingFlow });
