/* =========================================================
   SIGNET — Pricing page (interactive estimator)
   ========================================================= */

// Pricing model: marginal bracket pricing
//   First 10 heads        — $175/head
//   Next 15 heads (11-25) — $165/head
//   Next 25 heads (26-50) — $155/head
//   Beyond 50             — Enterprise (custom quote)
const BRACKETS = [
  { upTo: 10, rate: 175 },
  { upTo: 25, rate: 165 },
  { upTo: 50, rate: 155 },
];

const computeBreakdown = (heads) => {
  let remaining = heads;
  let prev = 0;
  let total = 0;
  const lines = [];
  for (const b of BRACKETS) {
    const span = Math.max(0, Math.min(remaining, b.upTo - prev));
    if (span > 0) {
      const sub = span * b.rate;
      lines.push({ from: prev + 1, to: prev + span, rate: b.rate, count: span, sub });
      total += sub;
    }
    remaining -= span;
    prev = b.upTo;
    if (remaining <= 0) break;
  }
  return { total, lines };
};

const ALL_INCLUSIVE_FEATURES = [
  "Helpdesk with your dedicated trio — Tech Support Agent, Sysadmin, Client Success",
  "Device & endpoint management, updated weekly",
  "Cybersecurity: SentinelOne EDR, hardened firewalls, 24/7 SOC",
  "AI integration & workflow automation",
  "Microsoft 365 with Teams administration",
  "Network management: UniFi, VPN, 5G failover, L3 & L7 firewalls",
  "Vendor management: procurement, assets, ISP & telco, AI spend",
  "Backup & business continuity with annual tabletops",
  "Onboarding, offboarding, and new-hire orientation",
  "Compliance support: CMMC, SOC 2, HIPAA, PCI",
];

const SOFTWARE_CATALOG = [
  { id: "m365-bp", name: "Microsoft 365 Business Premium", desc: "Office apps, Exchange, Teams, Intune, advanced security", price: 26.40, perSeat: true },
  { id: "egnyte", name: "Egnyte Cloud File Server", desc: "Secure cloud file sharing with hybrid sync, granular access controls, and included rsync.net offsite backup", price: 11.00, perSeat: true, perGB: 0.20, perGBAfter1TB: 0.12 },
  { id: "s1-complete", name: "SentinelOne Complete", desc: "Endpoint detection & response, ransomware rollback, threat hunting", price: 12.00, perSeat: true },
  { id: "ninja-365bu", name: "NinjaOne M365 Backup", desc: "Daily backups of Exchange, OneDrive, SharePoint, and Teams", price: 4.00, perSeat: true },
  { id: "barracuda-archive", name: "Barracuda Email Archiving", desc: "Tamper-proof email retention with eDiscovery and compliance search", price: 4.00, perSeat: true },
  { id: "teams-phone", name: "Microsoft Teams Phone System", desc: "Cloud-based business phone with unlimited domestic dialing", price: 24.00, perSeat: true, licenses: true },
  { id: "keeper", name: "Keeper Security Password Manager", desc: "Zero-knowledge password vault, secure sharing, and dark-web monitoring", price: 5.00, perSeat: true, licenses: true, unit: "seat" },
  { id: "tmobile", name: "T-Mobile Cell Phone Service", desc: "Business cellular line with unlimited talk, text, and data", price: 25.00, perSeat: true, licenses: true },
  { id: "tmobile-hotspot", name: "T-Mobile Mobile Hotspot", desc: "Always-on 5G data line — 5G modem hardware included", price: 30.00, perSeat: true, licenses: true },
  { id: "codetwo", name: "CodeTwo Email Signature Management", desc: "Centralized, brand-consistent email signatures across every device and client", price: 1.50, perSeat: true },
  { id: "activtrak", name: "ActivTrak Employee Monitoring", desc: "Workforce analytics with productivity reports and the Screen Details add-on for periodic screenshot capture", price: 45.00, perSeat: true, licenses: true, unit: "seat" },
  { id: "claude-ai", name: "Custom AI Integration", desc: "Powered by Claude.ai, delivered inside Microsoft Teams — purpose-built assistants for your team's workflows", price: 15.00, perSeat: true, estimated: true },
];

