/* ============================================================
   NeuroRoute — Landing: Features grid + interactive How-It-Works
   Globals used: Icon, Badge, ProviderLogo, COL, useState, useEffect, useRef
   ============================================================ */
const LD = window.DATA;

/* =====================  FEATURES  ===================== */
function FeaturesSection(){
  const cards=[
    {ic:'route', c:'blue', t:'The Right Model for Every Task',
      d:'Not every query needs your most expensive model. A factual question, a short summary, a formatting task — these don\u2019t need GPT-4o. NeuroRoute analyzes each request in under 2 ms and routes it to the model that delivers the same quality for far less. You set the quality bar; we find the cheapest model that clears it.',
      viz:'tasks'},
    {ic:'trenddown', c:'green', t:'See Exactly What You\u2019re Saving',
      d:'Every request shows what it actually cost, what GPT-4o would have charged, and how much you saved. No black boxes, no trust-us pricing. A real-time running total — most teams see 60\u201380% savings in the first week. Export it, audit every line item, share with your CFO.',
      viz:'savings'},
    {ic:'key', c:'cyan', t:'Your Keys, Your Control',
      d:'Bring your own keys from any provider. You pay providers directly at published rates — NeuroRoute never touches your money or your data. We earn only a small share of the savings we create. If we don\u2019t save you money, we don\u2019t get paid. Incentives perfectly aligned.',
      viz:'providers'},
    {ic:'link', c:'purple', t:'Drop-In Compatible',
      d:'Change one line — swap your OpenAI base URL to NeuroRoute\u2019s endpoint. Same API format, same SDKs, same streaming. Your existing code works instantly. No migration, no refactoring, no new SDKs. If you can call OpenAI today, you can use NeuroRoute in 5 minutes.',
      viz:'code'},
    {ic:'shield', c:'amber', t:'Enterprise-Grade Security',
      d:'PII detection scans every request before it reaches a model and keeps sensitive data on self-hosted models only. HMAC request signing prevents tampering. AES-256 encryption for stored keys. Per-org isolation, role-based access control, and a full audit trail of every action.',
      viz:'security'},
    {ic:'sparkles', c:'magenta', t:'Gets Smarter Over Time',
      d:'Rate any response \ud83d\udc4d / \ud83d\udc4e and NeuroRoute learns which models perform best for your workload — not generic benchmarks. A legal firm\u2019s \u201cquality\u201d differs from a startup\u2019s. After a few hundred requests, routing is personalized to your actual usage. The longer you use it, the more you save.',
      viz:'learning'},
  ];
  return (
    <section id="features" className="lp-sec">
      <FeatureVizStyles/>
      <div className="lp-head">
        <div className="eyebrow">WHY NEUROROUTE</div>
        <h2 className="display lp-h2">Stop overpaying for AI.<br/>Start routing <span className="route-text">intelligently.</span></h2>
        <p className="lp-p">Most teams send every request to GPT-4o or Claude Opus — even simple lookups a model 10× cheaper handles perfectly. NeuroRoute fixes this automatically.</p>
      </div>
      <div className="feat6">
        {cards.map(f=>(
          <div key={f.t} className="card card-pad card-hover feat6-card">
            <div className="m-ico" style={{background:`var(--${f.c}-t)`,color:`var(--${f.c})`,width:44,height:44,borderRadius:12}}><Icon name={f.ic} size={22}/></div>
            <h3 style={{fontSize:16.5,margin:'15px 0 8px'}}>{f.t}</h3>
            <p className="muted" style={{fontSize:13.5,margin:0,lineHeight:1.6}}>{f.d}</p>
            <div className="feat6-viz"><FeatViz kind={f.viz} color={f.c}/></div>
          </div>
        ))}
      </div>
    </section>
  );
}

