// EnvelopeSizer — the interactive "size your envelope" panel on /pricing/.
//
// Runs entirely in the browser and posts nothing. That is the point: a buyer
// evaluating a security product should be able to price it without handing
// their asset inventory to a vendor CRM first. It is the same "no demo wall"
// position the rest of the site takes, applied to pricing itself.
//
// Tier data and the incumbent-cost model live in data/pricingPlans.js.

function EnvelopeSizer({ tiers = [] }) {
  const { React } = window;
  const { useState, useMemo } = React;

  const [repos, setRepos] = useState(24);
  const [targets, setTargets] = useState(10);
  const [hosts, setHosts] = useState(512);
  const [clouds, setClouds] = useState(3);
  const [devs, setDevs] = useState(80);
  const [dep, setDep] = useState(1); // 0 Sekura cloud · 1 your cloud · 2 on-prem

  const money = (n) => '$' + Math.round(n).toLocaleString('en-US');
  const num = (n) => n.toLocaleString('en-US');
  const assets = { repos, targets, hosts, clouds, devs };

  // Cheapest tier that both fits every asset count and supports the chosen
  // deployment. Null means the estate is past a single Enterprise envelope.
  const tier = useMemo(
    () => tiers.find((t) => t.dep >= dep
      && repos <= t.repos && targets <= t.targets
      && hosts <= t.hosts && clouds <= t.clouds) || null,
    [tiers, dep, repos, targets, hosts, clouds],
  );

  const rows = useMemo(
    () => (window.IncumbentCosts ? window.IncumbentCosts(assets) : []),
    [repos, targets, hosts, clouds, devs],
  );
  const total = rows.reduce((s, r) => s + r[1], 0);
  const price = tier ? tier.price : 260000;
  const saving = total - price;

  const caps = tier || tiers[tiers.length - 1] || { repos: 0, targets: 0, hosts: 0, clouds: 0 };

  // Hosts step in blocks of 128 because capacity is sold in blocks of 256 —
  // a 1-host slider would imply a precision the envelope does not have.
  const sliders = [
    { id: 'repos', label: 'Repositories', v: repos, set: setRepos, min: 0, max: 200, step: 1 },
    { id: 'targets', label: 'Live applications & APIs', v: targets, set: setTargets, min: 0, max: 80, step: 1 },
    { id: 'hosts', label: 'Network hosts in scope', v: hosts, set: setHosts, min: 0, max: 8192, step: 128 },
    { id: 'clouds', label: 'Cloud accounts', v: clouds, set: setClouds, min: 0, max: 20, step: 1 },
    { id: 'devs', label: 'Engineers writing code', v: devs, set: setDevs, min: 0, max: 500, step: 5 },
  ];

  const bars = [
    { label: 'Repository slots', used: repos, cap: caps.repos },
    { label: 'Live targets', used: targets, cap: caps.targets },
    { label: 'Hosts', used: hosts, cap: caps.hosts },
    { label: 'Cloud accounts', used: clouds, cap: caps.clouds },
  ];

  const deployments = ['Sekura cloud', 'Your cloud', 'On-prem / air-gapped'];

  return (
    <section className="ah-sizer-section">
      <div className="ah-price-inner">
        <div className="ah-sizer">
          <div className="ah-sizer-head">
            <h2 className="ah-h3">Size your envelope</h2>
            <span className="ah-caption">Move the sliders — nothing is sent anywhere.</span>
          </div>

          <div className="ah-sizer-body">
            <div className="ah-sizer-inputs">
              {sliders.map((s) => (
                <div className="ah-field-row" key={s.id}>
                  <div className="ah-field-top">
                    <label htmlFor={`sz-${s.id}`}>{s.label}</label>
                    <span className="ah-field-val">{num(s.v)}</span>
                  </div>
                  <input
                    id={`sz-${s.id}`}
                    className="ah-range"
                    type="range"
                    min={s.min} max={s.max} step={s.step} value={s.v}
                    onChange={(e) => s.set(+e.target.value)}
                  />
                </div>
              ))}

              <div className="ah-field-row">
                <div className="ah-field-top">
                  <span className="ah-field-legend" id="ah-dep-label">Where it has to run</span>
                </div>
                <div className="ah-seg" role="group" aria-labelledby="ah-dep-label">
                  {deployments.map((d, i) => (
                    <button
                      key={d}
                      type="button"
                      aria-pressed={dep === i}
                      onClick={() => setDep(i)}
                    >
                      {d}
                    </button>
                  ))}
                </div>
              </div>
            </div>

            <div className="ah-sizer-readout">
              <p className="ah-eyebrow">{tier ? tier.name : 'Portfolio'}</p>
              <p className="ah-sizer-price">
                {tier
                  ? <>{tier.priceLabel || (tier.price === 0 ? '$0' : money(tier.price))}<span className="ah-sizer-per"> / year</span></>
                  : <>Let&rsquo;s scope it</>}
              </p>
              <p className="ah-sizer-note ah-small">
                {tier
                  ? tier.note
                  : 'Beyond a single Enterprise envelope. Priced against your full estate, available through AWS, Azure, GCP, OCI and Alibaba marketplaces.'}
              </p>

              <div className="ah-bars">
                {bars.map((b) => {
                  const over = b.used > b.cap;
                  const pct = b.cap > 0
                    ? Math.min(100, (b.used / b.cap) * 100)
                    : (b.used > 0 ? 100 : 0);
                  return (
                    <div className={`ah-bar ${over ? 'is-over' : ''}`} key={b.label}>
                      <div className="ah-bar-top">
                        <span>{b.label}</span>
                        <span className="ah-bar-num">
                          {b.used.toLocaleString('en-US')} / {b.cap > 0 ? b.cap.toLocaleString('en-US') : '—'}
                        </span>
                      </div>
                      <div className="ah-bar-track">
                        <div className="ah-bar-fill" style={{ width: pct + '%' }} />
                      </div>
                    </div>
                  );
                })}
              </div>

              <div className="ah-compare">
                <h3 className="ah-compare-title">What this replaces today</h3>
                {rows.length ? rows.map(([label, amt]) => (
                  <div className="ah-crow" key={label}>
                    <span>{label}</span><span className="ah-crow-amt">{money(amt)}</span>
                  </div>
                )) : (
                  <div className="ah-crow">
                    <span>Nothing in scope yet — add some assets.</span><span className="ah-crow-amt">—</span>
                  </div>
                )}
                <div className="ah-crow is-total">
                  <span>Current stack</span><span className="ah-crow-amt">{money(total)}</span>
                </div>

                <p className="ah-saving">
                  {total === 0
                    ? 'Set your asset counts to compare against your current stack.'
                    : saving > 0
                      ? <>Sekura replaces that for <b>{money(price)}</b> — <b>{money(saving)}</b> less per year, and it runs continuously instead of once.</>
                      : <>At this scope a single tool would cost less up front — but you&rsquo;d be buying one pillar, not both, and testing once a year instead of every commit.</>}
                </p>
                <p className="ah-caption ah-compare-foot">
                  Comparison figures are list-price estimates for each category, not quotes.
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.EnvelopeSizer = EnvelopeSizer;
