/* global React, RESEARCH, AGORA, CAREERS, Reveal, Star, Glyph, Magnetic, PLATFORMS */
const { useState:useStateR, useMemo:useMemoR, useEffect:useEffectR, useRef:useRefR } = React;

function hashNum(s){let h=0;for(let i=0;i<String(s).length;i++)h=(h*31+String(s).charCodeAt(i))>>>0;return h;}

const RSRC_COLOR={ 'PubMed':'#1a6fb5','Nature':'#0a8c3a','Europe PMC':'#7b4fbf','ClinicalTrials':'#b5321a',
  'NCBI Gene':'#1a6fb5','GeneCards':'#0a8c3a','Reactome':'#7b4fbf','KEGG':'#b5321a','DrugBank':'#0a8c3a','default':'#A8821B'};

function linksFor(tab, term){
  const q=encodeURIComponent(term);
  if(tab==='Genes') return [
    {src:'NCBI Gene', url:`https://www.ncbi.nlm.nih.gov/gene/?term=${q}`},
    {src:'GeneCards', url:`https://www.genecards.org/Search/Keyword?queryString=${q}`},
    {src:'PubMed', url:`https://pubmed.ncbi.nlm.nih.gov/?term=${q}&sort=date`} ];
  if(tab==='Pathways') return [
    {src:'Reactome', url:`https://reactome.org/content/query?q=${q}`},
    {src:'KEGG', url:`https://www.genome.jp/dbget-bin/www_bfind_sub?dbkey=pathway&keywords=${q}`},
    {src:'PubMed', url:`https://pubmed.ncbi.nlm.nih.gov/?term=${q}+pathway&sort=date`} ];
  if(tab==='Therapeutics') return [
    {src:'PubMed', url:`https://pubmed.ncbi.nlm.nih.gov/?term=${q}+therapy&sort=date`},
    {src:'ClinicalTrials', url:`https://clinicaltrials.gov/search?term=${q}`},
    {src:'DrugBank', url:`https://go.drugbank.com/unearth/q?searcher=drugs&query=${q}`} ];
  return [
    {src:'PubMed', url:`https://pubmed.ncbi.nlm.nih.gov/?term=${q}&sort=date`},
    {src:'Nature', url:`https://www.nature.com/search?q=${q}&order=date_desc`},
    {src:'ClinicalTrials', url:`https://clinicaltrials.gov/search?term=${q}`} ];
}