const FAQS = [
  {
    q: "What's actually included?",
    a: "Every engagement — regardless of headcount — includes the same all-inclusive service catalog: helpdesk, devices, cybersecurity, AI integration, Microsoft 365, network, vendor management, backup and business continuity, onboarding, and compliance support. There are no upsells or feature gates by tier.",
  },
  {
    q: "Why does the per-head price go down with more people?",
    a: "Because the work-per-head goes down too. Larger teams share infrastructure, get more value from automation, and let our engineers spend less time on repetitive setup. We pass that efficiency back to you with marginal bracket pricing — the first 10 heads are $175, the next 15 are $165, and the next 25 are $155.",
  },
  {
    q: "What does \"per head\" actually mean?",
    a: "A head is anyone with access into your company systems — W-2 employees, 1099 contractors, and hired consultants alike. Phones, laptops, and workstations for the same person count as one head. We don't charge separately for servers, network gear, or SaaS apps — those are included.",
  },
  {
    q: "Is everything month-to-month?",
    a: "Yes. No annual contracts, no exit fees, no auto-renewal traps. If we ever stop being worth the bill, you can leave with thirty days' notice. We've kept 96% of clients past year three anyway — turns out making it easy to leave makes people want to stay. One note on pricing: your managed-services rate per seat is fixed for the calendar year — seat count can rise or fall month-to-month, but the price per seat doesn't change. Third-party subscription costs (Microsoft 365, SentinelOne, Datto, and the like) are passed through and can change when the vendor changes their pricing — we'll let you know in advance when they do.",
  },
  {
    q: "What about equipment & license costs?",
    a: "Any software we prescribe is provided to you at or below MSRP. We're manufacturer agnostic on hardware — happy to work with whatever fits the job — and our vendor relationships often let us secure discounts on your behalf.",
  },
  {
    q: "What if our headcount grows or shrinks mid-month?",
    a: "Headcount changes aren't prorated. We count seats on the last day of each month, and that count drives the next invoice — so anyone added or removed during the month is reflected on the following bill, not the current one.",
  },
];

