/* =========================================================
   SIGNET — Contact page (Formspree-wired form)
   ========================================================= */

const CONTACT_ENDPOINT = "/api/contact";

const Contact = ({ go }) => {
  const [form, setForm] = React.useState({
    name: "", email: "", phone: "", company: "", seats: "", services: [], message: "",
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);

  const set = (k, v) => setForm({ ...form, [k]: v });
  const toggleService = (s) => {
    const has = form.services.includes(s);
    set("services", has ? form.services.filter((x) => x !== s) : [...form.services, s]);
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "We'd like to know who you are.";
    if (!form.email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) e.email = "Looks like the email needs another look.";
    if (!form.company.trim()) e.company = "Which company is this for?";
    if (!form.message.trim()) e.message = "Tell us a bit about what you need.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    setSubmitError(null);
    if (!validate()) return;
    setSubmitting(true);
    try {
      const response = await fetch(CONTACT_ENDPOINT, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json",
        },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone: form.phone || "Not provided",
          company: form.company,
          team_size: form.seats || "Not specified",
          services_of_interest: form.services.length ? form.services.join(", ") : "Not specified",
          message: form.message,
          _subject: `New Signet inquiry from ${form.name} at ${form.company}`,
          _replyto: form.email,
        }),
      });
      if (response.ok) {
        setSubmitted(true);
      } else {
        const data = await response.json().catch(() => ({}));
        const message = data && data.errors
          ? data.errors.map((e) => e.message).join(" ")
          : "Something went wrong on our end. Please try again, or email us directly at hello@signet.ms.";
        setSubmitError(message);
      }
    } catch (err) {
      setSubmitError("Network error — please check your connection and try again, or email us directly at hello@signet.ms.");
    } finally {
      setSubmitting(false);
    }
  };

  const SERVICE_TAGS = [
    "Request quote", "Helpdesk", "Device management", "Security & compliance", "AI integration",
    "Microsoft 365 + Teams", "Network", "Vendor management", "Backup & continuity", "Onboarding", "Something else"
  ];

  return (
    <main className="page-fade">
      <section className="page-head">
        <div className="shell">
          <span className="eyebrow">Get in touch</span>
          <h1>Tell us where you are. We'll send a plan in 48 hours.</h1>
          <p>
            Every inquiry is read by a principal engineer — not a sales
            development rep. If we're not the right fit, we'll tell you and
            point you toward someone we trust.
          </p>
        </div>
      </section>

      <div className="shell">
        <div className="contact-grid">
          <div className="contact-info">
            <span className="eyebrow">Other ways to reach us</span>
            <h2 style={{ marginTop: 16, fontSize: 32 }}>We try to write back the same day.</h2>
            <p>
              For prospects, the form on the right is fastest. Existing
              clients have a dedicated portal and on-call line — check the
              welcome packet we sent on day one.
            </p>
            <div className="contact-channels" style={{ marginTop: 32 }}>
              <div className="channel" style={{ borderTop: "none", paddingTop: 0, paddingBottom: 8 }}>
                <span className="label">Email</span>
                <div>
                  <div className="value">hello@signet.ms</div>
                </div>
              </div>
              <div className="channel" style={{ borderTop: "none", borderBottom: "none", paddingTop: 8, paddingBottom: 0 }}>
                <span className="label">Phone</span>
                <div>
                  <div className="value"><a href="tel:+12069707848" style={{ color: "inherit", textDecoration: "none" }}>206.970.7848</a></div>
                </div>
              </div>
            </div>
          </div>

          <div>
            {!submitted ? (
              <form className="form" onSubmit={submit} noValidate>
                <div style={{ display: "flex", gap: 16, alignItems: "center", marginBottom: 32, position: "relative", zIndex: 1 }}>
                  <span className="logo-mark lg"><QuillMark size={48} /></span>
                  <div>
                    <span className="eyebrow">A signature consult</span>
                    <h3 style={{ fontSize: 22, marginTop: 4 }}>Tell us about your team.</h3>
                  </div>
                </div>

                <div className="form-row">
                  <div className="form-field">
                    <label>Your name</label>
                    <input
                      type="text"
                      value={form.name}
                      onChange={(e) => set("name", e.target.value)}
                      className={errors.name ? "invalid" : ""}
                    />
                    {errors.name && <span className="err">{errors.name}</span>}
                  </div>
                  <div className="form-field">
                    <label>Work email</label>
                    <input
                      type="email"
                      value={form.email}
                      onChange={(e) => set("email", e.target.value)}
                      className={errors.email ? "invalid" : ""}
                    />
                    {errors.email && <span className="err">{errors.email}</span>}
                  </div>
                </div>

                <div className="form-row">
                  <div className="form-field">
                    <label>Company</label>
                    <input
                      type="text"
                      value={form.company}
                      onChange={(e) => set("company", e.target.value)}
                      className={errors.company ? "invalid" : ""}
                    />
                    {errors.company && <span className="err">{errors.company}</span>}
                  </div>
                  <div className="form-field">
                    <label>Phone <span style={{ color: "var(--ivory-mute)", textTransform: "none", letterSpacing: 0, fontFamily: "var(--sans)", fontSize: 11 }}>(optional)</span></label>
                    <input
                      type="tel"
                      value={form.phone}
                      onChange={(e) => set("phone", e.target.value)}
                      placeholder="(555) 555–0000"
                    />
                  </div>
                </div>

                <div className="form-field">
                  <label>Team size</label>
                  <select value={form.seats} onChange={(e) => set("seats", e.target.value)}>
                    <option value="">Select size</option>
                    <option>Under 10</option>
                    <option>10–40</option>
                    <option>40–100</option>
                    <option>100–250</option>
                    <option>250–1000</option>
                    <option>1000+</option>
                  </select>
                </div>

                <div className="form-field">
                  <label>What are you looking for? (pick all that apply)</label>
                  <div className="chip-group" style={{ marginTop: 6 }}>
                    {SERVICE_TAGS.map((s) => (
                      <span
                        key={s}
                        className={`chip ${form.services.includes(s) ? "on" : ""}`}
                        onClick={() => toggleService(s)}
                      >
                        {s}
                      </span>
                    ))}
                  </div>
                </div>

                <div className="form-field">
                  <label>Tell us about your situation</label>
                  <textarea
                    value={form.message}
                    onChange={(e) => set("message", e.target.value)}
                    className={errors.message ? "invalid" : ""}
                    placeholder="What's prompting the conversation? Current MSP, internal team, a recent incident?"
                  ></textarea>
                  {errors.message && <span className="err">{errors.message}</span>}
                </div>

                {submitError && (
                  <div style={{
                    marginTop: 16, padding: "14px 18px",
                    background: "rgba(217, 144, 104, 0.08)",
                    border: "1px solid rgba(217, 144, 104, 0.3)",
                    borderRadius: "var(--radius-sm)",
                    color: "var(--warn)",
                    fontSize: 14,
                    position: "relative", zIndex: 1,
                  }}>
                    {submitError}
                  </div>
                )}

                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 16 }}>
                  <p style={{ fontSize: 12, color: "var(--ink-soft)", maxWidth: 280 }}>
                    We respect your inbox. One reply, one follow-up, then silence
                    if you don't write back.
                  </p>
                  <button type="submit" className="btn btn-primary" disabled={submitting} style={submitting ? { opacity: 0.6, cursor: "wait" } : {}}>
                    {submitting ? "Sealing…" : "Send & expect a reply"} <Arrow />
                  </button>
                </div>
              </form>
            ) : (
              <div className="form">
                <div className="form-success">
                  <span className="logo-mark lg"><QuillMark size={56} /></span>
                  <h3 style={{ marginTop: 24 }}>Sealed & sent.</h3>
                  <p style={{ marginTop: 12 }}>
                    A principal engineer will read this and reply within one
                    business day. If we're a fit, we'll send a scoped plan
                    within 48 hours.
                  </p>
                  <p style={{ marginTop: 24, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--gold)" }}>
                    Confirmation no. SIG-{Math.floor(10000 + Math.random() * 90000)}
                  </p>
                  <div style={{ marginTop: 32 }}>
                    <button className="btn btn-ghost" onClick={() => { setSubmitted(false); setSubmitError(null); setForm({ name: "", email: "", phone: "", company: "", seats: "", services: [], message: "" }); }}>
                      Send another
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </main>
  );
};

window.Contact = Contact;
