// Contact page — title left, intro right; below: 2-column form with checkbox columns
// System: paper bg, mono eyebrows, italic display, blue accent, sketch underline

const ContactPage = () => {
  const [form, setForm] = React.useState({
    name: "", email: "", business: "", phone: "",
    challenges: [], budget: "", timetable: "",
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");

  const toggleArr = (key, val) => {
    setForm((f) => ({
      ...f,
      [key]: f[key].includes(val) ? f[key].filter((v) => v !== val) : [...f[key], val],
    }));
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setError("");
    setSending(true);
    try {
      const resp = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok) throw new Error(data.error || "Something went wrong. Please try again.");
      setSubmitted(true);
      // GTM/GA4 lead event on successful submit. No PII (name/email/phone are
      // intentionally omitted) — only non-sensitive lead-quality context.
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
        event: "contact_form_submit",
        form_name: "contact",
        lead_challenges: form.challenges,
        lead_budget: form.budget || "unspecified",
        lead_timetable: form.timetable || "unspecified",
      });
    } catch (err) {
      setError(err.message || "Something went wrong. Please try again.");
    } finally {
      setSending(false);
    }
  };

  return (
    <main style={{ background: "var(--paper)", paddingTop: 24 }}>
      {/* Header */}
      <section className="container r-page-head" style={{ paddingTop: 80, paddingBottom: 64 }}>
        <div className="mono" style={{ color: "var(--muted)", marginBottom: 24 }}>
          <span style={{ color: "var(--blue)" }}>◆</span>&nbsp;&nbsp;03 / Get in touch
        </div>
        <div className="r-grid-1-1" style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 80, alignItems: "end" }}>
          <h1 className="display r-h2-massive" style={{
            fontSize: "clamp(80px, 11vw, 168px)",
            margin: 0,
            lineHeight: 0.88,
            letterSpacing: "-0.035em",
          }}>
            <span style={{ fontStyle: "italic", fontWeight: 500 }}>{copyText("contact.title_em")}</span><br />
            {copyText("contact.title_rest")}
          </h1>
          <div>
            <div className="mono" style={{ color: "var(--blue)", marginBottom: 14 }}>↳ {copyText("contact.kicker")}</div>
            <p style={{ fontSize: 19, lineHeight: 1.55, margin: "0 0 16px 0", maxWidth: 520 }}>
              {copyText("contact.intro1")}
            </p>
            <p style={{ fontSize: 16, lineHeight: 1.6, margin: 0, color: "var(--muted)", maxWidth: 520 }}>
              {copyText("contact.intro2_pre")}
              <a href={`mailto:${copyText("contact.email")}`} style={{ color: "var(--blue)", borderBottom: "1px solid currentColor" }}>{copyText("contact.email")}</a>
              {copyText("contact.intro2_post")}
            </p>
          </div>
        </div>
      </section>

      <div className="container"><div className="hairline" /></div>

      {/* Form */}
      <section className="container r-page-section" style={{ paddingTop: 64, paddingBottom: 96 }}>
        {submitted ? (
          <div style={{ padding: "120px 24px", textAlign: "center" }}>
            <div className="mono" style={{ color: "var(--blue)", marginBottom: 16 }}>↳ Received</div>
            <h2 className="display" style={{ fontSize: 64, lineHeight: 1, fontWeight: 600, letterSpacing: "-0.025em", margin: 0 }}>
              <span style={{ fontStyle: "italic" }}>Thanks.</span> {copyText("contact.success_title")}
            </h2>
            <p style={{ fontSize: 17, color: "var(--muted)", marginTop: 24 }}>{copyText("contact.success_sub")}</p>
          </div>
        ) : (
          <form onSubmit={onSubmit}>
            {/* Top row: 2-column basic info */}
            <div className="r-form-fields" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", columnGap: 56, rowGap: 32, marginBottom: 64 }}>
              <Field label="Your name" required value={form.name} onChange={(v) => setForm({ ...form, name: v })} />
              <Field label="Email address" type="email" required value={form.email} onChange={(v) => setForm({ ...form, email: v })} />
              <Field label="Business name" value={form.business} onChange={(v) => setForm({ ...form, business: v })} />
              <Field label="Phone number" type="tel" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} />
            </div>

            <div className="hairline" style={{ marginBottom: 48 }} />

            {/* Three-column checkbox row */}
            <div className="r-form-checks" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr", gap: 56, marginBottom: 64 }}>
              <CheckGroup
                label="Marketing challenge you need help with"
                multi
                options={[
                  "Brand positioning",
                  "Demand generation",
                  "Media planning and buying",
                  "Experiential program development",
                  "AI Innovation",
                  "Campaign Development / Content Creation",
                  "Web Design and Development",
                ]}
                value={form.challenges}
                onChange={(v) => toggleArr("challenges", v)}
              />
              <CheckGroup
                label="Budget level"
                options={["<$100,000", "$100,000–$250,000", "$250,000–$500,000", "$500,000–$1M", "$1M–$5M", ">$5M"]}
                value={[form.budget]}
                onChange={(v) => setForm({ ...form, budget: v })}
              />
              <CheckGroup
                label="Timetable"
                options={["Immediate", "Next month", "3–6 months out"]}
                value={[form.timetable]}
                onChange={(v) => setForm({ ...form, timetable: v })}
              />
            </div>

            <div className="hairline" style={{ marginBottom: 32 }} />

            <div className="r-form-submit" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
              <span className="mono" style={{ color: "var(--muted)" }}>By submitting you agree to our <a href="#privacy" style={{ borderBottom: "1px solid currentColor" }}>privacy policy</a></span>
              <button
                type="submit"
                disabled={sending}
                style={{
                  background: "var(--blue)",
                  color: "#fff",
                  border: "none",
                  padding: "18px 32px",
                  borderRadius: 999,
                  fontSize: 14,
                  fontWeight: 500,
                  letterSpacing: "-0.005em",
                  cursor: sending ? "wait" : "pointer",
                  opacity: sending ? 0.65 : 1,
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 12,
                  transition: "opacity .15s",
                }}
              >
                {sending ? "Sending…" : copyText("contact.submit_button")} <ArrowUpRight size={14} />
              </button>
            </div>

            {error ? (
              <p role="alert" className="mono" style={{ color: "#c0392b", marginTop: 20, textAlign: "right" }}>
                {error}
              </p>
            ) : null}
          </form>
        )}
      </section>
    </main>
  );
};