function FeatViz({kind, color}){
  if(kind==='tasks') return (
    <div className="fv-tasks">
      {[['Simple Q','Gemini Flash','cyan'],['Complex','GPT-4o','blue'],['Code','GPT-4.1','purple']].map(([a,b,c])=>(
        <div key={a} className="fv-row"><span className="fv-pill">{a}</span><Icon name="arrowright" size={13} style={{color:'var(--tx-3)'}}/><span className={'fv-pill fv-'+c}>{b}</span></div>
      ))}
    </div>
  );
  if(kind==='savings') return (
    <div className="fv-save">
      <div><div className="fv-k">Your cost</div><div className="mono fv-good">$0.0008</div></div>
      <div><div className="fv-k">GPT-4o</div><div className="mono fv-bad" style={{textDecoration:'line-through'}}>$0.0089</div></div>
      <div><div className="fv-k">Saved</div><div className="mono route-text" style={{fontWeight:700}}>$0.0081</div></div>
    </div>
  );
  if(kind==='providers') return (
    <div className="row" style={{gap:8,flexWrap:'wrap'}}>
      {['openai','anthropic','google','groq','xai','mistral'].map(p=><ProviderLogo key={p} id={p} size={30}/>)}
    </div>
  );
  if(kind==='code') return (
    <div className="fv-code mono">
      <span className="tok-com">base_url=</span><span className="tok-str">"…neuroroute.ai/v1"</span>
      <Icon name="checkcircle" size={15} style={{color:'var(--green)',marginLeft:'auto',flex:'none'}}/>
    </div>
  );
  if(kind==='security') return (
    <div className="fv-sec">
      {['PII detection','HMAC signing','AES-256 at rest','RBAC + audit log'].map(s=>(
        <span key={s} className="fv-check"><Icon name="check" size={12} style={{color:'var(--green)'}}/>{s}</span>
      ))}
    </div>
  );
  if(kind==='learning') return (
    <div className="fv-learn">
      {[34,42,40,52,58,66,72,80].map((h,i)=><span key={i} style={{height:h+'%',background:i>4?'var(--magenta)':'var(--bg-3)'}}/>)}
      <span className="fv-learn-cap mono">quality ↑ over time</span>
    </div>
  );
  return null;
}

/* =====================  HOW IT WORKS — interactive  ===================== */
const HOW_QUERIES=[
  {id:'quick', ic:'info', label:'Quick Question', prompt:'What is the capital of France?',
    task:'Factual QA', conf:97, winner:'gemini-flash', cost:0.0001, base:0.0052, pct:98,
    why:'Simple factual lookup \u2014 a lightweight model handles this perfectly at ~30\u00d7 lower cost.',
    cands:[['gemini-flash',96],['gpt-4o-mini',88],['llama-70b',74],['claude-sonnet-4',70],['gpt-4o',64]]},
  {id:'code', ic:'code', label:'Write Code', prompt:'Write a Python function to sort a list of dicts by a key',
    task:'Code Generation', conf:94, winner:'gpt-4.1', cost:0.0044, base:0.0089, pct:51,
    why:'Code generation needs strong reasoning \u2014 routed to a code-specialized model at a 92% quality score.',
    cands:[['gpt-4.1',93],['claude-sonnet-4',90],['gpt-4o',88],['gemini-flash',72],['llama-70b',68]]},
  {id:'creative', ic:'sparkles', label:'Creative Writing', prompt:'Write a compelling product description for wireless headphones',
    task:'Creative', conf:91, winner:'claude-sonnet-4', cost:0.0031, base:0.0089, pct:65,
    why:'Creative tasks benefit from Claude\u2019s nuanced writing \u2014 best quality at moderate cost.',
    cands:[['claude-sonnet-4',94],['gpt-4o',90],['gpt-4.1',86],['gemini-flash',76],['gpt-4o-mini',70]]},
  {id:'analysis', ic:'analytics', label:'Data Analysis', prompt:'Analyze this sales data and identify the top 3 trends',
    task:'Analysis', conf:89, winner:'claude-sonnet-4', cost:0.0031, base:0.0089, pct:65,
    why:'Analytical tasks need structured reasoning \u2014 balanced cost and capability.',
    cands:[['claude-sonnet-4',92],['gemini-pro',90],['gpt-4o',89],['gemini-flash',74],['gpt-4o-mini',66]]},
  {id:'reasoning', ic:'cpu', label:'Complex Reasoning', prompt:'Compare microservices vs monolith for a fintech startup',
    task:'Deep Reasoning', conf:88, winner:'gpt-4o', cost:0.0089, base:0.0089, pct:0,
    why:'Deep reasoning required \u2014 a premium model is justified. No savings here, but this is only ~8% of typical traffic.',
    cands:[['gpt-4o',95],['claude-sonnet-4',94],['gpt-4.1',93],['gemini-pro',88],['gpt-4o-mini',60]]},
  {id:'summarize', ic:'doc', label:'Summarize Text', prompt:'Summarize this 2000-word article into 3 bullet points',
    task:'Summarization', conf:95, winner:'gpt-4o-mini', cost:0.0002, base:0.0089, pct:98,
    why:'Summarization is well-solved \u2014 the cheapest capable model delivers identical quality.',
    cands:[['gpt-4o-mini',91],['gemini-flash',89],['llama-70b',78],['claude-sonnet-4',72],['gpt-4o',66]]},
];

