/* Backentra — Join the list. Both "Join the list" and "Founding member offer" route
   here: the same page, one form, with the founding-member program explained beside it
   since the website is now the place that explains it. Renders in place of the site,
   so it is one document, not a separate page. window.BackentraJoin */
const JN = window.BackentraDesignSystem_93cf3a;
const { Button: JBtn, Icon: JIcon, Input: JInput, Select: JSelect, Textarea: JTextarea } = JN;
const jcontainer = { maxWidth: "var(--container-max)", margin: "0 auto", padding: "0 32px" };
const jlabel = { display: "block", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 11, letterSpacing: ".07em", textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 6 };
/* Required fields are marked in the label the primitives already render. */
const req = (t) => <React.Fragment>{t} <span style={{ color: "var(--accent-text)" }}>*</span></React.Fragment>;

const ROLES = ["Owner", "Co-owner / Partner", "General Manager", "Office Manager", "Operations Manager", "Estimator", "Other"];
const SIZES = ["Just me", "2 to 5", "6 to 10", "11 to 25", "26 to 50", "More than 50"];
const INDUSTRIES = ["Gutters", "Roofing", "Concrete & masonry", "Landscaping & lawn", "Tree service", "Plumbing", "HVAC", "Electrical", "Painting", "Remodeling & general contracting", "Pressure washing & exterior cleaning", "Pest control", "Snow & ice management"];

