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",
];

const BETA_OPTIONS = [
  "Molecular: ASO and siRNA candidate calls",
  "Population genetics",
  "Study record: qPCR, ELISA, and behavior together",
  "More than one of these",
  "Another bench workflow",
];

/* Page text for each ?module= value. `workflow` preselects the dropdown, `kind` labels the
   sign-up in the lead email and the dashboard, and `account` offers sign-in with a
   ConductScience account, which makes the visitor a beta user. */
const SIGNUP_MODULES = {
  molecular: {
    kind: "molecular-study",
    account: false,
    options: SIGNUP_OPTIONS,
    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: {
    kind: "beta",
    account: true,
    options: BETA_OPTIONS,
    workflow: "Population genetics",
    eyebrow: "Beta · Population genetics",
    title: "Join the beta for population genetics",
    intro: "Free during the beta. Go from one genotype file to structure, ancestry plots, and a methods section, and tell us what your analyses still need.",
    steps: [
      ["1", "Create your account", "One ConductScience account, the same sign-in used across ConductScience tools. It takes a minute."],
      ["2", "Run your data", "STRUCTURE, Genepop, GenAlEx, VCF, or PLINK files, in your browser."],
      ["3", "Shape what comes next", "Beta users get new analyses first and a direct line to the people building them."],
    ],
    links: [["Open the tool", "/population/app"], ["How it works", "/population"]],
    formTitle: "Or just leave your email",
    formNote: "We'll email you as new features open. No credit card.",
    painLabel: "What do you analyze, and what do you still do elsewhere? (optional)",
    painPlaceholder: "Example: 14 microsatellite loci in 300 fish from 12 rivers; we still make the maps in R.",
    rolePlaceholder: "PI, postdoc, geneticist...",
    submit: "Join the beta",
    done: "You're on the list",
    success: "You're in. We'll email you as new features open.",
  },
  general: {
    kind: "beta",
    account: true,
    options: BETA_OPTIONS,
    workflow: "Molecular: ASO and siRNA candidate calls",
    eyebrow: "Beta",
    title: "Join the ConductBiology beta",
    intro: "Free during the beta. Use Molecular, Population genetics, and the Study record as they grow, and tell us what your lab needs next.",
    steps: [
      ["1", "Create your account", "One ConductScience account, the same sign-in used across ConductScience tools. It takes a minute."],
      ["2", "Use the tools", "Molecular calls ASO and siRNA candidates, Population genetics goes from a genotype file to structure, and the Study record joins qPCR, ELISA, and behavior per animal. All run in your browser."],
      ["3", "Shape what comes next", "Beta users get new modules first and a direct line to the people building them."],
    ],
    links: [["See the tools", "/#modules"], ["Back to home", "/"]],
    formTitle: "Or just leave your email",
    formNote: "We'll email you as new features open. No credit card.",
    painLabel: "What should ConductBiology do for your lab? (optional)",
    painPlaceholder: "Example: we screen 40 siRNAs a quarter and pull qPCR, viability, and Westerns together by hand.",
    rolePlaceholder: "PI, postdoc, core director...",
    submit: "Join the beta",
    done: "You're on the list",
    success: "You're in. We'll email you as new features open.",
  },
};

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(kind) {
  const params = new URLSearchParams(window.location.search);
  return {
    kind,
    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();
  const account = useAccount();
  React.useEffect(() => {
    document.title = copy.title.includes("ConductBiology") ? copy.title : `ConductBiology: ${copy.title}`;
  }, []);
  return (
    <>
      <Nav current="signup" />
      <main style={{ minHeight: "calc(100vh - 61px)" }}>
        <SignupHero copy={copy} account={account} />
      </main>
    </>
  );
}

function SignupHero({ copy, account }) {
  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 className="signup-head">
          <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>

        <div className="signup-side">
          {copy.account && account && account.enabled ? <BetaAccountPanel account={account} /> : null}
          <SignupForm copy={copy} account={copy.account && account && account.user ? account.user : null}
                      accountOffered={Boolean(copy.account && account && account.enabled && !account.user)} />
        </div>

        <div className="signup-steps">
          <div style={{
            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>
      </div>
    </section>
  );
}

function BetaAccountPanel({ account }) {
  const joined = new URLSearchParams(window.location.search).get("joined");
  const here = `${window.location.pathname}${window.location.search.replace(/([?&])joined=1(&|$)/, "$1").replace(/[?&]$/, "")}`;
  const back = `${here}${here.includes("?") ? "&" : "?"}joined=1`;
  const card = { background: "white", border: "1px solid var(--ink-200)", borderRadius: 8, padding: 24, boxShadow: "0 24px 80px -34px rgba(15,23,42,.35)" };
  if (account.user) {
    return (
      <div style={{ ...card, borderColor: "#a7f3d0", background: "var(--ok-bg)" }} role="status">
        <div className="mono" style={{ fontSize: 11, color: "var(--ok)", letterSpacing: ".08em", textTransform: "uppercase", fontWeight: 600 }}>
          {joined ? "Welcome" : "Beta"}
        </div>
        <h2 style={{ margin: "8px 0 0", fontSize: 22, fontWeight: 700, letterSpacing: "-0.015em", color: "var(--ink-900)" }}>
          You're in the beta, {account.user.givenName || account.user.name}.
        </h2>
        <p style={{ margin: "8px 0 0", fontSize: 14, lineHeight: 1.5, color: "var(--ink-700)" }}>
          Signed in as {account.user.email}. We'll email you as new features open.
        </p>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 16 }}>
          <a href="/molecular/app" className="btn btn-primary btn-tap">Open Molecular</a>
          <a href="/population/app" className="btn btn-ghost btn-tap" style={{ background: "white" }}>Open Population genetics</a>
          <a href="/study/app" className="btn btn-ghost btn-tap" style={{ background: "white" }}>Open the Study record</a>
        </div>
      </div>
    );
  }
  return (
    <div style={card}>
      <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: "-0.015em", color: "var(--ink-900)" }}>Join with your ConductScience account</h2>
      <p style={{ margin: "7px 0 0", fontSize: 13.5, lineHeight: 1.5, color: "var(--ink-600)" }}>
        The fastest way in. Use the account you already have on conductscience.com, or create one.
      </p>
      <a href={`/api/auth/conductscience/start?next=${encodeURIComponent(back)}`} className="btn btn-primary btn-tap"
         style={{ marginTop: 16, width: "100%", padding: "12px 16px", fontSize: 15 }}>
        Create account or sign in
      </a>
    </div>
  );
}

