/* global React, Glyph, Star */
const { useState:useSh, useMemo:useShM, useEffect:useShE } = React;

/* ============================================================
   AETHER EXCHANGE — marketplace of next-decade AI products
   ============================================================ */
const PRODUCTS=[
  { id:'capsules', name:'Cognitive Capsules', icon:'brain', cat:'Reasoning', price:2400, unit:'/capsule',
    tagline:'Download a new way of thinking.',
    desc:'Small AI modules that teach an LLM a specialized reasoning capability \u2014 clinical reasoning, legal argumentation, scientific hypothesis generation \u2014 without replacing the whole model.',
    examples:['Clinical Reasoning','Legal Argumentation','Hypothesis Generation','Financial Modeling'],
    specs:['Hot-swappable at inference','Model-agnostic adapter','No retraining required','48ms load overhead'], v:'v2035.4' },
  { id:'vecdna', name:'Vector DNA Packs', icon:'dna2', cat:'Retrieval', price:1800, unit:'/pack',
    tagline:'Curated embedding spaces, domain-perfect.',
    desc:'Embedding spaces trained for narrow domains \u2014 oncology, aerospace, finance \u2014 that dramatically improve retrieval quality for RAG systems.',
    examples:['Oncology','Aerospace','Finance','Genomics'],
    specs:['3072-dim tuned space','+41% retrieval precision','Drop-in for any RAG stack','Quarterly re-training'], v:'v2035.1' },
  { id:'catalysts', name:'Neural Catalysts', icon:'spark', cat:'Optimization', price:1200, unit:'/license',
    tagline:'Performance-enhancing software for AI.',
    desc:'Optimization packages that automatically improve prompts, workflows, latency, and token efficiency across your AI applications.',
    examples:['Prompt Compiler','Latency Reducer','Token Economizer','Workflow Tuner'],
    specs:['Up to 6x token savings','Autonomous prompt rewriting','Live A/B under the hood','Zero-downtime deploy'], v:'v2036.0' },
  { id:'genomes', name:'Agent Genomes', icon:'network', cat:'Agents', price:5600, unit:'/species',
    tagline:'Buy an entire species of AI agents.',
    desc:'Prebuilt multi-agent architectures with defined communication patterns, memory systems, and decision policies \u2014 ready to deploy.',
    examples:['Research Swarm','Trading Desk','Ops Command','Discovery Lab'],
    specs:['Defined comms topology','Shared memory fabric','Policy-governed autonomy','Self-healing roster'], v:'v2035.7' },
  { id:'memory', name:'Synthetic Memory Libraries', icon:'layers', cat:'Memory', price:3200, unit:'/library',
    tagline:'Persistent long-term memory, plug-and-play.',
    desc:'Long-term memory modules any AI system can plug into \u2014 durable, queryable, and portable across models.',
    examples:['Founder Memory','Research Memory','Medical Memory','Enterprise Memory'],
    specs:['Infinite context tier','Cross-model portable','Encrypted at rest','Temporal recall API'], v:'v2035.9' },
  { id:'molecules', name:'Intelligence Molecules', icon:'cell', cat:'Reasoning', price:600, unit:'/molecule',
    tagline:'Reasoning components you combine like LEGO.',
    desc:'Small, reusable reasoning components developers snap together to compose sophisticated cognition.',
    examples:['Contradiction Detector','Bias Detector','Scientific Validator','Creativity Amplifier','Strategic Planner'],
    specs:['Composable interface','< 20ms per call','Chain or parallelize','Fully typed I/O'], v:'v2036.2' },
  { id:'antibodies', name:'Digital Antibodies', icon:'shield', cat:'Security', price:2800, unit:'/suite',
    tagline:'Immune defense for AI systems.',
    desc:'Security modules that detect hallucinations, prompt injection, data poisoning, and unsafe outputs before they ever reach the user.',
    examples:['Hallucination Guard','Injection Firewall','Poison Detector','Output Sentinel'],
    specs:['Pre-response interception','99.3% injection catch','Continuous threat updates','Audit-grade logging'], v:'v2036.1' },
  { id:'evolution', name:'Evolution Engines', icon:'orbit', cat:'Optimization', price:4400, unit:'/engine',
    tagline:'Autonomous, self-improving optimization.',
    desc:'Software that continuously tests thousands of prompt, workflow, and agent variants \u2014 automatically keeping the best-performing versions.',
    examples:['Prompt Evolver','Workflow Selector','Agent Breeder','Fitness Tracker'],
    specs:['10k variants / cycle','Survival-of-the-fittest loop','Auto-rollback on regress','Fitness dashboards'], v:'v2035.5' },
  { id:'reality', name:'Reality Simulators', icon:'globe', cat:'Simulation', price:8800, unit:'/world',
    tagline:'Test decisions before you make them.',
    desc:'Simulation engines that let companies test decisions against synthetic customers, markets, or biological systems before acting in the real world.',
    examples:['Synthetic Customers','Market Twin','Biological Sandbox','Policy Wind-Tunnel'],
    specs:['Monte-Carlo at scale','Calibrated to real data','Counterfactual replay','Confidence intervals'], v:'v2036.3' },
];
const SHOP_CATS=['All','Reasoning','Retrieval','Optimization','Agents','Memory','Security','Simulation'];

