// Contact modal
const ContactModal = ({ open, onClose }) => {
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [submitError, setSubmitError] = React.useState("");
  const [form, setForm] = React.useState({ name: "", email: "", organization: "", role: "", message: "" });
  const [errors, setErrors] = React.useState({});

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

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

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = "Required";
    if (!form.email.trim()) errs.email = "Required";else
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) errs.email = "Invalid email";
    if (!form.organization.trim()) errs.organization = "Required";
    if (!form.message.trim() || form.message.trim().length < 10) errs.message = "Tell us a little more";
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    setSending(true);
    setSubmitError("");
    try {
      const res = await fetch("https://formspree.io/f/meenkqog", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          organization: form.organization,
          role: form.role,
          message: form.message,
        }),
      });
      const data = await res.json();
      if (res.ok) {
        setSubmitted(true);
        setTimeout(() => {
          onClose();
          setTimeout(() => {
            setSubmitted(false);
            setForm({ name: "", email: "", organization: "", role: "", message: "" });
          }, 400);
        }, 2200);
      } else {
        setSubmitError((data && data.error) ? data.error : "Something went wrong. Please try again.");
      }
    } catch (_) {
      setSubmitError("Unable to send — please check your connection and try again.");
    } finally {
      setSending(false);
    }
  };

  return (
    <div className={`modal-backdrop ${open ? "open" : ""}`} onClick={(e) => {if (e.target === e.currentTarget) onClose();}}>
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby="contact-title">
        <aside className="modal-aside">
          <div className="eyebrow">Get in touch</div>
          <h3 id="contact-title">Tell us about your team and we'll be in touch within 2 working days.</h3>
          <p>Whether you're a ministry, an agency or an NGO — we'll set up a 30-minute call to map your workflow before recommending anything.</p>
          <ul>
            <li>
              <svg viewBox="0 0 24 24" fill="none"><path d="M5 13L9 17L19 7" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
              Pintone walkthrough
            </li>
            <li>
              <svg viewBox="0 0 24 24" fill="none"><path d="M5 13L9 17L19 7" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
              Procurement-ready pricing options
            </li>
            <li>
              <svg viewBox="0 0 24 24" fill="none"><path d="M5 13L9 17L19 7" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
              Pilot scoping if there's a fit
            </li>
          </ul>
        </aside>
        <div className="modal-form">
          <button className="modal-close" onClick={onClose} aria-label="Close">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M4 4L12 12M12 4L4 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>
          </button>
          {submitted ?
          <div className="form-success">
              <div className="form-success-icon">
                <svg viewBox="0 0 32 32" fill="none"><path d="M8 16L14 22L24 10" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </div>
              <h4>Thank you — message received.</h4>
              <p>A member of the Canda team will reply within 2 working days.</p>
            </div> :

          <form onSubmit={submit} noValidate>
              <h3 style={{ fontSize: 22, fontWeight: 600, color: "var(--c-blue)", letterSpacing: "-0.015em", margin: "0 0 6px" }}>Contact Canda</h3>
              <p style={{ fontSize: 14, color: "var(--c-gray-600)", margin: "0 0 24px" }}>All fields marked required.</p>
              <div className="form-row">
                <div className="form-field">
                  <label>Full name *</label>
                  <input type="text" value={form.name} onChange={update("name")} placeholder="Jane Doe" style={errors.name ? { borderColor: "var(--c-danger)" } : {}} />
                </div>
                <div className="form-field">
                  <label>Work email *</label>
                  <input type="email" value={form.email} onChange={update("email")} placeholder="jane@ministry.gov" style={errors.email ? { borderColor: "var(--c-danger)" } : {}} />
                </div>
              </div>
              <div className="form-row">
                <div className="form-field">
                  <label>Organisation *</label>
                  <input type="text" value={form.organization} onChange={update("organization")} placeholder="Ministry, agency or NGO" style={errors.organization ? { borderColor: "var(--c-danger)" } : {}} />
                </div>
                <div className="form-field">
                  <label>Role / title</label>
                  <input type="text" value={form.role} onChange={update("role")} placeholder="e.g. Programme director" />
                </div>
              </div>
              <div className="form-row">
                <div className="form-field full">
                  <label>What would you like to discuss? *</label>
                  <textarea value={form.message} onChange={update("message")} placeholder="A short description of your context and what you're hoping to solve…" style={errors.message ? { borderColor: "var(--c-danger)" } : {}} />
                </div>
              </div>
              {submitError && (
                <p style={{ color: "var(--c-danger)", fontSize: 14, margin: "0 0 12px" }}>{submitError}</p>
              )}
              <div className="form-actions">
                <span className="privacy">By submitting, you agree to Canda's privacy practices.</span>
                <button type="submit" className="btn-primary" style={{ padding: "13px 22px", opacity: sending ? 0.7 : 1 }} disabled={sending}>
                  {sending ? "Sending…" : "Send message"}
                  {!sending && (
                    <svg className="arrow" width="14" height="14" viewBox="0 0 14 14" fill="none">
                      <path d="M3 11L11 3M11 3H4.5M11 3V9.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  )}
                </button>
              </div>
            </form>
          }
        </div>
      </div>
    </div>);

};

window.ContactModal = ContactModal;