// WipeAway for Business — page-specific sections.
// Reuses shared components from sections.jsx / howitworks.jsx / pricing.jsx
// (all on window). Adds business styles + 12 sections + BusinessApp + render.

const { Reveal, Eyebrow, SectionHead, CalendarViz, HeroCarousel, HowItWorks, FinalCTA, Footer, Pricing, BuyModal, PayRow, KeyModal } = window;

// ─────────────────────────────────────────────────────────────────────────
//  CALENDLY — paste your scheduling link here. Until it's set (still contains
//  REPLACE-ME), "Book a demo" captures the form then shows a "we'll be in touch"
//  confirmation; once set, it shows the inline Calendly scheduler in-modal.
const CALENDLY_URL = 'https://calendly.com/REPLACE-ME/demo';
// ─────────────────────────────────────────────────────────────────────────
//  SMALL TEAM CHECKOUT — paste the Stripe Payment Link for the $99 "Small Team"
//  product here. The "Buy Now" button links straight to it (fully self-serve,
//  no form/call before payment). Until set, it points at this placeholder.
const SMALL_TEAM_CHECKOUT_URL = 'https://buy.stripe.com/eVq7sLcQa49PgThdYHgbm04';
// ─────────────────────────────────────────────────────────────────────────
//  ORGANISATION CHECKOUT — paste the Stripe Payment Link for the $500
//  "Organisation" product here. The "Buy Now" button links straight to it
//  (self-serve, no qualify form before payment). In the Stripe Dashboard, set
//  this Payment Link's success/redirect URL to  …/welcome-organisation.html
//  so customers land on the project-intake page after paying.
const ORGANISATION_CHECKOUT_URL = 'https://buy.stripe.com/8x200jeYi6hX7iH4o7gbm03';
// ─────────────────────────────────────────────────────────────────────────

// Business-relevant calendar names — overrides the individual defaults in howitworks.jsx
// (window-scoped so the individual homepage keeps Personal/Work/etc.).
window.WA_CAL_NAMES = ['Meeting Rooms', 'Staff Leave', 'Team Events', 'Client Bookings'];

// Brand wordmark, styled to match the top-of-page logo (Gabarito, "Away" in accent).
function WA() { return <span className="wa-brand">Wipe<span className="aw">Away</span></span>; }

// Hero carousel with business calendar names (?biz swaps the names in the iframe).
function fitHeroCar(wrap, ifr) {
  if (!wrap || !ifr) return;
  const DW = 672, DH = 461;
  const fit = () => {
    if (window.matchMedia('(max-width:1024px)').matches) {
      const w = wrap.clientWidth || DW;
      const s = w / DW;
      Object.assign(ifr.style, { position: 'absolute', top: '0', left: '0', width: DW + 'px', height: DH + 'px', transformOrigin: 'top left', transform: 'scale(' + s + ')' });
      wrap.style.height = Math.round(DH * s) + 'px';
    } else {
      Object.assign(ifr.style, { position: '', top: '', left: '', width: '', height: '', transform: '' });
      wrap.style.height = '';
    }
  };
  fit();
  let ro;
  if (window.ResizeObserver) { ro = new ResizeObserver(fit); ro.observe(wrap); }
  window.addEventListener('resize', fit);
  return () => { if (ro) ro.disconnect(); window.removeEventListener('resize', fit); };
}

function BizHeroCarousel() {
  const wrapRef = React.useRef(null);
  const ifrRef = React.useRef(null);
  React.useEffect(() => fitHeroCar(wrapRef.current, ifrRef.current), []);
  return (
    <div className="hero-car" ref={wrapRef}>
      <iframe
        ref={ifrRef}
        src="WipeAway%20Carousel.html?embed&biz"
        title="WipeAway demo"
        scrolling="no"
        loading="lazy">
      </iframe>
    </div>);
}