function JoinForm({ onDone }) {
  const [f, setF] = React.useState({ first: "", last: "", company: "", email: "", phone: "", industry: "", size: "", software: "", notes: "" });
  /* Honeypot: a field real visitors never see or fill, because it is visually hidden and
     never receives focus in tab order. A bot filling every input in the DOM fills this
     one too, and the server rejects the submission without saying why — no CAPTCHA, no
     extra step for a real person. See api/join.mjs. */
  const [hp, setHp] = React.useState("");
  const [err, setErr] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [failed, setFailed] = React.useState("");
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const required = ["first", "last", "company", "email", "phone", "industry"];
  const missing = required.filter((k) => !String(f[k]).trim());
  const submit = async (e) => {
    e.preventDefault();
    if (busy) return; /* a second Enter/click while the first request is in flight is a no-op, not a second row */
    if (missing.length) {
      setErr(true);
      window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("form_validation_error", { form: "join", fields: missing });
      return;
    }
    setBusy(true); setFailed("");
    window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("form_submit", { form: "join" });
    try {
      const res = await fetch("/api/join", {
        method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...f, website: hp }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        /* Server-side validation disagreeing with the client is still a field problem. */
        if (data.error === "missing_fields" || data.error === "invalid_email") { setErr(true); setBusy(false); return; }
        throw new Error(data.error || res.status);
      }
      /* An address already on the list is not a failure to the person filling the form. */
      window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("form_success", { form: "join" });
      window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("founding_member_submission", { duplicate: !!data.duplicate });
      onDone({ ...f, duplicate: !!data.duplicate });
    } catch (err2) {
      /* Nothing is cleared: whatever they typed is still in state. */
      setFailed("We could not save that just now. Your details are still here, so try again in a moment. If it keeps failing, email office@backentra.com and we will add you by hand.");
      setBusy(false);
      window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("form_failure", { form: "join" });
    }
  };
  const bad = (k) => err && missing.indexOf(k) >= 0;
  const inp = (k, label, ph, opts) => <JInput id={"j_" + k} label={label} value={f[k]} onChange={set(k)} placeholder={ph}
    error={bad(k) ? " " : null} wrapStyle={(opts && opts.wide) ? { gridColumn: "1 / -1" } : null} {...(opts && opts.rest)} />;
  const sel = (k, label, ph, list) => <JSelect id={"j_" + k} label={label} value={f[k]} onChange={set(k)} error={bad(k) ? " " : null}>
    <option value="">{ph}</option>{list.map((o) => <option key={o}>{o}</option>)}</JSelect>;

  return (
    <form onSubmit={submit} noValidate style={{ background: "var(--surface-card)", border: "1px solid var(--border)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-lg)", padding: 28 }}>
      <h1 style={{ fontSize: 24, margin: "0 0 6px" }}>Join the founding-member list</h1>
      <p style={{ fontSize: 14.5, color: "var(--text-muted)", margin: "0 0 22px", lineHeight: 1.55 }}>
        Tell us about the business. We reach out before launch to walk you through it and get your data moved over.
      </p>
      {/* Off-screen rather than display:none, so a screen reader that ignores CSS visibility
          still will not land here — and it carries tabIndex -1 and aria-hidden besides, so
          neither keyboard nor assistive-tech users can reach or announce it. Real visitors
          never see or fill this; a submission with it filled in is dropped server-side. */}
      <div aria-hidden="true" style={{ position: "absolute", width: 1, height: 1, overflow: "hidden", clip: "rect(0,0,0,0)", whiteSpace: "nowrap" }}>
        <label htmlFor="j_website">Leave this field empty</label>
        <input id="j_website" name="website" type="text" tabIndex={-1} autoComplete="off" value={hp} onChange={(e) => setHp(e.target.value)} />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }}>
        {inp("first", req("First name"), "Jane")}
        {inp("last", req("Last name"), "Doe")}
        {inp("company", req("Company name"), "Doe Gutter Co.")}
        {inp("email", req("Company email"), "jane@doegutter.com", { rest: { type: "email" } })}
        {inp("phone", req("Company phone"), "(555) 555-0100", { rest: { type: "tel" } })}
        {inp("industry", req("Industry"), "Gutters", { rest: { list: "j-industries" } })}
        <datalist id="j-industries">{INDUSTRIES.map((o) => <option key={o}>{o}</option>)}</datalist>
        {sel("size", "Company size", "Select a size", SIZES)}
        {inp("software", "What you use now", "Spreadsheets, QuickBooks, Jobber", { wide: true })}
        <JTextarea id="j_notes" label="Anything else we should know" rows={3} value={f.notes} onChange={set("notes")}
          placeholder="What are you using now? What is costing you the most time?" wrapStyle={{ gridColumn: "1 / -1" }} />
      </div>
      {err && missing.length ? <div role="alert" style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16, padding: "11px 14px", borderRadius: "var(--radius-md)", background: "var(--danger-soft)", color: "var(--danger)", fontSize: 13.5, fontWeight: 600 }}>
        <JIcon name="circle-alert" size={16} /> {missing.length} required {missing.length === 1 ? "field is" : "fields are"} still empty.
      </div> : null}
      {failed ? <div role="alert" style={{ display: "flex", alignItems: "flex-start", gap: 8, marginTop: 16, padding: "11px 14px", borderRadius: "var(--radius-md)", background: "var(--danger-soft)", color: "var(--danger)", fontSize: 13.5, lineHeight: 1.55, fontWeight: 600 }}>
        <JIcon name="circle-alert" size={16} style={{ flex: "none", marginTop: 2 }} /> {failed}
      </div> : null}
      <div style={{ marginTop: 20 }}><JBtn type="submit" variant="primary" size="lg" block disabled={busy} iconRight={<JIcon name="arrow-right" size={19} />}>{busy ? "Adding you to the list…" : "Join the founding-member list"}</JBtn></div>
      <p style={{ fontSize: 12.5, color: "var(--text-muted)", margin: "12px 0 0", lineHeight: 1.55, textAlign: "center" }}>
        Joining adds you to the Backentra mailing list. We email about launch and the founding-member program, and you can unsubscribe from any message.
      </p>
    </form>
  );
}

