/* global React */
const { useState, useEffect, useRef, useCallback } = React;

/* ============ ICONS (thin engraved line style) ============ */
const ic = (paths, vb='0 0 24 24') => (props) =>
  React.createElement('svg', {viewBox:vb, fill:'none', stroke:'currentColor', strokeWidth:1.4, strokeLinecap:'round', strokeLinejoin:'round', ...props}, paths.map((d,i)=>React.createElement('path',{key:i,d})));

const Icons = {
  helix: ic(['M7 3c0 5 10 5 10 10S7 13 7 21','M17 3c0 5-10 5-10 10s10 2 10 9','M8.5 6h7','M8 12h8','M8.5 18h7']),
  pulse: ic(['M2 12h4l2-7 4 14 2-7h8']),
  brain: ic(['M9.5 4a2.5 2.5 0 0 0-2.5 2.5A2.5 2.5 0 0 0 5 9a2.5 2.5 0 0 0 1 4 2.5 2.5 0 0 0 1 4 2.5 2.5 0 0 0 2.5 2.5V4z','M14.5 4A2.5 2.5 0 0 1 17 6.5 2.5 2.5 0 0 1 19 9a2.5 2.5 0 0 1-1 4 2.5 2.5 0 0 1-1 4 2.5 2.5 0 0 1-2.5 2.5V4z']),
  graph: ic(['M5 19V7','M12 19V4','M19 19v-8','M3 19h18']),
  layers: ic(['M12 3 3 8l9 5 9-5-9-5z','M3 13l9 5 9-5','M3 8v5','M21 8v5']),
  cell: ic(['M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z','M9 9a1.5 1.5 0 1 0 0-.01','M15 13a2 2 0 1 0 0-.01','M8 15a1 1 0 1 0 0-.01']),
  leaf: ic(['M11 21c-4 0-7-3-7-7 0-7 8-11 16-11 0 8-4 16-11 16-2 0-4-1-4-3','M5 19C9 12 13 9 17 7']),
  orbit: ic(['M12 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0','M12 12m-9 0a9 4.5 0 1 0 18 0a9 4.5 0 1 0-18 0']),
  eye: ic(['M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z','M12 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0']),
  target: ic(['M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0','M12 12m-5 0a5 5 0 1 0 10 0a5 5 0 1 0-10 0','M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0-2 0']),
  shield: ic(['M12 3 5 6v6c0 4 3 7 7 9 4-2 7-5 7-9V6l-7-3z','M9 12l2 2 4-4']),
  search: ic(['M11 11m-7 0a7 7 0 1 0 14 0a7 7 0 1 0-14 0','M21 21l-5-5']),
  flask: ic(['M9 3h6','M10 3v6L5 19a2 2 0 0 0 2 3h10a2 2 0 0 0 2-3l-5-10V3','M7.5 15h9']),
  globe: ic(['M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0','M3 12h18','M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18']),
  spark: ic(['M12 2c.6 5.5 4 8.9 9.5 9.5C16 12.1 12.6 15.5 12 21c-.6-5.5-4-8.9-9.5-9.5C8 11.9 11.4 8.5 12 2z']),
  code: ic(['M8 8l-4 4 4 4','M16 8l4 4-4 4','M13 5l-2 14']),
  cpu: ic(['M6 6h12v12H6z','M9 9h6v6H9z','M9 1v3M15 1v3M9 20v3M15 20v3M1 9h3M1 15h3M20 9h3M20 15h3']),
  dna2: ic(['M4 4c4 4 12 4 16 0','M4 20c4-4 12-4 16 0','M5 8c3 2 11 2 14 0','M5 16c3-2 11-2 14 0','M7 4v16M17 4v16']),
  network: ic(['M12 4m-2 0a2 2 0 1 0 4 0a2 2 0 1 0-4 0','M5 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0-4 0','M19 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0-4 0','M11 6 6 16M13 6l5 10M7 18h10']),
  arrow: ic(['M5 12h14','M13 6l6 6-6 6']),
  arrowDown: ic(['M12 5v14','M6 13l6 6 6-6']),
  fate: ic(['M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0','M12 12 5 7','M12 12l8-2','M12 12 9 21','M12 12l5 8','M12 12m-1.5 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0']),
  coin: ic(['M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0','M12 7v10','M9.5 9.5h3.5a1.7 1.7 0 0 1 0 3.4h-2.5a1.7 1.7 0 0 0 0 3.4H14']),
  columns: ic(['M3 9 12 4l9 5','M4 9v8M9 9v8M15 9v8M20 9v8','M3 20h18','M3 9h18']),
  building: ic(['M3 21h18','M5 21V5a1 1 0 0 1 1-1h7a1 1 0 0 1 1 1v16','M15 21V9h3a1 1 0 0 1 1 1v11','M8 8h2M8 12h2M8 16h2']),
  beaker: ic(['M6 3h12','M8 3v7l-3.5 8a2 2 0 0 0 2 3h11a2 2 0 0 0 2-3L18 10V3']),
  scope: ic(['M12 2a7 7 0 0 0-7 7c0 3 2 5 4 6v3a3 3 0 0 0 6 0v-3c2-1 4-3 4-6a7 7 0 0 0-7-7z','M9 21h6']),
  monitor: ic(['M3 4h18v12H3z','M8 20h8M12 16v4']),
  map: ic(['M9 4 3 6v14l6-2 6 2 6-2V4l-6 2-6-2z','M9 4v14M15 6v14']),
  link: ic(['M9 15l6-6','M11 6l1-1a3.5 3.5 0 0 1 5 5l-1 1','M13 18l-1 1a3.5 3.5 0 0 1-5-5l1-1']),
};

