const SIGNUP_ENDPOINT = "/api/early-access";
const SIGNUP_OPTIONS = [
  "Molecular study (ASO / siRNA)",
  "Population genetics",
  "qPCR / RDML",
  "ELISA / plate reader",
  "Behavior + assay joins",
  "ConductVision attachment",
  "ConductSignal attachment",
  "Other mixed assay workflow",
];

/* Page text for each ?module= value. `workflow` preselects the dropdown, and the lead
   email shows it in its Workflow row, so study requests arrive labeled. */
const SIGNUP_MODULES = {
  molecular: {
    workflow: "Molecular study (ASO / siRNA)",
    eyebrow: "Molecular study service",
    title: "Request a Molecular study",
    intro: "Tell us about one finished in-vitro ASO or siRNA screen. We'll reply to agree the criteria and a fixed price before you send any data.",
    steps: [
      ["1", "Tell us about your screen", "Candidates, assays, and the decision you need to make."],
      ["2", "Agree the criteria and price", "We set pass and fail rules with your scientist before anyone reviews results."],
      ["3", "Get the decision pack", "Within a week of clean files, signed, with every call and its reason."],
    ],
    links: [["Run it yourself in the tool", "/molecular/app"], ["How Molecular works", "/molecular"]],
    formTitle: "Request a study",
    formNote: "No payment now. We quote a fixed price before you send data.",
    painLabel: "About your screen",
    painPlaceholder: "Example: 24 siRNA candidates, qPCR knockdown at two doses, a viability assay, and a Western blot for protein.",
    rolePlaceholder: "Study director, assay lead, PI...",
    submit: "Request a study",
    done: "Request received",
    success: "Thanks. We'll email you to agree the criteria and price.",
  },
  population: {
    workflow: "Population genetics",
    eyebrow: "Population genetics",
    title: "Tell us about your population genetics work",
    intro: "The tool is ready to use now. Tell us what you analyze and what you still do elsewhere, and we'll email you when new features open.",
    steps: [
      ["1", "Try the tool", "Load your genotype file or the example. It runs in your browser."],
      ["2", "Tell us what you need", "Formats, analyses, or figures you still make in other programs."],
      ["3", "Hear first", "We'll email you when new features open."],
    ],
    links: [["Open the tool", "/population/app"], ["How it works", "/population"]],
    formTitle: "Get updates",
    formNote: "Free. We'll only email you about ConductBiology.",
    painLabel: "What you analyze",
    painPlaceholder: "Example: 14 microsatellite loci in 300 fish from 12 rivers; we still make the maps in R.",
    rolePlaceholder: "PI, postdoc, geneticist...",
    submit: "Get updates",
    done: "Thanks",
    success: "Thanks. We'll email you when new population genetics features open.",
  },
  general: {
    workflow: "qPCR / RDML",
    eyebrow: "Early access",
    title: "Tell us what ConductBiology should solve next",
    intro: "Molecular and Population genetics are ready to use. Tell us about your assay project so we know what to build next.",
    steps: [
      ["1", "Join early access", "Leave a work or institutional email plus the assay type you care about."],
      ["2", "Try the tools", "Molecular and Population genetics run in your browser, free during early access."],
      ["3", "Send one real workflow", "If it's a fit, we'll map one of your real projects with you directly."],
    ],
    links: [["Try the tools", "/#modules"], ["Back to home", "/"]],
    formTitle: "Sign up for early access",
    formNote: "No credit card. We'll use this to learn which workflows to build next.",
    painLabel: "Current data pain",
    painPlaceholder: "Example: qPCR Ct files, ELISA plates, and behavior exports all use different subject/sample IDs.",
    rolePlaceholder: "PI, postdoc, core director...",
    submit: "Join early access",
    done: "Signup received",
    success: "You're on the early-access list.",
  },
};

function signupCopy() {
  const key = new URLSearchParams(window.location.search).get("module");
  return SIGNUP_MODULES[key] && key !== "general" ? SIGNUP_MODULES[key] : SIGNUP_MODULES.general;
}

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() {
  const copy = signupCopy();
  React.useEffect(() => {
    document.title = `ConductBiology: ${copy.title}`;
  }, []);
  return (
    <>
      <Nav current="signup" />
      <main style={{ minHeight: "calc(100vh - 61px)" }}>
        <SignupHero copy={copy} />
      </main>
    </>
  );
}

function SignupHero({ copy }) {
  return (
    <section style={{
      borderBottom: "1px solid var(--ink-200)",
      background: "linear-gradient(180deg, white 0%, var(--ink-50) 100%)",
    }}>
      <div className="signup-grid signup-pad" style={{ maxWidth: 1180, margin: "0 auto" }}>
        <div>
          <div className="mono" style={{ fontSize: 11.5, color: "var(--brand-700)", letterSpacing: ".12em", textTransform: "uppercase", fontWeight: 600 }}>
            {copy.eyebrow}
          </div>
          <h1 style={{
            margin: "14px 0 0",
            maxWidth: 650,
            fontSize: "clamp(32px, 5vw, 52px)",
            lineHeight: 1.04,
            fontWeight: 700,
            letterSpacing: "-0.025em",
            color: "var(--ink-900)",
            textWrap: "balance",
          }}>
            {copy.title}
          </h1>
          <p style={{ margin: "22px 0 0", maxWidth: 560, fontSize: 18, lineHeight: 1.55, color: "var(--ink-600)" }}>
            {copy.intro}
          </p>

          <div style={{
            marginTop: 34,
            border: "1px solid var(--ink-200)",
            background: "white",
            borderRadius: 8,
            overflow: "hidden",
            boxShadow: "var(--shadow-sm)",
          }}>
            {copy.steps.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.5, lineHeight: 1.45, color: "var(--ink-600)" }}>{item[2]}</div>
                </div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 22, display: "flex", gap: 12, flexWrap: "wrap" }}>
            {copy.links.map(([label, href], i) => (
              <a key={href} href={href} className="btn btn-ghost btn-tap"
                 style={{ padding: "11px 15px", background: i === 0 ? "transparent" : "white" }}>
                {label}
              </a>
            ))}
          </div>
        </div>

        <SignupForm copy={copy} />
      </div>
    </section>
  );
}

function SignupForm({ copy }) {
  const [values, setValues] = React.useState({
    name: "",
    email: "",
    institution: "",
    role: "",
    workflow: copy.workflow,
    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: copy.success });
    } 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)",
      minWidth: 0,
    }}>
      <h2 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: "-0.015em", color: "var(--ink-900)" }}>
        {copy.formTitle}
      </h2>
      <p style={{ margin: "7px 0 0", fontSize: 13.5, lineHeight: 1.5, color: "var(--ink-600)" }}>
        {copy.formNote}
      </p>

      <div style={{ marginTop: 24, display: "grid", gap: 15 }}>
        <div className="form-2col">
          <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 className="form-2col">
          <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={copy.rolePlaceholder} 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>
          {copy.painLabel}
          <textarea value={values.pain} onChange={update("pain")} placeholder={copy.painPlaceholder} 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(--block)" : 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 btn-tap" disabled={disabled} style={{ padding: "12px 18px", opacity: disabled ? .72 : 1 }}>
          {state.status === "loading" ? "Submitting..." : state.status === "success" ? copy.done : copy.submit}
        </button>
      </div>
    </form>
  );
}

Object.assign(window, { SignupApp });