function Thanks({ data, onBack }) {
  const rows = [["Name", data.first + " " + data.last], ["Company", data.company], ["Email", data.email], ["Phone", data.phone], ["Industry", data.industry], ["Company size", data.size || "Not given"], ["Currently using", data.software || "Not given"]];
  if (data.notes) rows.push(["Notes", data.notes]);
  return (
    <div style={{ background: "var(--surface-card)", border: "1px solid var(--border)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-lg)", padding: 28 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 13, marginBottom: 8 }}>
        <span style={{ width: 46, height: 46, borderRadius: "var(--radius-pill)", background: "var(--success-soft)", color: "var(--success)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><JIcon name="check" size={24} /></span>
        <h1 style={{ fontSize: 24, margin: 0 }}>You're on the list, {data.first}.</h1>
      </div>
      <p style={{ fontSize: 15, color: "var(--text-body)", lineHeight: 1.6, margin: "0 0 20px" }}>
        A confirmation is on its way to <b>{data.email}</b>. We'll be in touch before launch to walk {data.company} through the platform and get your founding-member pricing set up.
      </p>
      <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", overflow: "hidden", marginBottom: 20 }}>
        <div style={{ ...jlabel, margin: 0, padding: "10px 14px", background: "var(--gray-50)", borderBottom: "1px solid var(--border)" }}>What you sent us</div>
        {rows.map(([k, v], i) => (
          <div key={k} style={{ display: "flex", gap: 14, padding: "9px 14px", borderTop: i ? "1px solid var(--border)" : "none", fontSize: 13.5 }}>
            <span style={{ flex: "none", width: 104, color: "var(--text-muted)" }}>{k}</span>
            <span style={{ flex: 1, minWidth: 0, color: "var(--text-strong)", wordBreak: "break-word" }}>{v}</span>
          </div>
        ))}
      </div>
      <p style={{ fontSize: 13.5, color: "var(--text-muted)", lineHeight: 1.6, margin: "0 0 20px" }}>
        Didn't get the confirmation? Email us at <a href="mailto:office@backentra.com" style={{ color: "var(--accent-text)", fontWeight: 600 }}>office@backentra.com</a> and a person will get back to you.
      </p>
      <JBtn variant="outline" onClick={onBack} iconLeft={<JIcon name="arrow-left" size={18} />}>Back to the site</JBtn>
    </div>
  );
}

/* The founding-member program, explained on the page rather than linked away. */
function FoundingPanel() {
  const P = window.BK_PLANS;
  const pct = P ? Math.round(P.FOUNDING_DISCOUNT * 100) : 25;
  const perks = [
    ["percent", pct + "% for life", "Off the standard rate of whatever plan you're on, for as long as your service stays continuous. Not a promo month."],
    ["phone-call", "A direct line to the builders", "No ticket queue. You talk to the people writing the software, and your workflow shapes what ships next."],
    ["upload", "Hands-on setup", "We move your clients, jobs and price list over with you. You don't start from an empty screen."],
    ["flag", "First access at launch", "Founding members are onboarded before general availability, in the order you joined the list."],
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
          <JIcon name="crown" size={19} color="var(--premium)" />
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 12, letterSpacing: ".09em", textTransform: "uppercase", color: "var(--premium)" }}>Founding member program</span>
        </div>
        <h2 style={{ fontSize: 30, lineHeight: 1.1, margin: "0 0 12px" }}>Get in first. Pay {pct}% for life.</h2>
        <p style={{ fontSize: 16, lineHeight: 1.6, color: "var(--text-body)", margin: 0 }}>
          The first group of companies on Backentra shapes what it becomes. In exchange, they keep {pct}% off the standard rate for as long as they stay with us.
        </p>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {perks.map(([ic, t, d]) => (
          <div key={t} style={{ display: "flex", gap: 14, padding: "15px 17px", background: "var(--surface-card)", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)" }}>
            <span style={{ width: 38, height: 38, borderRadius: "var(--radius-md)", background: "var(--orange-50)", color: "var(--accent-text)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><JIcon name={ic} size={19} /></span>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15.5, color: "var(--text-strong)", marginBottom: 3 }}>{t}</div>
              <div style={{ fontSize: 14, lineHeight: 1.55, color: "var(--text-muted)" }}>{d}</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ padding: "16px 18px", borderRadius: "var(--radius-lg)", background: "var(--navy-900)", color: "var(--gray-300)" }}>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 13.5, color: "#fff", marginBottom: 6 }}>One thing to know</div>
        <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.6 }}>
          Founding status is tied to continuous service. If you leave and come back later, the {pct}% does not come with you. It applies while you stay, not as a badge you keep.
        </p>
      </div>
    </div>
  );
}

function JoinPage({ onExit, onNav }) {
  const [sent, setSent] = React.useState(null);
  React.useEffect(() => { window.scrollTo({ top: 0 }); }, [sent]);
  React.useEffect(() => {
    window.BackentraSetMeta && window.BackentraSetMeta({
      path: "/join",
      title: "Join the Founding-Member List — Backentra",
      description: "Tell us about the business. We reach out before launch to walk you through Backentra and get founding-member pricing set up.",
    });
  }, []);
  return (
    <div style={{ background: "var(--surface-page)", minHeight: "100vh" }}>
      <window.BackentraSiteHeader current="join" onNav={onNav} />
      <div style={{ ...jcontainer, padding: "48px 32px 72px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.05fr 0.95fr", gap: 44, alignItems: "start" }}>
          {sent ? <Thanks data={sent} onBack={onExit} /> : <JoinForm onDone={setSent} />}
          <FoundingPanel />
        </div>
      </div>
      <window.BackentraSiteFooter onNav={onNav} />
    </div>
  );
}

window.BackentraJoin = JoinPage;
