/* Run the numbers — Mike, wide-monitor review: this used to be its own three-step page (a
 * three-input form, a separate "assumptions" card, a separate result section, then a separate
 * emailed-working gate) built to Dylan's original 7 Sept spec. Rebuilt as one continuation of
 * the corner widget (site/widget.jsx) instead: whatever a visitor already had running there —
 * platform, servers, units/server, rate, and the same live-since-you-arrived clock — keeps
 * ticking here, in the same dark box, and a visitor progresses through it like a short form
 * rather than scrolling past several differently-styled sections. "Enter your estate above" (the
 * old three-input intro, once its own section) is gone outright — the numbers are already live
 * above the fold, there's nothing left to separately ask for. The VC code that section used to
 * hold is reused below for an unrelated, newer block (what the savings could fund) rather than
 * left to rot or renumbered — see that section's own comment.
 *
 * Reuses widget.jsx's own globals (SW_PLATFORMS, swLoad/swSave, swCompute, swUsd, the field
 * styles) rather than re-implementing a second platform table and a second set of input styles —
 * widget.jsx's <script> loads before this one (see build_pages.py), so those names are already
 * global by the time this file runs. The corner widget itself is hidden on this one page
 * (SiteFoot hideWidget, site/nav.jsx) since this page's own dark box already is the expanded
 * widget; showing both would just be the same live numbers twice.
 *
 * The email gate is drawn but not wired: the automation (Resend or Cloudflare) is Mike's, and is
 * a finishing step, same as before.
 */

/* Continuing from the live savings widget: its "Run the full numbers" button hands off the
   visitor's own platform/servers/cores/rate as query params, so the number they were just
   watching keeps going instead of resetting to blank — Mike: "it'd be so cool if it's
   continuing." Read once at module scope, not per render. */
const HANDOFF = (() => {
  try {
    const qp = new URLSearchParams(location.search);
    return { platform: qp.get('platform'), servers: qp.get('servers'), cores: qp.get('cores'), rate: qp.get('rate') };
  } catch (e) { return {}; }
})();

function calcSeed() {
  const base = swLoad();
  const platform = SW_PLATFORMS.some(p => p.value === HANDOFF.platform) ? HANDOFF.platform : base.platform;
  const p = SW_PLATFORMS.find(x => x.value === platform) || SW_PLATFORMS[0];
  /* A query-param handoff naming a DIFFERENT platform than whatever was last persisted has to
     reset perServer/rate to that platform's own defaults too, not just carry over the previous
     platform's saved numbers — landing on ?platform=nutanix straight from a stale VMware session
     was silently keeping VMware's own $40/core (persisted in base.rate) instead of falling back
     to Nutanix's own default. Only reached when there's no explicit ?cores=/?rate= of its own. */
  const platformChanged = platform !== base.platform;
  const servers = HANDOFF.servers != null ? swNum(HANDOFF.servers) : base.servers;
  const perServer = HANDOFF.cores != null ? swNum(HANDOFF.cores) : (platformChanged ? p.perServer : base.perServer);
  const rate = HANDOFF.rate != null ? swNum(HANDOFF.rate) : (platformChanged ? p.rate : base.rate);
  return {
    firstVisit: base.firstVisit, platform,
    servers: servers ?? SW_DEFAULT_SERVERS, perServer: perServer ?? p.perServer, rate: rate ?? p.rate,
  };
}

/* Mike, 14 Sept: "wouldn't it be so cool if... based on the calculation, how they could
   reallocate into those six areas." Deliberately NOT added to the Compare pages' own cost
   calculator — Mike: "I don't want to clutter that one up... they move on to talk about the
   details of Basalt versus that particular platform" — this only belongs where the calculator IS
   the whole page.

   Second pass, 14 Sept: "it's all got to get tied back to the variable above in that page." Every
   card shows a real, live number computed from the same state the calculator above uses — nothing
   here is static copy.

   Third pass, 15 Sept — Triq V2 walkthrough: shrunk from six cards to three, matching the home
   page's own "what your team gets back" (see home.jsx's Outcomes — Luigi: "budget, people, and
   time... it's hard to get money, it's hard to hire people, it's impossible to get time back").
   Budget reads the computed dollar delta directly; People converts it to an FTE-equivalent (the
   one place a stated conversion assumption, $165k, does real work); Time originally reread the
   visitor's own server count as hosts consolidated under one control plane.

   Fourth pass, 16 Sept — Mike's own review: "I'm not really sure that time is measured in hosts...
   it's all about meetings, hours... not planes." Hosts-under-one-plane is an architecture fact,
   not a time claim — it doesn't actually say how much of anyone's day comes back. Time now reads
   `mgmtHoursYear` straight off the cost calculator's own state (widget.jsx's swCompute), the same
   number its own "Management hours/year" row shows — not re-derived from a dollar figure, so
   there's one hours computation on this page, not two that could drift apart.

   Fifth pass, same day, his own follow-up: "I am not actually seeing what you employ... you
   probably have to go out and do some research and find out how much management hours are per
   platform... and then what the average salary... wage per hour is." SW_PLATFORMS' own
   `mgmtHoursPerServerYear` (widget.jsx) is that per-platform research pass, and ADMIN_HOURLY_WAGE
   there is a real BLS figure, not an invented one — see that file's own comment for both
   citations. This card no longer keeps its own separate $165k/2080 approximation of an hourly
   rate; it cites the same real wage the calculator itself uses. */