function HowItWorksDemo(){
  const [sel,setSel]=useState(HOW_QUERIES[0]);
  const [phase,setPhase]=useState(0);          // 0 analyzing,1 scoring,2 selecting,3 done
  const [explored,setExplored]=useState(()=>new Set([HOW_QUERIES[0].id]));
  const timers=useRef([]);
  const run=(q)=>{
    timers.current.forEach(clearTimeout); timers.current=[];
    setSel(q); setPhase(0);
    setExplored(e=>new Set([...e,q.id]));
    timers.current.push(setTimeout(()=>setPhase(1),380));
    timers.current.push(setTimeout(()=>setPhase(2),1050));
    timers.current.push(setTimeout(()=>setPhase(3),1450));
  };
  useEffect(()=>{ run(HOW_QUERIES[0]); return ()=>timers.current.forEach(clearTimeout); },[]);
  const m=LD.modelById(sel.winner);
  const x=(n)=>'$'+(n*10000).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2});
  const phaseLabels=['Analyzing request','Scoring models','Selecting winner','Request routed'];
  return (
    <section id="how" className="lp-sec how-sec">
      <HowStyles/>
      <div className="aurora-bg dim"><span/><span/></div>
      <div className="lp-head" style={{position:'relative'}}>
        <div className="eyebrow">HOW IT WORKS</div>
        <h2 className="display lp-h2">See it in action</h2>
        <p className="lp-p">Pick a task. Watch NeuroRoute choose the optimal model in real time.</p>
      </div>

      <div className="how-grid">
        {/* LEFT: query selector */}
        <div className="how-col">
          <div className="how-col-h">Choose your query</div>
          <div className="how-queries">
            {HOW_QUERIES.map(q=>(
              <button key={q.id} className={'how-q'+(sel.id===q.id?' on':'')} onClick={()=>run(q)}>
                <span className="how-q-ic"><Icon name={q.ic} size={16}/></span>
                <span><span className="how-q-label">{q.label}</span><span className="how-q-prompt">{q.prompt}</span></span>
              </button>
            ))}
          </div>
        </div>

        {/* MIDDLE: pipeline */}
        <div className="how-col">
          <div className="how-col-h">NeuroRoute decides</div>
          <div className="how-pipe">
            {/* step 1 classify */}
            <div className={'how-step'+(phase>=0?' lit':'')}>
              <div className="how-step-top"><span className="how-step-n">1</span>{phaseLabels[0]}</div>
              {phase>=0 && <div className="how-class"><Badge color="blue">{sel.task}</Badge><span className="mono faint" style={{fontSize:11}}>{sel.conf}% confidence</span></div>}
            </div>
            {/* step 2 score */}
            <div className={'how-step'+(phase>=1?' lit':'')}>
              <div className="how-step-top"><span className="how-step-n">2</span>{phaseLabels[1]}</div>
              <div className="how-cands">
                {sel.cands.map(([id,score],i)=>{
                  const win=phase>=2 && id===sel.winner;
                  const dim=phase>=2 && id!==sel.winner;
                  return (
                    <div key={id} className={'how-cand'+(win?' win':'')+(dim?' dim':'')}>
                      <span className="how-cand-name"><ProviderLogo id={LD.modelById(id).provider} size={18}/>{LD.modelById(id).name}</span>
                      <span className="how-bar"><i style={{width:(phase>=1?score:0)+'%',background:win?COL.green:COL.blue,transitionDelay:(i*70)+'ms'}}/></span>
                      {win && <Icon name="check" size={14} style={{color:'var(--green)',flex:'none'}}/>}
                    </div>
                  );
                })}
              </div>
            </div>
            {/* step 3/4 routed */}
            <div className={'how-step'+(phase>=3?' lit':'')}>
              <div className="how-step-top"><span className="how-step-n">3</span>{phase>=3?phaseLabels[3]:phaseLabels[2]}</div>
              {phase>=3 && <div className="how-routed"><Icon name="route" size={15} style={{color:'var(--cyan)'}}/><span>Routed to <b style={{color:'#fff'}}>{m.name}</b></span><span className="how-arrow"/></div>}
            </div>
          </div>
        </div>

        {/* RIGHT: result */}
        <div className="how-col">
          <div className="how-col-h">The result</div>
          {phase>=3 ? (
            <div className="how-result">
              <div className="how-res-model">
                <ProviderLogo id={m.provider} size={36}/>
                <div><div style={{fontWeight:700,fontSize:15}}>{m.name}</div><div className="faint mono" style={{fontSize:11.5}}>{LD.providerById(m.provider).name}</div></div>
                <Badge color="green" style={{marginLeft:'auto'}}>Quality {m.q}% ✓</Badge>
              </div>
              <div className="how-costs">
                <div className="spread"><span className="faint">Your cost</span><span className="mono how-good">${sel.cost.toFixed(4)}</span></div>
                <div className="spread"><span className="faint">GPT-4o would cost</span><span className="mono how-bad" style={{textDecoration:'line-through'}}>${sel.base.toFixed(4)}</span></div>
                <div className="spread how-saved"><span style={{fontWeight:700}}>You saved</span><span className="display route-text" style={{fontSize:20}}>{sel.pct}%</span></div>
              </div>
              <div className="how-why"><span className="how-why-k">Why this model?</span>{sel.why}</div>
              <div className="how-tally">
                <div className="faint" style={{fontSize:12,marginBottom:8}}>If you sent 10,000 of these per month:</div>
                <div className="spread" style={{fontSize:13}}><span>Without NeuroRoute</span><span className="mono how-bad">{x(sel.base)}</span></div>
                <div className="spread" style={{fontSize:13,marginTop:5}}><span>With NeuroRoute</span><span className="mono how-good">{x(sel.cost)}</span></div>
                <div className="how-tally-save">You'd save {x(sel.base-sel.cost)}/mo {sel.pct>0?`(${sel.pct}%)`:''}</div>
              </div>
            </div>
          ) : (
            <div className="how-result how-thinking">
              <div className="how-spinner"/>
              <div className="faint">{phaseLabels[Math.min(phase,2)]}…</div>
            </div>
          )}
        </div>
      </div>

      {/* honesty note + summary */}
      <div className="how-foot">
        <div className="how-note"><Icon name="info" size={15} style={{color:'var(--tx-2)',flex:'none'}}/>In a typical workload only 5–10% of queries need premium models. The other 90% is where the savings stack up.</div>
        <div className={'how-summary'+(explored.size>=6?' all':'')}>
          <span className="faint" style={{fontSize:12.5}}>Across a typical mix of these queries</span>
          <span className="display route-text" style={{fontSize:24}}>Average savings: 72%</span>
          <span className="mono faint" style={{fontSize:11}}>{explored.size}/6 explored</span>
        </div>
      </div>
    </section>
  );
}