const Field = ({ label, type = "text", value, onChange, required }) => {
  const [focused, setFocused] = React.useState(false);
  return (
    <label style={{ display: "block" }}>
      <div className="mono" style={{ color: focused ? "var(--blue)" : "var(--muted)", marginBottom: 8, transition: "color .15s" }}>
        {label}{required && <span style={{ color: "var(--blue)" }}>*</span>}
      </div>
      <input
        type={type}
        value={value}
        required={required}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          width: "100%",
          background: "transparent",
          border: "none",
          borderBottom: focused ? "1.5px solid var(--blue)" : "1px solid var(--rule-strong)",
          padding: "12px 0",
          fontFamily: "var(--display)",
          fontSize: 22,
          fontWeight: 500,
          letterSpacing: "-0.015em",
          color: "var(--ink)",
          outline: "none",
          transition: "border-color .15s",
        }}
      />
    </label>
  );
};

const CheckGroup = ({ label, options, value, onChange, multi = false }) => (
  <div>
    <div className="mono" style={{ color: "var(--muted)", marginBottom: 16 }}>{label}</div>
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {options.map((opt) => {
        const active = value.includes(opt);
        return (
          <button
            type="button"
            key={opt}
            onClick={() => onChange(opt)}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              background: "transparent",
              border: "none",
              padding: "8px 0",
              cursor: "pointer",
              textAlign: "left",
              color: "var(--ink)",
              fontSize: 15,
              lineHeight: 1.4,
            }}
          >
            <span style={{
              width: 18, height: 18,
              border: "1.5px solid " + (active ? "var(--blue)" : "var(--rule-strong)"),
              borderRadius: multi ? 3 : 999,
              background: active ? "var(--blue)" : "transparent",
              display: "flex", alignItems: "center", justifyContent: "center",
              flexShrink: 0,
              transition: "all .15s",
            }}>
              {active && <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4l3 3 5-6" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>}
            </span>
            <span>{opt}</span>
          </button>
        );
      })}
    </div>
  </div>
);

window.ContactPage = ContactPage;