(function () {
  if (document.getElementById('wa-biz-styles')) return;
  const s = document.createElement('style');
  s.id = 'wa-biz-styles';
  s.textContent = `
  /* ---------- business hero ---------- */
  .biz-hero{position:relative;overflow:hidden;padding:64px 0 92px;}
  .biz-hero-grid{display:grid;grid-template-columns:1.04fr 1.06fr;gap:56px;align-items:center;}
  .biz-hero h1{font-size:clamp(38px,5.4vw,68px);font-weight:800;margin-top:22px;line-height:1.0;}
  .biz-hero .lede{font-size:clamp(16px,1.45vw,19.5px);color:var(--muted);max-width:540px;margin-top:22px;line-height:1.55;}
  .biz-hero-cta{display:flex;gap:14px;margin-top:34px;flex-wrap:wrap;}
  .biz-trust{margin-top:30px;display:flex;flex-direction:column;gap:14px;}
  .biz-trust .lbl{font-size:13.5px;color:var(--muted);max-width:480px;line-height:1.5;}
  .biz-trust .roles{display:flex;flex-wrap:wrap;gap:9px;}
  .biz-role{display:inline-flex;align-items:center;gap:8px;font-size:12.5px;font-weight:600;color:var(--text);
    background:var(--surface-2);border:1px solid var(--border);border-radius:999px;padding:8px 14px;line-height:1;}
  .biz-role i{color:var(--pink);font-size:15px;}

  /* inline brand wordmark */
  .wa-brand{font-family:'Gabarito',sans-serif;font-weight:700;letter-spacing:-.012em;}
  .wa-brand .aw{color:var(--pink);font-weight:500;}

  /* demo modal → calendly scheduling step */
  .modal.modal-wide{max-width:560px;max-height:92vh;overflow:auto;}
  .cal-inline{min-width:300px;height:min(640px,70vh);border-radius:12px;overflow:hidden;}
  /* lead-form modals can get tall — allow them to scroll within the viewport */
  .modal{max-height:92vh;overflow:auto;}
  .field select{width:100%;background:var(--surface-2);border:1px solid var(--border);border-radius:11px;padding:12px 14px;color:var(--text);font-family:inherit;font-size:15px;color-scheme:dark;}
  .field select:focus{outline:none;border-color:var(--pink);}
  /* grouped section headers inside long lead forms */
  .fgroup{font-family:'JetBrains Mono';font-size:11px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:var(--pink);margin:24px 0 13px;padding-bottom:8px;border-bottom:1px solid var(--border);}
  .fgroup:first-of-type{margin-top:20px;}
  .field .hint{font-size:12px;color:var(--muted);margin-top:5px;line-height:1.4;}
  .frow{display:grid;grid-template-columns:1fr 1fr;gap:0 14px;}
  @media(max-width:520px){.frow{grid-template-columns:1fr;}}
  .ok-list{text-align:left;max-width:340px;margin:20px auto 0;display:flex;flex-direction:column;gap:11px;padding:0;}
  .ok-list li{display:flex;gap:10px;align-items:flex-start;font-size:14px;color:var(--muted);list-style:none;}
  .ok-list li i{color:#2d8cff;font-size:16px;flex-shrink:0;margin-top:1px;}

  /* ---------- generic 3-col icon grid ---------- */
  .biz-cols{display:grid;grid-template-columns:repeat(3,1fr);gap:22px;margin-top:54px;}
  .biz-col{background:var(--surface);border:1px solid var(--border-soft);border-radius:var(--radius);padding:28px;}
  .lt .biz-col{background:var(--lt-surface);border-color:var(--lt-border);}
  .biz-col .ico{width:50px;height:50px;border-radius:14px;display:grid;place-items:center;color:var(--pink);
    background:linear-gradient(135deg,rgba(45,140,255,.15),rgba(29,78,216,.13));border:1px solid rgba(45,140,255,.22);margin-bottom:18px;}
  .biz-col .ico i{font-size:25px;}
  .biz-col h3{font-size:20px;color:var(--text);margin-bottom:9px;letter-spacing:-.01em;}
  .lt .biz-col h3{color:var(--lt-text);}
  .biz-col p{color:var(--muted);font-size:14.5px;line-height:1.55;}
  .lt .biz-col p{color:var(--lt-muted);}

  /* ---------- solution split ---------- */
  .biz-split{display:grid;grid-template-columns:1.05fr .95fr;gap:54px;align-items:center;margin-top:54px;}
  .biz-split .copy h2{font-size:clamp(28px,3.6vw,42px);margin:18px 0 0;}
  .biz-split .copy p{color:var(--muted);font-size:17px;line-height:1.55;margin-top:18px;max-width:520px;}
  .biz-split .viz{display:flex;justify-content:center;}

  /* ---------- who it's for: two tiers ---------- */
  .tier-label{display:flex;align-items:center;gap:14px;margin:52px 0 22px;}
  .tier-label .t{font-family:'Gabarito';font-weight:800;font-size:19px;color:var(--lt-text);letter-spacing:-.01em;white-space:nowrap;}
  .tier-label .t.muted2{font-size:13px;font-family:'JetBrains Mono';font-weight:600;letter-spacing:.12em;text-transform:uppercase;color:var(--dim);}
  .tier-label .ln{flex:1;height:1px;background:var(--lt-border);}
  .who-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;}
  .who-card{background:var(--lt-surface);border:1px solid var(--lt-border);border-radius:var(--radius);padding:28px;transition:transform .18s,box-shadow .22s,border-color .18s;}
  .who-card:hover{transform:translateY(-3px);box-shadow:0 18px 44px -24px rgba(0,0,0,.6);border-color:rgba(45,140,255,.35);}
  .who-card .ico{width:52px;height:52px;border-radius:14px;display:grid;place-items:center;color:#fff;
    background:var(--grad-primary);box-shadow:var(--glow-pink);margin-bottom:18px;}
  .who-card .ico i{font-size:26px;}
  .who-card h3{font-size:20px;color:var(--lt-text);margin-bottom:9px;letter-spacing:-.01em;}
  .who-card p{color:var(--lt-muted);font-size:14.5px;line-height:1.55;}
  .who-grid.sec .who-card{padding:22px;}
  .who-grid.sec .who-card .ico{width:44px;height:44px;border-radius:12px;background:var(--lt-surface);
    border:1px solid var(--lt-border);color:var(--pink);box-shadow:none;margin-bottom:15px;}
  .who-grid.sec .who-card .ico i{font-size:22px;}
  .who-grid.sec .who-card h3{font-size:17.5px;}
  .who-grid.sec .who-card p{font-size:13.5px;}

  /* ---------- checklist ---------- */
  .check-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px 40px;margin-top:48px;max-width:760px;margin-left:auto;margin-right:auto;}
  .check-item{display:flex;align-items:center;gap:14px;padding:15px 0;border-bottom:1px solid var(--lt-border);}
  .check-item .ck{width:26px;height:26px;border-radius:8px;flex-shrink:0;display:grid;place-items:center;color:#fff;
    background:var(--grad-primary);box-shadow:var(--glow-pink);}
  .check-item .ck i{font-size:16px;}
  .check-item span{font-size:16px;color:var(--lt-text);font-weight:600;letter-spacing:-.005em;}
  .check-foot{color:var(--lt-muted);font-size:15px;margin-top:26px;max-width:680px;line-height:1.55;margin-left:auto;margin-right:auto;text-align:center;}

  /* why-teams: larger, conversational checklist */
  .why-list{display:flex;flex-direction:column;gap:4px;margin-top:44px;max-width:680px;margin-left:auto;margin-right:auto;}
  .why-item{display:flex;align-items:center;gap:16px;padding:17px 0;border-bottom:1px solid var(--lt-border);}
  .why-item .ck{width:30px;height:30px;border-radius:9px;flex-shrink:0;display:grid;place-items:center;color:var(--pink);
    background:rgba(45,140,255,.13);border:1px solid rgba(45,140,255,.26);}
  .why-item .ck i{font-size:18px;}
  .why-item span{font-size:19px;color:var(--lt-text);font-weight:600;letter-spacing:-.01em;}
  .why-foot{color:var(--lt-muted);font-size:17px;margin-top:28px;max-width:640px;line-height:1.55;margin-left:auto;margin-right:auto;text-align:center;}

  /* ---------- scale stats ---------- */
  .scale-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:26px;margin-top:54px;}
  .scale-stat{text-align:center;background:var(--surface);border:1px solid var(--border-soft);border-radius:var(--radius);padding:38px 24px;}
  .scale-stat .v{font-family:'Gabarito';font-weight:800;font-size:clamp(40px,5vw,60px);line-height:1;}
  .scale-stat .k{color:var(--muted);font-size:15px;margin-top:14px;line-height:1.4;}
  .scale-foot{text-align:center;color:var(--muted);font-size:14.5px;margin-top:30px;max-width:620px;margin-left:auto;margin-right:auto;line-height:1.55;}

  /* ---------- example cleanups ---------- */
  .ex-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;margin-top:54px;}
  .ex-card{background:var(--lt-surface);border:1px solid var(--lt-border);border-radius:var(--radius);padding:28px;}
  .ex-card .ico{width:48px;height:48px;border-radius:13px;display:grid;place-items:center;color:var(--pink);
    background:linear-gradient(135deg,rgba(45,140,255,.14),rgba(29,78,216,.13));border:1px solid rgba(45,140,255,.22);margin-bottom:18px;}
  .ex-card .ico i{font-size:24px;}
  .ex-card h3{font-size:19px;color:var(--lt-text);margin-bottom:10px;letter-spacing:-.01em;}
  .ex-card p{color:var(--lt-muted);font-size:14.5px;line-height:1.6;}
  .ex-foot{color:var(--dim);font-size:13px;margin-top:24px;font-style:italic;}

  /* ---------- business pricing (4-tier) ---------- */
  .bizp-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-top:54px;align-items:stretch;}
  .bizp-card{position:relative;background:var(--lt-surface);border:1px solid var(--lt-border);border-radius:22px;padding:28px 24px;display:flex;flex-direction:column;}
  .bizp-card.team{border:1.5px solid var(--pink);box-shadow:var(--glow-pink),0 30px 80px -34px rgba(45,140,255,.4);}
  .bizp-card.tone-blue-strong{background:rgba(45,140,255,.07);border:1.5px solid var(--pink);box-shadow:var(--glow-pink),0 30px 80px -34px rgba(45,140,255,.4);}
  .bizp-card.tone-blue{background:rgba(45,140,255,.07);border-color:rgba(45,140,255,.34);}
  .bizp-card.tone-green{background:rgba(52,211,153,.07);border-color:rgba(52,211,153,.34);}
  .bizp-tag{position:absolute;top:-11px;left:24px;font-family:'JetBrains Mono';font-size:10px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#fff;background:var(--grad-primary);border-radius:99px;padding:5px 12px;box-shadow:var(--glow-pink);}
  .bizp-tag.green{background:linear-gradient(135deg,#34d399,#10b981);box-shadow:0 12px 30px -10px rgba(52,211,153,.5);}
  .bizp-name{font-family:'Gabarito';font-weight:800;font-size:20px;color:var(--lt-text);}
  .bizp-pricebox{min-height:74px;display:flex;flex-direction:column;justify-content:flex-end;margin-top:16px;}
  .bizp-from{font-size:12.5px;color:var(--lt-muted);font-weight:600;margin-bottom:3px;}
  .bizp-price{font-family:'Gabarito';font-weight:900;font-size:38px;color:var(--lt-text);line-height:1;}
  .bizp-price.sm{font-size:26px;font-weight:800;}
  .bizp-price .per{font-size:14px;font-weight:600;color:var(--lt-muted);font-family:'Hanken Grotesk';}
  .bizp-alt{font-size:13px;color:var(--lt-muted);min-height:18px;margin:6px 0 0;}
  .bizp-desc{color:var(--lt-muted);font-size:13.5px;line-height:1.5;margin:16px 0 18px;min-height:84px;}
  .bizp-list{list-style:none;padding:0;margin:0 0 22px;}
  .bizp-list li{display:flex;gap:10px;align-items:flex-start;font-size:13.5px;color:var(--lt-text);padding:6px 0;}
  .bizp-list .ck{width:20px;height:20px;border-radius:6px;background:rgba(45,140,255,.16);color:var(--pink);display:grid;place-items:center;flex-shrink:0;margin-top:1px;}
  .bizp-list .ck i{font-size:13px;}
  .bizp-btn{width:100%;margin-top:auto;}
  .bizp-secondary-block{margin-top:auto;display:flex;flex-direction:column;gap:7px;}
  .bizp-secondary-block.bizp-placeholder{visibility:hidden;}
  .bizp-primary-block{display:flex;flex-direction:column;gap:7px;margin-top:14px;}
  .bizp-sub{font-size:11.5px;line-height:1.4;color:var(--lt-muted);text-align:center;margin:0;min-height:15.5px;}
  .bizp-sub .pay-row{margin:0;padding:0;border:none;display:inline-flex;align-items:center;gap:9px;transform:scale(.62);transform-origin:center;vertical-align:middle;}
  .bizp-sub .pay-marks{gap:9px;}
  .bizp-sub .pm{height:14px;}
  .bizp-btn-stacked{flex-direction:column;gap:1px;padding:11px 18px;line-height:1.3;}
  .bizp-btn-main{font-size:16px;font-weight:700;display:flex;align-items:center;gap:7px;white-space:nowrap;}
  .bizp-btn-sub{font-size:9.5px;font-weight:500;opacity:.85;white-space:nowrap;text-align:center;}
  .bizp-foot{grid-column:3 / 5;align-self:start;text-align:center;color:var(--lt-muted);font-size:13.5px;margin-top:22px;line-height:1.55;}

  @media(max-width:1040px){
    .biz-hero-grid{grid-template-columns:1fr;gap:40px;}
    .nav-links{display:none;}
    .bizp-grid{grid-template-columns:1fr 1fr;gap:18px;}
    .bizp-foot{grid-column:1 / 3;}
  }
  @media(max-width:900px){
    .biz-cols,.who-grid,.who-grid.sec,.scale-grid,.ex-grid,.biz-split{grid-template-columns:1fr;gap:18px;}
    .biz-split{gap:34px;}
    .check-grid{grid-template-columns:1fr;}
  }
  @media(max-width:560px){
    .bizp-grid{grid-template-columns:1fr;}
    .bizp-foot{grid-column:auto;}
  }

  /* hero carousel wrapper — JS-scaled to fit portrait on mobile */
  .hero-car{width:100%;max-width:680px;}
  .hero-car iframe{width:100%;height:474px;border:none;display:block;background:transparent;}
  .hero-art-m{margin-top:26px;}
  @media(max-width:1024px){
    .hero-car{position:relative;overflow:hidden;width:100%;max-width:440px;margin:0 auto;border-radius:16px;}
    .biz-hero{padding:34px 0 52px;}
  }
  @media(max-width:900px){
    .biz-split{margin-top:0;}
  }
  `;
  document.head.appendChild(s);
})();