/* ============ PLATFORM DATA ============ */
const PLATFORMS = [
  { id:'plexis', name:'PLEXIS', icon:'helix', angle:-90,
    tag:'The First Closed-Loop RNA Discovery Platform',
    desc:'Transforms raw biological observation into testable therapeutic hypotheses, a self-correcting loop from signal to candidate.',
    caps:['RNA analysis','Therapeutic target ID','Biomarker discovery','Drug prioritization','Pathway analysis','Multiomic integration'] },
  { id:'fasi', name:'FASI', icon:'pulse', angle:-45,
    tag:'Disease-State Intelligence Engine',
    desc:'Models disease progression and predicts the biological transitions a patient will undergo before they happen.',
    caps:['Disease forecasting','Risk prediction','Early detection','Population analytics','Clinical decision support'] },
  { id:'kosmos', name:'KOSMOS RNA', icon:'brain', angle:0,
    tag:'Biological Knowledge Engine',
    desc:'An AI reasoning layer that reads the world\u2019s biological literature, datasets and pathways, and reasons across them.',
    caps:['Scientific reasoning','Literature synthesis','Pathway mapping','Knowledge graphs','Research acceleration'] },
  { id:'istos', name:'ISTOS', icon:'layers', angle:45,
    tag:'Tissue Intelligence Platform',
    desc:'Models tissue architecture and the microenvironment dynamics that govern how disease takes hold and spreads.',
    caps:['Spatial biology','Histopathology analysis','Tumor microenvironment','Tissue simulation'] },
  { id:'klothos', name:'KLOTHOS', icon:'flask', angle:90,
    tag:'Therapeutic Design Engine',
    desc:'Generates and evaluates novel intervention strategies, ranking candidates against the biology that matters.',
    caps:['Therapeutic generation','Candidate ranking','Treatment optimization','Intervention modeling'] },
  { id:'kytos', name:'KYTOS', icon:'cell', angle:135,
    tag:'Cellular Evolution Engine',
    desc:'Simulates cellular competition and evolutionary dynamics to anticipate resistance and clonal escape.',
    caps:['Cell-state transitions','Evolutionary simulation','Clonal dynamics','Population modeling'] },
  { id:'epanafero', name:'EPANAFERO', icon:'leaf', angle:180,
    tag:'Restoration Intelligence System',
    desc:'Charts the pathways that lead from a disease state back toward healthy biological function.',
    caps:['Regenerative strategies','Recovery modeling','Biological restoration','Health-state reconstruction'] },
  { id:'janus', name:'JANUS-X', icon:'cpu', angle:225,
    tag:'Biological Operating System',
    desc:'The agentic layer that coordinates every AetherCore platform into autonomous, end-to-end discovery workflows.',
    caps:['Multi-agent orchestration','AI research teams','Cross-platform reasoning','Autonomous discovery'] },
  { id:'moira', name:'MOIRA', icon:'fate', angle:270,
    tag:'Biological Foresight Engine',
    desc:'Named for the Greek Moirai who governed destiny, MOIRA models the hidden forces that shape cellular fate, forecasting state transitions and emerging therapeutic opportunities before disease becomes clinically apparent.',
    caps:['Predictive modeling','Cell-state forecasting','Multi-omics integration','Emerging-target ID','Disease-trajectory mapping','Systems-biology simulation'] },
];

