const SIGNUP_ENDPOINT = "/api/early-access";
const SIGNUP_OPTIONS = [
  "qPCR / RDML",
  "ELISA / plate reader",
  "Behavior + assay joins",
  "ConductVision attachment",
  "ConductSignal attachment",
  "Other mixed assay workflow",
];

function getAttribution() {
  const params = new URLSearchParams(window.location.search);
  return {
    source: window.location.pathname + window.location.search,
    utm_source: params.get("utm_source") || "",
    utm_medium: params.get("utm_medium") || "",
    utm_campaign: params.get("utm_campaign") || "",
    utm_term: params.get("utm_term") || "",
    utm_content: params.get("utm_content") || "",
  };
}

function SignupApp() {
  return (
    <>
      <Nav current="signup" />
      <main style={{ minHeight: "calc(100vh - 61px)" }}>
        <SignupHero />
      </main>
    </>
  );
}

function SignupHero() {
  return (
    <section style={{
      borderBottom: "1px solid var(--ink-200)",
      background: "linear-gradient(180deg, white 0%, var(--ink-50) 100%)",
    }}>
      <div style={{
        maxWidth: 1180,
        margin: "0 auto",
        padding: "72px 24px 80px",
        display: "grid",
        gridTemplateColumns: "minmax(0, .9fr) minmax(380px, 520px)",
        gap: 44,
        alignItems: "start",
      }}>
        <div>
          <div className="mono" style={{ fontSize: 11.5, color: "var(--brand-700)", letterSpacing: ".12em", textTransform: "uppercase", fontWeight: 600 }}>
            Early access
          </div>
          <h1 style={{
            margin: "14px 0 0",
            maxWidth: 650,
            fontSize: 52,
            lineHeight: 1.02,
            fontWeight: 600,
            letterSpacing: "-0.03em",
            color: "var(--ink-900)",
            textWrap: "balance",
          }}>
            Tell us what messy assay project ConductBench should solve first.
          </h1>
          <p style={{ margin: "22px 0 0", maxWidth: 560, fontSize: 18, lineHeight: 1.55, color: "var(--ink-600)" }}>
            We are opening ConductBench around qPCR, ELISA, sample maps, behavior exports, and the future ConductVision / ConductSignal handoff. Sign up and we will use the demand signal to prioritize the first real workflows.
          </p>

          <div style={{
            marginTop: 34,
            border: "1px solid var(--ink-200)",
            background: "white",
            borderRadius: 8,
            overflow: "hidden",
            boxShadow: "var(--shadow-sm)",
          }}>
            {[
              ["1", "Join early access", "Leave a work or institutional email plus the assay type you care about."],
              ["2", "Open the demo workspace", "Inspect the current study-record UI with synthetic qPCR, ELISA, and behavior data."],
              ["3", "Send one real workflow", "If there is fit, we can map one project by hand before building upload/auth."],
            ].map((item, index) => (
              <div key={item[0]} style={{
                display: "grid",
                gridTemplateColumns: "42px 1fr",
                gap: 14,
                padding: "17px 18px",
                borderTop: index === 0 ? "none" : "1px solid var(--ink-100)",
              }}>
                <div className="mono" style={{
                  width: 30,
                  height: 30,
                  borderRadius: 6,
                  background: "var(--brand-50)",
                  color: "var(--brand-700)",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: 12,
                  fontWeight: 600,
                }}>{item[0]}</div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink-900)" }}>{item[1]}</div>
                  <div style={{ marginTop: 3, fontSize: 13, lineHeight: 1.45, color: "var(--ink-600)" }}>{item[2]}</div>
                </div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 22, display: "flex", gap: 12, flexWrap: "wrap" }}>
            <a href="https://conductbench.com/demo/" className="btn btn-ghost" style={{ padding: "11px 15px" }}>
              Open demo workspace
            </a>
            <a href="https://conductbench.com/" className="btn" style={{ padding: "11px 15px", background: "white" }}>
              Back to product site
            </a>
          </div>
        </div>

        <SignupForm />
      </div>
    </section>
  );
}

