/* Backentra — Enterprise inquiry. What "Talk to us" opens: the intake that feeds the
   enterprise quote calculator, beside a plain explanation of how enterprise pricing is
   worked out, so a prospect can see what drives the number before they send anything.
   Every rate shown comes from BK_PLANS.ENTERPRISE. window.BackentraEnterprise */
const EN = window.BackentraDesignSystem_93cf3a;
const { Button: EBtn, Icon: EIcon, Input: EInput, Select: ESelect, Textarea: ETextarea } = EN;
const econtainer = { maxWidth: "var(--container-max)", margin: "0 auto", padding: "0 32px" };
const eeyebrow = { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 11, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--text-muted)" };
const ereq = (t) => <React.Fragment>{t} <span style={{ color: "var(--accent-text)" }}>*</span></React.Fragment>;
const emoney = (n) => "$" + Number(n).toLocaleString("en-US");

const SERVICE_HELP = {
  standard: "Standard support, shared account coverage",
  priority: "Priority queue, scheduled account check-ins",
  named: "Named contact, quarterly business review",
  dedicated: "Dedicated coverage, negotiated service plan",
};

function EnterpriseForm({ onDone }) {
  const P = window.BK_PLANS;
  const E = P ? P.ENTERPRISE : null;
  const [f, setF] = React.useState({
    company: "", website: "", first: "", last: "", role: "", email: "", phone: "",
    industry: "", area: "", full: "", field: "", locations: "", divisions: "",
    service: "standard", current: "", migrate: "", timeline: "", notes: "",
  });
  /* Honeypot — same pattern as join.jsx: invisible, unreachable by keyboard, never filled
     by a real visitor. api/enterprise.mjs reports success and sends nothing if it is set. */
  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 = ["company", "first", "last", "role", "email", "phone", "industry", "full", "field"];
  const missing = required.filter((k) => !String(f[k]).trim());
  const bad = (k) => err && missing.indexOf(k) >= 0;
  const inp = (k, label, ph, opts) => <EInput id={"e_" + 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) => <ESelect id={"e_" + k} label={label} value={f[k]} onChange={set(k)} error={bad(k) ? " " : null}>
    {ph ? <option value="">{ph}</option> : null}{list.map((o) => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}</ESelect>;

  /* Live estimate from the same engine HQ quotes with, so the range a prospect sees is
     the range we would actually build. Only shown once seat counts exist. */
  const est = React.useMemo(() => {
    if (!P || !E) return null;
    const full = parseInt(f.full, 10), field = parseInt(f.field, 10);
    if (!(full > 0)) return null;
    return P.enterpriseQuote({
      fullUsers: full, fieldUsers: field > 0 ? field : 0,
      locations: parseInt(f.locations, 10) || 1, divisions: parseInt(f.divisions, 10) || 2,
      service: f.service, addons: [], implementation: {}, discountPct: 0,
    });
  }, [f.full, f.field, f.locations, f.divisions, f.service]);

  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;
    if (missing.length) {
      setErr(true);
      window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("form_validation_error", { form: "enterprise", fields: missing });
      return;
    }
    setBusy(true); setFailed("");
    window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("form_submit", { form: "enterprise" });
    try {
      const res = await fetch("/api/enterprise", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...f, est: est, website2: hp }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        if (data.error === "missing_fields" || data.error === "invalid_email") { setErr(true); setBusy(false); return; }
        throw new Error(data.error || res.status);
      }
      window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("form_success", { form: "enterprise" });
      window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("enterprise_submission", {});
      onDone({ ...f, est: est });
    } catch (err2) {
      setFailed("We could not send that just now. Nothing you entered was lost, so try again in a moment. If it keeps failing, email office@backentra.com directly.");
      setBusy(false);
      window.BackentraAnalytics && window.BackentraAnalytics.trackEvent("form_failure", { form: "enterprise" });
    }
  };

  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" }}>Tell us about the operation</h1>
      <p style={{ fontSize: 14.5, color: "var(--text-muted)", margin: "0 0 22px", lineHeight: 1.55 }}>
        Enterprise pricing is built per company. These are the inputs it is calculated from, so the more accurate they are, the closer the quote comes back.
      </p>
      <div aria-hidden="true" style={{ position: "absolute", width: 1, height: 1, overflow: "hidden", clip: "rect(0,0,0,0)", whiteSpace: "nowrap" }}>
        <label htmlFor="e_website2">Leave this field empty</label>
        <input id="e_website2" name="website2" type="text" tabIndex={-1} autoComplete="off" value={hp} onChange={(e) => setHp(e.target.value)} />
      </div>

      <div style={{ ...eeyebrow, marginBottom: 12 }}>The company</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start", marginBottom: 26 }}>
        {inp("company", ereq("Company name"), "Northgate Property Group")}
        {inp("website", "Website", "northgate.com")}
        {inp("industry", ereq("Industry or trade"), "Property maintenance")}
        {inp("area", "Where you operate", "Central Texas, 4 metros")}
      </div>

      <div style={{ ...eeyebrow, marginBottom: 12 }}>Who we should talk to</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start", marginBottom: 26 }}>
        {inp("first", ereq("First name"), "John")}
        {inp("last", ereq("Last name"), "Doe")}
        {sel("role", ereq("Role"), "Select a role", ["Owner", "Co-owner / Partner", "President / CEO", "COO / Operations", "CFO / Finance", "General Manager", "IT", "Other"])}
        {inp("email", ereq("Work email"), "john@northgate.com", { rest: { type: "email" } })}
        {inp("phone", ereq("Phone"), "(555) 555-0100", { rest: { type: "tel" } })}
      </div>

      <div style={{ ...eeyebrow, marginBottom: 4 }}>Scale</div>
      <p style={{ fontSize: 13, color: "var(--text-muted)", margin: "0 0 12px", lineHeight: 1.5 }}>
        {E ? "Enterprise includes " + E.includedFull + " full users and " + E.includedField + " field users. Anything above that is priced by volume band." : "Seat counts drive the recurring price."}
      </p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start", marginBottom: 26 }}>
        {inp("full", ereq("Full users"), "Office, sales, management", { rest: { type: "number", min: 1 } })}
        {inp("field", ereq("Field users"), "Crew and technicians", { rest: { type: "number", min: 0 } })}
        {inp("locations", "Locations", E ? String(E.includedLocations) + " included" : "1", { rest: { type: "number", min: 1 } })}
        {inp("divisions", "Divisions", E ? String(E.includedDivisions) + " included" : "2", { rest: { type: "number", min: 1 } })}
        <ESelect id="e_service" label="Support level" value={f.service} onChange={set("service")} wrapStyle={{ gridColumn: "1 / -1" }}>
          {((E && E.service) || []).map((s) => <option key={s.key} value={s.key}>{s.label}{s.rate ? "  ·  +" + emoney(s.rate) + "/mo" : "  ·  included"}</option>)}
        </ESelect>
      </div>

      {est && <div style={{ marginBottom: 26, padding: "18px 20px", borderRadius: "var(--radius-lg)", background: "var(--orange-50)", border: "1px solid var(--orange-200)" }}>
        <div style={{ ...eeyebrow, color: "var(--orange-700)", marginBottom: 8 }}>Indicative, before discounts</div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 30, color: "var(--text-strong)", letterSpacing: "-.02em" }}>{emoney(est.monthly)}</span>
          <span style={{ fontSize: 14, color: "var(--text-body)" }}>per month</span>
          <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-muted)" }}>+ {emoney(est.implementation)} one-time setup</span>
        </div>
        <p style={{ margin: "10px 0 0", fontSize: 12.5, lineHeight: 1.55, color: "var(--text-body)" }}>
          Calculated from the figures above at standard rates. A real quote factors in migration, configuration, training, add-ons and any commercial terms we agree.
        </p>
      </div>}

      <div style={{ ...eeyebrow, marginBottom: 12 }}>Where you are today</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }}>
        {inp("current", "What you run on now", "ServiceTitan, spreadsheets, QuickBooks")}
        {sel("timeline", "When you want to be live", "No fixed date", ["Within 30 days", "1 to 3 months", "3 to 6 months", "Later this year", "Still evaluating"])}
        {sel("migrate", "Data to bring across", "Not sure yet", ["Clients only", "Clients and job history", "Everything, including financials", "Starting clean"])}
        <ETextarea id="e_notes" label="Anything else we should know" rows={3} value={f.notes} onChange={set("notes")}
          placeholder="Requirements, integrations, procurement process, security review" wrapStyle={{ gridColumn: "1 / -1" }} />
      </div>

      {err && missing.length ? <div role="alert" style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 18, padding: "11px 14px", borderRadius: "var(--radius-md)", background: "var(--danger-soft)", color: "var(--danger)", fontSize: 13.5, fontWeight: 600 }}>
        <EIcon 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: 18, padding: "11px 14px", borderRadius: "var(--radius-md)", background: "var(--danger-soft)", color: "var(--danger)", fontSize: 13.5, lineHeight: 1.55, fontWeight: 600 }}>
        <EIcon name="circle-alert" size={16} style={{ flex: "none", marginTop: 2 }} /> {failed}
      </div> : null}
      <div style={{ marginTop: 22 }}><EBtn type="submit" variant="primary" size="lg" block disabled={busy} iconRight={<EIcon name="arrow-right" size={19} />}>{busy ? "Sending…" : "Send this to our team"}</EBtn></div>
      <p style={{ fontSize: 12.5, color: "var(--text-muted)", margin: "12px 0 0", lineHeight: 1.55, textAlign: "center" }}>
        We reply within one business day. No card, no commitment, no automated sales sequence.
      </p>
    </form>
  );
}