/* ---------- RESEARCH ENGINE ---------- */
function Research(){
  const tabs=Object.keys(RESEARCH);
  const [tab,setTab]=useStateR(tabs[0]);
  const [q,setQ]=useStateR('');
  const [sel,setSel]=useStateR(null);
  const [thinking,setThinking]=useStateR(false);
  const items=RESEARCH[tab]||[];
  const filtered=useMemoR(()=>items.filter(i=>i.toLowerCase().includes(q.trim().toLowerCase())),[items,q]);

  // when a selection is made, play a short "reasoning" beat
  useEffectR(()=>{
    if(sel==null){ setThinking(false); return; }
    setThinking(true);
    const t=setTimeout(()=>setThinking(false),650);
    return ()=>clearTimeout(t);
  },[sel,tab]);

  const dossier=useMemoR(()=>{
    if(sel==null || !PLATFORMS.length) return null;
    const h=hashNum(sel+'|'+tab);
    const conf=68+(h%30);
    const idxs=[h%PLATFORMS.length,(h>>3)%PLATFORMS.length,(h>>6)%PLATFORMS.length];
    const plats=idxs.filter((v,i,a)=>a.indexOf(v)===i).slice(0,2).map(i=>PLATFORMS[i]).filter(Boolean);
    const allSig=['Transcriptomic','Spatial','Proteomic','Genomic','Epigenomic','Clinical'];
    const signals=allSig.filter((_,i)=>((h>>i)&1)).slice(0,3);
    return {conf, plats, signals:signals.length?signals:['Transcriptomic','Clinical'], links:linksFor(tab,sel)};
  },[sel,tab]);

  const submit=(e)=>{ e.preventDefault(); const t=q.trim(); if(t) setSel(t); };

  return React.createElement('section',{className:'section marble-deep veined grain',id:'research'},
    React.createElement('div',{className:'wrap'},
      React.createElement('div',{className:'eyebrow-row'},React.createElement(Reveal,{as:'span',className:'kicker center'},'Research Engine')),
      React.createElement(Reveal,{as:'h2',className:'display h-lg center',delay:80,style:{marginTop:'18px'}},
        'Interrogate biology, ',React.createElement('span',{className:'gild italic'},'instantly.')),
      React.createElement(Reveal,{as:'p',className:'serif-lead center mx-auto',delay:140,style:{maxWidth:'600px',marginTop:'22px'}},
        'Search any disease, gene, pathway, or therapeutic. The ecosystem routes it and pulls live evidence.'),
      React.createElement(Reveal,{variant:'r-scale',className:'console glass',delay:160},
        React.createElement('form',{className:'console-bar',onSubmit:submit},
          React.createElement(Glyph,{name:'search',width:20,height:20,className:'console-search-i'}),
          React.createElement('input',{className:'console-input',placeholder:'Search '+tab.toLowerCase()+', then press Enter\u2026',value:q,
            onChange:e=>setQ(e.target.value)}),
          React.createElement('span',{className:'console-live'},React.createElement('span',{className:'console-dot'}),'LIVE')
        ),
        React.createElement('div',{className:'console-tabs'},
          tabs.map(t=>React.createElement('button',{key:t,type:'button',className:`console-tab ${tab===t?'on':''}`,
            onClick:()=>{setTab(t);setSel(null);setQ('');}},t))),
        React.createElement('div',{className:'console-body'},
          React.createElement('div',{className:'console-chips'},
            filtered.length?filtered.map(i=>React.createElement('button',{key:i,type:'button',
              className:`console-chip ${sel===i?'on':''}`,onClick:()=>setSel(i)},i))
            :React.createElement('div',{className:'console-empty'},
              q.trim()?React.createElement('span',null,'Press Enter to analyze \u201c',q.trim(),'\u201d'):'No matches in this index.')),
          React.createElement('div',{className:`console-dossier ${dossier?'open':''}`},
            !dossier?React.createElement('div',{className:'dossier-placeholder'},
              React.createElement(Star,{size:18}),
              React.createElement('span',null,'Select an entry to generate a live dossier'))
            :thinking?React.createElement('div',{className:'dossier-thinking'},
              React.createElement('span',{className:'dossier-think-dot'}),
              React.createElement('span',{className:'dossier-think-dot'}),
              React.createElement('span',{className:'dossier-think-dot'}),
              React.createElement('span',{className:'dossier-think-t'},'Reasoning across the ecosystem\u2026'))
            :React.createElement(React.Fragment,null,
              React.createElement('div',{className:'dossier-head'},
                React.createElement('span',{className:'dossier-name display'},sel),
                React.createElement('span',{className:'dossier-tag'},tab.replace(/s$/,''))),
              React.createElement('div',{className:'dossier-conf'},
                React.createElement('div',{className:'dossier-conf-l'},'Model confidence',
                  React.createElement('span',{className:'gild stat-num'},dossier.conf+'%')),
                React.createElement('div',{className:'dossier-meter'},
                  React.createElement('div',{className:'dossier-meter-f',style:{width:dossier.conf+'%'}}))),
              React.createElement('div',{className:'dossier-row'},
                React.createElement('div',{className:'dossier-k'},'Routed to'),
                React.createElement('div',{className:'dossier-v'},dossier.plats.map(p=>
                  React.createElement('span',{key:p.id,className:'dossier-pill'},p.name)))),
              React.createElement('div',{className:'dossier-row'},
                React.createElement('div',{className:'dossier-k'},'Signals'),
                React.createElement('div',{className:'dossier-v'},dossier.signals.map(s=>
                  React.createElement('span',{key:s,className:'dossier-sig'},React.createElement(Star,{size:8}),s)))),
              React.createElement('div',{className:'dossier-row'},
                React.createElement('div',{className:'dossier-k'},'Evidence'),
                React.createElement('div',{className:'dossier-v dossier-links'},dossier.links.map(l=>
                  React.createElement('a',{key:l.src,href:l.url,target:'_blank',rel:'noopener noreferrer',
                    className:'dossier-link',style:{'--sc':RSRC_COLOR[l.src]||RSRC_COLOR.default}},
                    React.createElement('span',{className:'dossier-link-dot'}),l.src,
                    React.createElement('span',{className:'dossier-link-arr'},'\u2197')))))
            )
          )
        )
      )
    )
  );
}

