// Homepage — VivaMed Biopharma
window.HomeApp = (function(){
const { useState, useEffect, useRef } = React;

// ─────────── Hero — logo-mark particle field, codebase-style layout ───────────
// Circles bubble in from the screen edges to assemble the VivaMed "V of dots"
// mark, breathe at rest, and scatter/glow away from the cursor on hover.
function useLogoParticles(heroRef, canvasRef){
  useEffect(()=>{
    const hero = heroRef.current, canvas = canvasRef.current;
    if(!hero || !canvas) return;
    const ctx = canvas.getContext("2d");
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    // Exact VivaMed mark — 39 circles [x, y, radius] sampled directly from
    // assets/vivamed-logo.png. Two separated wings of 3 up top (the V mouth),
    // then continuous rows 6→5→4→3→2→1 converging to one large bottom circle.
    const LOGO = [
      [3.2,7.6,3.0],[21.0,7.6,3.1],[38.5,7.5,3.0],[110.4,7.6,3.0],[128.4,7.5,3.0],[146.5,7.5,3.0],
      [11.8,11.5,3.1],[29.8,11.5,3.1],[47.5,11.5,3.0],[101.4,11.5,3.1],[119.3,11.5,3.1],[137.5,11.5,3.0],
      [20.9,16.0,3.5],[38.9,16.0,3.5],[56.3,16.0,3.7],[92.4,16.0,3.7],[110.4,16.0,3.7],[128.6,16.0,3.7],
      [30.4,22.1,4.2],[48.4,22.1,4.2],[65.8,22.2,4.4],[82.9,22.2,4.2],[101.0,22.0,4.4],[119.2,22.1,4.4],
      [39.0,29.6,4.8],[57.0,29.6,4.8],[74.5,29.5,5.0],[92.4,29.5,5.0],[110.5,29.5,5.0],
      [47.8,38.8,5.5],[65.5,38.8,5.7],[83.4,38.6,5.7],[101.8,38.8,5.5],
      [56.7,50.2,7.0],[74.7,50.1,7.0],[92.9,50.2,7.0],
      [65.6,64.5,8.0],[83.8,64.5,8.1],
      [74.7,82.4,10.0],
    ];
    const LX0=Math.min(...LOGO.map(c=>c[0]-c[2])), LX1=Math.max(...LOGO.map(c=>c[0]+c[2]));
    const LY0=Math.min(...LOGO.map(c=>c[1]-c[2])), LY1=Math.max(...LOGO.map(c=>c[1]+c[2]));
    const LW=LX1-LX0, LH=LY1-LY0;
    // Wingtip cyan rgb(0,176,255) → converging-point deep blue rgb(0,65,239).
    const colorFor=(t)=>`0,${Math.round(176-111*t)},${Math.round(255-16*t)}`;

    let W=0, H=0, dpr=1, dots=[], raf=null, started=null;
    // `over` = cursor within hero (drives hover repulsion); `moveTs` = last
    // movement time (drives the idle check). A resting cursor must NOT block shows.
    const mouse={x:-9999,y:-9999,over:false,moveTs:-1e9};

    // Periodic "showtime": every so often (when idle) the dots break the V
    // into a playful shape, then reassemble. markH set in buildTargets.
    let markH=0, mode="logo", modeStart=0, nextShow=3.8, showEnd=0, showIdx=0;
    const SHOWS=["tornado","helix","galaxy"], SHOW_DUR=4.6, SHOW_GAP=5;
    const HELIX_R=()=>Math.min(W,H)*0.14, HELIX_H=()=>Math.min(H*0.58, markH*1.6);
    function targetFor(d,t){
      const cx=W*0.5, cy=H*0.47, N=dots.length, span=Math.min(W,H);
      if(mode==="helix"){
        const u=d.idx/(N-1), strand=d.idx%2, Hh=HELIX_H();
        const ang=u*Math.PI*4 + strand*Math.PI + t*1.7;
        return [cx+Math.cos(ang)*HELIX_R(), cy - Hh/2 + u*Hh];
      }
      if(mode==="tornado"){
        const u=d.idx/(N-1), Ht=Math.min(H*0.6, markH*1.6);
        const rad=(0.04+(1-u)*0.21)*span, ang=d.seed*6.2832 + t*(2.4+(1-u)*1.7);
        return [cx+Math.cos(ang)*rad, cy - Ht/2 + u*Ht + Math.sin(ang)*rad*0.1];
      }
      if(mode==="galaxy"){
        // 39 logo dots become the bright inner spiral-arm clusters.
        const arm=d.idx%2, a=0.12+(d.idx/N)*0.6;
        const ang=a*3.2*Math.PI + arm*Math.PI + t*0.5;
        const rad=a*span*0.30;
        return [cx+Math.cos(ang)*rad, cy+Math.sin(ang)*rad*0.6];
      }
      const bobX=Math.sin(t*0.9+d.phase)*2.2, bobY=Math.cos(t*0.8+d.phase)*2.2;
      return [d.hx+bobX, d.hy+bobY];
    }
    // How "present" the decorative layer is (fades in/out with the show).
    function showAlpha(t){
      if(mode==="logo") return 0;
      return Math.max(0, Math.min(1, (t-modeStart)/0.9, (showEnd-t)/0.9));
    }
    // Extra particles that only exist during a show: helix rungs + galaxy core/stars.
    function drawDecor(t){
      const A=showAlpha(t); if(A<=0.01) return;
      const cx=W*0.5, cy=H*0.47, span=Math.min(W,H), scale=markH/LH;
      ctx.shadowBlur=0;
      if(mode==="helix"){
        const Hh=HELIX_H(), R=HELIX_R(), NR=16;
        for(let r=0;r<=NR;r++){
          const u=r/NR, a0=u*Math.PI*4 + t*1.7, a1=a0+Math.PI;
          const x0=cx+Math.cos(a0)*R, x1=cx+Math.cos(a1)*R, yy=cy-Hh/2+u*Hh;
          const col=colorFor(u);
          for(let s=1;s<6;s++){
            const x=x0+(x1-x0)*(s/6);
            ctx.beginPath(); ctx.arc(x,yy,scale*0.85,0,6.2832);
            ctx.fillStyle=`rgba(${col},${0.55*A})`; ctx.fill();
          }
        }
      } else if(mode==="galaxy"){
        const g=ctx.createRadialGradient(cx,cy,0,cx,cy,span*0.20);
        g.addColorStop(0,`rgba(200,238,255,${0.9*A})`);
        g.addColorStop(0.22,`rgba(120,205,255,${0.5*A})`);
        g.addColorStop(1,"rgba(40,120,230,0)");
        ctx.fillStyle=g; ctx.fillRect(0,0,W,H);
        ctx.shadowColor=`rgba(190,235,255,${0.9*A})`; ctx.shadowBlur=44*A;
        ctx.beginPath(); ctx.arc(cx,cy,scale*3.0,0,6.2832);
        ctx.fillStyle=`rgba(230,247,255,${0.95*A})`; ctx.fill();
        ctx.shadowBlur=0;
        for(let j=0;j<150;j++){
          const sd=(j*0.61803)%1, arm=j%2, a=0.08+(j/150)*0.92;
          const ang=a*3.2*Math.PI + arm*Math.PI + t*0.5 + sd*0.5;
          const rad=a*span*0.42, x=cx+Math.cos(ang)*rad, y=cy+Math.sin(ang)*rad*0.6;
          const br=((1-a)*0.7+0.2)*A;
          ctx.beginPath(); ctx.arc(x,y,scale*(0.35+sd*0.7),0,6.2832);
          ctx.fillStyle=`rgba(${colorFor(a)},${br})`; ctx.fill();
        }
      }
    }

    function sizeCanvas(){
      dpr = Math.min(window.devicePixelRatio||1, 2);
      const r = hero.getBoundingClientRect();
      W=r.width; H=r.height;
      canvas.width=Math.round(W*dpr); canvas.height=Math.round(H*dpr);
      canvas.style.width=W+"px"; canvas.style.height=H+"px";
      ctx.setTransform(dpr,0,0,dpr,0,0);
    }

    // Place the exact logo circles, scaled uniformly to fit the hero's
    // right-hand zone (centred on mobile).
    function buildTargets(){
      // Big, centred backdrop filling most of the hero box, behind the copy.
      // On phones, sit it higher so it backs the large bold headline rather
      // than the small lede below it (which it was making hard to read).
      const mobile = W <= 640;
      const scale = mobile
        ? Math.min((W*0.84)/LW, (H*0.40)/LH)
        : Math.min((W*0.60)/LW, (H*0.66)/LH);
      const markW = LW*scale;
      markH = LH*scale;
      const left  = W*0.5 - markW/2;
      const top   = (mobile ? H*0.30 : H*0.47) - markH/2;
      return LOGO.map(([x,y,r])=>{
        const depth=(y-LY0)/LH;
        return {
          hx: left + (x-LX0)*scale,
          hy: top  + (y-LY0)*scale,
          baseR: r*scale,
          shade: depth,
          col: colorFor(depth),
        };
      });
    }

    function build(animate){
      sizeCanvas();
      const targets=buildTargets();
      dots = targets.map((t,i)=>{
        const fromLeft = t.hx < W*0.5;
        const ph = (i%17)/17*Math.PI*2 + (i%5)*0.7;
        const seed = (i*0.61803)%1;            // stable per-dot pseudo-random
        const base = {...t, idx:i, seed, phase:ph, r:t.baseR, vx:0, vy:0};
        if(!animate || reduce){
          return {...base, x:t.hx, y:t.hy, formed:true};
        }
        const sx = fromLeft ? -60 - (i%9)/9*W*0.35 : W+60 + (i%9)/9*W*0.35;
        const sy = (i*131%H);
        const edge = fromLeft ? t.hx/W : 1 - t.hx/W;       // cascade out-to-in
        return {
          ...base, x:sx, y:sy, formed:false,
          sx, sy, delay:0.1 + edge*0.6 + (i%7)/7*0.35, dur:0.9 + (i%5)/5*0.5
        };
      });
    }

    const REPEL=92, FORCE=1.35, K=0.05, DAMP=0.82;
    function frame(ts){
      if(started==null) started=ts;
      const t=(ts-started)/1000;

      // Showtime scheduler — fire when idle (no mouse movement for ~1.4s);
      // a stationary cursor over the hero does NOT count as interacting.
      const idle = (ts - mouse.moveTs) > 1400;
      if(mode==="logo"){
        if(t>3 && t>nextShow && idle){
          mode=SHOWS[showIdx%SHOWS.length]; showIdx++; modeStart=t; showEnd=t+SHOW_DUR;
        }
      } else if(t>showEnd){
        mode="logo"; nextShow=t+SHOW_GAP;
      }

      ctx.clearRect(0,0,W,H);
      const scale=markH/LH;
      drawDecor(t);
      for(const d of dots){
        let targetR=d.baseR, glow=0;

        if(!d.formed){
          const p=(t-d.delay)/d.dur;
          if(p<=0){ d.x=d.sx; d.y=d.sy; }
          else if(p<1){ const e=1-Math.pow(1-p,3); d.x=d.sx+(d.hx-d.sx)*e; d.y=d.sy+(d.hy-d.sy)*e; }
          else { d.formed=true; d.x=d.hx; d.y=d.hy; d.vx=0; d.vy=0; }
        }
        if(d.formed){
          const [tx,ty]=targetFor(d,t);
          if(mouse.over && mode==="logo"){
            const dx=d.x-mouse.x, dy=d.y-mouse.y, dist=Math.hypot(dx,dy)||0.001;
            if(dist<REPEL){ const f=1-dist/REPEL; d.vx+=(dx/dist)*f*FORCE; d.vy+=(dy/dist)*f*FORCE; targetR=d.baseR*(1+f*0.95); glow=f; }
          }
          // Springs snappier during a show so dots track the moving shape.
          const k = mode==="logo" ? K : K*1.7;
          d.vx+=(tx-d.x)*k; d.vy+=(ty-d.y)*k;
          d.vx*=DAMP; d.vy*=DAMP; d.x+=d.vx; d.y+=d.vy;
        }
        // During a show, even out the dot sizes so the big point circle
        // reads as just another star/strand bead.
        if(mode!=="logo") targetR=Math.min(targetR, scale*3.6);
        d.r += (targetR-d.r)*0.2;

        const col=d.col;
        // Every dot carries a soft halo so the mark reads as luminous bubbles;
        // hovered dots flare brighter and wider.
        ctx.shadowColor=`rgba(${col},${0.45+glow*0.4})`;
        ctx.shadowBlur=d.r*1.2 + glow*18;
        ctx.beginPath();
        ctx.arc(d.x,d.y,d.r,0,Math.PI*2);
        ctx.fillStyle=`rgba(${col},${Math.min(1, 0.9+glow*0.1)})`;
        ctx.fill();
      }
      raf=requestAnimationFrame(frame);
    }

    function onMove(e){ const r=hero.getBoundingClientRect(); mouse.x=e.clientX-r.left; mouse.y=e.clientY-r.top; mouse.over=true; mouse.moveTs=e.timeStamp; }
    function onLeave(){ mouse.over=false; mouse.x=-9999; mouse.y=-9999; }
    let rt=null;
    function onResize(){ clearTimeout(rt); rt=setTimeout(()=>build(false), 160); }

    build(true);
    if(reduce){ frame(0); }
    else {
      raf=requestAnimationFrame(frame);
      hero.addEventListener("mousemove", onMove);
      hero.addEventListener("mouseleave", onLeave);
      window.addEventListener("resize", onResize);
    }
    return ()=>{ if(raf) cancelAnimationFrame(raf); clearTimeout(rt);
      hero.removeEventListener("mousemove", onMove); hero.removeEventListener("mouseleave", onLeave);
      window.removeEventListener("resize", onResize); };
  }, []);
}

function HomeHero(){
  const heroRef = useRef(null);
  const canvasRef = useRef(null);
  useSpotlight(heroRef);
  useLogoParticles(heroRef, canvasRef);
  return (
    <section ref={heroRef} className="home-hero">
      <canvas ref={canvasRef} className="home-hero-canvas" aria-hidden="true"/>
      <div className="home-hero-tint" aria-hidden="true"/>
      <div className="home-hero-vignette" aria-hidden="true"/>

      <div className="home-hero-inner">
        <div className="home-pill-eyebrow hero-reveal-1">
          VIVAMED BIOPHARMA
        </div>
        <h1 className="home-h1 hero-reveal-2">
          Developing Tomorrow's Therapies<br/>
          with Speed, Impact, and Purpose.
        </h1>
        <p className="home-lede hero-reveal-3">
          A clinical-stage pharmaceutical company accelerating drug development through
          deep operating experience, strategic partnerships, and a diverse portfolio of
          high-impact therapies.
        </p>
        <div className="home-cta-row hero-reveal-4">
          <a className="home-cta-primary" href="/platform">Explore the Platform</a>
          <a className="home-cta-secondary" href="/pipeline">See the Pipeline</a>
        </div>
      </div>

      {/* Stats strip — sits flush at bottom of hero */}
      <div className="home-hero-metrics hero-reveal-5">
        <div className="home-hero-metrics-inner">
          <div className="home-hero-metric"><div className="v"><Counter value={50} suffix="+"/></div><div className="l">Active drug assets</div></div>
          <div className="home-hero-metric"><div className="v"><Counter value={150} suffix="+"/></div><div className="l">Licensed or developed</div></div>
          <div className="home-hero-metric"><div className="v"><Counter value={39}/></div><div className="l">Regulatory approvals</div></div>
          <div className="home-hero-metric"><div className="v"><Counter value={5}/></div><div className="l">Therapeutic areas</div></div>
          <div className="home-hero-metric"><div className="v"><Counter value={13}/></div><div className="l">Countries</div></div>
        </div>
      </div>
    </section>
  );
}

// ─────────── Three Pillars ───────────
function Pillars(){
  const pillars = [
    {
      num:"01", title:"Pipeline", name:"50+ Active Assets",
      desc:"Clinical and preclinical programs across neurology, pain, psychiatry, pulmonology, and rheumatology — all mechanistically stratified from Day 0.",
      stats:[["50+","Active assets"],["5","Therapeutic areas"]],
      href:"/pipeline",
      icon:(
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
          <path d="M4 18h4l2-12 4 12 2-6h4"/>
        </svg>
      ),
    },
    {
      num:"02", title:"Platform", name:"BioAtlas",
      desc:"A unified biomedical knowledge graph organizing disease biology around causal mechanisms and ranking therapeutic candidates for each endotype.",
      stats:[["79,000+","endotypes"],["40+","datasets"]],
      href:"/platform",
      icon:(
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
          <circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/>
        </svg>
      ),
    },
    {
      num:"03", title:"People", name:"Scientists & Builders",
      desc:"A team of physician-scientists, operators, and drug developers across five offices, advised by clinical leaders from Barrow Neurological Institute, Banner Health, the University of Arizona, and the University of Utah.",
      stats:[["13","Leadership"],["14","Advisors"]],
      href:"/people",
      icon:(
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
          <circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-3.5 3-6 7-6s7 2.5 7 6"/>
        </svg>
      ),
    },
  ];
  return (
    <section className="home-pillars">
      <div className="home-pillars-inner">
        <div className="home-pillars-eyebrow">What we do</div>
        <h2 className="home-pillars-lead">
          A biopharma built on three integrated pillars: a platform, a pipeline, and the people who
          make them work <em>in concert</em>.
        </h2>
        <div className="pillars-grid">
          {pillars.map((p, i)=>(
            <a key={p.num} href={p.href} className="pillar-card tile-reveal" style={{"--i": i}}>
              <div className="pillar-illo">{p.icon}</div>
              <div className="pillar-num">{p.num} · {p.title}</div>
              <h3 className="pillar-title">{p.name}</h3>
              <p className="pillar-desc">{p.desc}</p>
              <div className="pillar-stats">
                {p.stats.map((s,i)=>(<div key={i}><b>{s[0]}</b>{s[1]}</div>))}
              </div>
              <div className="pillar-cta">
                Learn more
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 8h10M9 4l4 4-4 4"/></svg>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────── BioAtlas Platform section (radial knowledge-graph viz) ───────────
function HomeAtlas(){
  const disease = {
    mondo:"MONDO:0011479",
    short:"0011479",
    name:"Postural Orthostatic Tachycardia Syndrome",
    sub:"6 endotypes · 48 ranked drugs",
  };
  const [activeE, setActiveE] = useState(0);
  const endotypes = window.POTS_ENDOTYPES;
  const ep = endotypes[activeE];
  const topDrug = ep.drugs[0];

  // Canvas geometry
  const W = 960, H = 760;
  const cx = W/2, cy = H/2;
  const rInner = 190;  // disease → endotype orbit
  const rOuter = 320;  // endotype → drug orbit
  const n = endotypes.length;

  const endoPos = endotypes.map((_,i)=>{
    const a = (i/n)*Math.PI*2 - Math.PI/2;
    return { a, x: cx + rInner*Math.cos(a), y: cy + rInner*Math.sin(a) };
  });
  const active = endoPos[activeE];

  const drugs = ep.drugs;
  const spread = Math.PI * 0.55;
  const drugPos = drugs.map((_,i)=>{
    const t = drugs.length === 1 ? 0 : (i/(drugs.length-1)) - 0.5;
    const a = active.a + t*spread;
    return { a, x: cx + rOuter*Math.cos(a), y: cy + rOuter*Math.sin(a) };
  });

  return (
    <section className="home-atlas" id="platform-preview">
      <div className="atlas-inner">
        <div className="atlas-heading">
          <div>
            <div className="atlas-eyebrow">The BioAtlas Platform</div>
            <h2>
              Pick any disease.<br/>
              Get a <span className="hl">mechanism-first</span> drug ranking.
            </h2>
          </div>
          <p>
            A proprietary knowledge graph: 79,000+ molecular endotypes scored against every
            phase-one-safe drug. The instrument below is live on a representative slice.
          </p>
        </div>

        <div className="atlas-viz">
          {/* LEFT — live demo card + platform CTA */}
          <div className="atlas-rail">
            <div className="atlas-rail-eyebrow">
              <span>Live demo</span>
              <span className="atlas-rail-count">1 / 79,000+</span>
            </div>
            <div className="atlas-demo-card">
              <div className="atlas-demo-status">
                <span className="atlas-demo-status-dot" aria-hidden="true"/>
                Active
              </div>
              <div className="atlas-demo-mondo">{disease.mondo}</div>
              <div className="atlas-demo-name">{disease.name}</div>
              <div className="atlas-demo-sub">{disease.sub}</div>
            </div>
            <a className="atlas-rail-cta" href="/platform">
              Browse the full atlas
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                <path d="M3 8h10M9 4l4 4-4 4"/>
              </svg>
            </a>
            <div className="atlas-rail-footnote">
              The instrument on the right is live on this representative slice.
              Tap any endotype node to rank its drug set.
            </div>
          </div>

          {/* RIGHT — instrument canvas */}
          <div className="atlas-canvas">
            <div className="atlas-corner tl">
              <div className="atlas-corner-label">VIV / ATLAS</div>
              <div className="atlas-corner-val">MECHANISM RANKING</div>
            </div>
            <div className="atlas-corner tr">
              <div className="atlas-corner-label">DISEASE FRAME</div>
              <div className="atlas-corner-val">{disease.mondo}</div>
            </div>
            <div className="atlas-corner bl">
              <div className="atlas-corner-label">ENDOTYPES · TIER 1</div>
              <div className="atlas-corner-val">N = {endotypes.length}  ·  MEAN CONF {(endotypes.reduce((s,x)=>s+x.conf,0)/endotypes.length).toFixed(2)}</div>
            </div>
            <div className="atlas-corner br">
              <div className="atlas-corner-label">RANKED ASSETS</div>
              <div className="atlas-corner-val">TOP-K 4 / POOL 210,422</div>
            </div>

            <svg className="atlas-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet">
              <defs>
                <radialGradient id="atlas-glow" cx="50%" cy="50%" r="50%">
                  <stop offset="0%" stopColor="#004AAD" stopOpacity="0.08"/>
                  <stop offset="100%" stopColor="#004AAD" stopOpacity="0"/>
                </radialGradient>
                <radialGradient id="atlas-center" cx="50%" cy="50%" r="50%">
                  <stop offset="0%" stopColor="#1A6BD6"/>
                  <stop offset="100%" stopColor="#004AAD"/>
                </radialGradient>
                <filter id="atlas-shadow" x="-50%" y="-50%" width="200%" height="200%">
                  <feGaussianBlur in="SourceAlpha" stdDeviation="6"/>
                  <feOffset dx="0" dy="6" result="off"/>
                  <feComponentTransfer><feFuncA type="linear" slope="0.35"/></feComponentTransfer>
                  <feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge>
                </filter>
              </defs>

              {/* ambient glow behind center */}
              <circle cx={cx} cy={cy} r={rOuter+40} fill="url(#atlas-glow)" />

              {/* rotating coordinate ring (outer, slow) */}
              <g className="atlas-rotor" style={{transformOrigin:`${cx}px ${cy}px`}}>
                <circle cx={cx} cy={cy} r={rOuter+16} className="atlas-ring outer" />
                {Array.from({length:72}).map((_,i)=>{
                  const a = (i/72)*Math.PI*2 - Math.PI/2;
                  const r1 = rOuter+16, r2 = rOuter + (i%6===0?28:20);
                  return <line key={i}
                    x1={cx+r1*Math.cos(a)} y1={cy+r1*Math.sin(a)}
                    x2={cx+r2*Math.cos(a)} y2={cy+r2*Math.sin(a)}
                    className={`atlas-tick${i%6===0?" major":""}`} />;
                })}
                {[0,90,180,270].map(deg=>{
                  const a = (deg/180)*Math.PI - Math.PI/2;
                  const x = cx + (rOuter+48)*Math.cos(a);
                  const y = cy + (rOuter+48)*Math.sin(a);
                  return <text key={deg} x={x} y={y+3} className="atlas-coord-lbl" textAnchor="middle">{deg.toString().padStart(3,'0')}°</text>;
                })}
              </g>

              {/* static mid + inner orbits */}
              <circle cx={cx} cy={cy} r={rInner} className="atlas-ring" strokeDasharray="2 4" />
              <circle cx={cx} cy={cy} r={rOuter} className="atlas-ring" strokeDasharray="1 5" />

              {/* CENTER → ENDOTYPE edges */}
              {endoPos.map((p,i)=>(
                <line key={`ei-${i}`} x1={cx} y1={cy} x2={p.x} y2={p.y}
                  className={`atlas-edge edge-inner${i===activeE?" on":""}`} />
              ))}

              {/* ENDOTYPE → DRUG edges (active only) */}
              {drugPos.map((p,i)=>(
                <line key={`eo-${i}`} x1={active.x} y1={active.y} x2={p.x} y2={p.y}
                  className="atlas-edge edge-outer on"
                  strokeOpacity={0.25 + drugs[i].score*0.7}
                  strokeWidth={1 + drugs[i].score*1.6} />
              ))}

              {/* ENDOTYPE nodes */}
              {endoPos.map((p,i)=>{
                const nd = endotypes[i];
                const on = i===activeE;
                return (
                  <g key={`en-${i}`} className={`atlas-endo-g${on?" on":""}`}
                     onClick={()=>setActiveE(i)} style={{cursor:"pointer"}}>
                    <circle cx={p.x} cy={p.y} r={on?26:16} className={`atlas-endo-node${on?" on":""}`} />
                    <text x={p.x} y={p.y+4} textAnchor="middle" className="atlas-endo-id">{nd.id}</text>
                    <text x={p.x} y={p.y + (on?48:36)} textAnchor="middle" className="atlas-endo-cap">{nd.tag.toUpperCase()}</text>
                    <text x={p.x} y={p.y + (on?62:50)} textAnchor="middle" className="atlas-endo-cap dim">conf {nd.conf.toFixed(2)}</text>
                  </g>
                );
              })}

              {/* DRUG nodes */}
              {drugPos.map((p,i)=>{
                const d = drugs[i];
                const top = i===0;
                const lblOffsetY = p.y < cy ? -24 : 32;
                return (
                  <g key={`dn-${i}`}>
                    <circle cx={p.x} cy={p.y} r={top?12:8} className={`atlas-drug-node${top?" top":""}`} />
                    {top && <circle cx={p.x} cy={p.y} r={18} className="atlas-drug-halo" />}
                    <text x={p.x} y={p.y + lblOffsetY} textAnchor="middle" className={`atlas-drug-lbl${top?" top":""}`}>{d.name}</text>
                    <text x={p.x} y={p.y + lblOffsetY + 12} textAnchor="middle" className="atlas-drug-score-lbl">{d.score.toFixed(3)}</text>
                  </g>
                );
              })}

              {/* CENTER disease node */}
              <g filter="url(#atlas-shadow)">
                <circle cx={cx} cy={cy} r={62} fill="url(#atlas-center)" stroke="#fff" strokeWidth="2"/>
                <circle cx={cx} cy={cy} r={54} fill="none" stroke="rgba(255,255,255,0.18)" strokeWidth="1"/>
                <text x={cx} y={cy-6} textAnchor="middle" className="atlas-c-mondo">MONDO</text>
                <text x={cx} y={cy+10} textAnchor="middle" className="atlas-c-id">{disease.short}</text>
                <text x={cx} y={cy+26} textAnchor="middle" className="atlas-c-cap">DISEASE · ROOT</text>
              </g>
            </svg>
          </div>

          {/* Right gutter — annotation card */}
          <div className="atlas-annot">
            <div className="atlas-annot-eyebrow">
              <span className="atlas-annot-dot"/>
              {ep.id} · {ep.tag} · conf {ep.conf.toFixed(2)}
            </div>
            <div className="atlas-annot-title">{ep.name}</div>
            <div className="atlas-annot-def">{ep.definition}</div>
            <div className="atlas-annot-genes">
              {ep.genes.map(g=><span key={g} className="atlas-annot-gene">{g}</span>)}
            </div>
            <div className="atlas-annot-drug">
              <div className="atlas-annot-drug-head">
                <span className="atlas-annot-drug-rank">#{topDrug.rank} · Top ranked</span>
                <span className="atlas-annot-drug-score">{topDrug.score.toFixed(3)}</span>
              </div>
              <div className="atlas-annot-drug-name">{topDrug.name}</div>
              <div className="atlas-annot-drug-mech">{topDrug.mech}</div>
              <div className="atlas-annot-bar">
                <span style={{width:`${topDrug.bar}%`}}/>
              </div>
            </div>
          </div>
        </div>

        <div className="atlas-footer-row">
          <div className="atlas-meta-chips">
            <span><b>79,000+</b> endotypes indexed</span>
            <span className="sep"/>
            <span><b>40+</b> integrated datasets</span>
            <span className="sep"/>
            <span><b>Auditable</b> mechanism ranking</span>
            <span className="sep"/>
            <span>Updated <b>Apr 2026</b></span>
          </div>
          <a className="home-cta-primary" href="/platform" style={{background:"#004AAD",color:"#fff"}}>
            Tour the full platform
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 8h10M9 4l4 4-4 4"/></svg>
          </a>
        </div>
      </div>
    </section>
  );
}

// ─────────── Pipeline snapshot — 5 therapeutic areas from the real site ───────────
function HomePipeline(){
  const areas = [
    { area:"Neurology",
      desc:"Neurodegeneration, autoimmune neuro, and rare CNS disorders — mechanistically stratified at entry.",
      color:"#004AAD", phase:"Phase 2", fill:.6 },
    { area:"Pain Management",
      desc:"Non-opioid analgesics and repurposed compounds for chronic and neuropathic pain phenotypes.",
      color:"#306CBC", phase:"Phase 2", fill:.55 },
    { area:"Psychiatry",
      desc:"Treatment-resistant depression, mood disorders, and novel receptor-class therapeutics.",
      color:"#145CDB", phase:"Phase 1", fill:.4 },
    { area:"Pulmonology",
      desc:"Severe asthma, COPD subtypes, and idiopathic pulmonary fibrosis — biomarker-stratified trials.",
      color:"#3393F0", phase:"Phase 2", fill:.65 },
    { area:"Rheumatology",
      desc:"Autoimmune and mast-cell disorders; rare connective tissue diseases with unmet need.",
      color:"#0A2B5C", phase:"Preclinical", fill:.25 },
  ];
  return (
    <section className="home-pipeline">
      <div className="home-pipeline-inner">
        <div className="home-pipeline-head">
          <div>
            <div className="home-pillars-eyebrow">Therapeutic areas</div>
            <h2>
              Focused where<br/>
              impact is most <em>urgent</em>.
            </h2>
          </div>
          <div className="right">
            We develop therapies across five high-priority categories — each chosen for clinical
            relevance, unmet need, and potential for scalable innovation. Every asset enters the
            clinic with a pre-defined responsive population and measurable biomarker.
          </div>
        </div>
        <div className="home-areas">
          {areas.map((a, i)=>(
            <a key={a.area} href="/pipeline" className="home-area tile-reveal" style={{"--i": i}}>
              <div className="home-area-top">
                <div className="home-area-dot" style={{background:a.color}}/>
                <div className="home-area-name">{a.area}</div>
              </div>
              <p className="home-area-desc">{a.desc}</p>
              <div className="home-area-phase">
                <div className="home-area-phase-row">
                  <span className="home-area-phase-lbl">Lead program</span>
                  <span className="home-area-phase-val">{a.phase}</span>
                </div>
                <div className="home-area-phase-bar" style={{"--phase-fill": a.fill, "--phase-color": a.color}}>
                  <span/>
                </div>
              </div>
              <div className="home-area-meta">
                <span>Explore programs</span>
                <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 8h10M9 4l4 4-4 4"/></svg>
              </div>
            </a>
          ))}
        </div>
        <div className="home-pipeline-cta">
          <a className="btn btn-primary" href="/pipeline">
            See the full pipeline
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" style={{marginLeft:8}}><path d="M3 8h10M9 4l4 4-4 4"/></svg>
          </a>
        </div>
      </div>
    </section>
  );
}

// ─────────── Numbers band ───────────
function HomeNumbers(){
  const nums = [
    { v:<Counter value={50} suffix="+"/>, l:"Active drug assets in development across five therapeutic areas", sub:"NCEs, repurposed drugs, and novel formulations" },
    { v:<Counter value={150} suffix="+"/>, l:"Drug assets licensed or developed to date by VivaMed and its founders", sub:"Twenty-year track record" },
    { v:<Counter value={39}/>, l:"Regulatory approvals supported across FDA, EMA, and global health authorities", sub:"Phase 1 through market authorization" },
    { v:<Counter value={13}/>, l:"Countries with active collaborations, clinical partners, or research teams", sub:"Phoenix · New York · Basel · Bogotá · Riyadh" },
  ];
  return (
    <section className="home-numbers">
      <div className="home-numbers-inner">
        <h3>By the numbers</h3>
        <h2>Proven execution across programs, platforms, and partners.</h2>
        <div className="numbers-grid">
          {nums.map((n,i)=>(
            <div key={i} className="num-cell tile-reveal" style={{"--i": i}}>
              <div className="num-v">{n.v}</div>
              <div className="num-l">{n.l}</div>
              <div className="num-sub">{n.sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────── Team preview strip — group photo + 6 headshots ───────────
function HomeTeamPreview(){
  const leaders = (window.PEOPLE_LEADERSHIP || []).slice(0, 6);
  return (
    <section className="home-team">
      <div className="home-team-inner">
        <div className="home-team-head">
          <div className="home-pillars-eyebrow">The People</div>
          <h2>
            Physicians, scientists,<br/>
            and <em>operators</em> who've<br/>
            shipped real medicines.
          </h2>
          <p>
            Our leadership brings combined decades of operating experience across discovery,
            clinical development, regulatory affairs, and commercialization &mdash; the kind of
            unique, hard-won expertise that actually moves programs across the finish line. Together
            they've supported 39 regulatory approvals, founded 15+ healthcare companies, and developed
            150+ drug assets, paired with a 14-member clinical advisory board from Barrow, Banner,
            Creighton, and the University of Arizona.
          </p>
          <a className="btn btn-primary" href="/people">
            Meet the team
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" style={{marginLeft:8}}><path d="M3 8h10M9 4l4 4-4 4"/></svg>
          </a>
        </div>
        <div className="home-team-right">
          <div className="home-team-photo">
            <img src="assets/team-photo.png" alt="The VivaMed team photographed together at an all-hands" loading="lazy"/>
            <div className="home-team-photo-fade" aria-hidden="true"/>
          </div>
          <div className="home-team-faces">
            {leaders.map(p=>(
              <a key={p.name} href="/people" className="home-team-face" title={`${p.name.split(",")[0]} — ${p.title}`}>
                <img src={p.photo} alt={p.name}/>
                <div className="home-team-face-meta">
                  <div className="n">{p.name.split(",")[0]}</div>
                  <div className="r">{p.title}</div>
                </div>
              </a>
            ))}
          </div>
        </div>
      </div>
      <style>{`
        .home-team {
          padding: 120px 0;
          background: #fff;
        }
        .home-team-inner {
          max-width: 1280px;
          margin: 0 auto;
          padding: 0 40px;
          display: grid;
          grid-template-columns: 1fr 1.3fr;
          gap: 72px;
          align-items: start;
        }
        @media (max-width: 1000px) { .home-team-inner { grid-template-columns: 1fr; gap: 48px; } }
        .home-team-head h2 {
          font-size: clamp(32px, 4.4vw, 52px);
          font-weight: 700;
          letter-spacing: -.02em;
          line-height: 1.05;
          color: #0B1C2C;
          margin: 18px 0 20px;
        }
        .home-team-head h2 em {
          font-style: normal;
          color: #004AAD;
        }
        .home-team-head p {
          font-size: 16px;
          line-height: 1.65;
          color: #4A5F77;
          margin: 0 0 28px;
        }
        .home-team-right {
          display: grid;
          gap: 24px;
        }
        .home-team-photo {
          position: relative;
          border-radius: 18px;
          overflow: hidden;
          box-shadow: 0 30px 80px -30px rgba(0, 74, 173, .35);
        }
        .home-team-photo img {
          width: 100%;
          height: auto;
          display: block;
        }
        .home-team-photo-fade {
          position: absolute;
          left: 0; right: 0; bottom: 0; height: 40%;
          background: linear-gradient(180deg, transparent 0%, rgba(11, 28, 44, .35) 100%);
          pointer-events: none;
        }
        .home-team-faces {
          display: grid;
          grid-template-columns: repeat(6, 1fr);
          gap: 14px;
        }
        @media (max-width: 900px) { .home-team-faces { grid-template-columns: repeat(3, 1fr); } }
        .home-team-face {
          position: relative;
          display: block;
          border-radius: 12px;
          overflow: hidden;
          text-decoration: none;
          aspect-ratio: 1 / 1.05;
          background: #e3ebf4;
          transition: transform 200ms ease;
        }
        .home-team-face:hover { transform: translateY(-3px); }
        .home-team-face img {
          width: 100%; height: 100%;
          object-fit: cover;
          display: block;
        }
        .home-team-face-meta {
          position: absolute;
          left: 0; right: 0; bottom: 0;
          padding: 10px 10px 9px;
          background: linear-gradient(180deg, transparent 0%, rgba(11, 28, 44, .85) 100%);
          color: #fff;
        }
        .home-team-face-meta .n {
          font-size: 12px;
          font-weight: 700;
          letter-spacing: -.005em;
          line-height: 1.15;
          margin-bottom: 2px;
        }
        .home-team-face-meta .r {
          font-size: 10px;
          line-height: 1.2;
          color: rgba(255,255,255,.75);
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      `}</style>
    </section>
  );
}

// ─────────── Partner logo strip (reuses shared PARTNER_LOGOS) ───────────
function HomePartnerStrip(){
  const logos = window.PARTNER_LOGOS || [];
  return (
    <section className="home-partners">
      <div className="home-partners-inner">
        <div className="home-partners-head">
          <div className="home-pillars-eyebrow">Our Partners</div>
          <h2>
            Collaborators advancing<br/>
            <em>tomorrow's therapies.</em>
          </h2>
          <p>
            Academic institutions, biotech innovators, and research partners across 13 countries ,
            each one chosen for scientific rigor and real-world execution capacity.
          </p>
        </div>
        <div className="home-partners-strip" role="list" aria-label="VivaMed research and development partners">
          {logos.map(p=>(
            <div key={p.file} className="home-partners-cell" role="listitem">
              <img src={`assets/partner-logos/${p.file}`} alt={p.alt} loading="lazy"/>
            </div>
          ))}
        </div>
        <div className="home-partners-cta">
          <a className="btn btn-ghost" href="/partnerships">
            See all partnerships
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" style={{marginLeft:8}}><path d="M3 8h10M9 4l4 4-4 4"/></svg>
          </a>
        </div>
      </div>
      <style>{`
        .home-partners {
          padding: 100px 0 120px;
          background: linear-gradient(180deg, #F5F8FC 0%, #fff 100%);
        }
        .home-partners-inner {
          max-width: 1280px;
          margin: 0 auto;
          padding: 0 40px;
        }
        .home-partners-head {
          text-align: center;
          max-width: 720px;
          margin: 0 auto 56px;
        }
        .home-partners-head h2 {
          font-size: clamp(30px, 4vw, 48px);
          font-weight: 700;
          letter-spacing: -.02em;
          line-height: 1.08;
          color: #0B1C2C;
          margin: 16px 0 16px;
        }
        .home-partners-head h2 em {
          font-style: normal;
          color: #004AAD;
        }
        .home-partners-head p {
          font-size: 15.5px;
          line-height: 1.65;
          color: #4A5F77;
          margin: 0;
        }
        .home-partners-strip {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
          gap: 28px 36px;
          align-items: center;
          justify-items: center;
        }
        .home-partners-cell {
          width: 100%;
          max-width: 170px;
          height: 72px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .home-partners-cell img {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain;
          filter: grayscale(1);
          opacity: 0.85;
          transition: filter 180ms ease, opacity 180ms ease;
        }
        .home-partners-cell img:hover {
          filter: grayscale(0);
          opacity: 1;
        }
        .home-partners-cta {
          margin-top: 48px;
          text-align: center;
        }
      `}</style>
    </section>
  );
}

// ─────────── Why us · Why now · Why partner ───────────
function HomeWhy(){
  const cols = [
    {
      eyebrow: "Why us",
      head: "Operators who've shipped.",
      body: "Our leadership has combined decades of experience across discovery, clinical development, regulatory affairs, and commercialization — translating into 39 approvals, 150+ assets developed, and 15+ healthcare companies founded.",
      cta: { href:"/people", label:"Meet the team" },
    },
    {
      eyebrow: "Why now",
      head: "Repurposing is hitting its stride.",
      body: "Proven molecules, faster regulatory paths, and a capital-efficient business model — all converging at the moment the industry most needs differentiated, lower-risk programs.",
      cta: { href:"/pipeline", label:"See the pipeline" },
    },
    {
      eyebrow: "Why partner",
      head: "Strong relationships, real access.",
      body: "Deep ties across academic medicine, clinical networks, regulators, and capital — translated into shared infrastructure, real deal flow, and programs that don't sit on the shelf.",
      cta: { href:"/partnerships", label:"Partner with us" },
    },
  ];
  return (
    <section className="home-why">
      <div className="home-why-inner">
        <div className="home-why-head">
          <div className="home-pillars-eyebrow" style={{color:"rgba(255,255,255,.75)"}}>The case for VivaMed</div>
          <h2>Why us. Why now. <em>Why partner.</em></h2>
        </div>
        <div className="home-why-grid">
          {cols.map((c, i)=>(
            <div key={c.eyebrow} className="home-why-cell tile-reveal" style={{"--i": i}}>
              <div className="home-why-eyebrow">{c.eyebrow}</div>
              <h3 className="home-why-h">{c.head}</h3>
              <p className="home-why-p">{c.body}</p>
              <a href={c.cta.href} className="home-why-link">
                {c.cta.label}
                <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 8h10M9 4l4 4-4 4"/></svg>
              </a>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        .home-why {
          padding: 140px 24px;
          background: #004AAD;
          color: #fff;
        }
        .home-why-inner {
          max-width: 1240px;
          margin: 0 auto;
        }
        .home-why-head {
          max-width: 820px;
          margin: 0 auto 72px;
          text-align: center;
        }
        .home-why-head h2 {
          font-size: clamp(32px, 4.6vw, 56px);
          font-weight: 700;
          letter-spacing: -.02em;
          line-height: 1.06;
          color: #fff;
          margin: 18px 0 0;
        }
        .home-why-head h2 em {
          font-style: italic;
          color: #fff;
          font-weight: 600;
          opacity: .82;
        }
        .home-why-grid {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 0;
        }
        @media (max-width: 900px) { .home-why-grid { grid-template-columns: 1fr; } }
        .home-why-cell {
          padding: 40px 36px 8px;
          position: relative;
        }
        .home-why-cell + .home-why-cell {
          border-left: 1px solid rgba(255,255,255,.18);
        }
        @media (max-width: 900px) {
          .home-why-cell + .home-why-cell {
            border-left: 0;
            border-top: 1px solid rgba(255,255,255,.18);
            margin-top: 16px;
            padding-top: 36px;
          }
        }
        .home-why-eyebrow {
          font-family: var(--mono, "IBM Plex Mono", monospace);
          font-size: 11px;
          font-weight: 600;
          letter-spacing: .14em;
          text-transform: uppercase;
          color: rgba(255,255,255,.7);
          margin-bottom: 18px;
        }
        .home-why-h {
          font-size: clamp(22px, 2.2vw, 28px);
          font-weight: 700;
          letter-spacing: -.01em;
          line-height: 1.15;
          color: #fff;
          margin: 0 0 16px;
        }
        .home-why-p {
          font-size: 15px;
          line-height: 1.7;
          color: rgba(255, 255, 255, .82);
          margin: 0 0 24px;
        }
        .home-why-link {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          font-family: var(--mono, "IBM Plex Mono", monospace);
          font-size: 12px;
          font-weight: 600;
          letter-spacing: .08em;
          text-transform: uppercase;
          color: #fff;
          text-decoration: none;
          border-bottom: 1px solid rgba(255,255,255,.35);
          padding-bottom: 3px;
          transition: border-bottom-color .15s ease;
        }
        .home-why-link:hover { border-bottom-color: #fff; }
      `}</style>
    </section>
  );
}

// ─────────── App ───────────
function App(){
  return (
    <>
      <HomeHero/>
      <Pillars/>
      <HomeNumbers/>
      <HomePartnerStrip/>
      <HomeWhy/>
      <FooterCTA/>
    </>
  );
}

return App;
})();
