// site/lead.jsx — "Book a walkthrough" lead-capture modal
// Opens on any click of an element with [data-book]. POSTs to a Cloudflare
// Pages Function at /api/lead. Falls back to a prefilled mailto if the
// endpoint isn't reachable (e.g. in preview, or before the Function is set up).
const { useState: lUS, useEffect: lUE, useRef: lUR } = React;

const LEAD_ENDPOINT = (typeof window !== "undefined" && window.WAKALIX_LEAD_ENDPOINT) || "/api/lead";
const LEAD_EMAIL = "contact@wakalix.com";

function field(label, node, opt) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--fg-2)" }}>
        {label}{opt ? <span style={{ color: "var(--fg-4)", fontWeight: 400 }}> · optional</span> : <span style={{ color: "var(--accent)" }}> *</span>}
      </span>
      {node}
    </label>
  );
}

function LeadModal() {
  const [open, setOpen] = lUS(false);
  const [status, setStatus] = lUS("idle"); // idle · submitting · success · error
  const [form, setForm] = lUS({ name: "", company: "", email: "", phone: "", problem: "", hp: "" });
  const firstRef = lUR(null);

  // open on any [data-book] click
  lUE(() => {
    const onClick = (e) => {
      const t = e.target.closest("[data-book]");
      if (t) { e.preventDefault(); setStatus("idle"); setOpen(true); }
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  // esc to close + focus + lock scroll
  lUE(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    setTimeout(() => firstRef.current && firstRef.current.focus(), 40);
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = prev; };
  }, [open]);

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

  const valid = form.name.trim() && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email.trim());

  const mailtoFallback = () => {
    const body = [
      `Name: ${form.name}`,
      `Company: ${form.company || "—"}`,
      `Email: ${form.email}`,
      `Phone: ${form.phone || "—"}`,
      "",
      form.problem ? `What's stuck:\n${form.problem}` : "",
    ].join("\n");
    return `mailto:${LEAD_EMAIL}?subject=${encodeURIComponent("wakalix — walkthrough request")}&body=${encodeURIComponent(body)}`;
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || status === "submitting") return;
    if (form.hp) { setStatus("success"); return; } // honeypot tripped — pretend success
    setStatus("submitting");
    try {
      const res = await fetch(LEAD_ENDPOINT, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          name: form.name.trim(), company: form.company.trim(),
          email: form.email.trim(), phone: form.phone.trim(),
          problem: form.problem.trim(), source: "wakalix.dev", company_url: form.hp,
        }),
      });
      if (!res.ok) throw new Error("bad status " + res.status);
      setStatus("success");
    } catch (err) {
      setStatus("error");
    }
  };

  if (!open) return null;

  const inputStyle = {
    height: 40, padding: "0 12px", borderRadius: "var(--r-2)", border: "var(--hairline) solid var(--border-2)",
    background: "var(--bg-sunken)", color: "var(--fg-1)", fontSize: 14, fontFamily: "inherit", outline: "none", width: "100%", boxSizing: "border-box",
  };

  return (
    <div role="dialog" aria-modal="true" aria-label="Book a walkthrough"
      onMouseDown={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{ position: "fixed", inset: 0, zIndex: 200, display: "grid", placeItems: "center", padding: 20,
        background: "oklch(0 0 0 / 0.55)", backdropFilter: "blur(3px)", WebkitBackdropFilter: "blur(3px)" }}>
      <div className="wx-card lead-pop" style={{ width: "100%", maxWidth: 452, padding: 0, overflow: "hidden", boxShadow: "var(--shadow-3)" }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "18px 20px", borderBottom: "var(--hairline) solid var(--border-1)" }}>
          <Mark size={30} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15.5, fontWeight: 600, color: "var(--fg-1)" }}>Book a walkthrough</div>
            <div style={{ fontSize: 12, color: "var(--fg-3)" }}>A live look at the engine on a real problem.</div>
          </div>
          <button onClick={() => setOpen(false)} aria-label="Close" className="btn" data-variant="ghost"
            style={{ width: 30, height: 30, padding: 0, justifyContent: "center" }}><Ico name="x" size={15} /></button>
        </div>

        {status === "success" ? (
          <div style={{ padding: "34px 24px 30px", textAlign: "center" }}>
            <span style={{ width: 48, height: 48, borderRadius: 999, background: "var(--ok-soft)", color: "var(--ok)", display: "grid", placeItems: "center", margin: "0 auto 16px" }}>
              <Ico name="check" size={24} stroke={2.4} />
            </span>
            <div style={{ fontSize: 17, fontWeight: 600, color: "var(--fg-1)", marginBottom: 6 }}>Got it — thank you.</div>
            <div style={{ fontSize: 13.5, color: "var(--fg-3)", lineHeight: 1.55, maxWidth: 320, margin: "0 auto" }}>
              We'll be in touch within one business day to set up your walkthrough.
            </div>
            <button onClick={() => setOpen(false)} className="btn btn-lg" data-variant="primary" style={{ marginTop: 22 }}>Done</button>
          </div>
        ) : (
          <form onSubmit={submit} style={{ padding: "20px 20px 22px", display: "flex", flexDirection: "column", gap: 14 }}>
            {field("Name", <input ref={firstRef} style={inputStyle} value={form.name} onChange={set("name")} placeholder="Jane Doe" autoComplete="name" />)}
            {field("Work email", <input style={inputStyle} type="email" value={form.email} onChange={set("email")} placeholder="jane@company.com" autoComplete="email" />)}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="lead-row">
              {field("Company", <input style={inputStyle} value={form.company} onChange={set("company")} placeholder="Company" autoComplete="organization" />, true)}
              {field("Phone", <input style={inputStyle} type="tel" value={form.phone} onChange={set("phone")} placeholder="+1 555 123 4567" autoComplete="tel" />, true)}
            </div>
            {field("What's the one problem?",
              <textarea style={{ ...inputStyle, height: 70, padding: "9px 12px", resize: "vertical" }} value={form.problem} onChange={set("problem")}
                placeholder="A feature that's stuck, a flaky test suite, a migration nobody has time for…" />, true)}
            {/* honeypot — hidden from humans */}
            <input tabIndex={-1} autoComplete="off" value={form.hp} onChange={set("hp")} name="company_url"
              style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} aria-hidden="true" />

            {status === "error" && (
              <div style={{ display: "flex", gap: 9, alignItems: "flex-start", padding: "11px 13px", borderRadius: "var(--r-2)", background: "var(--bad-soft)", border: "var(--hairline) solid oklch(from var(--bad) l c h / 0.4)" }}>
                <Ico name="x" size={14} c="var(--bad)" style={{ marginTop: 1, flexShrink: 0 }} />
                <span style={{ fontSize: 12.5, color: "var(--fg-2)", lineHeight: 1.5 }}>
                  Couldn't reach the server. <a href={mailtoFallback()} style={{ color: "var(--accent)", fontWeight: 600 }}>Email it to us directly</a> instead.
                </span>
              </div>
            )}

            <button type="submit" className="btn btn-lg" data-variant="primary" disabled={!valid || status === "submitting"}
              style={{ width: "100%", marginTop: 2, opacity: valid && status !== "submitting" ? 1 : 0.55 }}>
              {status === "submitting" ? "Sending…" : <>Request walkthrough <Ico name="arrowR" size={14} className="arr" /></>}
            </button>
            <div style={{ fontSize: 11.5, color: "var(--fg-4)", textAlign: "center", lineHeight: 1.5 }}>
              No spam. We use this only to set up your walkthrough.
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LeadModal });
