// Tools + Footer
function Tools(){
  return (
    <section className="section">
      <div className="section-inner">
        <SectionHead
          eyebrow="BioAtlas enterprise tools"
          title="Clinical-grade analysis at enterprise scale."
          lede="A suite of tools that turns 79,000+ endotypes and 39.4M drug predictions into actionable clinical and commercial intelligence."
        />
        <div className="tools-grid">
          {TOOLS.map((t,i)=>(
            <div key={i} className={`tool-card tile-reveal${t.featured?" featured":""}`} style={{"--i": i}}>
              <div className="tool-badge"><span style={{width:6,height:6,borderRadius:3,background:"currentColor",display:"inline-block"}}/>{t.badge}</div>
              <h3 className="tool-title">{t.title}</h3>
              <p className="tool-desc">{t.desc}</p>
              {t.stats.length>0 && (
                <div className="tool-stats">
                  {t.stats.map((s,j)=>(
                    <div key={j}>
                      <div className="tool-stat-v">{s[0]}</div>
                      <div className="tool-stat-l">{s[1]}</div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// Panels reused by the standalone Prediction + Lazarus sections below.
function TaxonomyPanel(){
  return (
    <div className="layers">
      {TAXONOMY_LAYERS.map(l=>(
        <div key={l.num} className="layer-card">
          <div className="layer-num"><span className="layer-num-badge">{l.num}</span>Tier {l.num}</div>
          <div className="layer-count">{l.count}</div>
          <div className="layer-count-sub">{l.sub}</div>
          <h3>{l.title}</h3>
          <p>{l.body}</p>
          <div className="layer-chips">
            {l.chips.map(c=><span key={c} className="gene-chip lg">{c}</span>)}
          </div>
        </div>
      ))}
    </div>
  );
}

function ScoringPanel(){
  const principles = [
    { k:"Multi-omic", d:"Each prediction integrates orthogonal layers — human genetics, transcriptomics, functional genomics, and known pharmacology — never a single signal." },
    { k:"Directionally aware", d:"We check a drug pushes the pathway the right way — inhibit vs. activate — matched to what the subtype actually needs, from established pharmacology." },
    { k:"Mechanism-grounded & auditable", d:"Every prediction traces to a named, inspectable rule against the subtype's causal biology. No black-box score to take on faith." },
    { k:"Safety-gated", d:"Contraindication and adverse-event signals act as a final gate, so unsafe pairings can't surface near the top." },
  ];
  return (
    <div className="tab-panel-dark">
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(240px,1fr))",gap:18}}>
        {principles.map((p,i)=>(
          <div key={p.k} style={{padding:"22px 20px",background:"rgba(255,255,255,.04)",border:"1px solid rgba(255,255,255,.10)",borderRadius:14}}>
            <div style={{fontFamily:"var(--mono)",fontSize:12,letterSpacing:".14em",color:"#5AA0F0"}}>0{i+1}</div>
            <div style={{fontSize:16,fontWeight:700,color:"#fff",margin:"10px 0 8px"}}>{p.k}</div>
            <div style={{fontSize:13.5,lineHeight:1.55,color:"#9DB1C5"}}>{p.d}</div>
          </div>
        ))}
      </div>
      <p style={{marginTop:20,fontSize:13,color:"#6E8297",fontFamily:"var(--mono)",lineHeight:1.5}}>
        Calibrated against FDA-validated repurposing successes. The underlying feature set and weights are proprietary.
      </p>
    </div>
  );
}

function LazarusPanel(){
  return (
    <div className="laz">
      <div>
        <div style={{fontFamily:"var(--mono)",fontSize:11,letterSpacing:".12em",textTransform:"uppercase",color:"var(--primary)",marginBottom:14}}>Five revival pathways</div>
        <div className="laz-strategies">
          {LAZARUS_STEPS.map(s=>(
            <div key={s.n} className="laz-step">
              <div className={`laz-step-n${s.n>3?" d":""}`}>{s.n}</div>
              <div>
                <div className="laz-step-name">{s.name}</div>
                <div className="laz-step-desc">{s.d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="laz-example">
        <div style={{fontFamily:"var(--mono)",fontSize:11,letterSpacing:".14em",textTransform:"uppercase",color:"var(--link)"}}>Illustrative revival · Selumetinib (MEK inhibitor)</div>
        <div className="laz-orig">
          <div>
            <div className="laz-orig-lbl">Original indication</div>
            <div className="laz-orig-name">Non-Small Cell Lung Cancer</div>
          </div>
          <div className="laz-fail">PHASE 3 · FAILED</div>
        </div>
        <div className="laz-revivals">
          {LAZARUS_REVIVALS.map((r,i)=>(
            <div key={i} className="laz-rev">
              <div className="laz-rev-head">
                <span className="laz-rev-strat">{i+1}. {r.strat}</span>
              </div>
              <p className="laz-rev-desc">{r.d}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// Causal-genetics content as a ticker panel (three evidence axes + convergence
// stats + the "honest by design" note). IP-clean: no internal names/weights.
function CausalGeneticsPanel(){
  const AXES = [
    { tag:"Population genetics", sub:"GWAS × QTL",
      body:"Colocalization + Mendelian randomization: disease signal and gene expression trace to the same causal variant, replicated across ancestries.",
      chips:["PCSK9 → coronary disease","IL23R → IBD","HMGCR → lipids"] },
    { tag:"Functional dependency", sub:"CRISPR screens",
      body:"Genome-wide screens confirm cells truly depend on the gene — pan-essential housekeeping genes are filtered out.",
      chips:["selective dependency","not pan-essential"] },
    { tag:"Clinical genetics", sub:"ClinVar · ClinGen · Orphanet",
      body:"Pathogenic variants and curated gene–disease validity add rare-Mendelian proof that GWAS alone can't see.",
      chips:["pathogenic variants","curated validity","rare Mendelian"] },
  ];
  const CONV = [
    { n:"~130K", l:"causal gene–disease links" },
    { n:"3", l:"independent evidence axes" },
    { n:"17 / 19", l:"orthogonal substrates confirm (p < 0.05)" },
  ];
  return (
    <div className="cg-panel">
      <div className="cg-axes">
        {AXES.map((a,i)=>(
          <div key={a.tag} className="cg-axis">
            <div className="cg-axis-num">0{i+1}</div>
            <div className="cg-axis-tag">{a.tag}</div>
            <div className="cg-axis-sub">{a.sub}</div>
            <p className="cg-axis-body">{a.body}</p>
            <div className="cg-chips">{a.chips.map(c=><span key={c} className="cg-chip">{c}</span>)}</div>
          </div>
        ))}
      </div>
      <div className="cg-stats">
        {CONV.map(c=>(
          <div key={c.l} className="cg-stat"><b>{c.n}</b>{c.l}</div>
        ))}
      </div>
      <p className="cg-note">
        <span className="cg-note-mark">Honest by design</span>
        Genetics tells us <em>which</em> gene drives a disease — not which way to push it. Direction comes from established pharmacology.
      </p>
      <style>{`
        .cg-axes{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:18px;margin-bottom:22px}
        .cg-axis{background:#fff;border:1px solid #e3ebf4;border-radius:14px;padding:22px 20px}
        .cg-axis-num{font-family:var(--mono,"IBM Plex Mono",monospace);font-size:12px;letter-spacing:.14em;color:#3393F0}
        .cg-axis-tag{font-size:16px;font-weight:800;color:#0B1C2C;margin-top:10px;letter-spacing:-.01em}
        .cg-axis-sub{font-family:var(--mono,"IBM Plex Mono",monospace);font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#6E8297;margin-top:3px}
        .cg-axis-body{font-size:13.5px;line-height:1.55;color:#4A5F77;margin:12px 0 14px}
        .cg-chips{display:flex;flex-wrap:wrap;gap:7px}
        .cg-chip{font-family:var(--mono,"IBM Plex Mono",monospace);font-size:11.5px;padding:5px 10px;border-radius:7px;background:#eef4fc;color:#004AAD;border:1px solid #d9e6f7}
        .cg-stats{display:flex;flex-wrap:wrap;gap:10px 28px;padding:18px 4px 0;border-top:1px solid #e3ebf4;margin-bottom:16px}
        .cg-stat{font-size:13px;color:#6E8297}
        .cg-stat b{font-family:var(--mono,"IBM Plex Mono",monospace);font-size:17px;font-weight:700;color:#004AAD;margin-right:7px}
        .cg-note{font-size:13px;line-height:1.6;color:#6E8297;margin:0}
        .cg-note em{color:#004AAD;font-style:italic;font-weight:600}
        .cg-note-mark{font-family:var(--mono,"IBM Plex Mono",monospace);font-size:10.5px;letter-spacing:.12em;text-transform:uppercase;color:#004AAD;font-weight:700;margin-right:8px}
      `}</style>
    </div>
  );
}

// Auto-cycling "ticker" that slides through the platform internals so the page
// stays short. Pauses on hover/focus; respects reduced motion.
function PlatformTabs(){
  const tabs = [
    { key:"taxonomy", label:"Taxonomy",
      eyebrow:"Mechanism-based classification",
      title:"Three layers of mechanistic organization.",
      lede:"BioAtlas replaces traditional organ-based disease classification with a three-tier mechanism hierarchy. Every disease is placed within its molecular context, from broad signaling families down to atomic endotype definitions.",
      Panel: TaxonomyPanel },
    { key:"genetics", label:"Causal genetics",
      eyebrow:"Causal genetics",
      title:"Association isn't causation. We require proof of cause.",
      lede:"Every endotype is anchored to a causal gene — confirmed across three independent classes of human evidence — before we predict a single drug for it.",
      Panel: CausalGeneticsPanel },
    { key:"scoring", label:"How prediction works",
      eyebrow:"Multi-omic prediction",
      title:"How every drug–subtype match is predicted.",
      lede:"Each prediction integrates multiple orthogonal layers of evidence and is directionally aware — it checks a drug pushes the pathway the right way, not just that it hits the target. A bounded AI reviewer can promote a well-reasoned candidate but never override the safety gate. Every prediction is auditable.",
      Panel: ScoringPanel },
    { key:"lazarus", label:"Lazarus revival",
      eyebrow:"Lazarus revival engine",
      title:"Revive the failed trial.",
      lede:"Phase 2 and Phase 3 failures aren't always biological dead ends. Lazarus re-examines a failed compound against BioAtlas endotypes — separating responders from non-responders — to find the rescue population a shelved asset still helps, plus adjacent diseases that share the same mechanism.",
      Panel: LazarusPanel },
  ];

  const FADE_MS = 240;
  const CYCLE_MS = 7000;

  const [active, setActive] = React.useState(0);
  const [shown, setShown] = React.useState(0);
  const [fading, setFading] = React.useState(false);
  const [cycleId, setCycleId] = React.useState(0);
  const pausedRef = React.useRef(false);
  const intervalRef = React.useRef(null);
  const reducedRef = React.useRef(false);
  const sectionRef = React.useRef(null);

  const startInterval = React.useCallback(() => {
    clearInterval(intervalRef.current);
    if (reducedRef.current) return;
    intervalRef.current = setInterval(() => {
      if (pausedRef.current) return;
      setActive(prev => (prev + 1) % tabs.length);
      setCycleId(c => c + 1);
    }, CYCLE_MS);
  }, [tabs.length]);

  React.useEffect(() => {
    reducedRef.current = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches || false;
    if (reducedRef.current) { setShown(active); return; }
    startInterval();
    return () => clearInterval(intervalRef.current);
  }, [startInterval]);

  React.useEffect(() => {
    if (active === shown) return;
    if (reducedRef.current) { setShown(active); return; }
    setFading(true);
    const t = setTimeout(() => { setShown(active); setFading(false); }, FADE_MS);
    return () => clearTimeout(t);
  }, [active, shown]);

  const onTabClick = (i) => {
    setActive(i);
    setCycleId(c => c + 1);
    startInterval();
  };

  // Let an in-page CTA (e.g. the hero's "See the scoring engine") jump here.
  React.useEffect(() => {
    const handler = (e) => {
      const idx = tabs.findIndex(t => t.key === e.detail);
      if (idx < 0) return;
      setActive(idx);
      setCycleId(c => c + 1);
      startInterval();
      const el = sectionRef.current;
      if (el) {
        const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
        el.scrollIntoView({ behavior: reduced ? "auto" : "smooth", block: "start" });
      }
    };
    window.addEventListener("vm:show-platform-tab", handler);
    return () => window.removeEventListener("vm:show-platform-tab", handler);
  }, [startInterval, tabs.length]);

  const tab = tabs[shown];

  return (
    <section
      ref={sectionRef}
      className="section surface platform-tabs"
      onPointerEnter={()=>{ pausedRef.current = true; }}
      onPointerLeave={()=>{ pausedRef.current = false; }}
      onFocusCapture={()=>{ pausedRef.current = true; }}
      onBlurCapture={()=>{ pausedRef.current = false; }}
    >
      <div className="section-inner">
        <div className="platform-tabs-head">
          <div className="section-eyebrow"><span className="line"/>Inside the platform</div>
          <h2 className="section-title">Four systems, one operating model.</h2>
          <p className="section-lede">A mechanism taxonomy, causal-genetics proof, a multi-omic prediction engine, and a revival pathway for trial failures — each working off the same endotype layer.</p>
        </div>
        <div className="platform-tabs-nav-wrap">
          <div className="platform-tabs-nav" role="tablist" aria-label="Platform internals">
            {tabs.map((t, i) => (
              <button key={t.key}
                role="tab"
                aria-selected={i===active}
                aria-controls={`tab-panel-${t.key}`}
                id={`tab-${t.key}`}
                className="platform-tabs-tab"
                onClick={()=>onTabClick(i)}>
                <span className="platform-tabs-tab-num">0{i+1}</span>
                <span className="platform-tabs-tab-label">{t.label}</span>
              </button>
            ))}
          </div>
          <div className="platform-tabs-progress" aria-hidden="true">
            <span key={`progress-${cycleId}`}/>
          </div>
        </div>
        <div className={`platform-tabs-content${fading ? " is-fading" : ""}`}>
          <div className="platform-tabs-panel-head">
            <div className="section-eyebrow"><span className="line"/>{tab.eyebrow}</div>
            <h3 className="platform-tabs-panel-title">{tab.title}</h3>
            <p className="platform-tabs-panel-lede">{tab.lede}</p>
          </div>
          <div
            id={`tab-panel-${tab.key}`}
            role="tabpanel"
            aria-labelledby={`tab-${tab.key}`}
            className="platform-tabs-panel">
            <tab.Panel/>
          </div>
        </div>
      </div>
    </section>
  );
}

function CTAStrip(){
  return (
    <section className="footer-cta">
      <h2>Ready to stratify your pipeline?</h2>
      <p>Run your candidate compounds against 79,000+ molecular endotypes. Identify the responsive subpopulation. Generate the biomarker. Design the trial.</p>
      <div className="footer-cta-actions">
        <a className="btn btn-dark" href="mailto:info@vivamed.com">Request platform access →</a>
        <a className="btn btn-ghost" href="/partnerships" style={{borderColor:"rgba(255,255,255,.4)"}}>Explore partnerships</a>
      </div>
    </section>
  );
}

function PageFooter(){
  return (
    <footer className="foot">
      <div className="foot-inner">
        <div className="foot-col">
          <img src="assets/vivamed-logo-300.png" alt="VivaMed" style={{height:36,filter:"brightness(0) invert(1)",opacity:.95,marginBottom:14}}/>
          <p style={{fontSize:13.5,color:"#9DB1C5",margin:0,maxWidth:300,lineHeight:1.55}}>
            Precision drug repurposing. Mechanism-grounded. Biomarker enriched.
          </p>
        </div>
        <div className="foot-col">
          <h4>Product</h4>
          <ul>
            <li><a href="/platform">BioAtlas Platform</a></li>
            <li><a href="/pipeline">Pipeline</a></li>
            <li><a href="/partnerships">Partnerships</a></li>
          </ul>
        </div>
        <div className="foot-col">
          <h4>Company</h4>
          <ul>
            <li><a href="/people">Team</a></li>
            <li><a href="/advisors">Advisors</a></li>
            <li><a href="/partnerships">Partnerships</a></li>
            <li><a href="/contact">Contact</a></li>
          </ul>
        </div>
        <div className="foot-col">
          <h4>Legal &amp; contact</h4>
          <ul>
            <li><a href="/privacy-policy">Privacy Policy</a></li>
            <li><a href="/terms-of-use">Terms of Use</a></li>
            <li><a href="mailto:info@vivamed.com">info@vivamed.com</a></li>
            <li><a href="/contact">Contact page</a></li>
          </ul>
        </div>
      </div>
      <div className="foot-copy">
        <span>© 2026 VivaMed BioPharma · All rights reserved</span>
        <span>Phoenix · New York · Basel · Bogotá · Riyadh</span>
      </div>
    </footer>
  );
}

function FooterCTA(){
  return (
    <>
      <CTAStrip/>
      <PageFooter/>
    </>
  );
}

Object.assign(window, { Tools, PlatformTabs, FooterCTA, CTAStrip, PageFooter });
