// Multi-step quote request modal with validation + configurator prefill.
function Field({ label, children, half, required }) {
  return (
    <label style={{ display: "block", gridColumn: half ? "span 1" : "span 2" }}>
      <span style={{ display: "block", fontFamily: FONT.body, fontSize: 12.5, fontWeight: 700, letterSpacing: "0.1em",
        textTransform: "uppercase", color: NP.textL2, marginBottom: 8 }}>{label}{required && <span style={{ color: NP.gold }}> *</span>}</span>
      {children}
    </label>
  );
}
const inputStyle = {
  width: "100%", fontFamily: FONT.body, fontSize: 15.5, color: NP.textL, background: NP.panel2,
  border: `1px solid ${NP.lineL}`, borderRadius: 3, padding: "13px 15px", outline: "none", boxSizing: "border-box",
};
function TextInput(props) {
  return <input {...props} style={{ ...inputStyle, ...(props.style || {}) }}
    onFocus={(e) => (e.target.style.borderColor = NP.gold)}
    onBlur={(e) => (e.target.style.borderColor = NP.lineL)} />;
}
function PickRow({ options, value, onChange, multi }) {
  const sel = multi ? value : [value];
  const pick = (o) => { if (multi) { onChange(value.includes(o) ? value.filter((x) => x !== o) : [...value, o]); } else onChange(o); };
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
      {options.map((o) => {
        const on = sel.includes(o);
        return (
          <button key={o} type="button" onClick={() => pick(o)}
            style={{ fontFamily: FONT.body, fontSize: 14, fontWeight: 600, padding: "11px 17px", borderRadius: 999, cursor: "pointer", transition: "all .15s",
              background: on ? "rgba(200,174,118,0.14)" : NP.panel2, color: on ? NP.gold : NP.textL,
              border: `1px solid ${on ? NP.gold : NP.lineL}` }}>{o}</button>
        );
      })}
    </div>
  );
}