/* How the number is arrived at. Rates read from the model, not retyped. */
function HowPriced() {
  const P = window.BK_PLANS;
  const E = P ? P.ENTERPRISE : null;
  if (!E) return null;
  const band = (rows) => rows.map((b, i) => {
    const prev = i ? rows[i - 1].upTo : 0;
    const label = b.upTo === Infinity ? "Above " + prev : (prev + 1) + " to " + b.upTo;
    return <div key={label} style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "7px 0", borderTop: i ? "1px solid var(--border)" : "none", fontSize: 13.5 }}>
      <span style={{ color: "var(--text-body)" }}>{label}</span>
      <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--text-strong)" }}>{emoney(b.rate)}<span style={{ color: "var(--text-muted)", fontWeight: 400 }}> /user</span></span>
    </div>;
  });
  const steps = [
    ["layers", "A platform minimum", "Every enterprise agreement starts at " + emoney(E.floor) + " per month. That is the floor, not the price."],
    ["users", "Seats above what is included", E.includedFull + " full users and " + E.includedField + " field users come with it. Beyond that, users are priced by volume band, so the rate falls as the count rises."],
    ["git-branch", "Structure", "Extra locations at " + emoney(E.locationRate) + ", divisions at " + emoney(E.divisionRate) + ", separate workspaces at " + emoney(E.workspaceRate) + " per month. " + E.includedLocations + " location and " + E.includedDivisions + " divisions are included."],
    ["headset", "The support level you pick", "Standard is included. Priority, named and dedicated account management each carry a monthly rate."],
    ["wrench", "One-time setup", "Onboarding, data migration, configuration and training are quoted once, from " + emoney(E.minOnboarding) + " depending on scope. Never rolled into the monthly to make it look smaller."],
    ["handshake", "Commercial terms", "Annual billing and multi-year commitments earn a discount. Anything past that is an exception that gets written down, not a haggle."],
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div>
        <div style={{ ...eeyebrow, color: "var(--accent-text)", marginBottom: 12 }}>How enterprise pricing works</div>
        <h2 style={{ fontSize: 30, lineHeight: 1.1, margin: "0 0 12px" }}>No mystery number.</h2>
        <p style={{ fontSize: 16, lineHeight: 1.6, color: "var(--text-body)", margin: 0 }}>
          Enterprise is quoted per company because the shape of the company changes the cost. Here is exactly what goes into it.
        </p>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {steps.map(([ic, t, d], i) => (
          <div key={t} style={{ display: "flex", gap: 14, padding: "14px 16px", background: "var(--surface-card)", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)" }}>
            <span style={{ width: 30, height: 30, borderRadius: "var(--radius-pill)", background: "var(--navy-900)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13 }}>{i + 1}</span>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 3 }}>
                <EIcon name={ic} size={15} color="var(--accent-text)" />
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, color: "var(--text-strong)" }}>{t}</span>
              </div>
              <div style={{ fontSize: 13.5, lineHeight: 1.55, color: "var(--text-muted)" }}>{d}</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div style={{ padding: "15px 17px", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", background: "var(--surface-card)" }}>
          <div style={{ ...eeyebrow, marginBottom: 9 }}>Full users, per month</div>
          {band(E.fullBands)}
        </div>
        <div style={{ padding: "15px 17px", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", background: "var(--surface-card)" }}>
          <div style={{ ...eeyebrow, marginBottom: 9 }}>Field users, per month</div>
          {band(E.fieldBands)}
        </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 }}>What we will not do</div>
        <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.6 }}>
          Quote a recurring price below the platform minimum to win a deal, then recover it in setup fees. Setup is quoted separately and honestly, and the monthly is what it costs to run.
        </p>
      </div>
    </div>
  );
}

function EnterpriseThanks({ data, onBack }) {
  const rows = [["Company", data.company], ["Contact", data.first + " " + data.last + " · " + data.role], ["Email", data.email], ["Phone", data.phone], ["Industry", data.industry], ["Full users", data.full], ["Field users", data.field], ["Locations", data.locations || "1"], ["Divisions", data.divisions || "2"], ["Support level", data.service]];
  if (data.timeline) rows.push(["Timeline", data.timeline]);
  if (data.current) rows.push(["Currently using", data.current]);
  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" }}><EIcon name="check" size={24} /></span>
        <h1 style={{ fontSize: 24, margin: 0 }}>Got it, {data.first}.</h1>
      </div>
      <p style={{ fontSize: 15, color: "var(--text-body)", lineHeight: 1.6, margin: "0 0 20px" }}>
        We'll build a quote for {data.company} and come back to <b>{data.email}</b> within one business day, with the line items broken out so you can see what each piece costs.
      </p>
      {data.est && <div style={{ padding: "16px 18px", borderRadius: "var(--radius-lg)", background: "var(--orange-50)", border: "1px solid var(--orange-200)", marginBottom: 20 }}>
        <div style={{ ...eeyebrow, color: "var(--orange-700)", marginBottom: 6 }}>Indicative from what you sent</div>
        <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 26, color: "var(--text-strong)" }}>{emoney(data.est.monthly)}<span style={{ fontSize: 14, fontWeight: 400, color: "var(--text-muted)" }}> /mo + {emoney(data.est.implementation)} setup</span></div>
      </div>}
      <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", overflow: "hidden", marginBottom: 20 }}>
        <div style={{ ...eeyebrow, 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: 112, 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" }}>
        Need us sooner? Email <a href="mailto:office@backentra.com" style={{ color: "var(--accent-text)", fontWeight: 600 }}>office@backentra.com</a> and reference {data.company}.
      </p>
      <EBtn variant="outline" onClick={onBack} iconLeft={<EIcon name="arrow-left" size={18} />}>Back to the site</EBtn>
    </div>
  );
}

function EnterprisePage({ onExit, onNav }) {
  const [sent, setSent] = React.useState(null);
  React.useEffect(() => { window.scrollTo({ top: 0 }); }, [sent]);
  React.useEffect(() => {
    window.BackentraSetMeta && window.BackentraSetMeta({
      path: "/enterprise",
      title: "Enterprise — Backentra",
      description: "Enterprise pricing is built per company. Tell us about the operation and we reply within one business day with a real quote.",
    });
  }, []);
  return (
    <div style={{ background: "var(--surface-page)", minHeight: "100vh" }}>
      <window.BackentraSiteHeader current="enterprise" onNav={onNav} />
      <div style={{ ...econtainer, padding: "48px 32px 72px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.05fr 0.95fr", gap: 44, alignItems: "start" }}>
          {sent ? <EnterpriseThanks data={sent} onBack={onExit} /> : <EnterpriseForm onDone={setSent} />}
          <HowPriced />
        </div>
      </div>
      <window.BackentraSiteFooter onNav={onNav} />
    </div>
  );
}

window.BackentraEnterprise = EnterprisePage;
