/* global React */
const { useState: useStateContact } = React;

function ContactPage() {
  const [form, setForm] = useStateContact({ name: "", email: "", phone: "", company: "", message: "" });
  const [state, setState] = useStateContact("idle"); // idle | submitting | success | error
  const [errorMsg, setErrorMsg] = useStateContact("");

  const update = (k) => (e) => {
    setForm((f) => ({ ...f, [k]: e.target.value }));
    if (state === "error") setState("idle");
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name.trim())  { setErrorMsg("Name is required."); setState("error"); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim()))  { setErrorMsg("A valid email is required."); setState("error"); return; }
    if (form.phone.replace(/\D/g, "").length < 7)  { setErrorMsg("A valid phone number is required."); setState("error"); return; }

    setState("submitting");
    setErrorMsg("");
    try {
      const r = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const d = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(d.error || "Server error");
      setState("success");
      if (window.dataLayer) {
        window.dataLayer.push({
          event: "demo_request",
          email_domain: form.email.split("@")[1] || "",
          has_company: !!form.company.trim(),
        });
      }
    } catch (err) {
      setErrorMsg(err.message || "Could not submit. Please try again.");
      setState("error");
    }
  };

  return (
    <main>
      <section className="subhero">
        <div className="subhero__crumb">Home / Contact</div>
        <h1 className="display h1" style={{ fontSize: "clamp(2.25rem, 6vw, 5rem)" }}>
          Let's <em style={{ fontStyle: "normal", background: "linear-gradient(90deg, var(--blue-2), var(--sky))", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" }}>talk</em>.<br />
          Real humans on the corridor.
        </h1>
        <p className="lead" style={{ maxWidth: "60ch", marginTop: "1rem" }}>
          Tell us a bit about your fleet and we'll get back to you within one business day. Built in Canada, priced in CAD — and yes, we answer the phone.
        </p>
      </section>

      <section className="section" style={{ paddingTop: "1rem" }}>
        <div className="contact-grid" style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: "clamp(2rem, 5vw, 5rem)", alignItems: "start" }}>
          {/* ── Form column ─────────────────────────────────────────── */}
          <div>
            {state === "success" ? (
              <div style={{ padding: "2rem 2.25rem", border: "1px solid color-mix(in oklab, var(--ok), transparent 60%)", borderRadius: "16px", background: "color-mix(in oklab, var(--ok), transparent 92%)" }}>
                <div className="mono" style={{ color: "var(--ok)", fontSize: "0.75rem", letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: "0.6rem" }}>● Thanks — we've got it</div>
                <h3 style={{ fontFamily: "var(--display)", fontSize: "1.5rem", lineHeight: 1.2, marginBottom: "0.75rem" }}>We'll be in touch within 1 business day.</h3>
                <p style={{ color: "var(--paper)", lineHeight: 1.6 }}>
                  A reply will land in your inbox from <strong>info@cygnik.com</strong>. If you need to reach us sooner — call us at <a href="tel:+18887771672" style={{ color: "var(--blue-2)", textDecoration: "none" }}>(888) 777-1672</a> or hit reply to the confirmation email.
                </p>
              </div>
            ) : (
              <form onSubmit={submit} noValidate style={{ display: "grid", gap: "1.1rem" }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }} className="contact-row">
                  <FormField label="Name" required>
                    <input type="text" name="name" required autoComplete="name" value={form.name} onChange={update("name")} disabled={state === "submitting"} placeholder="Gurpreet Singh" />
                  </FormField>
                  <FormField label="Company">
                    <input type="text" name="company" autoComplete="organization" value={form.company} onChange={update("company")} disabled={state === "submitting"} placeholder="Acme Transport" />
                  </FormField>
                </div>

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }} className="contact-row">
                  <FormField label="Email" required>
                    <input type="email" name="email" required autoComplete="email" value={form.email} onChange={update("email")} disabled={state === "submitting"} placeholder="you@yourfleet.com" />
                  </FormField>
                  <FormField label="Phone" required>
                    <input type="tel" name="phone" required autoComplete="tel" value={form.phone} onChange={update("phone")} disabled={state === "submitting"} placeholder="(416) 555-0123" />
                  </FormField>
                </div>

                <FormField label="Anything we should know?">
                  <textarea name="message" rows={4} value={form.message} onChange={update("message")} disabled={state === "submitting"} placeholder="Fleet size, lanes you run, current TMS — anything that helps us prep for the call." style={{ resize: "vertical", minHeight: "120px" }} />
                </FormField>

                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: "0.75rem" }}>
                  <button type="submit" className="btn btn--solid" disabled={state === "submitting"} style={{ minWidth: "200px" }}>
                    {state === "submitting" ? "Sending…" : <>Send to our team <Arrow /></>}
                  </button>
                  {state === "error" && (
                    <div className="mono" style={{ color: "#F87171", fontSize: "0.78rem", letterSpacing: "0.06em" }}>{errorMsg}</div>
                  )}
                </div>

                <p style={{ marginTop: "0.5rem", color: "var(--muted)", fontSize: "0.78rem", lineHeight: 1.5 }}>
                  By submitting, you agree we may email or call you about Lanexa. Your information stays with Lanexa and our parent, Cygnik Tech — we do not sell or share contact details.
                </p>
              </form>
            )}
          </div>

          {/* ── Detail column ───────────────────────────────────────── */}
          <aside style={{ display: "grid", gap: "1.75rem" }}>
            <div style={{ padding: "1.5rem 1.6rem", border: "1px solid var(--line)", borderRadius: "14px", background: "rgba(255,255,255,0.025)" }}>
              <div className="mono" style={{ fontSize: "0.7rem", letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--muted)", marginBottom: "0.85rem" }}>Lanexa Technologies Inc.</div>
              <div style={{ lineHeight: 1.6 }}>
                Suite 400 – 1940 Eglinton Ave E<br />
                Scarborough, ON M1L 4R1<br />
                Canada
              </div>
              <div style={{ marginTop: "1rem", fontFamily: "var(--mono)", fontSize: "0.85rem", lineHeight: 1.7 }}>
                <div><a href="tel:+18887771672" style={{ color: "var(--paper)", textDecoration: "none" }}>(888) 777-1672</a></div>
                <div><a href="mailto:info@cygnik.com" style={{ color: "var(--paper)", textDecoration: "none" }}>info@cygnik.com</a></div>
              </div>
            </div>

            <div style={{ padding: "1.5rem 1.6rem", border: "1px solid var(--line)", borderRadius: "14px", background: "rgba(255,255,255,0.025)" }}>
              <div className="mono" style={{ fontSize: "0.7rem", letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--muted)", marginBottom: "0.85rem" }}>Parent company</div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: "1.25rem", marginBottom: "0.45rem" }}>Cygnik Tech</div>
              <p style={{ color: "var(--muted)", lineHeight: 1.55, fontSize: "0.92rem" }}>
                Lanexa is designed and developed by Cygnik Tech, a Canadian product studio building software for the trucking and logistics industry.
              </p>
              <div style={{ marginTop: "1rem" }}>
                <a href="https://cygnik.tech" target="_blank" rel="noopener noreferrer" className="btn" style={{ display: "inline-flex", alignItems: "center", gap: "0.45rem" }}>
                  Visit cygnik.tech <Arrow />
                </a>
              </div>
            </div>

          </aside>
        </div>
      </section>
    </main>
  );
}

// Compact field wrapper with consistent label + input styling.
function FormField({ label, required, children }) {
  return (
    <label style={{ display: "block" }}>
      <span className="mono" style={{ display: "block", fontSize: "0.7rem", letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted)", marginBottom: "0.5rem" }}>
        {label}{required && <span style={{ color: "var(--blue-2)", marginLeft: 4 }}>*</span>}
      </span>
      {React.cloneElement(children, {
        style: {
          width: "100%",
          padding: "0.85rem 1rem",
          font: "500 0.98rem var(--sans, Inter, system-ui, sans-serif)",
          color: "var(--paper)",
          background: "rgba(255,255,255,0.04)",
          border: "1px solid var(--line-2)",
          borderRadius: "10px",
          outline: "none",
          transition: "border-color .15s ease, background .15s ease",
          ...(children.props.style || {}),
        },
        onFocus: (e) => { e.currentTarget.style.borderColor = "var(--blue-2)"; e.currentTarget.style.background = "rgba(255,255,255,0.06)"; },
        onBlur: (e) => { e.currentTarget.style.borderColor = "var(--line-2)"; e.currentTarget.style.background = "rgba(255,255,255,0.04)"; },
      })}
    </label>
  );
}

Object.assign(window, { ContactPage });
