// Contact page
function ContactPage({ onNavigate }) {
  const [form, setForm] = React.useState({ name: "", email: "", company: "", interest: "platform", message: "" });
  const [submitted, setSubmitted] = React.useState(false);
  const [status, setStatus] = React.useState("idle"); // idle | sending | error
  const [error, setError] = React.useState("");
  const hpRef = React.useRef(null); // honeypot

  const submit = async (e) => {
    e.preventDefault();
    if (status === "sending") return;
    setStatus("sending");
    setError("");
    try {
      const res = await fetch("/contact/submit.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, company_url: hpRef.current ? hpRef.current.value : "" }),
      });
      let data = {};
      try { data = await res.json(); } catch (_) { /* non-JSON response */ }
      if (res.ok && data.ok) {
        setSubmitted(true);
        setStatus("idle");
      } else {
        setStatus("error");
        setError(data.error || "Something went wrong. Please try again.");
      }
    } catch (_) {
      setStatus("error");
      setError("We couldn't reach the server. Please try again, or email info@activemanage.co.uk.");
    }
  };

  return (
    <div className="page">
      <section className="hero" style={{ paddingTop: 80, paddingBottom: 80 }}>
        <div className="aurora"><div className="blob"></div></div>
        <div className="aurora-grid"></div>
        <div className="container">
          <div className="contact-grid">
            <div>
              <span className="eyebrow rise" data-d="1">Get in touch</span>
              <h1 className="h-display rise" data-d="2" style={{ marginTop: 24, fontSize: "clamp(40px, 5.5vw, 72px)" }}>
                Let's talk.
              </h1>
              <p className="lead rise" data-d="3" style={{ marginTop: 24, maxWidth: 440 }}>
                Whether you have a brief, a question, or want a 30-minute platform tour — we read everything that comes through this form.
              </p>

              <div style={{ marginTop: 56, display: "flex", flexDirection: "column", gap: 24 }}>
                <ContactRow label="Email" value="info@activemanage.co.uk" mono />
                <ContactRow label="Phone" value="(+44) 33 000 11 300" mono />
                <ContactRow label="Office" value={<>ActiveManage Ltd.<br/>Enterprise Centre, David Lane<br/>Basford, Nottingham NG6 0JU</>} />
                <ContactRow label="Hours" value="Mon–Fri · 09:00–18:00 GMT" />
              </div>
            </div>

            <div>
              <div className="contact-form-card" style={{ background: "var(--bg-elev)", border: "1px solid var(--line)", borderRadius: 16 }}>
                {!submitted ? (
                  <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
                    <div className="mono" style={{ color: "var(--fg-faint)", marginBottom: 4 }}>NEW ENQUIRY · 5 FIELDS</div>
                    {/* Honeypot — hidden from humans; bots that fill it are silently dropped server-side */}
                    <input
                      ref={hpRef}
                      type="text"
                      name="company_url"
                      tabIndex={-1}
                      autoComplete="off"
                      aria-hidden="true"
                      style={{ position: "absolute", left: "-9999px", top: "-9999px", width: 1, height: 1, opacity: 0, pointerEvents: "none" }}
                    />
                    <Field label="Your name" value={form.name} onChange={(v) => setForm({...form, name: v})} placeholder="Sarah Patel" />
                    <Field label="Work email" value={form.email} onChange={(v) => setForm({...form, email: v})} placeholder="sarah@yourcompany.co.uk" type="email" />
                    <Field label="Company" value={form.company} onChange={(v) => setForm({...form, company: v})} placeholder="Acme Healthcare" />
                    <div>
                      <label className="mono" style={{ color: "var(--fg-muted)", display: "block", marginBottom: 8 }}>I'M INTERESTED IN</label>
                      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                        {[
                          ["platform", "The Platform"],
                          ["bespoke", "Bespoke build"],
                          ["both", "Both"],
                          ["other", "Just exploring"],
                        ].map(([id, label]) => (
                          <button key={id} type="button" onClick={() => setForm({...form, interest: id})} style={{
                            padding: "12px 16px",
                            border: "1px solid",
                            borderColor: form.interest === id ? "var(--fg)" : "var(--line)",
                            background: form.interest === id ? "var(--fg)" : "transparent",
                            color: form.interest === id ? "var(--bg)" : "var(--fg)",
                            borderRadius: 8,
                            fontSize: 13,
                            fontWeight: 500,
                            textAlign: "left",
                            transition: "all 0.15s",
                          }}>{label}</button>
                        ))}
                      </div>
                    </div>
                    <div>
                      <label className="mono" style={{ color: "var(--fg-muted)", display: "block", marginBottom: 8 }}>TELL US MORE</label>
                      <textarea
                        value={form.message}
                        onChange={(e) => setForm({...form, message: e.target.value})}
                        placeholder="A few lines about what you're trying to build..."
                        rows={5}
                        style={{
                          width: "100%",
                          padding: 14,
                          border: "1px solid var(--line)",
                          borderRadius: 8,
                          background: "var(--bg)",
                          color: "var(--fg)",
                          fontSize: 14,
                          fontFamily: "inherit",
                          resize: "vertical",
                          outline: "none",
                          transition: "border-color 0.2s",
                        }}
                        onFocus={(e) => e.target.style.borderColor = "var(--fg)"}
                        onBlur={(e) => e.target.style.borderColor = "var(--line)"}
                      />
                    </div>
                    {status === "error" && (
                      <div role="alert" style={{
                        fontSize: 13, color: "#C4383C", lineHeight: 1.5,
                        background: "rgba(229,72,77,0.08)", border: "1px solid rgba(229,72,77,0.28)",
                        borderRadius: 8, padding: "10px 12px",
                      }}>
                        {error}
                      </div>
                    )}
                    <button type="submit" className="btn btn-primary" disabled={status === "sending"} style={{ alignSelf: "flex-start", marginTop: 8, opacity: status === "sending" ? 0.7 : 1, cursor: status === "sending" ? "default" : "pointer" }}>
                      {status === "sending" ? "Sending…" : "Send enquiry"}
                      {status !== "sending" && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>}
                    </button>
                    <p style={{ fontSize: 12, color: "var(--fg-faint)", marginTop: 8 }}>
                      We'll reply within one working day. By submitting, you agree to our privacy policy.
                    </p>
                  </form>
                ) : (
                  <div style={{ textAlign: "center", padding: "40px 0" }}>
                    <div style={{
                      width: 56, height: 56, borderRadius: "50%",
                      background: "var(--accent)",
                      display: "grid", placeItems: "center",
                      margin: "0 auto 24px",
                      color: "var(--accent-ink)",
                    }}>
                      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 13l4 4L19 7"/></svg>
                    </div>
                    <h3 className="h-medium" style={{ marginBottom: 12 }}>Got it. Thanks{form.name && `, ${form.name.split(" ")[0]}`}.</h3>
                    <p className="body" style={{ marginBottom: 24 }}>We'll be in touch within one working day at <strong style={{ color: "var(--fg)" }}>{form.email || "your inbox"}</strong>.</p>
                    <button className="btn btn-ghost" onClick={() => { setSubmitted(false); setStatus("idle"); setError(""); setForm({ name: "", email: "", company: "", interest: "platform", message: "" }); }}>Send another</button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function ContactRow({ label, value, mono }) {
  return (
    <div>
      <div className="mono" style={{ color: "var(--fg-faint)", marginBottom: 6 }}>{label.toUpperCase()}</div>
      <div style={{ fontSize: 17, fontFamily: mono ? "var(--font-mono)" : "var(--font-body)", letterSpacing: mono ? "-0.005em" : "0" }}>{value}</div>
    </div>
  );
}

function Field({ label, value, onChange, placeholder, type = "text" }) {
  return (
    <div>
      <label className="mono" style={{ color: "var(--fg-muted)", display: "block", marginBottom: 8 }}>{label.toUpperCase()}</label>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width: "100%",
          padding: "12px 14px",
          border: "1px solid var(--line)",
          borderRadius: 8,
          background: "var(--bg)",
          color: "var(--fg)",
          fontSize: 15,
          fontFamily: "inherit",
          outline: "none",
          transition: "border-color 0.2s",
        }}
        onFocus={(e) => e.target.style.borderColor = "var(--fg)"}
        onBlur={(e) => e.target.style.borderColor = "var(--line)"}
      />
    </div>
  );
}

Object.assign(window, { ContactPage });