/* ---- ratings (deterministic per product) ---- */
const REVIEW_AUTHORS=['R. Sethi','M. Okonkwo','K. Lindqvist','E. Voss','A. Turing Lab','Dr. N. Patel','Helix Bio','Northwind AI'];
const REVIEW_TEXT=[
  'Cut our integration time from months to a single afternoon.',
  'The retrieval precision gain was immediately measurable in production.',
  'Deployed across three teams. Zero regressions, meaningful speedups.',
  'Genuinely feels a decade ahead of anything else we evaluated.',
  'Documentation and the package spec are exemplary.',
  'Paid for itself within the first billing cycle.',
];
function prodStats(p){
  const h=Math.abs(hash(p.id));
  const rating=(4.3+((h%7)/10)).toFixed(1);
  const reviews=120+(h%880);
  const installs=(2+(h%48))+'.'+(h%9)+'k';
  const revs=[0,1,2].map(i=>({
    who:REVIEW_AUTHORS[(h+i*3)%REVIEW_AUTHORS.length],
    txt:REVIEW_TEXT[(h+i*5)%REVIEW_TEXT.length],
    stars:5-((h+i)%2) }));
  return { rating, reviews, installs, revs };
}
function Stars({ n }){
  return React.createElement('span',{className:'px-stars'},
    [1,2,3,4,5].map(i=>React.createElement('span',{key:i,className:`px-star ${i<=Math.round(n)?'on':''}`},'\u2605')));
}

/* ---- bundles ---- */
const BUNDLES=[
  { id:'b-founder', name:'Founder Stack', ids:['capsules','catalysts','memory'], off:.25,
    d:'Everything a small team needs to ship intelligent product fast.' },
  { id:'b-research', name:'Research Stack', ids:['vecdna','molecules','reality'], off:.3,
    d:'Discovery-grade retrieval, reasoning, and simulation in one bundle.' },
  { id:'b-enterprise', name:'Enterprise Defense', ids:['antibodies','genomes','evolution'], off:.28,
    d:'Hardened agents, continuous optimization, and full-spectrum AI security.' },
];

function money(n){ return '$'+n.toLocaleString('en-US'); }