/* ============ JOURNEY / TIMELINES ============ */
const JOURNEY = [
  { n:'01', t:'Patient arrives', d:'A complete biological baseline begins, every signal captured.', icon:'scope' },
  { n:'02', t:'Multiomic profiling', d:'Genome, transcriptome, proteome and tissue read in concert.', icon:'dna2' },
  { n:'03', t:'AI interpretation', d:'KOSMOS reasons across the data against all known biology.', icon:'brain' },
  { n:'04', t:'Disease prediction', d:'FASI forecasts transitions before symptoms emerge.', icon:'pulse' },
  { n:'05', t:'Therapeutic generation', d:'KLOTHOS designs candidate interventions in silico.', icon:'flask' },
  { n:'06', t:'Personalized intervention', d:'A protocol matched to one patient\u2019s exact biology.', icon:'target' },
  { n:'07', t:'Continuous monitoring', d:'The loop stays open, response tracked in real time.', icon:'monitor' },
  { n:'08', t:'Outcome optimization', d:'EPANAFERO steers the system back toward health.', icon:'leaf' },
];

const ERAS = [
  { yr:'2025', t:'Reactive Medicine', d:'We treat disease once it has already declared itself. The body speaks; we respond, late.', icon:'pulse' },
  { yr:'2030', t:'Predictive Medicine', d:'Models forecast disease from biological signal years before the first symptom appears.', icon:'graph' },
  { yr:'2040', t:'Preventative Medicine', d:'Interventions are designed and deployed before progression, disease intercepted at its origin.', icon:'shield' },
  { yr:'2050', t:'Restorative Medicine', d:'Damaged biological systems are guided, deliberately, back toward their healthy state.', icon:'leaf' },
  { yr:'2060', t:'Biological Intelligence', d:'A complete operating system for biology, understood, predictable, and engineerable end to end.', icon:'cpu' },
];

const RESEARCH = {
  Diseases:['Cancer','Alzheimer\u2019s','Parkinson\u2019s','Diabetes','ALS','Multiple Sclerosis','Huntington\u2019s','Glioblastoma','Rare Diseases'],
  Genes:['TP53','BRCA1','APOE','SOD1','EGFR','KRAS','PTEN','MYC','VEGFA'],
  Pathways:['MAPK / ERK','PI3K-AKT','Wnt signaling','mTOR','Apoptosis','NF-\u03baB','Immune evasion'],
  Therapeutics:['siRNA','mRNA','Antisense','CRISPR','Small molecule','Monoclonal antibody','Cell therapy'],
};

const AGORA = [
  { t:'Creator Portal', icon:'spark', d:'Independent scientists publish and license biological models.' },
  { t:'Enterprise Portal', icon:'building', d:'Pharma and institutions deploy AetherCore at scale.' },
  { t:'Licensing Marketplace', icon:'link', d:'Models, datasets and engines, exchanged with provenance.' },
  { t:'Therapeutic Engines', icon:'flask', d:'On-demand generation pipelines for new modalities.' },
  { t:'Biological AI Models', icon:'cpu', d:'Foundation models for RNA, tissue and disease state.' },
  { t:'Research Partnerships', icon:'network', d:'Co-development across the global research frontier.' },
];

const CAREERS = ['AI Research','Bioinformatics','Computational Biology','Machine Learning','Software Engineering','Systems Biology','Clinical Informatics','Therapeutic Design'];

const MANIFESTO = [
  ['We believe biology is the next', 'frontier of intelligence.'],
  ['We believe disease', 'can be understood.'],
  ['We believe prediction', 'is possible.'],
  ['We believe prevention', 'is achievable.'],
  ['We believe restoration', 'is inevitable.'],
  ['We believe the future of medicine', 'will be engineered.'],
];

const NAV_LINKS = ['Mission','Platforms','Precision Medicine','Future','Research','Careers'];

/* ============ SHARED ATOMS ============ */

// Reveal-on-scroll wrapper, driven by synchronous scroll/resize handlers + a
// setInterval fallback (timers fire even when rAF is throttled in a backgrounded
// iframe) + an IntersectionObserver. Never depends on requestAnimationFrame.
const _revealItems = new Set();
function _revealScan(){
  if(_revealItems.size===0) return;
  const vh = window.innerHeight || document.documentElement.clientHeight || 800;
  _revealItems.forEach(item=>{
    const el = item.el;
    if(!el || !el.isConnected){ _revealItems.delete(item); return; }
    const r = el.getBoundingClientRect();
    if(r.top < vh*0.94 && r.bottom > vh*0.02){ item.show(); _revealItems.delete(item); }
  });
}
let _revealIO = null;
if(typeof window!=='undefined' && !window.__revealBound){
  window.__revealBound=true;
  window.addEventListener('scroll', _revealScan, {passive:true});
  window.addEventListener('resize', _revealScan, {passive:true});
  window.addEventListener('load', _revealScan);
  setInterval(_revealScan, 250); // fires even when rAF is throttled
  if('IntersectionObserver' in window){
    _revealIO = new IntersectionObserver((entries)=>{
      entries.forEach(e=>{ if(e.isIntersecting){ const it=e.target.__revealItem; if(it){ it.show(); _revealItems.delete(it); _revealIO.unobserve(e.target); } } });
    },{threshold:0.12, rootMargin:'0px 0px -6% 0px'});
  }
}
function Reveal({children, variant='', delay=0, className='', as='div', once=true, style={}, ...rest}){
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(()=>{
    const el = ref.current; if(!el) return;
    const r0 = el.getBoundingClientRect();
    if(r0.top < (window.innerHeight||800)*0.95 && r0.bottom > 0){ setSeen(true); return; }
    const item = { el, show:()=>setSeen(true) };
    el.__revealItem = item;
    _revealItems.add(item);
    if(_revealIO) _revealIO.observe(el);
    _revealScan();
    return ()=>{ _revealItems.delete(item); if(_revealIO) _revealIO.unobserve(el); };
  },[once]);
  return React.createElement(as, {
    ref, className:`reveal ${variant} ${seen?'is-in':''} ${className}`,
    style:{transitionDelay:`${delay}ms`, ...style}, ...rest
  }, children);
}