/* ---------- THE AGORA ---------- */
const AGORA_URL='https://agorabio.replit.app/';
const AGORA_NODES=[
  {label:'Creators',icon:'spark'},{label:'Researchers',icon:'scope'},{label:'Startups',icon:'flask'},
  {label:'Pharma',icon:'building'},{label:'Institutions',icon:'columns'},{label:'Clinics',icon:'pulse'},
];
function agoraPos(i,n,r){ const a=(i/n)*Math.PI*2 - Math.PI/2; return {x:50+Math.cos(a)*r, y:50+Math.sin(a)*r}; }

function AgoraEmblem({size=70}){
  return React.createElement('span',{className:'agora-emblem',style:{width:size,height:size}},
    React.createElement('svg',{viewBox:'0 0 48 48',fill:'none'},
      React.createElement('circle',{cx:24,cy:24,r:22,stroke:'var(--gold)',strokeWidth:1.2,opacity:.5}),
      React.createElement('path',{d:'M12 18 24 11l12 7',stroke:'currentColor',strokeWidth:1.6,strokeLinecap:'round',strokeLinejoin:'round'}),
      React.createElement('path',{d:'M14 18v12M20 18v12M28 18v12M34 18v12',stroke:'currentColor',strokeWidth:1.6,strokeLinecap:'round'}),
      React.createElement('path',{d:'M11 31h26',stroke:'currentColor',strokeWidth:1.6,strokeLinecap:'round'}),
      React.createElement('path',{d:'M24 4c.5 3.4 2.3 5.2 5.6 5.6C26.3 10 24.5 11.8 24 15c-.5-3.2-2.3-5-5.6-5.4C21.7 9.2 23.5 7.4 24 4z',fill:'var(--gold-bright)',stroke:'none'})
    )
  );
}