/* build a downloadable, "fully functional" product package (manifest + starter) */
function downloadProduct(p){
  const manifest={
    product:p.name, version:p.v, tagline:p.tagline, category:p.cat,
    price_usd:p.price+p.unit, issued:new Date().toISOString(), vendor:'AetherCore Labs \u00b7 Aether Exchange',
    description:p.desc, variants:p.examples, capabilities:p.specs,
    install:'aether install '+p.id+'@'+p.v,
    api:{ endpoint:'https://api.aethercore.labs/x/'+p.id, auth:'Bearer <ATHR_KEY>',
      example:'curl -X POST https://api.aethercore.labs/x/'+p.id+" -d '{\"input\":\"...\"}'" },
    license:'AetherCore Exchange Commercial License 2035', checksum:'sha256:'+Math.abs(hash(p.id+p.v)).toString(16).padStart(12,'0') };
  const readme=`AETHERCORE EXCHANGE \u2014 ${p.name} (${p.v})\n${'='.repeat(52)}\n\n${p.tagline}\n\n${p.desc}\n\nVARIANTS\n${p.examples.map(e=>'  \u2022 '+e).join('\n')}\n\nCAPABILITIES\n${p.specs.map(s=>'  \u2022 '+s).join('\n')}\n\nQUICKSTART\n  ${manifest.install}\n  ${manifest.api.example}\n\nLICENSE: ${manifest.license}\nPRICE: ${money(p.price)}${p.unit}\n\n\u00A9 2035 AetherCore Labs. Ten years ahead.\n`;
  const files=[
    { name:p.id+'.manifest.json', body:JSON.stringify(manifest,null,2) },
    { name:'README.txt', body:readme },
  ];
  // bundle both into one download as a .json wrapper (browser-only, no zip dep)
  const bundle=new Blob([JSON.stringify({ __aether_package:p.id, version:p.v, files },null,2)],{type:'application/json'});
  const url=URL.createObjectURL(bundle);
  const a=document.createElement('a'); a.href=url; a.download='aether-'+p.id+'-'+p.v+'.aetherpkg.json'; a.click();
  setTimeout(()=>URL.revokeObjectURL(url),1000);
  window.toast&&window.toast(p.name+' package downloaded \u00b7 '+p.v,'success');
}
function hash(s){ let h=0; for(let i=0;i<s.length;i++)h=(h*31+s.charCodeAt(i))|0; return h; }

/* ---- library of owned products (localStorage) ---- */
function ownedList(){ try{return JSON.parse(localStorage.getItem('aether_owned_v1'))||[]}catch(e){return[]} }
function acquire(p){
  const owned=ownedList(); if(!owned.includes(p.id)){ owned.push(p.id); try{localStorage.setItem('aether_owned_v1',JSON.stringify(owned));}catch(e){} }
  window.dispatchEvent(new CustomEvent('aether-owned'));
  downloadProduct(p);
}

/* ---- product card ---- */
function ProductCard({ p, owned, onOpen }){
  const st=prodStats(p);
  return React.createElement('div',{className:'px-card anim-up',onClick:()=>onOpen(p)},
    React.createElement('div',{className:'px-top'},
      React.createElement('span',{className:'px-ic'},React.createElement(Glyph,{name:p.icon,width:26,height:26})),
      React.createElement('span',{className:'px-ver'},p.v)),
    React.createElement('h3',{className:'px-name'},p.name),
    React.createElement('div',{className:'px-rate'},React.createElement(Stars,{n:st.rating}),
      React.createElement('span',{className:'px-rate-n'},st.rating),
      React.createElement('span',{className:'px-rate-c'},'('+st.reviews+')'),
      React.createElement('span',{className:'px-installs'},st.installs+' installs')),
    React.createElement('div',{className:'px-tag'},p.tagline),
    React.createElement('p',{className:'px-desc'},p.desc),
    React.createElement('div',{className:'px-vars'},p.examples.slice(0,3).map(e=>React.createElement('span',{key:e,className:'px-var'},e)),
      p.examples.length>3&&React.createElement('span',{className:'px-var more'},'+'+(p.examples.length-3))),
    React.createElement('div',{className:'px-foot'},
      React.createElement('span',{className:'px-price'},money(p.price),React.createElement('small',null,p.unit)),
      owned?React.createElement('span',{className:'px-owned'},React.createElement(Star,{size:11}),'OWNED')
        :React.createElement('span',{className:'px-cat'},p.cat)));
}