function FeatureVizStyles(){
  return <style>{`
.feat6{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}
.feat6-card{display:flex;flex-direction:column}
.feat6-viz{margin-top:auto;padding-top:16px;border-top:1px solid var(--line);margin-top:18px}
.fv-tasks{display:flex;flex-direction:column;gap:8px}
.fv-row{display:flex;align-items:center;gap:9px}
.fv-pill{font-family:var(--font-mono);font-size:11px;padding:4px 9px;border-radius:7px;background:var(--bg-3);border:1px solid var(--line-2);color:var(--tx-1);white-space:nowrap}
.fv-cyan{background:var(--cyan-t);color:#5fe2f5;border-color:rgba(34,211,238,.3)}
.fv-blue{background:var(--blue-t);color:#7db0ff;border-color:rgba(59,130,246,.3)}
.fv-purple{background:var(--purple-t);color:#b095fb;border-color:rgba(139,92,246,.3)}
.fv-save{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}
.fv-k{font-size:10.5px;color:var(--tx-2);margin-bottom:3px}
.fv-good{color:#43d6a3;font-size:13px}.fv-bad{color:#ff8095;font-size:13px}
.fv-code{display:flex;align-items:center;gap:6px;font-size:11.5px;background:var(--bg-inset);border:1px solid var(--line-2);border-radius:8px;padding:9px 11px;overflow:hidden}
.fv-code .tok-com{color:var(--tx-2)}.fv-code .tok-str{color:#43d6a3}
.fv-sec{display:flex;flex-wrap:wrap;gap:7px}
.fv-check{display:inline-flex;align-items:center;gap:5px;font-size:11px;color:var(--tx-1);background:var(--bg-3);border:1px solid var(--line);border-radius:7px;padding:4px 8px}
.fv-learn{display:flex;align-items:flex-end;gap:5px;height:48px;position:relative}
.fv-learn>span{flex:1;border-radius:3px 3px 0 0;transition:.3s}
.fv-learn-cap{position:absolute;right:0;top:-4px;font-size:9.5px;color:var(--magenta)}
@media(max-width:860px){.feat6{grid-template-columns:1fr}}
`}</style>;
}