// ---------- BUSINESS NAV ----------
function BizNav({ onDemo, onKey }) {
  const [menu, setMenu] = React.useState(false);
  const jump = (id) => (e) => {
    e.preventDefault();
    setMenu(false);
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 60, behavior: 'smooth' });
  };
  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <a className="logo" href="/for-business.html">
          <span className="mark"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M8 2v4M16 2v4M3 10h18M21 6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6z" /></svg></span>
          <span className="logo-lock"><span className="logo-name">Wipe<span className="brand-away">Away</span></span><span className="logo-sub">for Business</span></span>
        </a>
        <div className="nav-links">
          <a href="#problem">The problem</a>
          <a href="#how">How it works</a>
          <a href="#whofor">Who it's for</a>
          <a href="#pricing">Pricing</a>
        </div>
        <div className="nav-right">
          <a className="nav-cross" href="/"><i className="ti ti-user"></i>WipeAway Personal</a>
          <a href="#" className="nav-cust" onClick={(e) => {e.preventDefault();onKey();}}>Already a customer?</a>
          <a className="btn btn-primary btn-sm" href="#pricing">Buy Now <span className="arrow">→</span></a>
        </div>
        <button className="nav-burger" aria-label="Menu" aria-expanded={menu} onClick={() => setMenu((m) => !m)}>
          <span></span><span></span><span></span>
        </button>
      </div>
      {menu &&
        <div className="nav-sheet">
          <a href="#problem" onClick={jump('problem')}>The problem</a>
          <a href="#how" onClick={jump('how')}>How it works</a>
          <a href="#whofor" onClick={jump('whofor')}>Who it's for</a>
          <a href="#pricing" onClick={jump('pricing')}>Pricing</a>
          <a href="#faq" onClick={jump('faq')}>FAQ</a>
          <a href="#" onClick={(e) => {e.preventDefault();setMenu(false);onKey();}}>Already a customer?</a>
          <a className="nav-sheet-cross" href="/"><i className="ti ti-user"></i>WipeAway Personal</a>
        </div>}
    </nav>);
}