function SignupForm({ copy, account, accountOffered }) {
  const [values, setValues] = React.useState({
    name: account ? account.name : "",
    email: account ? account.email : "",
    institution: "",
    role: "",
    workflow: copy.workflow,
    pain: "",
    conductProducts: "",
    company: "",
  });
  const [state, setState] = React.useState({ status: "idle", message: "" });
  React.useEffect(() => {
    if (account) setValues((v) => ({ ...v, name: v.name || account.name, email: account.email }));
  }, [account]);
  const kind = account ? "beta-account" : copy.kind;
  const formTitle = account ? "Tell us about your work (optional)" : accountOffered ? copy.formTitle : copy.formTitle.replace(/^Or just leave your email$/, "Join the beta");

  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(kind) }),
      });
      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: account ? "Thanks. We'll use this to decide what to build first." : 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)" }}>
        {formTitle}
      </h2>
      <p style={{ margin: "7px 0 0", fontSize: 13.5, lineHeight: 1.5, color: "var(--ink-600)" }}>
        {account ? "Optional. It helps us decide what to build first." : 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} readOnly={Boolean(account)} />
          </label>
        </div>

        <div className="form-2col">
          <label>
            Institution (optional)
            <input value={values.institution} onChange={update("institution")} autoComplete="organization" disabled={disabled} />
          </label>
          <label>
            Role (optional)
            <input value={values.role} onChange={update("role")} placeholder={copy.rolePlaceholder} disabled={disabled} />
          </label>
        </div>

        <label>
          {copy.kind === "molecular-study" ? "Workflow focus" : "What do you want to use?"}
          <select value={values.workflow} onChange={update("workflow")} disabled={disabled}>
            {copy.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>

        {copy.kind === "molecular-study" ? (
          <label>
            ConductScience products you already use
            <input value={values.conductProducts} onChange={update("conductProducts")} placeholder="ConductVision, ConductSignal, equipment, tools..." disabled={disabled} />
          </label>
        ) : null}

        <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" ? (account ? "Sent" : copy.done) : (account ? "Send" : copy.submit)}
        </button>
      </div>
    </form>
  );
}

Object.assign(window, { SignupApp });