const STEPS = ["Project", "Location", "Contact"];
function QuoteModal({ open, onClose, prefill }) {
  const w = useW();
  const mobile = w < 560;
  const [step, setStep] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(false);
  const [f, setF] = React.useState({ interest: "Not sure yet", size: "", timeline: "", address: "", city: "", zip: "", first: "", last: "", email: "", phone: "", notes: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));

  React.useEffect(() => {
    if (open) {
      document.body.style.overflow = "hidden";
      setStep(0); setDone(false); setSending(false); setError(false);
      if (prefill && prefill.style) set("interest", normalizeInterest(prefill.style));
      if (prefill && prefill.notes) set("notes", prefill.notes);
    } else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  if (!open) return null;
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email);
  const phoneOk = f.phone.replace(/\D/g, "").length >= 10;
  const zipOk = /^\d{5}$/.test(f.zip);
  const valid = [
    !!f.interest && !!f.timeline,
    !!f.city && zipOk,
    !!f.first && !!f.last && emailOk && phoneOk,
  ];
  const next = async () => {
    if (step < 2) { setStep(step + 1); return; }
    if (!valid[2] || sending) return;
    setSending(true); setError(false);
    const lead = {
      interest: f.interest, size: f.size || "—", timeline: f.timeline,
      address: f.address || "—", city: f.city, zip: f.zip,
      name: `${f.first} ${f.last}`, email: f.email, phone: f.phone,
      notes: f.notes || "—",
      estimate: prefill && prefill.est ? `$${prefill.est.lo.toLocaleString()}–${prefill.est.hi.toLocaleString()}` : "—",
    };
    const r = await submitLead(lead, `New quote request — ${f.first} ${f.last} (${f.city})`);
    setSending(false);
    if (r.ok) setDone(true); else setError(true);
  };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 300, background: "rgba(10,8,6,0.86)", backdropFilter: "blur(3px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "min(720px, 96vw)", maxHeight: "92vh", overflowY: "auto",
        background: NP.panel, border: `1px solid ${NP.lineL}`, borderRadius: 6, boxShadow: "0 40px 120px rgba(0,0,0,0.6)" }}>
        {/* header */}
        <div style={{ padding: mobile ? "20px 20px 0" : "26px 36px 0", display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <NPLogoImg onDark height={42} />
          <button onClick={onClose} style={{ background: "none", border: "none", color: NP.textL2, fontSize: 28, cursor: "pointer", lineHeight: 1 }}>×</button>
        </div>

        {done ? (
          <div style={{ padding: "30px 36px 56px", textAlign: "center" }}>
            <div style={{ width: 64, height: 64, borderRadius: 32, margin: "20px auto 0", background: "rgba(200,174,118,0.15)",
              border: `1px solid ${NP.gold}`, display: "flex", alignItems: "center", justifyContent: "center", color: NP.gold, fontSize: 30 }}>✓</div>
            <h3 style={{ fontFamily: FONT.disp, fontWeight: 700, fontSize: 34, textTransform: "uppercase", color: NP.textL, margin: "24px 0 12px" }}>Request received</h3>
            <p style={{ fontFamily: FONT.body, fontSize: 16.5, lineHeight: 1.6, color: NP.textL2, maxWidth: 420, margin: "0 auto" }}>
              Thanks, {f.first}. A NorthPoint estimator will reach out within one business day to schedule your free on-site measure.
            </p>
            <div style={{ marginTop: 26 }}><Btn variant="solid" onClick={onClose}>Done</Btn></div>
          </div>
        ) : (
          <React.Fragment>
            {/* progress */}
            <div style={{ padding: mobile ? "16px 20px 4px" : "22px 36px 4px", display: "flex", gap: 8 }}>
              {STEPS.map((s, i) => (
                <div key={s} style={{ flex: 1 }}>
                  <div style={{ height: 3, borderRadius: 2, background: i <= step ? NP.gold : NP.lineL, transition: "background .3s" }} />
                  <div style={{ fontFamily: FONT.body, fontSize: 11.5, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase",
                    color: i === step ? NP.gold : NP.textL2, marginTop: 8 }}>{i + 1}. {s}</div>
                </div>
              ))}
            </div>

            {prefill && prefill.summary && step === 0 && (
              <div style={{ margin: mobile ? "12px 20px 0" : "16px 36px 0", padding: "12px 16px", borderRadius: 4, background: "rgba(200,174,118,0.10)", border: `1px solid rgba(200,174,118,0.3)` }}>
                <span style={{ fontFamily: FONT.body, fontSize: 13.5, color: NP.textL }}>Starting from your design: <strong style={{ color: NP.gold }}>{prefill.summary}</strong>
                  {prefill.est && <span style={{ color: NP.textL2 }}> · est. ${prefill.est.lo.toLocaleString()}–${prefill.est.hi.toLocaleString()}</span>}</span>
              </div>
            )}

            <div style={{ padding: mobile ? "20px 20px 8px" : "26px 36px 8px", minHeight: 280 }}>
              {step === 0 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
                  <Field label="What are you interested in?" required><PickRow options={["Lattice", "Solid Cover", "Louvered", "Insulated", "Privacy / Screens", "Not sure yet"]} value={f.interest} onChange={(v) => set("interest", v)} /></Field>
                  <Field label="Approx. size (optional)"><PickRow options={["Small", "Medium", "Large", "Grand", "Not sure"]} value={f.size} onChange={(v) => set("size", v)} /></Field>
                  <Field label="Timeline" required><PickRow options={["ASAP", "1–3 months", "3–6 months", "Just exploring"]} value={f.timeline} onChange={(v) => set("timeline", v)} /></Field>
                </div>
              )}
              {step === 1 && (
                <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: 18 }}>
                  <Field label="Street address (optional)"><TextInput value={f.address} onChange={(e) => set("address", e.target.value)} placeholder="1234 E Desert Ln" /></Field>
                  <Field label="City" half required>
                    <select value={f.city} onChange={(e) => set("city", e.target.value)} style={{ ...inputStyle, appearance: "none" }}>
                      <option value="" style={{ color: "#000" }}>Select a city…</option>
                      {["Phoenix", "Scottsdale", "Tempe", "Chandler", "Gilbert", "Mesa", "Queen Creek", "San Tan Valley", "Rio Verde", "Other"].map((c) => <option key={c} value={c} style={{ color: "#000" }}>{c}</option>)}
                    </select>
                  </Field>
                  <Field label="ZIP" half required><TextInput value={f.zip} onChange={(e) => set("zip", e.target.value.replace(/\D/g, "").slice(0, 5))} placeholder="85295" inputMode="numeric" /></Field>
                </div>
              )}
              {step === 2 && (
                <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: 18 }}>
                  <Field label="First name" half required><TextInput value={f.first} onChange={(e) => set("first", e.target.value)} placeholder="Jordan" /></Field>
                  <Field label="Last name" half required><TextInput value={f.last} onChange={(e) => set("last", e.target.value)} placeholder="Reyes" /></Field>
                  <Field label="Email" half required><TextInput value={f.email} onChange={(e) => set("email", e.target.value)} placeholder="you@email.com" /></Field>
                  <Field label="Phone" half required><TextInput value={f.phone} onChange={(e) => set("phone", e.target.value)} placeholder="(623) 330-9095" inputMode="tel" /></Field>
                  <Field label="Anything else? (optional)"><textarea value={f.notes} onChange={(e) => set("notes", e.target.value)} rows={3} placeholder="Tell us about your space, goals, or questions…" style={{ ...inputStyle, resize: "vertical" }} /></Field>
                </div>
              )}
            </div>

            {/* footer */}
            {error && (
              <div style={{ margin: mobile ? "0 20px" : "0 36px", padding: "12px 16px", borderRadius: 4, background: "rgba(180,70,50,0.12)", border: "1px solid rgba(180,70,50,0.4)" }}>
                <span style={{ fontFamily: FONT.body, fontSize: 13.5, color: NP.textL }}>Something went wrong sending your request. Please call <strong style={{ color: NP.gold }}>(623) 330-9095</strong> or email info@northpointpergolas.com.</span>
              </div>
            )}
            <div style={{ padding: mobile ? "12px 20px 24px" : "12px 36px 30px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <button onClick={() => (step === 0 ? onClose() : setStep(step - 1))}
                style={{ fontFamily: FONT.body, fontSize: 14, fontWeight: 600, background: "none", border: "none", color: NP.textL2, cursor: "pointer" }}>
                {step === 0 ? "Cancel" : "← Back"}
              </button>
              <Btn variant="solid" onClick={next} style={{ opacity: (valid[step] && !sending) ? 1 : 0.4, pointerEvents: (valid[step] && !sending) ? "auto" : "none" }}>
                {step < 2 ? "Continue →" : (sending ? "Sending…" : "Submit request")}
              </Btn>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}
function normalizeInterest(s) {
  const m = { "Lattice Cover": "Lattice", "Solid Cover": "Solid Cover", "Louvered System": "Louvered", "Insulated Panel": "Insulated" };
  return m[s] || "Not sure yet";
}
window.QuoteModal = QuoteModal;