// ---------- SECTION 1 — HERO ----------
function BizHero({ onDemo }) {
  const isMobile = useIsMobile();
  return (
    <header className="biz-hero" id="top">
      <div className="glow" style={{ width: 640, height: 640, left: -180, top: -140, background: 'radial-gradient(circle,rgba(29,78,216,.30),transparent 70%)' }}></div>
      <div className="glow" style={{ width: 520, height: 520, right: -120, top: 30, background: 'radial-gradient(circle,rgba(45,140,255,.20),transparent 70%)' }}></div>
      <div className="wrap biz-hero-grid">
        <Reveal style={{ position: 'relative', zIndex: 2 }}>
          <Eyebrow>WipeAway for Business</Eyebrow>
          <h1>Clear thousands of calendar events. <span className="grad-text">Keep everything else.</span></h1>
          <p className="lede">Google gives you no clean way to bulk-delete old events without deleting the calendar itself — losing your sharing permissions, integrations, and history along the way. <WA /> removes the clutter and keeps the calendar exactly as it was.</p>
          {isMobile && <div className="hero-art-m"><BizHeroCarousel /></div>}
          {!isMobile &&
          <div className="biz-hero-cta">
            <a className="btn btn-primary" href="#pricing">Buy Now <span className="arrow">→</span></a>
            <a className="btn btn-ghost" href="#how">See how it works ↓</a>
          </div>}
          <div className="biz-trust">
            <div className="lbl">Trusted by admins, IT teams and operations managers to delete the thousands of ancient events haunting the shared calendar — without triggering the “who deleted the room-booking calendar?!” group chat.</div>
            <div className="roles">
              <span className="biz-role"><i className="ti ti-shield-check"></i>Privacy-first</span>
              <span className="biz-role"><i className="ti ti-lock" style={{ color: '#fbbf24' }}></i>Google OAuth verified</span>
              <span className="biz-role"><i className="ti ti-database-off"></i>No calendar data stored</span>
            </div>
          </div>
        </Reveal>
        {!isMobile &&
        <Reveal delay={120} style={{ position: 'relative', zIndex: 2, justifySelf: 'end', width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
          <BizHeroCarousel />
        </Reveal>}
      </div>
    </header>);
}

// ---------- SECTION 2 — THE PROBLEM ----------
function ProblemSection() {
  const cols = [
    ['ti-trash-x', 'Deleting the calendar deletes everything', 'Colours, sharing permissions, integrations, and booking links all disappear the moment you delete a calendar — even if you only wanted to clear old events.'],
    ['ti-clock-hour-4', 'Manual cleanup takes hours, not minutes', 'Selecting and deleting events one by one — or worse, year by year — can take an entire afternoon for a calendar with thousands of entries.'],
    ['ti-calendar-off', "Shared and resource calendars can't just be rebuilt", "Meeting room calendars, staff rotas, and departmental schedules often can't be deleted and recreated without breaking existing bookings and integrations."]];
  return (
    <section className="section" id="problem">
      <div className="wrap">
        <SectionHead eyebrow="The problem" title="Google Calendar has no real bulk-delete tool" />
        <div className="biz-cols">
          {cols.map((c, i) =>
            <Reveal className="biz-col" key={c[1]} delay={i * 70}>
              <div className="ico"><i className={'ti ' + c[0]}></i></div>
              <h3>{c[1]}</h3>
              <p>{c[2]}</p>
            </Reveal>)}
        </div>
      </div>
    </section>);
}

// ---------- SECTION 3 — THE SOLUTION ----------
function SolutionSection() {
  return (
    <section className="section" id="solution" style={{ paddingTop: 40 }}>
      <div className="wrap">
        <div className="biz-split">
          <Reveal className="copy">
            <Eyebrow>The solution</Eyebrow>
            <h2><WA /> clears the events. Your calendar stays exactly where it is.</h2>
            <p>Select any calendar, set a cut-off date if needed, and <WA /> removes the events — recurring series and all — while the calendar itself, its colour, its sharing settings, and its integrations stay completely untouched.</p>
          </Reveal>
          <Reveal className="viz" delay={120}><CalendarViz /></Reveal>
        </div>
      </div>
    </section>);
}

// ---------- SECTION 4 — WHO IT'S FOR ----------
function WhoItsFor() {
  const primary = [
    ['ti-building', 'Google Workspace Admins', 'Clean up departmental, resource, or project calendars without rebuilding sharing permissions.'],
    ['ti-school', 'Schools & Universities', 'Clear last year\'s timetables and exam schedules while keeping the calendar structure for the new term.'],
    ['ti-briefcase', 'Operations Teams', 'Reset meeting room, facilities, or rota calendars between projects without breaking integrations.']];
  const secondary = [
    ['ti-stethoscope', 'Healthcare Practices', 'Remove years of old appointment data while keeping booking calendars intact.'],
    ['ti-users-group', 'Recruitment Agencies', 'Clear thousands of old interview slots after a hiring cycle ends.'],
    ['ti-device-laptop', 'IT & Managed Service Providers', 'Run the cleanup together with your client\'s own sign-in, as part of onboarding or offboarding.'],
    ['ti-building-store', 'Retail & Hospitality', 'Reset seasonal staff rotas and shift calendars without losing the setup your team relies on.'],
    ['ti-speakerphone', 'Social Media & Marketing Teams', 'Clear completed campaign schedules, content calendars, and launch plans while keeping team access and calendar structure intact.'],
    ['ti-building-community', 'Property & Facilities Management', 'Wipe outdated viewing, inspection and maintenance schedules across managed sites.']];
  return (
    <section className="section" id="whofor" style={{ paddingTop: 40 }}>
      <div className="wrap">
        <SectionHead lt eyebrow="Built for teams with real calendar clutter" title="If any of this sounds familiar, you're in the right place" />
        <Reveal className="tier-label"><span className="t">Where <WA /> fits best</span><span className="ln"></span></Reveal>
        <div className="who-grid">
          {primary.map((c, i) =>
            <Reveal className="who-card" key={c[1]} delay={i * 70}>
              <div className="ico"><i className={'ti ' + c[0]}></i></div>
              <h3>{c[1]}</h3>
              <p>{c[2]}</p>
            </Reveal>)}
        </div>
        <Reveal className="tier-label"><span className="t muted2">Also useful for</span><span className="ln"></span></Reveal>
        <div className="who-grid sec">
          {secondary.map((c, i) =>
            <Reveal className="who-card" key={c[1]} delay={i * 70}>
              <div className="ico"><i className={'ti ' + c[0]}></i></div>
              <h3>{c[1]}</h3>
              <p>{c[2]}</p>
            </Reveal>)}
        </div>
      </div>
    </section>);
}

// ---------- SECTION 6 — WHAT STAYS UNTOUCHED ----------
function WhatStays() {
  const items = ['Calendar colour and name', 'Sharing permissions and access levels', 'Calendar subscriptions', 'Connected integrations', 'Resource booking links', 'Calendar ID and URL'];
  return (
    <section className="section" id="preserved" style={{ paddingTop: 40 }}>
      <div className="wrap">
        <SectionHead lt eyebrow="What's preserved" title="Everything except the events you choose to remove" />
        <Reveal className="check-grid">
          {items.map((x) =>
            <div className="check-item" key={x}>
              <span className="ck"><i className="ti ti-check"></i></span>
              <span>{x}</span>
            </div>)}
        </Reveal>
        <Reveal className="check-foot">Only the events themselves are removed — everything that makes the calendar work for your team stays exactly as it was.</Reveal>
      </div>
    </section>);
}

// ---------- SECTION 7 — SCALE ----------
function ScaleSection() {
  const stats = [
    ['3+ /sec', 'Sustained deletion speed, even under Google\'s rate limits'],
    ['100%', 'Calendar structure preserved, every time'],
    ['0', 'Manual clicks required after you press start']];
  return (
    <section className="section" style={{ paddingTop: 40 }}>
      <div className="wrap">
        <SectionHead lt eyebrow="Built to handle real volume" title="Thousands of events. One sitting." />
        <div className="scale-grid">
          {stats.map((s, i) =>
            <Reveal className="scale-stat" key={s[0]} delay={i * 70}>
              <div className="v grad-text">{s[0]}</div>
              <div className="k">{s[1]}</div>
            </Reveal>)}
        </div>
        <Reveal className="scale-foot" tag="p">Successfully tested on calendars containing thousands of events, across recurring series and individual entries alike.</Reveal>
      </div>
    </section>);
}

// ---------- SECTION 7B — WHY TEAMS CHOOSE ----------
function WhyTeams() {
  const items = ['No need to recreate the calendar', 'No need to reassign sharing permissions', 'No need to reconnect integrations', 'No need to update booking or resource links', 'No need to notify anyone about a replacement calendar'];
  return (
    <section className="section" style={{ paddingTop: 40 }}>
      <div className="wrap">
        <SectionHead lt eyebrow="Why admins choose WipeAway" title="It's not really about deleting events. It's about avoiding breakage." sub="Admins don't lose sleep over old calendar events. They lose sleep over what breaks when they try to fix it." />
        <Reveal className="why-list">
          {items.map((x) =>
            <div className="why-item" key={x}>
              <span className="ck"><i className="ti ti-check"></i></span>
              <span>{x}</span>
            </div>)}
        </Reveal>
        <Reveal className="why-foot" tag="p">The calendar your team already knows keeps working — just without years of clutter in it.</Reveal>
      </div>
    </section>);
}

// ---------- SECTION 8 — SECURITY ----------
function SecuritySection() {
  const cols = [
    ['ti-shield-lock', 'No calendar data stored', <><WA /> never stores the content of your events. Everything is processed directly through Google's own Calendar API, in your authenticated session.</>],
    ['ti-lock-access', 'Minimal permissions requested', 'Only calendar access and your email address are requested — nothing broader. Revoke access any time from your Google account settings.'],
    ['ti-certificate', 'Limited Use compliant', <><WA />'s use of Google user data adheres to Google's API Services User Data Policy, including the Limited Use requirements.</>]];
  return (
    <section className="section" id="security" style={{ paddingTop: 40 }}>
      <div className="wrap">
        <SectionHead lt eyebrow="Security" title="Built on Google's own infrastructure. Nothing stored, nothing shared." />
        <div className="biz-cols">
          {cols.map((c, i) =>
            <Reveal className="biz-col" key={c[1]} delay={i * 70}>
              <div className="ico"><i className={'ti ' + c[0]}></i></div>
              <h3>{c[1]}</h3>
              <p>{c[2]}</p>
            </Reveal>)}
        </div>
      </div>
    </section>);
}

// ---------- SECTION 8B — EXAMPLE CLEANUPS ----------
function ExampleCleanups() {
  const cards = [
    ['ti-school', 'School timetable reset', '3 calendars, 1,700+ events removed at the end of the academic year — calendar permissions and sharing settings left exactly as they were for the new term.'],
    ['ti-door', 'Meeting room calendar reset', 'A facilities calendar cleared of old bookings, with room-booking integrations and resource links left fully intact.'],
    ['ti-users', 'Recruitment campaign archive', 'Thousands of interview slots removed after a hiring campaign ended, with the calendar structure retained for the next round.'],
    ['ti-stethoscope', 'Clinic appointment archive', 'Years of past patient appointments cleared from a booking calendar, while the calendar and its integrations stayed fully in place.'],
    ['ti-presentation', 'Event & Conference Archive', 'Thousands of speaker sessions, exhibitor meetings, and event bookings removed after a conference ended — ready for the next event without rebuilding the calendar.'],
    ['ti-calendar-stats', 'Annual calendar reset', "A company-wide shared calendar cleared of the previous year's noise at the start of a new financial year."]];
  return (
    <section className="section" style={{ paddingTop: 40 }}>
      <div className="wrap">
        <SectionHead lt eyebrow="What this looks like in practice" title="A few examples of the kind of cleanup teams run" />
        <div className="ex-grid">
          {cards.map((c, i) =>
            <Reveal className="ex-card" key={c[1]} delay={i * 70}>
              <div className="ico"><i className={'ti ' + c[0]}></i></div>
              <h3>{c[1]}</h3>
              <p>{c[2]}</p>
            </Reveal>)}
        </div>
        <Reveal className="ex-foot" tag="p">Illustrative examples based on typical cleanup scenarios.</Reveal>
      </div>
    </section>);
}

// ---------- SECTION 9 — BUSINESS PRICING (4 tiers) ----------
function BizPricing({ onBuy, onQuote, onEnterprise }) {
  const tiers = [
    {
      name: 'Individual', from: false, price: '$9.99', per: '/year', big: true,
      alt: 'or $19.99 lifetime',
      desc: 'For personal calendars and one-off cleanups.',
      list: [],
      cta: 'Buy Now', action: onBuy, primary: true, showPay: true
    },
    {
      name: 'Small Team', from: true, price: '$99', per: '', big: true, badge: 'Most popular', tone: 'blue-strong',
      desc: 'For small businesses and teams managing multiple shared calendars.',
      list: ['Multiple users', 'Shared calendar cleanups', 'Priority support', 'Optional 15-minute onboarding session with the founder'],
      cta: 'Buy Now', href: SMALL_TEAM_CHECKOUT_URL, primary: true, showPay: true
    },
    {
      name: 'Organisation', from: true, price: '$500', per: '', big: true, badge: 'For complex cleanups', tone: 'blue',
      desc: 'For schools, clinics, agencies, departments and multi-calendar environments.',
      list: ['Large-scale calendar cleanups', 'Multiple stakeholders', 'Procurement friendly', 'Guided onboarding'],
      dual: {
        primary:   { cta: 'Get Started', href: ORGANISATION_CHECKOUT_URL, sub: 'Pay by card and get started immediately.' },
        secondary: { cta: 'Request a Quote', action: onQuote, sub: 'Need a quote, purchase order or approval first? We’ll prepare everything for you.' }
      }
    },
    {
      name: 'Enterprise', from: false, price: 'Custom Quote', per: '', big: false, badge: 'Custom solution', tone: 'green',
      desc: 'For large Google Workspace environments and organisation-wide calendar projects.',
      list: ['Dedicated support', 'Procurement-friendly', 'Custom requirements', 'Volume pricing'],
      cta: 'Book a Discovery Call', action: onEnterprise, primary: false
    }];
  return (
    <section className="section" id="pricing" style={{ paddingTop: 40 }}>
      <div className="wrap">
        <SectionHead lt eyebrow="Pricing" title="Pricing that scales from one calendar to the whole organisation." />
        <div className="bizp-grid">
          {tiers.map((t, i) =>
            <Reveal className={'bizp-card' + (t.tone ? ' tone-' + t.tone : '')} key={t.name} delay={i * 70}>
              {t.badge && <span className={'bizp-tag' + (t.tone === 'green' ? ' green' : '')}>{t.badge}</span>}
              <div className="bizp-name">{t.name}</div>
              <div className="bizp-pricebox">
                <span className="bizp-from">{t.from ? 'From' : '\u00a0'}</span>
                <div className={'bizp-price' + (t.big ? '' : ' sm')}>{t.price}{t.per && <span className="per">{t.per}</span>}</div>
              </div>
              <div className="bizp-alt">{t.alt || '\u00a0'}</div>
              <div className="bizp-desc">{t.desc}</div>
              {t.list.length > 0 &&
                <ul className="bizp-list">
                  {t.list.map((x) => <li key={x}><span className="ck"><i className="ti ti-check"></i></span>{x}</li>)}
                </ul>}
              {t.dual
                ? <>
                    <div className="bizp-secondary-block">
                      <button className="btn btn-lt-ghost" onClick={t.dual.secondary.action}>{t.dual.secondary.cta} <span className="arrow">→</span></button>
                      <p className="bizp-sub">{t.dual.secondary.sub}</p>
                    </div>
                    <div className="bizp-primary-block">
                      <a className="btn btn-primary bizp-btn" href={t.dual.primary.href} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none' }}>{t.dual.primary.cta} <span className="arrow">→</span></a>
                      <p className="bizp-sub">{t.dual.primary.sub}</p>
                    </div>
                  </>
                : <>
                    <div className="bizp-secondary-block bizp-placeholder" aria-hidden="true">
                      <button className="btn btn-lt-ghost" tabIndex="-1">placeholder <span className="arrow">→</span></button>
                      <p className="bizp-sub">placeholder text line</p>
                    </div>
                    <div className="bizp-primary-block">
                      {t.href
                        ? <a className={'btn bizp-btn ' + (t.primary ? 'btn-primary' : 'btn-lt-ghost')} href={t.href} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none' }}>{t.cta} <span className="arrow">→</span></a>
                        : <button className={'btn bizp-btn ' + (t.primary ? 'btn-primary' : 'btn-lt-ghost')} onClick={t.action}>{t.cta} <span className="arrow">→</span></button>}
                      <p className="bizp-sub">{t.showPay ? <PayRow dark /> : '\u00a0'}</p>
                    </div>
                  </>}
            </Reveal>)}
        </div>
      </div>
    </section>);
}

// ---------- SECTION 10 — FINAL CTA (business copy, FinalCTA styling) ----------
function BizFinalCTA({ onDemo }) {
  return (
    <section className="section" style={{ paddingTop: 30 }}>
      <div className="wrap">
        <Reveal className="cta-box">
          <Eyebrow>Ready when you are</Eyebrow>
          <h2 style={{ marginTop: 20 }}>Ready to see how clean<br />your calendars could be?</h2>
          <p>No commitment. We'll show you exactly how it works on a calendar like yours.</p>
          <button className="btn btn-primary" onClick={onDemo} style={{ fontSize: 17, padding: '17px 30px' }}>Book a demo <span className="arrow">→</span></button>
        </Reveal>
      </div>
    </section>);
}

// ---------- BUSINESS CONTACT / DEMO MODAL ----------
// Two-step for 'demo': capture lead details → inline Calendly scheduler (pre-filled).
// 'contact' kind stays a single-step enquiry form.
function BizContactModal({ onClose, kind }) {
  const isDemo = kind === 'demo';
  const [step, setStep] = React.useState('form');   // 'form' | 'schedule' | 'sent'
  const [form, setForm] = React.useState({ name: '', email: '', org: '', message: '' });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const calRef = React.useRef(null);
  const upd = (key) => (e) => setForm((f) => ({ ...f, [key]: e.target.value }));

  React.useEffect(() => {
    const k = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, []);

  // On the scheduling step, mount Calendly inline, pre-filled with captured details.
  React.useEffect(() => {
    if (step !== 'schedule' || !calRef.current || !window.Calendly) return;
    calRef.current.innerHTML = '';
    window.Calendly.initInlineWidget({
      url: CALENDLY_URL + '?hide_gdpr_banner=1&background_color=111829&text_color=eef2fb&primary_color=2d8cff',
      parentElement: calRef.current,
      prefill: { name: form.name, email: form.email, customAnswers: { a1: form.org, a2: form.message } }
    });
  }, [step]);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr('');
    // Fold org + context into the message (the endpoint only accepts name/email/message).
    const composed =
      '[Business enquiry' + (isDemo ? ' — demo request' : '') + ']\n' +
      'Organisation: ' + (form.org.trim() || '—') + '\n\n' +
      (form.message.trim() || '(No message provided.)');
    let ok = false;
    try {
      const r = await fetch('/api/contact', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: form.name, email: form.email, message: composed })
      });
      ok = r.ok;
    } catch (_) { ok = false; }
    setBusy(false);
    const calendlyReady = window.Calendly && CALENDLY_URL.indexOf('REPLACE-ME') === -1;
    // Demo + Calendly: proceed to the scheduler regardless — the lead was already captured above.
    if (isDemo && calendlyReady) { setStep('schedule'); return; }
    // Otherwise require a successful save so no enquiry is silently lost.
    if (ok) setStep('sent');
    else setErr("Couldn't send that just now — please try again in a moment.");
  };

  const firstName = (form.name || '').trim().split(' ')[0];

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className={'modal' + (step === 'schedule' ? ' modal-wide' : '')} onClick={(e) => e.stopPropagation()}>
        <button className="x" onClick={onClose}>✕</button>

        {step === 'sent' && (
          <div style={{ textAlign: 'center', padding: '8px 0' }}>
            <div className="ok-ico"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#2d8cff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg></div>
            <h3>Thanks — we'll be in touch</h3>
            <p className="msub" style={{ marginBottom: 0 }}>We've got your details and we'll reply shortly to set up a time that works for your team.</p>
          </div>
        )}

        {step === 'form' && (<>
          <Eyebrow>{isDemo ? 'Book a demo' : 'Talk to us'}</Eyebrow>
          <h3 style={{ marginTop: 16 }}>{isDemo ? 'Book a demo' : 'Contact our team'}</h3>
          <p className="msub">{isDemo
            ? 'Tell us a little about your calendars — then pick a time that suits you.'
            : <>Tell us a little about your calendars and we'll show you exactly how <WA /> would work for your team.</>}</p>
          <form onSubmit={submit}>
            <div className="field"><label>Your name</label><input required placeholder="Jane Doe" value={form.name} onChange={upd('name')} /></div>
            <div className="field"><label>Work email</label><input required type="email" placeholder="jane@yourcompany.com" value={form.email} onChange={upd('email')} /></div>
            <div className="field"><label>Organisation</label><input placeholder="Company, school, or practice" value={form.org} onChange={upd('org')} /></div>
            <div className="field"><label>Message</label><textarea rows="3" value={form.message} onChange={upd('message')} placeholder="How many calendars and users are involved?"></textarea></div>
            <button className="btn btn-primary" style={{ width: '100%' }} type="submit" disabled={busy}>{busy ? 'Sending…' : (isDemo ? 'Continue to scheduling' : 'Send enquiry')} <span className="arrow">→</span></button>
            {err ? <div className="modal-note" style={{ color: '#ff7d96' }}>{err}</div> : <div className="modal-note">We'll only use your details to respond to this enquiry.</div>}
          </form>
        </>)}

        {step === 'schedule' && (<>
          <Eyebrow>Almost there</Eyebrow>
          <h3 style={{ marginTop: 16 }}>{firstName ? 'Pick a time, ' + firstName : 'Pick a time'}</h3>
          <p className="msub">Choose a slot below — we've pre-filled your details.</p>
          <div className="cal-inline" ref={calRef}></div>
        </>)}
      </div>
    </div>);
}

// ---------- ORGANISATION / ENTERPRISE QUALIFICATION MODALS ----------
// Both POST to the existing /api/contact (folding extra fields into `message`).
function QualifyModal({ onClose, variant }) {
  const isEnt = variant === 'enterprise';
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [f, setF] = React.useState({ name: '', email: '', org: '', role: '', calendars: '', cleaning: '', summary: '', message: '' });
  const upd = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

  React.useEffect(() => {
    const k = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr('');
    let composed;
    if (isEnt) {
      composed = '[Enterprise — discovery call]\n' +
        'Organisation: ' + (f.org.trim() || '—') + '\n' +
        'Estimated calendars: ' + (f.calendars.trim() || '—') + '\n\n' +
        (f.summary.trim() || '(No project summary provided.)');
    } else {
      composed = '[Organisation access request]\n' +
        'Organisation: ' + (f.org.trim() || '—') + '\n' +
        'Role: ' + (f.role.trim() || '—') + '\n' +
        'Calendars involved: ' + (f.calendars || '—') + '\n' +
        'Cleaning: ' + (f.cleaning || '—') + '\n\n' +
        (f.message.trim() || '(No additional message.)');
    }
    let ok = false;
    try {
      const r = await fetch('/api/contact', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: f.name, email: f.email, message: composed })
      });
      ok = r.ok;
    } catch (_) { ok = false; }
    setBusy(false);
    if (ok) setSent(true);
    else setErr("Couldn't send that just now — please try again in a moment.");
  };

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="x" onClick={onClose}>✕</button>
        {sent ? (
          <div style={{ textAlign: 'center', padding: '8px 0' }}>
            <div className="ok-ico"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#2d8cff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg></div>
            <h3>Thank you</h3>
            <p className="msub" style={{ marginBottom: 0 }}>{isEnt
              ? "We've received your details and will be in touch to arrange your discovery call."
              : "We've received your enquiry and will review your requirements. We'll respond within one business day."}</p>
          </div>
        ) : (<>
          <Eyebrow>{isEnt ? 'Enterprise' : 'Organisation access'}</Eyebrow>
          <h3 style={{ marginTop: 16 }}>{isEnt ? 'Book a discovery call' : 'Request organisation access'}</h3>
          <p className="msub">{isEnt
            ? "Tell us about your project and we'll set up a call to scope it out."
            : "Tell us about your environment and we'll review your requirements."}</p>
          <form onSubmit={submit}>
            <div className="field"><label>Your name</label><input required placeholder="Jane Doe" value={f.name} onChange={upd('name')} /></div>
            <div className="field"><label>Work email</label><input required type="email" placeholder="jane@yourorg.com" value={f.email} onChange={upd('email')} /></div>
            <div className="field"><label>{isEnt ? 'Organisation' : 'Organisation name'}</label><input required placeholder="Company, school, or practice" value={f.org} onChange={upd('org')} /></div>
            {!isEnt && <div className="field"><label>Role</label><input placeholder="e.g. IT Administrator" value={f.role} onChange={upd('role')} /></div>}
            {isEnt
              ? <div className="field"><label>Estimated number of calendars</label><input required placeholder="e.g. ~250" value={f.calendars} onChange={upd('calendars')} /></div>
              : <div className="field"><label>How many calendars are involved?</label>
                  <select required value={f.calendars} onChange={upd('calendars')}>
                    <option value="" disabled>Select a range…</option>
                    <option>1–10</option><option>10–50</option><option>50–100</option><option>100+</option>
                  </select></div>}
            {!isEnt && <div className="field"><label>What are you cleaning?</label>
              <select required value={f.cleaning} onChange={upd('cleaning')}>
                <option value="" disabled>Select an option…</option>
                <option>School timetables</option><option>Resource calendars</option><option>Appointment calendars</option><option>Shared team calendars</option><option>Other</option>
              </select></div>}
            {isEnt
              ? <div className="field"><label>Brief project summary</label><textarea required rows="3" placeholder="What are you trying to achieve?" value={f.summary} onChange={upd('summary')}></textarea></div>
              : <div className="field"><label>Anything else? (optional)</label><textarea rows="2" placeholder="Tell us more about your environment" value={f.message} onChange={upd('message')}></textarea></div>}
            <button className="btn btn-primary" style={{ width: '100%' }} type="submit" disabled={busy}>{busy ? 'Sending…' : (isEnt ? 'Book a discovery call' : 'Request access')} <span className="arrow">→</span></button>
            {err ? <div className="modal-note" style={{ color: '#ff7d96' }}>{err}</div> : <div className="modal-note">We'll only use your details to respond to this enquiry.</div>}
          </form>
        </>)}
      </div>
    </div>);
}

