/* ============================================================
   NeuroRoute — Landing: tier-based Pricing (Basic / Standard /
   Premium / Enterprise). Flat platform fee + metered per-1M-token
   rate. BYOK or SISL-managed keys.
   Globals: Icon, LogoMark, COL, go, useState
   ============================================================ */
function PricingSection(){
  const [faq,setFaq]=useState(0);
  const [showAll,setShowAll]=useState(false);

  /* Fixed launch pricing — flat monthly platform fee + metered $/1M tokens.
     Rates are the NeuroRoute platform charge; provider cost is separate
     (paid directly under BYOK, or passed through at cost under managed keys). */
  const TIERS=[
    {key:'basic',name:'Basic',badge:'',base:99,inr:0.20,outr:0.40,
     tag:'Start routing and cut your bill from day one.',
     feats:[
       'Smart routing across 6 strategies',
       '11+ providers behind one API',
       'Cost & usage dashboard + per-request savings proof',
       'Daily & monthly budget caps',
       'Adaptive quality learning',
       'GDPR data export (JSON)',
       'Community support']},
    {key:'standard',name:'Standard',badge:'',base:119,inr:0.30,outr:0.50,
     tag:'For teams running AI in production.',
     feats:[
       'Everything in Basic',
       'Context compression — up to ~40% fewer input tokens',
       'Team workspaces & role-based access',
       'PII detection & routing policy',
       'Server-side memory & project context',
       'Per-request routing explain',
       'Email support']},
    {key:'premium',name:'Premium',badge:'POPULAR',base:149,inr:0.40,outr:0.70,
     tag:'The full optimization + governance stack.',
     feats:[
       'Everything in Standard',
       'Semantic + exact-match caching',
       'Bring your own provider keys (BYOK)',
       'Fusion & learned routing',
       'MCP server (OAuth 2.1) + event webhooks',
       'Encryption at rest, erasure & audit log',
       'Guardrails & spend alerts',
       'Priority support']},
    {key:'enterprise',name:'Enterprise',badge:'CUSTOM',custom:true,
     tag:'For large orgs, security & procurement.',
     feats:[
       'Everything in Premium',
       'SSO (OIDC & SAML)',
       'Customer-managed keys (CMEK)',
       'Scheduled key rotation',
       'OpenTelemetry export & custom providers',
       'Zero-retention, compliance & audit',
       'Dedicated support & SLA']},
  ];

  /* Full capability matrix — what's actually shipped, mapped to the tier it
     unlocks at. A feature checked at a tier is included at every tier above it. */
  const TIER_ORDER=['basic','standard','premium','enterprise'];
  const MATRIX=[
    {cat:'Routing & models', rows:[
      ['Smart routing — 6 strategies','cheapest, best-quality, task-aware, fastest, balanced, cascade','basic'],
      ['11+ provider adapters','OpenAI, Anthropic, Google/Vertex, Azure, AWS Bedrock, xAI, Groq, DeepInfra, OpenRouter, vLLM & more','basic'],
      ['Automatic task classification','10 task types drive model selection','basic'],
      ['Cascade execution','try cheap, escalate only on low confidence','basic'],
      ['Health monitoring & failover','30s provider health probes, automatic fallback','basic'],
      ['Adaptive quality learning','model scores retrain hourly from real thumbs-up/down','basic'],
      ['Per-key routing overrides','strategy override + model allowlist per API key','standard'],
      ['Config-as-code routing rules','hard task→model pins, weighted A/B splits','premium'],
      ['Fusion routing','panel of models + independent judge picks the winner','premium'],
      ['Learned routing (KNN)','soft-pins what worked on similar past prompts','premium'],
      ['Tool-aware agent routing','biases toward tool-capable models & cheap inner steps','premium'],
    ]},
    {cat:'Cost optimization', rows:[
      ['Cost estimator & savings dashboard','pre-send preview, routed-vs-baseline reporting','basic'],
      ['Provider prompt-caching','reuses Anthropic/Vertex system-prompt cache automatically','basic'],
      ['Context compression','whitespace/JSON/dedup + ML (LLMLingua-2) engines','standard'],
      ['Exact-match response cache (L1)','identical requests served instantly','premium'],
      ['Semantic response cache (L2)','near-duplicate prompts served from cache','premium'],
      ['Prompt-cache warming','pre-warms the runner-up model for fast switches','premium'],
    ]},
    {cat:'Context & memory', rows:[
      ['Server-side conversation memory','prior turns injected automatically, windowed to fit','standard'],
      ['Persistent project context','standing instructions prepended to every request','standard'],
      ['Context summarization / handoff','long conversations compacted before injection','premium'],
    ]},
    {cat:'Data & privacy', rows:[
      ['GDPR data export (JSON)','streamed, no secrets, one-click from Settings','basic'],
      ['Configurable retention mode','zero-strict / zero / retain, per-org','standard'],
      ['CSV/ZIP + async export','large exports via background job, GCS-backed','premium'],
      ['Scheduled usage export','hourly/daily/weekly push to your GCS bucket','premium'],
      ['Encryption at rest','AES-256-GCM, per-org data key','premium'],
      ['Org erasure / right-to-be-forgotten','request → grace → execute → certificate','premium'],
      ['Customer-managed key (CMEK)','wrap your data key with your own cloud KMS key','enterprise'],
      ['Scheduled key rotation','automatic re-encryption sweep on a schedule','enterprise'],
    ]},
    {cat:'Security & access', rows:[
      ['Google sign-in','OAuth2 login for the dashboard','basic'],
      ['SSRF-guarded egress','every customer-supplied URL dial-time validated','basic'],
      ['Role-based access','admin, billing, viewer roles per user','standard'],
      ['PII detection & routing policy','auto-restrict sensitive requests to safe providers','standard'],
      ['Output guardrails','PII/profanity/custom + webhook rules on model output','premium'],
      ['Scoped service API keys','keys limited to specific capabilities','premium'],
      ['Admin & security audit log','queryable log of every privileged action','premium'],
      ['Generic OIDC SSO','Okta, Azure AD & other OIDC providers','enterprise'],
      ['SAML 2.0 SSO','SP-initiated SAML for IdPs that do not speak OIDC','enterprise'],
    ]},
    {cat:'Integrations', rows:[
      ['Bring-your-own provider keys (BYOK)','route through your own provider account','premium'],
      ['MCP server','9 tools + OAuth 2.1 one-click connect','premium'],
      ['Event webhooks','budget-tripped, key-created, erasure — HMAC-signed','premium'],
      ['Custom OpenAI-compatible provider','wire up a self-hosted or exotic endpoint','enterprise'],
      ['OpenTelemetry trace export','OTLP spans into your observability stack','enterprise'],
    ]},
    {cat:'Governance & observability', rows:[
      ['Budget caps','daily & monthly hard limits, per key and per org','basic'],
      ['Usage, billing & key dashboards','live, org-scoped, no demo data','basic'],
      ['Playground','live chat with routing metadata + cost estimate','basic'],
      ['Per-request routing explain','why this model, this cost, this confidence','standard'],
      ['Prompt template library','versioned, reusable prompt templates','standard'],
      ['Workspaces','team-level budgets & isolation inside one org','standard'],
      ['Budget & error-rate alerts','email/webhook alerts on spend, latency, health','premium'],
      ['Run-scoped agent budgets','hard spend cap for one multi-step agent run','premium'],
    ]},
    {cat:'Support', rows:[
      ['Community support','docs + community channels','basic'],
      ['Email support','business-hours response','standard'],
      ['Priority support','faster response times','premium'],
      ['Dedicated support & SLA','named contact, negotiated SLA','enterprise'],
    ]},
  ];

  const faqs=[
    ['How does NeuroRoute pricing work?',
     'A flat monthly platform fee for your tier, plus a metered per-million-token rate on the traffic you route through us. That per-token rate is the NeuroRoute platform charge — provider cost is separate: pay providers directly with your own keys (BYOK), or let us manage keys and pass provider cost through at cost. You can model your bill before you send a request.'],
    ['What’s the difference between the tiers?',
     'Intelligent routing and hard budget caps are in every tier. Standard adds context compression, team workspaces and role-based access. Premium adds caching, BYOK, fusion & learned routing, the MCP server, guardrails and encryption at rest. Enterprise adds SSO, customer-managed keys (CMEK), OpenTelemetry and compliance controls. The full matrix above shows exactly what unlocks where.'],
    ['BYOK or managed keys — which do I pick?',
     'Either, on any tier, and you can mix per provider. With BYOK you keep your own provider keys and pay providers directly at their published rates; we bill only the platform fee plus the per-token rate. With managed keys we handle provider relationships and pass provider cost through at cost on a single invoice. Same routing, same savings either way.'],
    ['Does the per-token rate apply to provider cost too?',
     'No. The per-1M-token rate is the NeuroRoute platform charge only. Provider cost is billed separately — directly to you under BYOK, or passed through at cost under managed keys. Every response carries X-Request-Cost and X-Savings headers, and your dashboard shows a real-time total against the flagship-model baseline, so the savings are auditable.'],
    ['Are there lock-in contracts or minimums?',
     'No lock-in, no minimums, no per-seat fees. Tiers are month-to-month. Enterprise is a negotiated contract with custom rates, dedicated support, and an SLA — talk to sales to design the right terms for your org.'],
    ['Can I change tiers or negotiate Enterprise pricing?',
     'Yes. Tiers are set with you and can move up or down as your needs change. Enterprise is custom-priced with volume discounts, custom token rates, SSO/CMEK, dedicated support and an SLA — talk to sales and we’ll tailor it.'],
  ];

  const rate=(n)=>'$'+n.toFixed(2);

  return (
    <section id="pricing" className="lp-sec pr-sec">
      <PricingStyles/>
      <div className="lp-head">
        <div className="eyebrow">PRICING</div>
        <h2 className="display lp-h2">Simple, transparent<br/><span className="route-text">tier pricing.</span></h2>
        <p className="lp-p">A flat monthly platform fee plus a metered per-million-token rate. Bring your own provider keys or let us manage them. Choose the tier that fits and move up as you grow.</p>
      </div>

      {/* tier cards */}
      <div className="pt-grid">
        {TIERS.map(t=>(
          <div key={t.key} className={'pt-card'+(t.badge==='POPULAR'?' pop':'')+(t.custom?' ent':'')}>
            {t.badge && <span className={'pt-badge'+(t.badge==='CUSTOM'?' cust':'')}>{t.badge}</span>}
            <div className="pt-name">{t.name}</div>
            {t.custom ? (
              <div className="pt-price">
                <div className="pt-price-cust route-text">Custom</div>
                <div className="pt-price-sub">talk to sales</div>
              </div>
            ) : (
              <div className="pt-price">
                <div className="pt-price-main"><b className="mono">${t.base}</b><span>/mo base</span></div>
                <div className="pt-price-sub mono">{rate(t.inr)} / 1M in · {rate(t.outr)} / 1M out</div>
              </div>
            )}
            <p className="pt-tag">{t.tag}</p>
            <button className={'btn btn-block '+(t.badge==='POPULAR'?'btn-grad':'btn-ghost')}
              onClick={()=> window.openLeadForm ? window.openLeadForm() : (window.location.href='mailto:CloudSales@sislinfotech.com?subject=NeuroRoute - Sales enquiry ('+t.name+')')}>
              Contact Sales Team{t.badge==='POPULAR' && <Icon name="arrowright" size={15}/>}
            </button>
            <ul className="pt-feats">
              {t.feats.map((f,i)=>(
                <li key={i}><Icon name="check" size={14} style={{color:'var(--green)',flex:'none'}}/>{f}</li>
              ))}
            </ul>
          </div>
        ))}
      </div>

      <p className="pt-note faint">
        <Icon name="info" size={14} style={{flex:'none',verticalAlign:'-2px',marginRight:6}}/>
        Provider cost is billed separately — paid directly to providers under BYOK, or passed through at cost under SISL-managed keys. The per-token rate above is the NeuroRoute platform charge only.
      </p>

      {/* full feature matrix */}
      <div className="pt-fm-wrap card">
        <button className="pt-fm-toggle" onClick={()=>setShowAll(s=>!s)} aria-expanded={showAll}>
          <span><b>Compare every feature</b> — what unlocks at each tier</span>
          <Icon name="chevdown" size={18} className="pt-fm-chev" style={{transform:showAll?'rotate(180deg)':'none'}}/>
        </button>
        {showAll && (
          <div className="pt-fm-scroll">
            <table className="pt-fm">
              <thead>
                <tr>
                  <th className="pt-fm-feat">Capability</th>
                  <th>Basic</th><th>Standard</th><th className="pt-fm-pop">Premium</th><th>Enterprise</th>
                </tr>
              </thead>
              <tbody>
                {MATRIX.map(group=>[
                  <tr key={group.cat} className="pt-fm-cat"><td colSpan="5">{group.cat}</td></tr>,
                  ...group.rows.map((r,ri)=>{
                    const fromIdx=TIER_ORDER.indexOf(r[2]);
                    return (
                      <tr key={group.cat+ri}>
                        <td className="pt-fm-feat">
                          <div className="pt-fm-name">{r[0]}</div>
                          <div className="pt-fm-desc">{r[1]}</div>
                        </td>
                        {TIER_ORDER.map((tk,i)=>(
                          <td key={tk} className={i===2?'pt-fm-pop':''}>
                            {i>=fromIdx
                              ? <Icon name="check" size={15} style={{color:'var(--green)'}}/>
                              : <span className="pt-fm-no">—</span>}
                          </td>
                        ))}
                      </tr>
                    );
                  })
                ])}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* enterprise band */}
      <div className="pr-ent">
        <div className="aurora-bg dim"><span/><span/></div>
        <div className="pr-ent-in">
          <div>
            <div className="eyebrow" style={{marginBottom:8}}>ENTERPRISE</div>
            <h3 className="display" style={{fontSize:26,marginBottom:6}}>Big volume, strict procurement? Let’s talk.</h3>
            <p className="muted" style={{fontSize:14,lineHeight:1.6,margin:'0 0 14px',maxWidth:560}}>Custom token rates and volume discounts, plus everything security and compliance asks for before they sign off.</p>
            <div className="pr-ent-feats">
              {['Custom rates & volume discounts','SSO (OIDC & SAML)','Customer-managed keys (CMEK)','Zero-retention & compliance','Self-hosted models','OpenTelemetry export','Dedicated support + SLA'].map(f=>(
                <span key={f} className="pt-chip"><Icon name="check" size={13} style={{color:'var(--cyan)',flex:'none'}}/>{f}</span>
              ))}
            </div>
          </div>
          <a className="btn btn-grad btn-lg" onClick={()=> window.openLeadForm && window.openLeadForm()} style={{flex:'none',cursor:'pointer'}}>Contact NeuroRoute Sales Team<Icon name="arrowright" size={16}/></a>
        </div>
      </div>

      {/* FAQ */}
      <div className="pr-faq">
        <h3 className="display" style={{fontSize:22,textAlign:'center',margin:'8px 0 22px'}}>Frequently asked questions</h3>
        {faqs.map((f,i)=>(
          <div key={i} className={'pr-q'+(faq===i?' open':'')}>
            <button className="pr-q-head" onClick={()=>setFaq(faq===i?-1:i)}>
              <span>{f[0]}</span><Icon name="chevdown" size={18} className="pr-q-chev"/>
            </button>
            <div className="pr-q-body"><p>{f[1]}</p></div>
          </div>
        ))}
      </div>
    </section>
  );
}

function PricingStyles(){
  return <style>{`
.pr-sec{position:relative}

.pt-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;align-items:start}
.pt-card{position:relative;display:flex;flex-direction:column;background:var(--bg-2);border:1px solid var(--line-2);
  border-radius:var(--r-xl);padding:24px 20px;transition:.18s}
.pt-card:hover{border-color:var(--line-strong);transform:translateY(-3px)}
.pt-card.pop{border-color:rgba(226,79,214,.55);box-shadow:0 24px 60px -28px rgba(226,79,214,.5);background:linear-gradient(180deg,rgba(226,79,214,.06),transparent 40%)}
.pt-card.ent{background:linear-gradient(180deg,rgba(59,130,246,.05),transparent 40%)}
.pt-badge{position:absolute;top:16px;right:16px;font-family:var(--font-mono);font-size:9.5px;font-weight:700;letter-spacing:.1em;
  padding:3px 9px;border-radius:99px;background:var(--grad-brand);color:#fff}
.pt-badge.cust{background:var(--purple-t);color:#c084fc;border:1px solid rgba(192,132,252,.4)}
.pt-name{font-family:var(--font-display);font-weight:800;font-size:18px;letter-spacing:-.01em}
.pt-price{margin:14px 0 4px;min-height:52px}
.pt-price-main{display:flex;align-items:baseline;gap:6px}
.pt-price-main b{font-size:32px;font-weight:700;color:var(--tx-0)}
.pt-price-main span{font-size:12.5px;color:var(--tx-2)}
.pt-price-sub{font-size:12px;color:var(--tx-2);margin-top:4px}
.pt-price-cust{font-family:var(--font-display);font-weight:700;font-size:30px}
.pt-tag{font-size:12.5px;color:var(--tx-1);line-height:1.5;margin:6px 0 16px;min-height:54px}
.pt-feats{list-style:none;margin:18px 0 0;padding:18px 0 0;border-top:1px solid var(--line);display:flex;flex-direction:column;gap:10px}
.pt-feats li{display:flex;align-items:flex-start;gap:9px;font-size:12.5px;color:var(--tx-1);line-height:1.4}
.pt-note{max-width:820px;margin:16px auto 0;text-align:center;font-size:12px;line-height:1.6}

.pt-fm-wrap{margin-top:26px;overflow:hidden}
.pt-fm-toggle{width:100%;display:flex;align-items:center;justify-content:space-between;gap:14px;background:none;border:none;
  color:var(--tx-0);font-family:var(--font-ui);font-size:14.5px;padding:18px 22px;cursor:pointer;text-align:left}
.pt-fm-toggle b{font-weight:700}
.pt-fm-chev{color:var(--tx-2);transition:.25s;flex:none}
.pt-fm-scroll{overflow-x:auto;border-top:1px solid var(--line)}
.pt-fm{width:100%;border-collapse:collapse;font-size:13px;min-width:720px}
.pt-fm th{font-family:var(--font-mono);font-size:10.5px;letter-spacing:.05em;text-transform:uppercase;color:var(--tx-2);
  font-weight:700;text-align:center;padding:14px 10px;border-bottom:1px solid var(--line);white-space:nowrap}
.pt-fm th.pt-fm-feat{text-align:left;min-width:280px}
.pt-fm th.pt-fm-pop,.pt-fm td.pt-fm-pop{background:rgba(226,79,214,.07)}
.pt-fm th.pt-fm-pop{color:var(--magenta)}
.pt-fm td{padding:11px 10px;border-bottom:1px solid var(--line);text-align:center;vertical-align:middle}
.pt-fm td.pt-fm-feat{text-align:left}
.pt-fm-name{font-weight:600;color:var(--tx-0);font-size:13px}
.pt-fm-desc{color:var(--tx-3);font-size:11px;margin-top:2px;line-height:1.4}
.pt-fm-cat td{padding:16px 10px 7px;border-bottom:none;font-family:var(--font-mono);font-size:10px;letter-spacing:.09em;
  text-transform:uppercase;color:var(--cyan);font-weight:700}
.pt-fm-no{color:var(--tx-3)}

.pt-chip{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:var(--tx-1);background:rgba(255,255,255,.04);
  border:1px solid var(--line-2);border-radius:8px;padding:6px 10px}

.pr-ent{position:relative;overflow:hidden;margin-top:26px;border-radius:var(--r-xl);border:1px solid var(--line-2);background:linear-gradient(120deg,#11141f,#161020)}
.pr-ent .aurora-bg{opacity:.3}
.pr-ent-in{position:relative;display:flex;gap:28px;align-items:center;justify-content:space-between;padding:30px;flex-wrap:wrap}
.pr-ent-feats{display:flex;flex-wrap:wrap;gap:8px;max-width:640px}

.pr-faq{max-width:760px;margin:44px auto 0}
.pr-q{border:1px solid var(--line);border-radius:12px;margin-bottom:10px;background:var(--bg-2);overflow:hidden;transition:.2s}
.pr-q.open{border-color:var(--line-2)}
.pr-q-head{width:100%;display:flex;align-items:center;justify-content:space-between;gap:14px;background:none;border:none;color:var(--tx-0);font-family:var(--font-ui);font-weight:600;font-size:14.5px;text-align:left;padding:16px 18px;cursor:pointer}
.pr-q-chev{color:var(--tx-2);transition:.25s;flex:none}
.pr-q.open .pr-q-chev{transform:rotate(180deg);color:var(--cyan)}
.pr-q-body{max-height:0;overflow:hidden;transition:max-height .3s ease}
.pr-q.open .pr-q-body{max-height:320px}
.pr-q-body p{margin:0;padding:0 18px 16px;color:var(--tx-1);font-size:13.5px;line-height:1.65}

@media(max-width:980px){.pt-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:880px){
  .pr-ent-in{flex-direction:column;align-items:flex-start}
  .pt-tag,.pt-price{min-height:0}
}
@media(max-width:520px){.pt-grid{grid-template-columns:1fr}}
`}</style>;
}

window.PricingSection=PricingSection;