/* ---- product modal ---- */
function ProductModal({ p, owned, onClose }){
  if(!p) return null;
  return React.createElement('div',{className:'px-overlay',onMouseDown:onClose},
    React.createElement('div',{className:'px-modal',onMouseDown:e=>e.stopPropagation()},
      React.createElement('button',{className:'px-close',onClick:onClose},'\u00D7'),
      React.createElement('div',{className:'px-modal-head'},
        React.createElement('span',{className:'px-modal-ic'},React.createElement(Glyph,{name:p.icon,width:34,height:34})),
        React.createElement('div',null,
          React.createElement('div',{className:'px-modal-cat'},p.cat+' \u00b7 '+p.v),
          React.createElement('h2',{className:'px-modal-name'},p.name))),
      React.createElement('div',{className:'px-modal-tag'},p.tagline),
      React.createElement('p',{className:'px-modal-desc'},p.desc),
      React.createElement('div',{className:'px-modal-cols'},
        React.createElement('div',null,
          React.createElement('div',{className:'px-modal-lbl'},'Variants'),
          React.createElement('div',{className:'px-modal-list'},p.examples.map(e=>React.createElement('span',{key:e,className:'px-chip'},React.createElement(Star,{size:9}),e)))),
        React.createElement('div',null,
          React.createElement('div',{className:'px-modal-lbl'},'Capabilities'),
          React.createElement('div',{className:'px-modal-list col'},p.specs.map(s=>React.createElement('span',{key:s,className:'px-spec'},'\u2192 ',s))))),
      React.createElement('div',{className:'px-modal-foot'},
        React.createElement('div',{className:'px-modal-price'},money(p.price),React.createElement('small',null,p.unit)),
        React.createElement('div',{className:'px-modal-actions'},
          React.createElement('button',{className:'btn btn-ghost',onClick:()=>downloadProduct(p)},'Download spec'),
          React.createElement('button',{className:'btn btn-gold',onClick:()=>{acquire(p);onClose();}},owned?'Re-download':'Acquire & download'))),
      (()=>{ const st=prodStats(p); return React.createElement('div',{className:'px-reviews'},
        React.createElement('div',{className:'px-modal-lbl'},'Verified reviews \u00b7 ',st.rating,' \u2605 ('+st.reviews+')'),
        st.revs.map((r,i)=>React.createElement('div',{key:i,className:'px-review'},
          React.createElement('div',{className:'px-review-head'},
            React.createElement('span',{className:'px-review-who'},r.who),
            React.createElement(Stars,{n:r.stars})),
          React.createElement('p',{className:'px-review-txt'},r.txt)))); })()));
}

/* ---- submit idea form ---- */
function SubmitIdea(){
  const [name,setName]=useSh(''); const [tag,setTag]=useSh(''); const [desc,setDesc]=useSh(''); const [price,setPrice]=useSh('');
  const [sent,setSent]=useSh(false);
  const submit=(e)=>{ e.preventDefault(); if(name.trim().length<2||desc.trim().length<8) return;
    const body='NEW AETHER EXCHANGE PRODUCT PROPOSAL\n\nProduct: '+name+'\nTagline: '+tag+'\nSuggested price: '+price+'\n\nDescription:\n'+desc;
    window.location.href='mailto:kJOSHI2@bidmc.harvard.edu?subject='+encodeURIComponent('AETHERCORE LABS')+'&body='+encodeURIComponent(body);
    // stash locally too
    try{ const list=JSON.parse(localStorage.getItem('aether_ideas_v1'))||[]; list.unshift({name,tag,desc,price,at:Date.now()}); localStorage.setItem('aether_ideas_v1',JSON.stringify(list.slice(0,50))); }catch(e){}
    setSent(true); window.toast&&window.toast('Proposal submitted','success'); };
  if(sent) return React.createElement('div',{className:'idea-done'},React.createElement(Star,{size:16}),
    'Proposal sent. Our exchange team will review and price it.',
    React.createElement('button',{className:'btn btn-ghost',onClick:()=>{setSent(false);setName('');setTag('');setDesc('');setPrice('');}},'Submit another'));
  return React.createElement('form',{className:'idea-form',onSubmit:submit},
    React.createElement('div',{className:'idea-row'},
      React.createElement('input',{className:'idea-in',placeholder:'PRODUCT NAME',value:name,onChange:e=>setName(e.target.value)}),
      React.createElement('input',{className:'idea-in',placeholder:'SUGGESTED PRICE (E.G. $1,500/LICENSE)',value:price,onChange:e=>setPrice(e.target.value)})),
    React.createElement('input',{className:'idea-in full',placeholder:'ONE-LINE TAGLINE',value:tag,onChange:e=>setTag(e.target.value)}),
    React.createElement('textarea',{className:'idea-area',placeholder:'What does it do? Who is it for? What makes it ten years ahead?',value:desc,onChange:e=>setDesc(e.target.value)}),
    React.createElement('button',{type:'submit',className:'btn btn-gold'},'Submit to the Exchange',React.createElement(Glyph,{name:'arrow',width:16,height:16})));
}