// ---------- ORGANISATION INVOICE / PROPOSAL REQUEST MODAL ----------
// Procurement-friendly path for the Organisation tier: capture requirements,
// then send a proposal/invoice manually. POSTs to the existing /api/contact
// (extra fields folded into `message`, tagged so it's easy to triage).
// Maps the existing "Organisation type" dropdown value to the PDF sector
// slug used by /api/send-link's SECTOR_PDF_MAP — avoids asking the user
// to pick their sector twice via two near-identical dropdowns.
//   School / University        -> education
//   Agency, Corporate          -> business
//   Healthcare                 -> healthcare
//   Non-Profit, Government,
//   Other                      -> other
function orgTypeToSector(orgType) {
  const map = {
    'School / University': 'education',
    'Agency':              'business',
    'Corporate':           'business',
    'Healthcare':          'healthcare',
    'Non-Profit':          'other',
    'Government':          'other',
    'Other':               'other'
  };
  return map[orgType] || 'other';
}

// ---------- ORGANISATION QUOTE / INVOICE / PO REQUEST MODAL ----------
// Procurement route for the Organisation tier ("Request a Quote"). Captures the
// information a finance team needs to raise a valid quote/invoice/PO, then routes
// it to the existing /api/contact (all fields folded into `message`, tagged for
// easy triage). No payment is taken here — you price + invoice manually.
function QuoteRequestModal({ onClose }) {
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [f, setF] = React.useState({
    org: '', orgType: '', website: '',
    name: '', title: '', email: '', phone: '',
    billingContact: '', billingEmail: '', billingAddress: '',
    needType: '', taxId: '', poRequired: '', quoteBeforePo: '',
    calendars: '', events: '', message: ''
  });
  const upd = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

  React.useEffect(() => {
    const k = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr('');
    const L = (label, v) => label + ': ' + ((v || '').toString().trim() || '—') + '\n';
    const composed =
      '[Organisation quote / invoice request]\n\n' +
      '— Organisation —\n' +
      L('Organisation name', f.org) + L('Organisation type', f.orgType) + L('Website', f.website) +
      '\n— Primary contact —\n' +
      L('Full name', f.name) + L('Job title', f.title) + L('Work email', f.email) + L('Phone', f.phone) +
      '\n— Billing —\n' +
      L('Billing contact (if different)', f.billingContact) + L('Billing email', f.billingEmail) + L('Billing address', f.billingAddress) +
      '\n— Tax & procurement —\n' +
      L('What they need', f.needType) + L('VAT / Tax ID', f.taxId) +
      L('Purchase order required', f.poRequired) + L('Formal quote before PO', f.quoteBeforePo) +
      '\n— Project —\n' +
      L('Approx. calendars', f.calendars) + L('Approx. events', f.events) +
      '\nNotes: ' + (f.message.trim() || '(none)');
    let ok = false;
    try {
      const r = await fetch('/api/contact', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: f.name || f.org || 'Organisation quote request', email: f.email, message: composed, skipAutoReply: true })
      });
      ok = r.ok;
    } catch (_) { ok = false; }

    // Instant auto-reply to the requester, with the sector-specific PDF
    // attached — fires alongside the internal notification above. Reuses
    // /api/send-link's existing sector/PDF lookup (source: 'quote') rather
    // than duplicating that logic. Best-effort: a failure here is logged
    // but doesn't block the "request received" confirmation, since the
    // internal notification above is the part that must not be lost.
    let landingPage = '', device = '', utmSource = '';
    try {
      landingPage = window.location.pathname || '';
      device = /Mobi|Android/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
      utmSource = new URLSearchParams(window.location.search).get('utm_source') || '';
    } catch (e) {}
    fetch('/api/send-link', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: f.email, source: 'quote', sector: orgTypeToSector(f.orgType), landingPage, device, utmSource })
    }).catch((e) => console.warn('Quote auto-reply email failed to send:', e));

    setBusy(false);
    if (ok) setSent(true);
    else setErr("Couldn't send that just now — please try again in a moment.");
  };

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="x" onClick={onClose}>✕</button>
        {sent ? (
          <div style={{ textAlign: 'center', padding: '8px 0' }}>
            <div className="ok-ico"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#2d8cff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg></div>
            <h3>Thanks — we've received your request</h3>
            <p className="msub">We'll review your requirements and send a quote or invoice package within 1 business day.</p>
            <ul className="ok-list">
              <li><i className="ti ti-check"></i> Recommended package</li>
              <li><i className="ti ti-check"></i> Pricing proposal</li>
              <li><i className="ti ti-check"></i> Invoice or quote (if requested)</li>
              <li><i className="ti ti-check"></i> Next steps and onboarding options</li>
            </ul>
          </div>
        ) : (<>
          <Eyebrow>Procurement friendly</Eyebrow>
          <h3 style={{ marginTop: 16 }}>Request a quote or invoice</h3>
          <p className="msub">Tell us what your finance team needs and we'll prepare a quote, invoice or PO package — typically within one business day. No payment is taken now.</p>
          <form onSubmit={submit}>
            <div className="fgroup">Organisation details</div>
            <div className="field"><label>Organisation name</label><input required placeholder="St Mary's Academy" value={f.org} onChange={upd('org')} /></div>
            <div className="field"><label>Organisation type</label>
              <select required value={f.orgType} onChange={upd('orgType')}>
                <option value="" disabled>Select a type…</option>
                <option>School / University</option><option>Healthcare</option><option>Agency</option>
                <option>Corporate</option><option>Non-Profit</option><option>Government</option><option>Other</option>
              </select></div>
            <div className="field"><label>Organisation website <span style={{ color: 'var(--dim)' }}>(optional)</span></label><input placeholder="https://" value={f.website} onChange={upd('website')} /></div>

            <div className="fgroup">Primary contact</div>
            <div className="frow">
              <div className="field"><label>Full name</label><input required placeholder="Jane Doe" value={f.name} onChange={upd('name')} /></div>
              <div className="field"><label>Job title</label><input required placeholder="IT Manager" value={f.title} onChange={upd('title')} /></div>
            </div>
            <div className="frow">
              <div className="field"><label>Work email</label><input required type="email" placeholder="jane@organisation.com" value={f.email} onChange={upd('email')} /></div>
              <div className="field"><label>Phone <span style={{ color: 'var(--dim)' }}>(optional)</span></label><input placeholder="+44 …" value={f.phone} onChange={upd('phone')} /></div>
            </div>

            <div className="fgroup">Billing information</div>
            <div className="field"><label>Billing contact <span style={{ color: 'var(--dim)' }}>(if different)</span></label><input placeholder="Accounts payable" value={f.billingContact} onChange={upd('billingContact')} /></div>
            <div className="field"><label>Billing email</label><input required type="email" placeholder="accounts@organisation.com" value={f.billingEmail} onChange={upd('billingEmail')} /></div>
            <div className="field"><label>Billing address</label><textarea required rows="3" placeholder="Street, city, postal/zip code, country" value={f.billingAddress} onChange={upd('billingAddress')}></textarea></div>

            <div className="fgroup">Tax &amp; procurement</div>
            <div className="field"><label>What do you need?</label>
              <select required value={f.needType} onChange={upd('needType')}>
                <option value="" disabled>Select an option…</option>
                <option>A quote</option><option>An invoice</option><option>Purchase order process</option><option>Not sure yet</option>
              </select></div>
            <div className="field"><label>VAT number / Tax ID <span style={{ color: 'var(--dim)' }}>(optional)</span></label><input placeholder="e.g. GB123456789" value={f.taxId} onChange={upd('taxId')} />
              <div className="hint">If your organisation requires this to appear on invoices, please provide it here.</div></div>
            <div className="frow">
              <div className="field"><label>Purchase order required?</label>
                <select required value={f.poRequired} onChange={upd('poRequired')}>
                  <option value="" disabled>Select…</option><option>Yes</option><option>No</option><option>Not sure</option>
                </select></div>
              <div className="field"><label>Formal quote before PO?</label>
                <select value={f.quoteBeforePo} onChange={upd('quoteBeforePo')}>
                  <option value="" disabled>Select…</option><option>Yes</option><option>No</option>
                </select></div>
            </div>

            <div className="fgroup">Project information</div>
            <div className="frow">
              <div className="field"><label>Approx. number of calendars</label>
                <select required value={f.calendars} onChange={upd('calendars')}>
                  <option value="" disabled>Select a range…</option>
                  <option>1–10</option><option>11–50</option><option>51–200</option><option>200+</option>
                </select></div>
              <div className="field"><label>Approx. number of events</label>
                <select value={f.events} onChange={upd('events')}>
                  <option value="" disabled>Select a range…</option>
                  <option>Under 5,000</option><option>5,000–25,000</option><option>25,000–100,000</option><option>100,000+</option>
                </select></div>
            </div>
            <div className="field"><label>Anything we should know? <span style={{ color: 'var(--dim)' }}>(optional)</span></label><textarea rows="3" placeholder="School timetable reset · meeting room clean-up · multiple departments · specific deadline…" value={f.message} onChange={upd('message')}></textarea></div>

            <button className="btn btn-primary" style={{ width: '100%', marginTop: 6 }} type="submit" disabled={busy}>{busy ? 'Sending…' : 'Submit request'} <span className="arrow">→</span></button>
            {err ? <div className="modal-note" style={{ color: '#ff7d96' }}>{err}</div> : <div className="modal-note">We'll only use your details to prepare and send your quote.</div>}
          </form>
        </>)}
      </div>
    </div>);
}

