/* Backentra marketing site — composed from DS primitives. Renders into #root. */
const MK = window.BackentraDesignSystem_93cf3a;
const { Button, Icon, Card, Badge, SegmentedControl } = MK;

const container = { maxWidth: "var(--container-max)", margin: "0 auto", padding: "0 32px" };

function Hero({ onJoin }) {
  return (
    <section style={{ background: "var(--gray-100)", padding: "84px 0 72px" }}>
      <div style={{ ...container, maxWidth: 820, textAlign: "center" }}>
        <div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 9, marginBottom: 18, padding: "6px 14px 6px 8px", borderRadius: "var(--radius-pill)", background: "var(--orange-50)", border: "1px solid var(--orange-200)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 9px", borderRadius: "var(--radius-pill)", background: "var(--orange-700)", color: "#fff", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "var(--text-2xs)", letterSpacing: ".06em" }}>SOON</span>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 13.5, color: "var(--orange-700)" }}>Founding-member spots are open now</span>
          </div>
          <h1 style={{ fontSize: 56, lineHeight: 1.02, margin: "0 0 20px" }}>Run your service business like it's built to last.</h1>
          <p style={{ fontSize: 19, lineHeight: 1.55, color: "var(--text-body)", maxWidth: 640, margin: "0 auto 30px" }}>
            Backentra gives service-based business owners the structure, support, and tools to run a stronger, more profitable business: jobs, schedule, clients, and invoicing in one dependable place. We're building it now, and the first group of companies gets in first.
          </p>
          <div style={{ display: "flex", gap: 12, marginBottom: 22, justifyContent: "center" }}>
            <Button variant="primary" size="lg" onClick={onJoin} iconRight={<Icon name="arrow-right" size={20} />}>Join the list</Button>
            <Button variant="outline" size="lg" onClick={onJoin} iconLeft={<Icon name="crown" size={18} />}>Founding member offer</Button>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--text-muted)", fontSize: 14, justifyContent: "center" }}>
            <Icon name="check" size={16} color="var(--success)" /> No card, nothing to install
            <span style={{ margin: "0 6px", color: "var(--border-strong)" }}>·</span>
            <Icon name="check" size={16} color="var(--success)" /> We'll email you before launch
          </div>
        </div>
      </div>
    </section>
  );
}