function Agora(){
  const N=AGORA_NODES.length;
  const nodes=AGORA_NODES.map((p,i)=>({...p, ...agoraPos(i,N,38)}));
  // transaction arcs between non-adjacent participants, bowing through the central agora
  const pairs=[[0,2],[2,4],[4,0],[1,3],[3,5],[5,1],[0,3],[1,4]];
  return React.createElement('section',{className:'section marble veined grain',id:'agora'},
    React.createElement('div',{className:'wrap'},
      React.createElement('div',{className:'agora-head'},
        React.createElement('div',null,
          React.createElement(Reveal,{as:'span',className:'kicker'},'The Agora'),
          React.createElement(Reveal,{as:'h2',className:'display h-lg',delay:80,style:{marginTop:'16px',maxWidth:'12ch'}},
            'The marketplace for ',React.createElement('span',{className:'gild italic'},'biological intelligence.'))),
        React.createElement(Reveal,{as:'p',className:'body',delay:140,style:{maxWidth:'380px'}},
          'Where creators, researchers, startups, pharma, and institutions exchange the models that move medicine forward.')),
      // marketplace stage
      React.createElement(Reveal,{variant:'r-scale',className:'agora-market'},
        React.createElement('div',{className:'agora-stage'},
          React.createElement('svg',{viewBox:'0 0 100 100',className:'agora-svg',preserveAspectRatio:'none'},
            React.createElement('defs',null,
              pairs.map((p,i)=>React.createElement('path',{key:'p'+i,id:'agtx'+i,
                d:`M ${nodes[p[0]].x} ${nodes[p[0]].y} Q 50 50 ${nodes[p[1]].x} ${nodes[p[1]].y}`}))),
            // faint connection lines
            pairs.map((p,i)=>React.createElement('use',{key:'u'+i,href:'#agtx'+i,className:'agora-wire'})),
            // travelling transaction coins
            pairs.map((p,i)=>React.createElement('circle',{key:'c'+i,r:1.5,className:'agora-coin'},
              React.createElement('animateMotion',{dur:(3.4+i*0.35)+'s',repeatCount:'indefinite',begin:(i*0.5)+'s',rotate:'auto',keyPoints:'0;1',keyTimes:'0;1',calcMode:'linear'},
                React.createElement('mpath',{href:'#agtx'+i})))),
            pairs.map((p,i)=>React.createElement('circle',{key:'c2'+i,r:1.1,className:'agora-coin alt'},
              React.createElement('animateMotion',{dur:(3.4+i*0.35)+'s',repeatCount:'indefinite',begin:(i*0.5+1.7)+'s',rotate:'auto'},
                React.createElement('mpath',{href:'#agtx'+i}))))
          ),
          // central agora emblem (hyperlinked)
          React.createElement('a',{className:'agora-core',href:AGORA_URL,target:'_blank',rel:'noopener noreferrer',title:'Enter the Agora'},
            React.createElement('span',{className:'agora-core-glow'}),
            React.createElement(AgoraEmblem,{size:62}),
            React.createElement('span',{className:'agora-core-name'},'AGORA'),
            React.createElement('span',{className:'agora-core-sub'},'BIO MARKETPLACE')),
          // participant nodes
          nodes.map((nd,i)=>React.createElement('div',{key:nd.label,className:'agora-part',
            style:{left:nd.x+'%',top:nd.y+'%'}},
            React.createElement('span',{className:'agora-part-disc'},React.createElement(Glyph,{name:nd.icon,width:20,height:20})),
            React.createElement('span',{className:'agora-part-label'},nd.label)))
        ),
        React.createElement('a',{className:'btn btn-gold agora-enter',href:AGORA_URL,target:'_blank',rel:'noopener noreferrer'},
          'Enter the Agora',React.createElement(Glyph,{name:'arrow',className:'arr',width:16,height:16}))
      ),
      React.createElement('div',{className:'agora-grid'},
        AGORA.map((a,i)=>React.createElement(Reveal,{key:a.t,className:'agora-card card-marble',delay:60+i*70,
          role:'link',tabIndex:0,onClick:()=>window.open(AGORA_URL,'_blank','noopener')},
          React.createElement('div',{className:'agora-ic'},React.createElement(Glyph,{name:a.icon,width:26,height:26})),
          React.createElement('h3',{className:'agora-t'},a.t),
          React.createElement('p',{className:'agora-d'},a.d),
          React.createElement('span',{className:'agora-arrow'},React.createElement(Glyph,{name:'arrow',width:18,height:18}))
        ))
      )
    )
  );
}

/* ---------- CAREERS ---------- */
function Careers(){
  return React.createElement('section',{className:'section marble-deep veined grain',id:'careers'},
    React.createElement('div',{className:'wrap'},
      React.createElement('div',{className:'eyebrow-row'},React.createElement(Reveal,{as:'span',className:'kicker center'},'Careers')),
      React.createElement(Reveal,{as:'h2',className:'display h-lg center',delay:80,style:{marginTop:'18px'}},
        'Help build the ',React.createElement('span',{className:'gild italic'},'future of biology.')),
      React.createElement('div',{className:'careers-grid'},
        CAREERS.map((c,i)=>React.createElement(Reveal,{key:c,className:'career-card',delay:30+i*55,role:'button',tabIndex:0,
          onClick:()=>window.openContact('AETHERCORE LABS','I\u2019m interested in the '+c+' track at AetherCore Labs.\n\nName:\nBackground:\nLink to work / CV:\n')},
          React.createElement('span',{className:'career-i'},React.createElement(Star,{size:11})),
          React.createElement('span',{className:'career-t'},c),
          React.createElement('span',{className:'career-arrow'},'\u2197'))) ),
      React.createElement(Reveal,{className:'center',delay:120,style:{marginTop:'52px'}},
        React.createElement(Magnetic,{strength:0.4},
          React.createElement('button',{className:'btn btn-gold',onClick:()=>window.goDashboard()},
            'Join Now',React.createElement(Glyph,{name:'arrow',className:'arr',width:16,height:16}))))
    )
  );
}