/* ---- full shop view (dashboard) ---- */
function Marketplace(){
  const [cat,setCat]=useSh('All');
  const [modal,setModal]=useSh(null);
  const [owned,setOwned]=useSh(ownedList());
  const [q,setQ]=useSh('');
  const [sort,setSort]=useSh('featured');
  useShE(()=>{ const h=()=>setOwned(ownedList()); window.addEventListener('aether-owned',h); return ()=>window.removeEventListener('aether-owned',h); },[]);
  const list=useShM(()=>{
    let r=PRODUCTS.filter(p=>(cat==='All'||p.cat===cat)&&(!q.trim()||(p.name+p.desc+p.tagline).toLowerCase().includes(q.toLowerCase())));
    if(sort==='price-lo') r=[...r].sort((a,b)=>a.price-b.price);
    else if(sort==='price-hi') r=[...r].sort((a,b)=>b.price-a.price);
    else if(sort==='rating') r=[...r].sort((a,b)=>prodStats(b).rating-prodStats(a).rating);
    else if(sort==='name') r=[...r].sort((a,b)=>a.name.localeCompare(b.name));
    return r;
  },[cat,q,sort]);
  const ownedProds=PRODUCTS.filter(p=>owned.includes(p.id));
  return React.createElement('div',{className:'view'},
    React.createElement('div',{className:'lib-head anim-up'},
      React.createElement('span',{className:'kicker'},'Aether Exchange'),
      React.createElement('h1',{className:'display lib-title'},'The ',React.createElement('span',{className:'gild italic'},'marketplace.')),
      React.createElement('p',{className:'lib-lead'},'Next-decade AI products \u2014 fully specified, priced, and downloadable today. Acquire one, or propose your own.')),
    React.createElement('div',{className:'qstats anim-up',style:{animationDelay:'.05s',marginBottom:'22px'}},
      React.createElement('div',{className:'qstat'},React.createElement('span',{className:'qstat-n'},PRODUCTS.length),React.createElement('span',{className:'qstat-l'},'Products')),
      React.createElement('div',{className:'qstat'},React.createElement('span',{className:'qstat-n'},owned.length),React.createElement('span',{className:'qstat-l'},'Owned')),
      React.createElement('div',{className:'qstat'},React.createElement('span',{className:'qstat-n'},BUNDLES.length),React.createElement('span',{className:'qstat-l'},'Bundles')),
      React.createElement('div',{className:'qstat'},React.createElement('span',{className:'qstat-n'},'2035+'),React.createElement('span',{className:'qstat-l'},'Roadmap'))),
    ownedProds.length>0 && React.createElement('div',{className:'anim-up'},
      React.createElement('div',{className:'divlabel'},'MY LIBRARY'),
      React.createElement('div',{className:'lib-mine'},
        ownedProds.map(p=>React.createElement('button',{key:p.id,className:'lib-mine-item',onClick:()=>downloadProduct(p)},
          React.createElement('span',{className:'lib-mine-ic'},React.createElement(Glyph,{name:p.icon,width:18,height:18})),
          React.createElement('span',{className:'lib-mine-body'},
            React.createElement('span',{className:'lib-mine-n'},p.name),
            React.createElement('span',{className:'lib-mine-v'},p.v)),
          React.createElement('span',{className:'lib-mine-dl'},React.createElement(Glyph,{name:'arrowDown',width:15,height:15}))))),
      React.createElement('div',{className:'divlabel'},'BROWSE')),
    React.createElement('div',{className:'px-bundles anim-up'},
      BUNDLES.map(b=>{ const items=b.ids.map(id=>PRODUCTS.find(x=>x.id===id)); const full=items.reduce((s,x)=>s+x.price,0); const now=Math.round(full*(1-b.off));
        return React.createElement('div',{key:b.id,className:'bundle-card'},
          React.createElement('div',{className:'bundle-badge'},Math.round(b.off*100)+'% OFF'),
          React.createElement('div',{className:'bundle-name'},b.name),
          React.createElement('div',{className:'bundle-d'},b.d),
          React.createElement('div',{className:'bundle-items'},items.map(x=>React.createElement('span',{key:x.id,className:'bundle-chip'},
            React.createElement(Glyph,{name:x.icon,width:13,height:13}),x.name))),
          React.createElement('div',{className:'bundle-foot'},
            React.createElement('div',{className:'bundle-price'},React.createElement('span',{className:'bundle-was'},money(full)),money(now)),
            React.createElement('button',{className:'btn btn-gold bundle-btn',onClick:()=>{items.forEach(acquire);window.toast&&window.toast(b.name+' acquired','success');}},'Get bundle'))); })),
    React.createElement('div',{className:'lib-search anim-up',style:{animationDelay:'.06s'}},
      React.createElement(Glyph,{name:'search',width:20,height:20,className:'lib-search-ic'}),
      React.createElement('input',{className:'lib-input',placeholder:'Search products\u2026',value:q,onChange:e=>setQ(e.target.value)}),
      React.createElement('select',{className:'px-sort',value:sort,onChange:e=>setSort(e.target.value)},
        React.createElement('option',{value:'featured'},'Featured'),
        React.createElement('option',{value:'rating'},'Top rated'),
        React.createElement('option',{value:'price-lo'},'Price: low to high'),
        React.createElement('option',{value:'price-hi'},'Price: high to low'),
        React.createElement('option',{value:'name'},'Name A\u2013Z'))),
    React.createElement('div',{className:'lib-cats anim-up',style:{animationDelay:'.08s'}},
      SHOP_CATS.map(c=>React.createElement('button',{key:c,className:`lib-cat ${cat===c?'on':''}`,onClick:()=>setCat(c)},c.toUpperCase()))),
    React.createElement('div',{className:'px-grid'},
      list.length?list.map(p=>React.createElement(ProductCard,{key:p.id,p:p,owned:owned.includes(p.id),onOpen:setModal}))
        :React.createElement('div',{className:'lib-empty'},'No products match your search.')),
    React.createElement('div',{className:'divlabel'},'HAVE AN IDEA?'),
    React.createElement('div',{className:'idea-block'},
      React.createElement('div',{className:'idea-copy'},
        React.createElement('h3',{className:'idea-h'},'Propose a product'),
        React.createElement('p',null,'Submit a concept to the Aether Exchange. If it ships, you earn a share of every sale.')),
      React.createElement(SubmitIdea,null)),
    React.createElement(ProductModal,{p:modal,owned:modal&&owned.includes(modal.id),onClose:()=>setModal(null)}));
}