function HowStyles(){
  return <style>{`
.how-sec{position:relative;overflow:hidden;border-top:1px solid var(--line);border-bottom:1px solid var(--line);background:var(--bg-0)}
.how-sec .aurora-bg{opacity:.32}
.how-grid{display:grid;grid-template-columns:1fr 1.15fr 1fr;gap:18px;position:relative;align-items:stretch}
.how-col{display:flex;flex-direction:column;gap:12px}
.how-col-h{font-family:var(--font-mono);font-size:10.5px;letter-spacing:.14em;text-transform:uppercase;color:var(--tx-2)}
.how-queries{display:flex;flex-direction:column;gap:8px}
.how-q{display:flex;align-items:flex-start;gap:11px;text-align:left;background:var(--bg-2);border:1px solid var(--line);border-radius:12px;padding:12px 13px;cursor:pointer;transition:.15s;color:var(--tx-1)}
.how-q:hover{border-color:var(--line-strong);background:var(--bg-3)}
.how-q.on{border-color:var(--blue);box-shadow:0 0 0 3px rgba(59,130,246,.18);background:linear-gradient(120deg,rgba(59,130,246,.1),rgba(226,79,214,.04))}
.how-q-ic{width:30px;height:30px;border-radius:8px;display:grid;place-items:center;flex:none;background:var(--bg-3);color:var(--cyan);border:1px solid var(--line-2)}
.how-q.on .how-q-ic{background:var(--blue-t);color:#7db0ff}
.how-q-label{display:block;font-weight:700;font-size:13.5px;color:var(--tx-0)}
.how-q-prompt{display:block;font-size:11.5px;color:var(--tx-2);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px}

.how-pipe{display:flex;flex-direction:column;gap:10px;flex:1}
.how-step{background:var(--bg-2);border:1px solid var(--line);border-radius:12px;padding:13px 14px;opacity:.45;transition:.35s;transform:translateY(4px)}
.how-step.lit{opacity:1;transform:none;border-color:var(--line-2)}
.how-step-top{display:flex;align-items:center;gap:9px;font-size:12.5px;font-weight:600;color:var(--tx-1)}
.how-step-n{width:20px;height:20px;border-radius:6px;background:var(--bg-3);border:1px solid var(--line-2);display:grid;place-items:center;font-size:11px;font-family:var(--font-mono);color:var(--tx-2)}
.how-step.lit .how-step-n{background:var(--blue-t);color:#7db0ff;border-color:rgba(59,130,246,.4)}
.how-class{display:flex;align-items:center;gap:10px;margin-top:10px}
.how-cands{display:flex;flex-direction:column;gap:7px;margin-top:10px}
.how-cand{display:flex;align-items:center;gap:9px;transition:.3s;opacity:1}
.how-cand.dim{opacity:.4}
.how-cand-name{display:flex;align-items:center;gap:7px;font-size:11.5px;font-weight:600;color:var(--tx-1);width:118px;flex:none;white-space:nowrap;overflow:hidden}
.how-cand.win .how-cand-name{color:#fff}
.how-bar{flex:1;height:7px;border-radius:99px;background:var(--bg-inset);overflow:hidden}
.how-bar i{display:block;height:100%;width:0;border-radius:99px;transition:width .6s cubic-bezier(.3,.9,.3,1)}
.how-routed{display:flex;align-items:center;gap:9px;margin-top:10px;font-size:12.5px;color:var(--tx-1);animation:fade .4s}
.how-arrow{flex:1;height:2px;background:linear-gradient(90deg,var(--cyan),transparent);border-radius:99px;position:relative}

.how-result{background:var(--bg-2);border:1px solid var(--line-2);border-radius:14px;padding:16px;flex:1;display:flex;flex-direction:column;gap:14px;animation:fade .4s}
.how-thinking{align-items:center;justify-content:center;gap:16px;color:var(--tx-2)}
.how-spinner{width:34px;height:34px;border-radius:50%;border:3px solid var(--bg-3);border-top-color:var(--blue);animation:spin .8s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
.how-res-model{display:flex;align-items:center;gap:11px}
.how-costs{display:flex;flex-direction:column;gap:9px;background:var(--bg-inset);border:1px solid var(--line);border-radius:10px;padding:13px}
.how-good{color:#43d6a3}.how-bad{color:#ff8095}
.how-saved{border-top:1px solid var(--line);padding-top:10px;margin-top:2px}
.how-why{font-size:12.5px;color:var(--tx-1);line-height:1.55;background:var(--bg-inset);border:1px solid var(--line);border-radius:10px;padding:12px}
.how-why-k{display:block;font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--tx-2);margin-bottom:5px;font-family:var(--font-mono)}
.how-tally{border-top:1px solid var(--line);padding-top:13px}
.how-tally-save{margin-top:10px;text-align:center;font-weight:700;font-size:13.5px;color:#43d6a3;background:var(--green-t);border:1px solid rgba(16,185,129,.3);border-radius:9px;padding:8px}

.how-foot{display:grid;grid-template-columns:1.4fr 1fr;gap:18px;margin-top:22px;position:relative;align-items:center}
.how-note{display:flex;gap:10px;font-size:13px;color:var(--tx-1);line-height:1.55;background:var(--bg-2);border:1px solid var(--line);border-radius:12px;padding:14px 16px}
.how-summary{display:flex;flex-direction:column;align-items:flex-end;gap:2px;text-align:right;border-radius:12px;padding:14px 16px;border:1px solid var(--line-2);background:var(--bg-2);transition:.3s}
.how-summary.all{border-color:rgba(226,79,214,.4);box-shadow:0 0 0 3px rgba(226,79,214,.12)}
@media(max-width:920px){.how-grid{grid-template-columns:1fr}.how-foot{grid-template-columns:1fr}.how-summary{align-items:flex-start;text-align:left}.how-q-prompt{max-width:none;white-space:normal}}
`}</style>;
}

window.FeaturesSection=FeaturesSection;
window.HowItWorksDemo=HowItWorksDemo;