const Pricing = ({ go }) => {
  const [heads, setHeads] = React.useState(15);
  const [open, setOpen] = React.useState(0);
  const [selectedSoftware, setSelectedSoftware] = React.useState({ "m365-bp": true });
  const [egnyteGB, setEgnyteGB] = React.useState(100);
  const [lineCounts, setLineCounts] = React.useState({
    "teams-phone": 10,
    "keeper": 10,
    "tmobile": 10,
    "tmobile-hotspot": 2,
    "activtrak": 5,
  });
  const enterprise = heads > 50;
  const { total, lines } = computeBreakdown(Math.min(heads, 50));
  const effectiveRate = heads > 0 ? Math.round(total / Math.min(heads, 50)) : 0;
  const annual = total * 12;

  const fmt = (n) => `$${n.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
  const fmtStorage = (gb) => {
    if (gb >= 1000) {
      const tb = gb / 1024;
      return `${tb % 1 === 0 ? tb.toFixed(0) : tb.toFixed(1)} TB`;
    }
    return `${gb} GB`;
  };

  const toggleSoftware = (id) => setSelectedSoftware((s) => ({ ...s, [id]: !s[id] }));

  // Egnyte tiered storage cost: first 1024 GB at $0.20/GB, then $0.12/GB
  const storageCostFor = (item, gb) => {
    if (!item.perGB) return 0;
    if (!item.perGBAfter1TB || gb <= 1024) {
      return gb * item.perGB;
    }
    return 1024 * item.perGB + (gb - 1024) * item.perGBAfter1TB;
  };

  const lineTotalFor = (item) => {
    let t = 0;
    if (item.perSeat) {
      const qty = item.licenses ? (lineCounts[item.id] || 0) : heads;
      t += item.price * qty;
    }
    if (item.perGB) t += storageCostFor(item, egnyteGB);
    return t;
  };

  const softwareTotal = SOFTWARE_CATALOG.reduce((sum, item) => {
    if (!selectedSoftware[item.id]) return sum;
    return sum + lineTotalFor(item);
  }, 0);
  const grandTotal = (enterprise ? 0 : total) + softwareTotal;

  return (
    <main className="page-fade">
      <section className="page-head">
        <div className="shell">
          <span className="eyebrow">Pricing</span>
          <h1>Simple &amp; Transparent.<br/>All-inclusive.</h1>
          <p>
            One service catalog, one slider, one number. Drag to your team's
            size and see exactly what you'd pay each month. Price-locked for
            one year.
          </p>
        </div>
      </section>

      <section className="tight">
        <div className="shell">
          <div className="estimator">
            {/* LEFT: slider + breakdown */}
            <div className="est-left">
              <div className="est-header">
                <span className="eyebrow">Your team</span>
                <h2>{enterprise ? "50+ people" : `${heads} ${heads === 1 ? "person" : "people"}`}</h2>
                <p>Drag the dial to your team's size.</p>
              </div>

              <div className="slider-wrap">
                <input
                  type="range"
                  min="5"
                  max="100"
                  step="1"
                  value={heads}
                  onChange={(e) => setHeads(parseInt(e.target.value, 10))}
                  className="slider"
                  style={{
                    background: `linear-gradient(to right, var(--gold) 0%, var(--gold) ${((heads - 5) / 95) * 100}%, var(--surface-2) ${((heads - 5) / 95) * 100}%, var(--surface-2) 100%)`,
                  }}
                />
                <div className="slider-ticks">
                  <span>5</span>
                  <span>25</span>
                  <span>50</span>
                  <span>75</span>
                  <span>100+</span>
                </div>
              </div>

              {/* Bracket breakdown */}
              <div className="brackets">
                <div className="brackets-head">
                  <span className="eyebrow">Bracket math</span>
                </div>
                <div className="bracket-rows">
                  <div className={`bracket-row ${heads >= 1 ? "on" : ""}`}>
                    <span className="b-range">Heads 1–10</span>
                    <span className="b-rate">$175 / head</span>
                    <span className="b-people">{Math.min(heads, 10)} {Math.min(heads, 10) === 1 ? "person" : "people"}</span>
                    <span className="b-sub">{fmt(Math.min(heads, 10) * 175)}</span>
                  </div>
                  <div className={`bracket-row ${heads > 10 ? "on" : ""}`}>
                    <span className="b-range">Heads 11–25</span>
                    <span className="b-rate">$165 / head</span>
                    <span className="b-people">{Math.max(0, Math.min(heads, 25) - 10)} people</span>
                    <span className="b-sub">{fmt(Math.max(0, Math.min(heads, 25) - 10) * 165)}</span>
                  </div>
                  <div className={`bracket-row ${heads > 25 ? "on" : ""}`}>
                    <span className="b-range">Heads 26–50</span>
                    <span className="b-rate">$155 / head</span>
                    <span className="b-people">{Math.max(0, Math.min(heads, 50) - 25)} people</span>
                    <span className="b-sub">{fmt(Math.max(0, Math.min(heads, 50) - 25) * 155)}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* RIGHT: total card */}
            <div className="est-right">
              {!enterprise ? (
                <React.Fragment>
                  <span className="eyebrow">Your estimate</span>
                  <div className="est-total">{fmt(total)}</div>
                  <div className="est-unit">per month, all-inclusive</div>
                  <div className="est-meta">
                    <div>
                      <span className="lbl">Effective rate</span>
                      <span className="val">${effectiveRate}<span style={{ fontSize: 13, color: "var(--ivory-mute)" }}> / head</span></span>
                    </div>
                    <div>
                      <span className="lbl">Annualized</span>
                      <span className="val">{fmt(annual)}</span>
                    </div>
                  </div>
                  <div className="est-actions">
                    <button className="btn btn-primary" onClick={() => go("contact")}>
                      Get this quote in writing <Arrow />
                    </button>
                  </div>
                  <p className="est-note">
                    Estimate covers everything in the all-inclusive catalog.
                    No setup or onboarding fees.
                  </p>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <span className="eyebrow">Enterprise</span>
                  <div className="est-total" style={{ fontSize: 56 }}>Let's talk.</div>
                  <p className="est-note" style={{ marginTop: 24, fontSize: 16, color: "var(--ivory-soft)" }}>
                    For teams of 50+, we structure custom enterprise packages
                    with dedicated principals, custom SLAs, and quarterly business
                    reviews. Same all-inclusive services, pricing tailored to
                    your stack and footprint.
                  </p>
                  <div className="est-actions" style={{ marginTop: 32 }}>
                    <button className="btn btn-primary" onClick={() => go("contact")}>
                      Get a custom quote <Arrow />
                    </button>
                  </div>
                </React.Fragment>
              )}
            </div>
          </div>

          {/* SOFTWARE & LICENSING */}
          <div className="software-section">
            <div className="software-head">
              <div>
                <span className="eyebrow">Software & licensing</span>
                <h2>Sold <em>separately</em>.</h2>
              </div>
              <p>
                These recommended services are provided and fully managed
                by us. Toggle what you'd like included and the total updates
                against the same {heads}-person team above.
              </p>
            </div>

            <div className="software-list">
              {SOFTWARE_CATALOG.map((item) => {
                const lineTotal = lineTotalFor(item);
                const isOn = !!selectedSoftware[item.id];
                return (
                  <React.Fragment key={item.id}>
                    <div
                      className={`software-row ${isOn ? "on" : ""}`}
                      onClick={() => toggleSoftware(item.id)}
                    >
                      <div className="sw-toggle">
                        <span className={`sw-check ${isOn ? "on" : ""}`}>
                          {isOn ? "✓" : ""}
                        </span>
                      </div>
                      <div className="sw-info">
                        <div className="sw-name">{item.name}</div>
                        <div className="sw-desc">{item.desc}</div>
                      </div>
                      <div className="sw-rate">
                        {fmt(item.price)}<span className="sw-unit"> / {item.unit || (item.licenses ? "line" : (item.perSeat ? "seat" : "month"))}</span>
                        {item.estimated && (
                          <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--gold)", marginTop: 4 }}>
                            Estimated
                          </div>
                        )}
                        {item.perGB && (
                          <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ivory-mute)", marginTop: 4 }}>
                            + ${item.perGB.toFixed(2)} / GB
                            {item.perGBAfter1TB && (
                              <div style={{ marginTop: 2 }}>${item.perGBAfter1TB.toFixed(2)} / GB after 1 TB</div>
                            )}
                          </div>
                        )}
                      </div>
                      <div className="sw-line-total">
                        {isOn ? fmt(lineTotal) : <span style={{ color: "var(--ivory-mute)" }}>—</span>}
                      </div>
                    </div>
                    {item.perGB && isOn && (
                      <div className="software-addon" onClick={(e) => e.stopPropagation()}>
                        <div className="addon-label">
                          <span className="eyebrow">Storage</span>
                          <span className="addon-val">{fmtStorage(egnyteGB)}</span>
                        </div>
                        <input
                          type="range"
                          min="10"
                          max="10240"
                          step="10"
                          value={egnyteGB}
                          onChange={(e) => setEgnyteGB(parseInt(e.target.value, 10))}
                          className="slider addon-slider"
                          style={{
                            background: `linear-gradient(to right, var(--gold) 0%, var(--gold) ${((egnyteGB - 10) / 10230) * 100}%, var(--surface-2) ${((egnyteGB - 10) / 10230) * 100}%, var(--surface-2) 100%)`,
                          }}
                        />
                        <div className="addon-ticks">
                          <span>10 GB</span>
                          <span>5 TB</span>
                          <span>10 TB</span>
                        </div>
                        <div className="addon-breakdown">
                          <span>{heads} seats × ${item.price.toFixed(2)} = {fmt(item.price * heads)}</span>
                          {egnyteGB <= 1024 ? (
                            <span>{fmtStorage(egnyteGB)} × ${item.perGB.toFixed(2)}/GB = {fmt(storageCostFor(item, egnyteGB))}</span>
                          ) : (
                            <span>
                              1 TB × ${item.perGB.toFixed(2)} + {fmtStorage(egnyteGB - 1024)} × ${item.perGBAfter1TB.toFixed(2)} = {fmt(storageCostFor(item, egnyteGB))}
                            </span>
                          )}
                        </div>
                      </div>
                    )}
                    {item.estimated && isOn && (
                      <div className="software-addon" onClick={(e) => e.stopPropagation()} style={{ paddingTop: 14, paddingBottom: 14 }}>
                        <div style={{ fontSize: 13, color: "var(--ivory-soft)", lineHeight: 1.55 }}>
                          <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--gold)", marginRight: 8 }}>Note</span>
                          This is an <em>estimated</em> per-seat cost. Actual fees are
                          based on total token usage and billed monthly in arrears.
                          We'll review the projection with you before activation.
                        </div>
                      </div>
                    )}
                    {item.licenses && isOn && (
                      <div className="software-addon" onClick={(e) => e.stopPropagation()}>
                        <div className="addon-label">
                          <span className="eyebrow">{(item.unitPlural || (item.unit ? item.unit + "s" : "Lines"))}</span>
                          <span className="addon-val">{lineCounts[item.id] || 0}</span>
                        </div>
                        <input
                          type="range"
                          min="1"
                          max="100"
                          step="1"
                          value={lineCounts[item.id] || 0}
                          onChange={(e) => setLineCounts({ ...lineCounts, [item.id]: parseInt(e.target.value, 10) })}
                          className="slider addon-slider"
                          style={{
                            background: `linear-gradient(to right, var(--gold) 0%, var(--gold) ${(((lineCounts[item.id] || 1) - 1) / 99) * 100}%, var(--surface-2) ${(((lineCounts[item.id] || 1) - 1) / 99) * 100}%, var(--surface-2) 100%)`,
                          }}
                        />
                        <div className="addon-ticks">
                          <span>1</span>
                          <span>50</span>
                          <span>100</span>
                        </div>
                        <div className="addon-breakdown">
                          <span>{lineCounts[item.id] || 0} {(item.unitPlural || (item.unit ? item.unit + "s" : "lines")).toLowerCase()} × ${item.price.toFixed(2)} = {fmt(item.price * (lineCounts[item.id] || 0))}</span>
                        </div>
                      </div>
                    )}
                  </React.Fragment>
                );
              })}
            </div>

            <div className="software-totals">
              <div className="sw-tot-row">
                <span>Software subtotal</span>
                <span className="amt">{fmt(softwareTotal)}</span>
              </div>
              {!enterprise && (
                <div className="sw-tot-row">
                  <span>Managed services</span>
                  <span className="amt">{fmt(total)}</span>
                </div>
              )}
              {!enterprise ? (
                <div className="sw-tot-row grand">
                  <span>Estimated monthly total</span>
                  <span className="amt">{fmt(grandTotal)}</span>
                </div>
              ) : (
                <div className="sw-tot-row grand">
                  <span>Plus enterprise MSA quote</span>
                  <span className="amt" style={{ fontSize: 24 }}>To be scoped</span>
                </div>
              )}
            </div>
          </div>

          {/* WHAT'S INCLUDED */}
          <div className="includes-card">
            <div className="includes-head">
              <span className="eyebrow">Every package, every team size</span>
              <h3>What's <em>included</em>.</h3>
            </div>
            <ul className="includes-list">
              {ALL_INCLUSIVE_FEATURES.map((f) => (
                <li key={f}>{f}</li>
              ))}
            </ul>
          </div>
        </div>
      </section>

      {/* What's NOT extra */}
      <section style={{ borderTop: "1px solid var(--edge)" }}>
        <div className="shell">
          <div className="section-header">
            <div>
              <span className="eyebrow">Never billed separately</span>
              <h2 style={{ marginTop: 20 }}>What never costs <em>extra</em>.</h2>
            </div>
            <p className="lead">
              The line items other MSPs nickel-and-dime — onboarding fees,
              project hours, after-hours surcharges — are baked in. No
              surprises on the invoice.
            </p>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }}>
            {[
              "Onboarding (the full 90-day handover)",
              "New-hire orientation for every employee",
              "Same-day new-hire provisioning",
              "Quarterly business reviews",
              "Incident response",
              "Annual cyber security awareness training",
              "Annual disaster-recovery tabletop",
              "Vendor renewal negotiation",
            ].map((i) => (
              <div key={i} style={{ display: "flex", gap: 12, padding: 20, background: "var(--surface)", borderRadius: 10, border: "1px solid var(--edge)" }}>
                <span style={{ color: "var(--gold)", fontFamily: "var(--mono)" }}>✓</span>
                <span style={{ fontSize: 15 }}>{i}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section>
        <div className="shell">
          <div className="pricing-faq">
            <div>
              <span className="eyebrow">Common questions</span>
              <h2 style={{ marginTop: 20 }}>Pricing <em>FAQ</em>.</h2>
              <p style={{ marginTop: 20, color: "var(--ivory-soft)" }}>
                Don't see what you're looking for? Send us a note and we'll
                answer plainly.
              </p>
            </div>
            <div>
              {FAQS.map((f, i) => (
                <div
                  key={i}
                  className={`faq-item ${open === i ? "open" : ""}`}
                  onClick={() => setOpen(open === i ? -1 : i)}
                >
                  <div className="faq-q">
                    <span>{f.q}</span>
                    <span className="faq-toggle">+</span>
                  </div>
                  <div className="faq-a">{f.a}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      <CtaStrip go={go} />
    </main>
  );
};

window.Pricing = Pricing;