// ---------- APP ----------
function BusinessApp() {
  const [modal, setModal] = React.useState(null); // 'demo' | 'contact' | 'buy'
  const onDemo = () => setModal('demo');
  const onContact = () => setModal('contact');
  const onBuy = () => setModal('buy');
  const onQuote = () => setModal('quote');
  const onEnterprise = () => setModal('enterprise');
  const onKey = () => setModal('key');
  const isMobile = useIsMobile();

  // Desktop composition — unchanged from the original page (FAQ added in an lt band).
  const desktopMain = (
    <>
      <BizHero onDemo={onDemo} />
      <ProblemSection />
      <SolutionSection />

      <div className="lt-top"></div>
      <div className="lt">
        <WhoItsFor />
      </div>
      <div className="lt-bot"></div>

      <HowItWorks />

      <div className="lt-top"></div>
      <div className="lt">
        <WhatStays />
        <ScaleSection />
        <WhyTeams />
        <SecuritySection />
        <ExampleCleanups />
        <BizPricing onBuy={onBuy} onQuote={onQuote} onEnterprise={onEnterprise} />
      </div>
      <div className="lt-bot"></div>

      <div className="lt-top"></div>
      <div className="lt"><FAQ /></div>
      <div className="lt-bot"></div>
    </>
  );

  // Mobile/tablet composition — Pricing pulled up (Hero → Problem → Solution →
  // Pricing → rest), trust strip below hero, send-link capture, FAQ. Desktop untouched.
  const mobileMain = (
    <>
      <BizHero onDemo={onDemo} />
      <MobileTrustStrip />
      <ProblemSection />
      <SolutionSection />

      <div className="lt-top"></div>
      <div className="lt">
        <BizPricing onBuy={onBuy} onQuote={onQuote} onEnterprise={onEnterprise} />
        <WhoItsFor />
      </div>
      <div className="lt-bot"></div>

      <HowItWorks />

      <div className="lt-top"></div>
      <div className="lt">
        <WhatStays />
        <ScaleSection />
        <WhyTeams />
        <SecuritySection />
        <ExampleCleanups />
      </div>
      <div className="lt-bot"></div>

      <SendLinkCard />

      <div className="lt-top"></div>
      <div className="lt"><FAQ /></div>
      <div className="lt-bot"></div>
    </>
  );

  return (
    <>
      <BizNav onDemo={onDemo} onKey={onKey} />
      {isMobile ? mobileMain : desktopMain}

      <Footer onContact={onContact} />

      {isMobile && <BizMobileStickyCTA onQuote={onQuote} />}
      {isMobile && <div className="m-cta-spacer"></div>}

      {modal === 'demo' && <BizContactModal kind="demo" onClose={() => setModal(null)} />}
      {modal === 'contact' && <BizContactModal kind="contact" onClose={() => setModal(null)} />}
      {modal === 'enterprise' && <QualifyModal variant="enterprise" onClose={() => setModal(null)} />}
      {modal === 'quote' && <QuoteRequestModal onClose={() => setModal(null)} />}
      {modal === 'buy' && <BuyModal onClose={() => setModal(null)} />}
      {modal === 'key' && <KeyModal onClose={() => setModal(null)} />}
    </>);
}

ReactDOM.createRoot(document.getElementById('root')).render(<BusinessApp />);
