// Contact modal — 5-field form with Google Sheets webhook submission.

function ContactModal({ open, onClose }) {
  const [form, setForm] = React.useState({ name: "", company: "", role: "", email: "", message: "" });
  const [errs, setErrs] = React.useState({});
  const [status, setStatus] = React.useState("idle"); // idle | submitting | success | error
  const overlayRef = React.useRef(null);
  const firstFieldRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    setTimeout(() => firstFieldRef.current && firstFieldRef.current.focus(), 240);
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  React.useEffect(() => {
    if (open) {
      setStatus("idle");
      setErrs({});
      setForm({ name: "", company: "", role: "", email: "", message: "" });
    }
  }, [open]);

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Please enter your name";
    if (!form.company.trim()) e.company = "Please enter your company";
    if (!form.role.trim()) e.role = "Please enter your role";
    if (!form.email.trim()) e.email = "Please enter your email";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Please enter a valid email";
    if (!form.message.trim()) e.message = "Please write a short note";
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setStatus("submitting");

    const WEBHOOK = window.DEALVAULT_SHEETS_WEBHOOK;
    const payload = {
      ...form,
      submittedAt: new Date().toISOString(),
      source: "dealvault.tech",
      userAgent: navigator.userAgent,
    };

    try {
      if (WEBHOOK && /^https:\/\/script\.google\.com/.test(WEBHOOK)) {
        // Google Apps Script Web App endpoint — use no-cors form-encoded POST
        // to avoid the CORS preflight that opaque Apps Script endpoints reject.
        const body = new URLSearchParams(payload);
        await fetch(WEBHOOK, {
          method: "POST",
          mode: "no-cors",
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
          body,
        });
      } else {
        // Demo mode — simulate
        await new Promise((r) => setTimeout(r, 900));
      }
      setStatus("success");
    } catch (err) {
      console.warn("[DealVault] submission error", err);
      setStatus("error");
    }
  };

  const handleOverlayClick = (e) => {
    if (e.target === overlayRef.current) onClose();
  };

  if (!open && status === "idle") return null;

  return (
    <div
      ref={overlayRef}
      className={"modal-overlay " + (open ? "open" : "")}
      role="dialog"
      aria-modal="true"
      aria-labelledby="contact-modal-title"
      onMouseDown={handleOverlayClick}
    >
      <div className="modal" onMouseDown={(e) => e.stopPropagation()}>
        <button className="modal__close" aria-label="Close" onClick={onClose}><X size={14} /></button>

        {status !== "success" ? (
          <>
            <div className="label" style={{ marginBottom: 14 }}>Send request</div>
            <h3 id="contact-modal-title">Send a brief. Get a shortlist.</h3>
            <p className="modal__sub">
              Tell us about your product, audience, and budget — we'll come back within
              one business day with next steps. Free for our clients.
            </p>

            <form className="form" onSubmit={submit} noValidate>
              <div className="modal-row">
                <div className={"field " + (errs.name ? "err" : "")}>
                  <label htmlFor="f-name">Name *</label>
                  <input ref={firstFieldRef} id="f-name" type="text" autoComplete="name"
                    placeholder="Alex Morgan" value={form.name} onChange={set("name")} aria-invalid={!!errs.name} />
                  {errs.name && <span className="err-msg">{errs.name}</span>}
                </div>
                <div className={"field " + (errs.company ? "err" : "")}>
                  <label htmlFor="f-company">Company *</label>
                  <input id="f-company" type="text" autoComplete="organization"
                    placeholder="Acme Fintech" value={form.company} onChange={set("company")} aria-invalid={!!errs.company} />
                  {errs.company && <span className="err-msg">{errs.company}</span>}
                </div>
              </div>

              <div className="modal-row">
                <div className={"field " + (errs.role ? "err" : "")}>
                  <label htmlFor="f-role">Role *</label>
                  <input id="f-role" type="text" autoComplete="organization-title"
                    placeholder="Head of Growth" value={form.role} onChange={set("role")} aria-invalid={!!errs.role} />
                  {errs.role && <span className="err-msg">{errs.role}</span>}
                </div>
                <div className={"field " + (errs.email ? "err" : "")}>
                  <label htmlFor="f-email">Email *</label>
                  <input id="f-email" type="email" autoComplete="email" inputMode="email"
                    placeholder="alex@acme.com" value={form.email} onChange={set("email")} aria-invalid={!!errs.email} />
                  {errs.email && <span className="err-msg">{errs.email}</span>}
                </div>
              </div>

              <div className={"field " + (errs.message ? "err" : "")}>
                <label htmlFor="f-message">Message *</label>
                <textarea id="f-message" rows="4"
                  placeholder="A line or two about your product, audience, and what you're looking for."
                  value={form.message} onChange={set("message")} aria-invalid={!!errs.message} />
                {errs.message && <span className="err-msg">{errs.message}</span>}
              </div>

              {status === "error" && (
                <div className="err-msg" style={{ background: "color-mix(in srgb, var(--accent) 12%, transparent)", padding: "10px 14px", borderRadius: 4 }}>
                  Couldn't send right now. Please email us directly at dmitrii@dealvault.tech
                </div>
              )}

              <div className="form-foot">
                <span className="note">We'll only use this to reply to you.</span>
                <button className="btn btn-primary" type="submit" disabled={status === "submitting"}>
                  {status === "submitting" ? "Sending…" : "Send brief"}
                  {status !== "submitting" && <ArrowR size={14} />}
                </button>
              </div>
            </form>
          </>
        ) : (
          <div className="modal__success" role="status" aria-live="polite">
            <div className="icon"><Check size={28} /></div>
            <div className="label" style={{ marginBottom: 14 }}>Received</div>
            <h3 style={{ marginBottom: 16 }}>Brief received. Talk soon.</h3>
            <p className="body-m" style={{ color: "var(--muted)", maxWidth: "42ch" }}>
              Thanks, {form.name.split(" ")[0] || "there"}. We'll review your note and come
              back within one business day. If it's urgent, email{" "}
              <a href="mailto:dmitrii@dealvault.tech" style={{ color: "var(--accent)" }}>dmitrii@dealvault.tech</a>.
            </p>
            <div style={{ marginTop: 28, display: "flex", gap: 12 }}>
              <button className="btn btn-ink" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.ContactModal = ContactModal;
