/* ============================================================
   QuoteModal — multi-field form, validation, mock submit
   ============================================================ */

const QuoteModal = ({ open, onClose }) => {
  const empty = { name: "", phone: "", email: "", service: "", region: "", date: "", notes: "" };
  const [form, setForm] = useState(empty);
  const [errors, setErrors] = useState({});
  const [stage, setStage] = useState("form"); // form | sending | done

  useEffect(() => {
    if (open) { setStage("form"); setErrors({}); setForm(empty); }
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const set = (k, v) => { setForm((f) => ({ ...f, [k]: v })); setErrors((e) => ({ ...e, [k]: undefined })); };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Please enter your name";
    if (!/^[+0-9 ()-]{7,}$/.test(form.phone.trim())) e.phone = "Enter a valid phone number";
    if (form.email && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email.trim())) e.email = "Enter a valid email";
    if (!form.service) e.service = "Select a service";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setStage("sending");
    fetch("submit.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...form, form_source: "quote_modal" }),
    })
      .then((r) => r.json())
      .then((res) => {
        if (res.ok) setStage("done");
        else {
          setStage("form");
          setErrors({ name: res.message || "Submission failed. Please try again." });
        }
      })
      .catch(() => {
        setStage("form");
        setErrors({ name: "Network error. Please call us at +65 935 7444 7." });
      });
  };

  const services = ["Residential", "Commercial", "F&B", "Deep Clean", "Not sure yet"];
  const regions = ["Central", "East", "West", "North", "North-East"];

  return (
    <div className={`modal-overlay ${open ? "open" : ""}`} onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        {stage === "done" ? (
          <div className="success">
            <div className="check"><Icon name="check" /></div>
            <h3>Request received!</h3>
            <p>Thank you, {form.name.split(" ")[0] || "there"}. Our team will get back to you with a free, no-obligation quote within one business day.</p>
            <button className="btn btn-dark btn-lg" style={{ marginTop: 28 }} onClick={onClose}>Close</button>
          </div>
        ) : (
          <>
            <div className="modal-head">
              <button className="modal-close" onClick={onClose} aria-label="Close"><Icon name="x" /></button>
              <h3>Get a Free Quote</h3>
              <p>Tell us a little about your space and we'll get back within one business day.</p>
            </div>
            <form className="modal-body" onSubmit={submit} noValidate>
              <div className="field-row">
                <div className={`field ${errors.name ? "err" : ""}`}>
                  <label>Name <span className="req">*</span></label>
                  <input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Your name" />
                  {errors.name && <div className="msg">{errors.name}</div>}
                </div>
                <div className={`field ${errors.phone ? "err" : ""}`}>
                  <label>Phone <span className="req">*</span></label>
                  <input value={form.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+65 ..." inputMode="tel" />
                  {errors.phone && <div className="msg">{errors.phone}</div>}
                </div>
              </div>

              <div className={`field ${errors.email ? "err" : ""}`}>
                <label>Email</label>
                <input value={form.email} onChange={(e) => set("email", e.target.value)} placeholder="you@example.com" inputMode="email" />
                {errors.email && <div className="msg">{errors.email}</div>}
              </div>

              <div className={`field ${errors.service ? "err" : ""}`}>
                <label>Service needed <span className="req">*</span></label>
                <div className="chip-row">
                  {services.map((s) => (
                    <button type="button" key={s} className={`chip ${form.service === s ? "active" : ""}`} onClick={() => set("service", s)}>{s}</button>
                  ))}
                </div>
                {errors.service && <div className="msg">{errors.service}</div>}
              </div>

              <div className="field-row">
                <div className="field">
                  <label>Region</label>
                  <select value={form.region} onChange={(e) => set("region", e.target.value)}>
                    <option value="">Select region</option>
                    {regions.map((r) => <option key={r} value={r}>{r} Singapore</option>)}
                  </select>
                </div>
                <div className="field">
                  <label>Preferred date</label>
                  <input type="date" value={form.date} onChange={(e) => set("date", e.target.value)} />
                </div>
              </div>

              <div className="field">
                <label>Notes</label>
                <textarea value={form.notes} onChange={(e) => set("notes", e.target.value)} placeholder="Square footage, frequency, special requirements..."></textarea>
              </div>

              <button type="submit" className="btn btn-primary btn-lg" style={{ width: "100%" }} disabled={stage === "sending"}>
                {stage === "sending" ? "Sending…" : <>Request My Free Quote <Icon name="arrow" /></>}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
};

window.QuoteModal = QuoteModal;