// Spark / four-point star
function Star({size=14, className=''}){
  return React.createElement('span',{className:`spark ${className}`,style:{width:size,height:size}},
    React.createElement('svg',{viewBox:'0 0 24 24',fill:'currentColor'},
      React.createElement('path',{d:'M12 0c.8 7.5 3.5 10.2 12 12-8.5 1.8-11.2 4.5-12 12-.8-7.5-3.5-10.2-12-12C8.5 10.2 11.2 7.5 12 0z'})
    )
  );
}

function Rule({className=''}){
  return React.createElement('div',{className:`rule ${className}`},
    React.createElement('span',{className:'line'}),
    React.createElement(Star,{size:13}),
    React.createElement('span',{className:'line r'})
  );
}

// Magnetic hover wrapper
function Magnetic({children, strength=0.35, className='', ...rest}){
  const ref = useRef(null);
  const onMove = useCallback((e)=>{
    const el = ref.current; if(!el) return;
    const r = el.getBoundingClientRect();
    const x = (e.clientX - (r.left+r.width/2))*strength;
    const y = (e.clientY - (r.top+r.height/2))*strength;
    el.style.setProperty('--bx', x+'px'); el.style.setProperty('--by', y+'px');
  },[strength]);
  const onLeave = useCallback(()=>{
    const el=ref.current; if(!el)return;
    el.style.setProperty('--bx','0px'); el.style.setProperty('--by','0px');
  },[]);
  return React.createElement('div',{ref, onMouseMove:onMove, onMouseLeave:onLeave, className, style:{display:'inline-flex'}, ...rest}, children);
}

// Animated counter
function Counter({to, suffix='', dur=1800, className=''}){
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(()=>{
    const el = ref.current; if(!el) return;
    let started=false; let raf;
    const io = new IntersectionObserver((es)=>{
      es.forEach(e=>{
        if(e.isIntersecting && !started){
          started=true;
          const t0=performance.now();
          const tick=(now)=>{
            const p=Math.min(1,(now-t0)/dur);
            const e2=1-Math.pow(1-p,3);
            setVal(Math.round(to*e2));
            if(p<1) raf=requestAnimationFrame(tick);
          };
          raf=requestAnimationFrame(tick);
          io.unobserve(el);
        }
      });
    },{threshold:0.5});
    io.observe(el);
    return ()=>{io.disconnect(); cancelAnimationFrame(raf);};
  },[to,dur]);
  return React.createElement('span',{ref, className:`stat-num ${className}`}, val, suffix);
}

function Glyph({name, ...props}){
  const C = Icons[name] || Icons.spark;
  return React.createElement(C, props);
}

/* ============ ACTIONS ============ */
const CONTACT_EMAIL = 'kJOSHI2@bidmc.harvard.edu';
function mailtoLink(subject='AETHERCORE LABS', body=''){
  let u = 'mailto:'+CONTACT_EMAIL+'?subject='+encodeURIComponent(subject);
  if(body) u += '&body='+encodeURIComponent(body);
  return u;
}
function openContact(subject='AETHERCORE LABS', body=''){ window.location.href = mailtoLink(subject, body); }
function goDashboard(){ window.location.href = 'AetherCore%20Dashboard.html'; }
function scrollToId(id){ const el=document.getElementById(id); if(el) window.scrollTo({top:Math.max(0,el.offsetTop-10),behavior:'smooth'}); }

Object.assign(window, {
  Icons, Glyph, PLATFORMS, JOURNEY, ERAS, RESEARCH, AGORA, CAREERS, MANIFESTO, NAV_LINKS,
  Reveal, Star, Rule, Magnetic, Counter,
  CONTACT_EMAIL, mailtoLink, openContact, goDashboard, scrollToId,
});