function Pillars() {
  const items = (window.BackentraPillars || []).map(([ic, t, lead, d]) => [ic, t, lead + " " + d]);
  return (
    <section style={{ background: "var(--navy-900)", padding: "72px 0" }}>
      <div style={container}>
        <div style={{ textAlign: "center", marginBottom: 48 }}>
          <div className="bk-eyebrow" style={{ color: "var(--accent-text-on-dark)", marginBottom: 12 }}>Built for business</div>
          <h2 style={{ color: "#fff", fontSize: 38, margin: 0 }}>We're in your corner.</h2>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 28 }}>
          {items.map(([ic, t, d]) => (
            <div key={t}>
              <div style={{ width: 52, height: 52, borderRadius: "var(--radius-lg)", background: "var(--surface-inverse-2)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 18 }}>
                <Icon name={ic} size={26} color="var(--accent-text)" />
              </div>
              <h3 style={{ color: "#fff", fontSize: 20, margin: "0 0 8px", letterSpacing: "0.06em", textTransform: "uppercase" }}>{t}</h3>
              <p style={{ color: "var(--gray-300)", fontSize: 15, lineHeight: 1.6, margin: 0 }}>{d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Features() {
  const feats = [
    ["calendar", "Smart scheduling", "Dispatch the right crew to the right job. Drag-and-drop calendar with travel time built in."],
    ["receipt", "Invoicing that gets paid", "Send invoices from the field and get paid faster with reminders and card payments."],
    ["users", "Client history", "Every job, note, and photo for every client, right where your team needs it."],
    ["bar-chart-3", "Reports that matter", "Know your revenue, margins, and crew utilization at a glance. No spreadsheets."],
  ];
  return (
    <section style={{ padding: "84px 0", background: "var(--surface-card)" }}>
      <div style={container}>
        <div style={{ maxWidth: 620, marginBottom: 48 }}>
          <div className="bk-eyebrow" style={{ marginBottom: 12 }}>Everything in one place</div>
          <h2 style={{ fontSize: 38, margin: "0 0 14px" }}>The tools to run a stronger business.</h2>
          <p style={{ fontSize: 17, color: "var(--text-body)", margin: 0 }}>From the first call to the final invoice, Backentra keeps the whole job organized.</p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 20 }}>
          {feats.map(([ic, t, d]) => (
            <Card key={t} interactive>
              <div style={{ display: "flex", gap: 16 }}>
                <div style={{ width: 44, height: 44, borderRadius: "var(--radius-md)", background: "var(--orange-50)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
                  <Icon name={ic} size={22} color="var(--accent-text)" />
                </div>
                <div>
                  <h3 style={{ fontSize: 18, margin: "0 0 6px" }}>{t}</h3>
                  <p style={{ fontSize: 15, color: "var(--text-muted)", margin: 0, lineHeight: 1.55 }}>{d}</p>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>
    </section>
  );
}

function Industries({ onProduct }) {
  const trades = ["Gutters", "Roofing", "Concrete & masonry", "Landscaping & lawn", "Tree service", "Plumbing", "HVAC", "Electrical", "Painting", "Remodeling & general contracting", "Pressure washing", "Snow & ice management"];
  return (
    <section style={{ padding: "72px 0", background: "var(--surface-card)" }}>
      <div style={container}>
        <div style={{ textAlign: "center", maxWidth: 620, margin: "0 auto 32px" }}>
          <div className="bk-eyebrow" style={{ marginBottom: 12 }}>Who it's for</div>
          <h2 style={{ fontSize: 36, margin: "0 0 12px" }}>Built for the trades.</h2>
          <p style={{ fontSize: 16.5, lineHeight: 1.6, color: "var(--text-body)", margin: 0 }}>
            Service businesses that run crews, quote work on site, and get paid after the job is done. If that is the shape of your day, this is built for you.
          </p>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10, justifyContent: "center" }}>
          {trades.map((t) => (
            <span key={t} style={{ display: "inline-flex", alignItems: "center", height: 38, padding: "0 16px", borderRadius: "var(--radius-pill)", background: "var(--gray-50)", border: "1px solid var(--border)", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 14, color: "var(--text-body)" }}>{t}</span>
          ))}
        </div>
        <p style={{ textAlign: "center", fontSize: 14, color: "var(--text-muted)", margin: "20px 0 0" }}>
          Not on the list? The platform does not care what the trade is, only that the work flows the same way. <a href="/product" onClick={(e) => { e.preventDefault(); onProduct(); }} style={{ color: "var(--accent-text)", fontWeight: 600 }}>See how it works</a>.
        </p>
      </div>
    </section>
  );
}

function Pricing({ onJoin, onPlans }) {
  const P = window.BK_PLANS;
  const tiers = ((P && P.TIERS) || []).filter((t) => t.monthly);
  const ent = ((P && P.TIERS) || []).filter((t) => !t.monthly)[0];
  const annualPct = P ? Math.round(P.ANNUAL_DISCOUNT * 100) : 15;
  const money = (n) => "$" + Number(n).toLocaleString("en-US");
  return (
    <section style={{ padding: "84px 0", background: "var(--surface-page)" }}>
      <div style={container}>
        <div style={{ textAlign: "center", marginBottom: 34 }}>
          <div className="bk-eyebrow" style={{ marginBottom: 12 }}>Plans &amp; pricing</div>
          <h2 style={{ fontSize: 38, margin: "0 0 14px" }}>One price for the whole platform.</h2>
          <p style={{ fontSize: 16.5, color: "var(--text-body)", margin: "0 auto", maxWidth: 580 }}>
            Every plan includes unlimited jobs, unlimited clients, and unlimited portal users. What changes is how many people work in it.
          </p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", gap: 14, alignItems: "stretch" }}>
          {tiers.map((t) => (
            <button key={t.key} type="button" onClick={onPlans} aria-label={t.name + ", " + money(t.monthly) + " per month. See plans and pricing."} style={{
              cursor: "pointer", textAlign: "left", font: "inherit", width: "100%",
              background: t.popular ? "var(--navy-900)" : "var(--surface-card)",
              border: "1px solid " + (t.popular ? "var(--navy-900)" : "var(--border)"),
              borderRadius: "var(--radius-xl)", padding: "22px 20px",
              boxShadow: t.popular ? "var(--shadow-lg)" : "var(--shadow-sm)",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10, minHeight: 24 }}>
                <h3 style={{ fontSize: 17, margin: 0, color: t.popular ? "#fff" : "var(--text-strong)" }}>{t.name}</h3>
                {t.popular && <Badge tone="accent" solid>Recommended</Badge>}
              </div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 30, color: t.popular ? "#fff" : "var(--text-strong)", letterSpacing: "-.02em" }}>{money(t.monthly)}</span>
                <span style={{ color: t.popular ? "var(--gray-400)" : "var(--text-muted)", fontSize: 13.5 }}>/mo</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 12, fontSize: 12.5, fontFamily: "var(--font-mono)", color: t.popular ? "var(--gray-300)" : "var(--text-body)" }}>
                <Icon name="users" size={14} color="var(--accent-text)" /> {t.seats} {t.seats === 1 ? "full user" : "full users"}{t.field ? " · field seats" : ""}
              </div>
            </button>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 14, marginTop: 26, flexWrap: "wrap" }}>
          <Button variant="primary" size="lg" onClick={onPlans} iconRight={<Icon name="arrow-right" size={19} />}>See plans &amp; pricing</Button>
          <span style={{ fontSize: 13.5, color: "var(--text-muted)" }}>
            Annual billing saves {annualPct}%.{ent ? " " + ent.name + " is quoted per company." : ""}
          </span>
        </div>
      </div>
    </section>
  );
}

function CTA({ onJoin }) {
  return (
    <section style={{ padding: "72px 0", background: "var(--surface-card)" }}>
      <div style={{ ...container }}>
        <div style={{ background: "var(--accent-solid)", borderRadius: "var(--radius-2xl)", padding: "56px 48px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 32, flexWrap: "wrap" }}>
          <div>
            <h2 style={{ color: "#fff", fontSize: 34, margin: "0 0 8px" }}>Built to back you up.</h2>
            <p style={{ color: "rgba(255,255,255,0.9)", fontSize: 17, margin: 0 }}>Join the list and we'll reach out before launch. Founding-member pricing is open until we go live.</p>
          </div>
          <Button variant="secondary" size="lg" onClick={onJoin} iconRight={<Icon name="arrow-right" size={20} />}>Join the list</Button>
        </div>
      </div>
    </section>
  );
}

/* Full-account sign-in dialog.
   Hand-rolled because this site ships no UI library, which means everything a <dialog> or a
   modal component would give us for free has to be written out: without it the page behind
   stays fully tabbable, so a keyboard or screen-reader user tabs straight out of the dialog
   into content they cannot see, with no way back and no way to close.

   What is deliberate here:
     role="dialog" + aria-modal      announces it as a dialog and tells assistive tech to
                                     treat everything outside as inert
     aria-labelledby/-describedby    gives it a name and a first line, read on open
     focus moves in, and back out    the trigger gets focus again on close, so the keyboard
                                     does not get dumped at the top of the document
     Tab / Shift+Tab wrap            focus cannot leave the card while it is open
     Escape closes                   capture phase, so it wins before anything else listening
     backdrop click closes           target check only, so a drag out of the card is not a close
     body scroll locked              the page behind must not scroll under the overlay

   Focusables are re-read on every Tab rather than cached on open: the card's contents are
   static today, but a cached list silently stops matching the DOM the moment they are not. */
const BK_FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';


/* The real not-found route. Reachable both by a stale/mistyped link inside the app and by
   loading an unknown URL directly (the Vercel rewrite hands the request to index.html, and
   the router below resolves the path to "notfound"), so it has to work as a first paint,
   not just as a state transition. */
function NotFound({ onNav }) {
  React.useEffect(() => {
    window.BackentraSetMeta && window.BackentraSetMeta({
      title: "Page not found — Backentra",
      description: "That page does not exist. Here is the site.",
      robots: "noindex, nofollow",
    });
  }, []);
  const go = (k) => (e) => { e.preventDefault(); onNav(k); };
  return (
    <div style={{ background: "var(--surface-card)", minHeight: "100vh" }}>
      <window.BackentraSiteHeader current="notfound" onNav={onNav} />
      <section style={{ padding: "96px 0 120px" }}>
        <div style={{ ...container, maxWidth: 640, textAlign: "center" }}>
          <div className="bk-eyebrow" style={{ marginBottom: 14 }}>404</div>
          <h1 style={{ fontSize: 38, lineHeight: 1.15, margin: "0 0 14px" }}>We can't find that page.</h1>
          <p style={{ fontSize: 17, lineHeight: 1.6, color: "var(--text-body)", margin: "0 auto 28px", maxWidth: 480 }}>
            The address may be mistyped, or the page may have moved. Here is the way back.
          </p>
          <a href="/" onClick={go("home")} style={{ display: "inline-flex", alignItems: "center", gap: 8, height: 48, padding: "0 24px",
            borderRadius: "var(--radius-md)", background: "var(--accent-solid)", color: "#fff", fontFamily: "var(--font-display)",
            fontWeight: 600, fontSize: 16, textDecoration: "none" }}>
            Back to Backentra <Icon name="arrow-right" size={18} color="#fff" />
          </a>
        </div>
      </section>
      <window.BackentraSiteFooter onNav={onNav} />
    </div>
  );
}

function Site() {
  /* Real routing: the URL is the source of truth. Initial state reads whatever path the
     browser is actually on (a direct load or a refresh), not always the homepage, and the
     router keeps history in sync so back/forward and bookmarking work like any other site. */
  const pathToPage = window.BackentraPathToPage;
  const pageToPath = window.BackentraPageToPath;
  const [page, setPageState] = React.useState(() => pathToPage(window.location.pathname));

  /* Every page and every link should go through nav(): it is the only path that pushes
     history, so it is what keeps the address bar, back/forward and the rendered page in
     sync. (product/founding/privacy/terms/pipeline used to take a raw setState setter
     here — harmless while the whole app was one URL, silently wrong now that it isn't,
     because the page would change without the address bar following it.) */
  const nav = (key) => {
    const k = key || "home";
    const path = pageToPath(k);
    if (window.location.pathname !== path) window.history.pushState({ page: k }, "", path);
    setPageState(k);
    window.scrollTo({ top: 0 });
  };
  const go = (k) => () => nav(k);
  const exit = () => nav("home");
  const onJoin = go("join");

  /* Back/forward: the browser changes location.pathname on its own, so this only has to
     read it and update state — no history call, or every Back press would push a new
     entry and Back would stop working after one press. */
  React.useEffect(() => {
    const onPop = () => { setPageState(pathToPage(window.location.pathname)); window.scrollTo({ top: 0 }); };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  React.useEffect(() => {
    window.BackentraAnalytics && window.BackentraAnalytics.trackPageView(page);
  }, [page]);

  /* Every branch below is an early return out of this same component instance, so every
     hook this component ever calls has to run on every render regardless of which branch
     fires — otherwise the hook count changes between renders and React's hook bookkeeping
     breaks. This is why the homepage's meta effect lives up here rather than down by its
     JSX: down there it would only run on the branch that falls all the way through. */
  React.useEffect(() => {
    if (page === "home") window.BackentraSetMeta && window.BackentraSetMeta({ path: "/" });
  }, [page]);

  if (page === "join") return <window.BackentraJoin onExit={exit} onNav={nav} />;
  if (page === "enterprise") return <window.BackentraEnterprise onExit={exit} onNav={nav} />;
  if (page === "referral") return <window.BackentraReferral onExit={exit} onJoin={onJoin} onNav={nav} />;
  if (page === "plans") return <window.BackentraPlans onExit={exit} onJoin={onJoin} onEnterprise={go("enterprise")} onNav={nav} />;
  if (page === "product") return <window.BackentraProduct onNav={nav} onJoin={() => nav("join")} />;
  if (page === "founding") return <window.BackentraFounding onNav={nav} onJoin={() => nav("join")} />;
  if (page === "privacy" || page === "terms") return <window.BackentraLegal kind={page} onNav={nav} />;
  if (page === "pipeline") return <window.BackentraPipeline onNav={nav} onJoin={() => nav("join")} />;
  if (page === "blog") return <window.BackentraBlog onNav={nav} onJoin={onJoin} />;
  if (page === "blog-crm-guide") return <window.BackentraBlogPost onNav={nav} onJoin={onJoin} />;
  if (page === "blog-vision") return <window.BackentraBlogPostVision onNav={nav} onJoin={onJoin} />;
  if (typeof page === "string" && page.indexOf("blog-") === 0) return <window.BackentraBlogPostGeneric slug={page.slice(5)} onNav={nav} onJoin={onJoin} />;
  if (page === "about") return <window.BackentraAbout onExit={exit} onJoin={onJoin} onNav={nav} />;
  if (page === "preview") return <window.BackentraPreview onNav={nav} onJoin={onJoin} />;
  if (page === "notfound") return <NotFound onNav={nav} />;

  /* A page key nobody handles used to fall through and render the homepage, so a link to a
     removed page looked like it had worked — that is how nine dead "See integrations" CTAs
     stayed invisible. Fail loudly in the console instead, and still show the homepage so a
     visitor is never stranded. A genuinely unknown URL no longer reaches this path at all:
     the router above resolves it to "notfound" and shows the real 404 page. */
  if (page !== "home") {
    console.error('Unrouted page key: "' + page + '". Falling back to home — check the link that set it.');
  }

  return (
    <div style={{ background: "var(--surface-card)" }}>
      {/* No onShowFullSignIn: SiteHeader takes { current, onNav } only, and deliberately routes
          Sign in to the demo-key gate pre-launch (see the comment in sitechrome.jsx). The design
          version passed a handler that was never defined in this file, so every render threw
          `ReferenceError: onShowFullSignIn is not defined` and the homepage came up blank. */}
      {/* One section per component, one per line. The previous single-line version made
          every edit a pattern-match against a 400-character string, and an orphaned
          reference in it blanked the page three separate times. */}
      <window.BackentraSiteHeader current="home" onNav={nav} />
      <Hero onJoin={onJoin} />
      <Pillars />
      <Features />
      <Industries onProduct={go("product")} />
      <Pricing onJoin={onJoin} onPlans={go("plans")} />
      <CTA onJoin={onJoin} />
      <window.BackentraSiteFooter onNav={nav} />

    </div>
  );
}

window.BackentraSite = Site;
/* Standalone repo: this page IS the site, so it mounts unconditionally.
   The design ships this mount guarded behind a marketing-page flag on window, because inside
   the design system the operator app could claim the same #root. That flag is only ever set by
   the design system's own index.html, so the guarded version would simply never mount here and
   the site would render nothing at all. Kept unconditional deliberately — do not "restore" the
   guard from a future drop without re-reading this. */
ReactDOM.createRoot(document.getElementById("root")).render(<Site />);