/* ---------- GLOBAL IMPACT ---------- */
function GlobalImpact(){
  const nodes=[
    {x:18,y:38,c:'Research'},{x:30,y:60,c:'Universities'},{x:46,y:30,c:'Governments'},
    {x:52,y:54,c:'Hospitals'},{x:68,y:42,c:'Pharma'},{x:80,y:64,c:'Research'},
    {x:62,y:24,c:'Universities'},{x:36,y:46,c:'Hospitals'},{x:74,y:34,c:'Governments'},
  ];
  const arcs=[[0,2],[2,4],[4,8],[1,3],[3,4],[7,5],[2,6],[8,5],[3,7]];
  const legend=['Research','Hospitals','Universities','Governments','Pharma'];
  return React.createElement('section',{className:'section marble veined grain',id:'impact'},
    React.createElement('div',{className:'wrap'},
      React.createElement('div',{className:'eyebrow-row'},React.createElement(Reveal,{as:'span',className:'kicker center'},'Global Impact')),
      React.createElement(Reveal,{as:'h2',className:'display h-lg center',delay:80,style:{marginTop:'18px'}},
        'A network ',React.createElement('span',{className:'gild italic'},'without borders.')),
      React.createElement(Reveal,{variant:'r-scale',className:'globe-stage',delay:140},
        React.createElement('svg',{viewBox:'0 0 100 72',className:'globe-svg',preserveAspectRatio:'xMidYMid meet'},
          // latitude/longitude grid
          [20,36,52].map(r=>React.createElement('ellipse',{key:'lat'+r,cx:50,cy:36,rx:46,ry:r*0.62,className:'globe-grid'})),
          [0,1,2,3].map(i=>React.createElement('ellipse',{key:'lon'+i,cx:50,cy:36,rx:46-i*15,ry:30,className:'globe-grid'})),
          React.createElement('ellipse',{cx:50,cy:36,rx:46,ry:30,className:'globe-edge'}),
          arcs.map((a,i)=>{
            const A=nodes[a[0]],B=nodes[a[1]];
            const x1=A.x*0.92+4,y1=A.y*0.5+8,x2=B.x*0.92+4,y2=B.y*0.5+8;
            const mx=(x1+x2)/2,my=(y1+y2)/2-9;
            return React.createElement('path',{key:i,d:`M${x1} ${y1} Q ${mx} ${my} ${x2} ${y2}`,className:'globe-arc',
              style:{animationDelay:(i*0.4)+'s'}});
          }),
          nodes.map((n,i)=>{
            const x=n.x*0.92+4,y=n.y*0.5+8;
            return React.createElement('g',{key:i,className:'globe-node',style:{animationDelay:(i*0.3)+'s'}},
              React.createElement('circle',{cx:x,cy:y,r:2.4,className:'globe-halo'}),
              React.createElement('circle',{cx:x,cy:y,r:0.9,className:'globe-core'}));
          })
        ),
        React.createElement('div',{className:'globe-legend'},
          legend.map(l=>React.createElement('span',{key:l,className:'globe-leg'},
            React.createElement('span',{className:'globe-leg-dot'}),l)))
      )
    )
  );
}

Object.assign(window,{ Research, Agora, Careers, GlobalImpact });