function SignupForm() {
  const [values, setValues] = React.useState({
    name: "",
    email: "",
    institution: "",
    role: "",
    workflow: SIGNUP_OPTIONS[0],
    pain: "",
    conductProducts: "",
    company: "",
  });
  const [state, setState] = React.useState({ status: "idle", message: "" });

  const update = (key) => (event) => {
    setValues({ ...values, [key]: event.target.value });
  };

  const submit = async (event) => {
    event.preventDefault();
    if (!values.name.trim() || !values.email.trim()) {
      setState({ status: "error", message: "Name and email are required." });
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email.trim())) {
      setState({ status: "error", message: "Please enter a valid email address." });
      return;
    }

    setState({ status: "loading", message: "Submitting..." });
    try {
      const response = await fetch(SIGNUP_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...values, ...getAttribution() }),
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok || !payload.success) {
        throw new Error(payload.error || "Signup failed. Please try again.");
      }
      try {
        localStorage.setItem("conductbench_signup", JSON.stringify({
          email: values.email.trim().toLowerCase(),
          at: new Date().toISOString(),
        }));
      } catch (_error) {}
      setState({ status: "success", message: "You are on the early-access list. The demo workspace is ready now." });
    } catch (error) {
      setState({ status: "error", message: error.message || "Signup failed. Please try again." });
    }
  };

  const disabled = state.status === "loading" || state.status === "success";

  return (
    <form onSubmit={submit} style={{
      background: "white",
      border: "1px solid var(--ink-200)",
      borderRadius: 8,
      padding: 26,
      boxShadow: "0 24px 80px -34px rgba(15,23,42,.35)",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 18 }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: "-0.015em", color: "var(--ink-900)" }}>
            Sign up for early access
          </h2>
          <p style={{ margin: "7px 0 0", fontSize: 13.5, lineHeight: 1.5, color: "var(--ink-600)" }}>
            No credit card. We will use this to learn which workflows are worth building first.
          </p>
        </div>
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-500)", whiteSpace: "nowrap" }}>v0.5.2</div>
      </div>

      <div style={{ marginTop: 24, display: "grid", gap: 15 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <label>
            Name
            <input value={values.name} onChange={update("name")} autoComplete="name" required disabled={disabled} />
          </label>
          <label>
            Email
            <input type="email" value={values.email} onChange={update("email")} autoComplete="email" required disabled={disabled} />
          </label>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <label>
            Institution / company
            <input value={values.institution} onChange={update("institution")} autoComplete="organization" disabled={disabled} />
          </label>
          <label>
            Role
            <input value={values.role} onChange={update("role")} placeholder="PI, postdoc, core director..." disabled={disabled} />
          </label>
        </div>

        <label>
          Workflow focus
          <select value={values.workflow} onChange={update("workflow")} disabled={disabled}>
            {SIGNUP_OPTIONS.map(option => <option key={option}>{option}</option>)}
          </select>
        </label>

        <label>
          Current data pain
          <textarea value={values.pain} onChange={update("pain")} placeholder="Example: qPCR Ct files, ELISA plates, and behavior exports all use different subject/sample IDs." disabled={disabled} />
        </label>

        <label>
          ConductScience products you already use
          <input value={values.conductProducts} onChange={update("conductProducts")} placeholder="ConductVision, ConductSignal, equipment, tools..." disabled={disabled} />
        </label>

        <div style={{ position: "absolute", left: "-10000px", width: 1, height: 1, overflow: "hidden" }} aria-hidden="true">
          <label>
            Company
            <input tabIndex="-1" value={values.company} onChange={update("company")} autoComplete="off" />
          </label>
        </div>
      </div>

      {state.message && (
        <div role="status" style={{
          marginTop: 18,
          padding: "11px 12px",
          borderRadius: 7,
          fontSize: 13.5,
          lineHeight: 1.45,
          color: state.status === "error" ? "var(--danger)" : state.status === "success" ? "var(--ok)" : "var(--ink-700)",
          background: state.status === "error" ? "rgba(220,38,38,.08)" : state.status === "success" ? "rgba(22,163,74,.08)" : "var(--ink-50)",
          border: `1px solid ${state.status === "error" ? "rgba(220,38,38,.2)" : state.status === "success" ? "rgba(22,163,74,.2)" : "var(--ink-200)"}`,
        }}>
          {state.message}
        </div>
      )}

      <div style={{ marginTop: 22, display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
        <button type="submit" className="btn btn-primary" disabled={disabled} style={{ padding: "12px 18px", opacity: disabled ? .72 : 1 }}>
          {state.status === "loading" ? "Submitting..." : state.status === "success" ? "Signup received" : "Join early access"}
        </button>
        <a href="https://conductbench.com/demo/" className="btn btn-ghost" style={{ padding: "12px 18px" }}>
          Open demo
        </a>
      </div>
    </form>
  );
}

Object.assign(window, { SignupApp });