Object.assign(window,{ Marketplace, PRODUCTS, downloadProduct, HomeExchange:homeExchange });

/* ---- compact homepage section ---- */
function homeExchange(){
  const top=PRODUCTS.slice(0,6);
  return React.createElement('section',{className:'section marble veined grain exchange-sec',id:'exchange'},
    React.createElement('div',{className:'wrap'},
      React.createElement('div',{className:'eyebrow-row'},React.createElement(window.Reveal,{as:'span',className:'kicker center greek'},'Aether Exchange')),
      React.createElement(window.Reveal,{as:'h2',className:'display h-lg center greek',delay:80,style:{marginTop:'18px'}},
        'The marketplace ',React.createElement('span',{className:'gild italic'},'ten years ahead.')),
      React.createElement(window.Reveal,{as:'p',className:'serif-lead center mx-auto',delay:140,style:{maxWidth:'640px',marginTop:'20px'}},
        'Downloadable AI products from the next decade \u2014 cognitive capsules, agent genomes, reality simulators. Browse, acquire, or propose your own.'),
      React.createElement('div',{className:'exchange-grid'},
        top.map((p,i)=>React.createElement(window.Reveal,{key:p.id,className:'exchange-card',delay:60+i*60},
          React.createElement('span',{className:'exchange-ic'},React.createElement(Glyph,{name:p.icon,width:24,height:24})),
          React.createElement('div',{className:'exchange-name'},p.name),
          React.createElement('div',{className:'exchange-tag'},p.tagline),
          React.createElement('div',{className:'exchange-price'},money(p.price),React.createElement('small',null,p.unit))))),
      React.createElement(window.Reveal,{className:'center',delay:120,style:{marginTop:'44px'}},
        React.createElement('a',{className:'btn btn-gold',href:'AetherCore%20Dashboard.html'},'Enter the Exchange',
          React.createElement(Glyph,{name:'arrow',className:'arr',width:16,height:16})))));
}