const TEAM_GETS_BACK_FTE_COST = 165000;

function TeamGetsBack({ state }) {
  const { SectionHeader, Card } = DS;
  const { savingsYear, mgmtHoursYear, platform } = swCompute(state);
  const hasSavings = savingsYear != null && savingsYear > 0;
  const fte = hasSavings ? savingsYear / TEAM_GETS_BACK_FTE_COST : null;
  const dollars = hasSavings ? swUsdWhole(savingsYear) + '/year' : '-';

  const items = [
    { title: 'Budget', unit: 'Measured in dollars', value: dollars,
      body: 'The delta above, freed up for security, modernization, or mission systems.' },
    { title: 'People', unit: 'Measured in FTEs', value: fte != null ? fte.toFixed(1) + ' engineers/year' : '-',
      body: 'The fully-loaded engineer-equivalent of that same delta, assuming ' + swUsdWhole(TEAM_GETS_BACK_FTE_COST) + ' fully loaded, illustrative, not a published benchmark.' },
    { title: 'Time', unit: 'Measured in hours, not hosts', value: mgmtHoursYear != null ? Math.round(mgmtHoursYear).toLocaleString() + ' hrs/year' : '-',
      body: 'The recurring management hours ' + platform.label + '’s control-plane-per-cluster architecture demands (patch cycles, STIG upkeep, per-cluster config) at $' + ADMIN_HOURLY_WAGE + '/hour, fully loaded (U.S. Bureau of Labor Statistics). The hours themselves are an illustrative estimate, not a published benchmark.' },
  ];

  return (
    <section style={{ padding: '70px var(--gutter)', background: 'var(--surface-page)' }}>
      <SectionHeader eyebrow="What that number actually buys" title="Where the funds can go"
        lead="Three lenses on the same delta above: change your own numbers there and every figure below moves with them." />
      <div className="leverage-grid" style={{ marginTop: 32 }}>
        {items.map((c, i) => (
          <Card key={c.title} seed={240 + i} eyebrow={c.title} title={c.value} meta={c.unit}>{c.body}</Card>
        ))}
      </div>
    </section>
  );
}

function Calculator() {
  const [state, setState] = React.useState(calcSeed);
  const [now, setNow] = React.useState(Date.now());

  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  React.useEffect(() => { swSave(state); }, [state]);

  return (
    <div>
      <SiteNav active={null} />
      <ReviewBar page="V" />

      {/* Mike, 14 Sept: the separate intro block (the old VA — "Run the numbers," a lead
          paragraph) went straight into a dark section holding a separate dark card, and
          didn't add much on its own — dropped so the live calculator is the very first thing
          on the page, on the same dark/inverse background every other technical or
          numbers-driven section already uses (Platform overview, Security & trust,
          Federal/DDIL), not two competing treatments stacked on each other. The inputs/gate/sent
          step flow itself now lives in widget.jsx's shared LiveCostFlow — the Compare pages'
          own cost calculator uses the exact same one, see pages.jsx's ComparePresetCost. */}
      <Reviewed id="VB" top={30}>
        <section style={{ padding: '90px var(--gutter) 90px', background: 'var(--surface-inverse)' }}>
          {/* Mike: centered, not pinned to the left gutter — "the most simple page." */}
          <div style={{ maxWidth: 640, margin: '0 auto' }}>
            <LiveCostFlow state={state} setState={setState} now={now} platformOptions={SW_FEATURED_PLATFORMS}
              heading="What the status quo is costing your organization" />
          </div>
        </section>
      </Reviewed>

      <SectionDivider seed={241} />
      <Reviewed id="VC"><TeamGetsBack state={state} /></Reviewed>

      {/* Mike: the light VC section and the footer's own dark background were running together
          with no seam between them at all — the same hairline every other section-to-section
          boundary on the site already gets. */}
      <SectionDivider seed={242} />
      <SiteFoot hideWidget />
    </div>
  );
}
