window.PipelineApp = (function(){
const { useState, useMemo } = React;

// ─────────── Hero infographic — mechanism diagram (top) ───────────
function MechanismDiagram(){
  const nodes = [
    { kind:"trigger", label:"Chronic stress / Neurodegeneration" },
    { kind:"loss",    label:"GABAergic tone depleted" },
    { kind:"restore", label:"Restored homeostatic tone" },
    { kind:"outcome", label:"Slowed hippocampal atrophy", badge:"APOE ε4" },
  ];
  return (
    <div className="mech">
      <div className="mech-head">
        <div className="mech-eyebrow">VM-NEU-001 · Mechanism</div>
        <div className="mech-tag">First-in-class</div>
      </div>
      <ol className="mech-steps">
        {nodes.map((n,i)=>(
          <li key={i} className={`mech-node mech-${n.kind}`}>
            <span className="mech-node-num">{i+1}</span>
            <span className="mech-node-label">{n.label}</span>
            {n.badge && <span className="apoe-badge">{n.badge}</span>}
          </li>
        ))}
      </ol>
    </div>
  );
}

// ─────────── Hero infographic — portfolio Gantt (bottom) ───────────
function PortfolioGantt(){
  const stages = window.PIPELINE_STAGES;
  const tas = window.TA_PORTFOLIO;
  const assets = window.PIPELINE_ASSETS;

  const grid = useMemo(() => {
    const m = {};
    tas.forEach(t => { m[t.key] = {}; stages.forEach(s => m[t.key][s] = 0); });
    assets.forEach(a => {
      const stage = window.stageOf(a.nextPhase);
      a.ta.forEach(taKey => { if (m[taKey]) m[taKey][stage] += 1; });
    });
    return m;
  }, []);

  const maxCount = Math.max(1, ...tas.flatMap(t => stages.map(s => grid[t.key][s])));

  return (
    <div className="pipe-gantt">
      <div className="pipe-gantt-head">
        <span>Sample portfolio · 17 candidates</span>
        <span className="pipe-gantt-head-legend">by stage</span>
      </div>
      <div className="pipe-gantt-axis">
        <span/>
        {stages.map(s => <span key={s}>{s.replace("Phase ","P")}</span>)}
      </div>
      <div className="pipe-gantt-rows">
        {tas.map(t => (
          <div key={t.key} className="pipe-gantt-row ta-row">
            <div className="pipe-gantt-code">
              <span className="ta-dot" style={{background:t.dot}}/>
              {t.name}
            </div>
            <div className="pipe-gantt-track" style={{gridTemplateColumns:`repeat(${stages.length}, 1fr)`}}>
              {stages.map(s => {
                const c = grid[t.key][s];
                const op = c === 0 ? 0 : (0.35 + (c / maxCount) * 0.55);
                return (
                  <div key={s} className="pipe-gantt-cell">
                    {c > 0 && (
                      <div className="pipe-gantt-fill ta-count" style={{background:t.dot, opacity:op}}>
                        <span>{c}</span>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─────────── Pipeline hero ───────────
function PipeHero(){
  const T = window.PORTFOLIO_TOTALS;
  return (
    <section className="pipe-hero">
      <div className="pipe-hero-inner">
        <div className="pipe-hero-left">
          <h1>Targeting what others won't.<br/>Advancing what others can't.</h1>
          <p className="pipe-hero-lede">
            VivaMed BioPharma's pipeline includes over <b>50 active drug assets</b> — ranging from
            new chemical entities to repurposed drugs — focused on areas of critical unmet need.
          </p>
          <div className="hero-ctas">
            <a className="btn btn-primary" href="#assets">Explore the candidates</a>
            <a className="btn btn-ghost" href="/platform">Read the platform →</a>
          </div>
          <div className="pipe-hero-kpis" style={{gridTemplateColumns:"repeat(4, minmax(0,1fr))"}}>
            <div><div className="n">{T.assetsLabel}</div><div className="l">Active drug assets</div></div>
            <div><div className="n">{T.licensedLabel}</div><div className="l">Licensed or developed</div></div>
            <div><div className="n">{T.approvalsLabel}</div><div className="l">Regulatory approvals</div></div>
            <div><div className="n">{T.ta}</div><div className="l">Therapeutic areas</div></div>
          </div>
        </div>
        <div className="pipe-hero-right">
          <MechanismDiagram/>
          <PortfolioGantt/>
        </div>
      </div>
    </section>
  );
}

// ─────────── Lead asset spotlight ───────────
function LeadAsset(){
  const lead = window.PIPELINE_ASSETS.find(a => a.isLead);
  if (!lead) return null;
  const ta = window.TA_PORTFOLIO.find(t => t.key === lead.ta[0]);
  return (
    <section className="section" id="lead">
      <div className="section-inner">
        <SectionHead
          eyebrow="Lead program · Spotlight"
          title="Non-addictive relief for severe neuropathic pain."
          lede="A first-in-class small molecule targeting a genetically validated, historically undruggable channel through a novel indirect mechanism — durable preclinical analgesia with no opioid liability. Lead indication: trigeminal neuralgia."
        />
        <article className="lead-card">
          <header className="lead-card-head">
            <div className="lead-card-area">
              <span className="dot" style={{background:ta?.dot}}/>{ta?.name}
            </div>
            <div className="lead-card-tags">
              <span className="lead-tag">{lead.classification}</span>
              <span className="lead-tag lead-tag-ghost">{lead.drugType}</span>
            </div>
          </header>
          <div className="lead-card-grid">
            <div className="lead-card-body">
              <div className="lead-card-code">{lead.code}</div>
              <h3 className="lead-card-disease">{lead.disease}</h3>
              {lead.long.map((p,i)=><p key={i} className="lead-card-prose">{p}</p>)}
            </div>
            <aside className="lead-card-meta">
              <dl>
                <div><dt>Therapeutic Category</dt><dd>{ta?.name}</dd></div>
                <div><dt>Disease Area</dt><dd>{lead.disease}</dd></div>
                <div><dt>Drug Type</dt><dd>{lead.drugType}</dd></div>
                <div><dt>Classification</dt><dd>{lead.classification}</dd></div>
                <div><dt>Next Phase</dt><dd>{lead.nextPhase}</dd></div>
              </dl>
            </aside>
          </div>
        </article>
      </div>
    </section>
  );
}

// ─────────── Portfolio buckets (TA descriptions) ───────────
function PortfolioBuckets(){
  return (
    <section className="section" id="portfolio">
      <div className="section-inner">
        <SectionHead
          eyebrow="Portfolio by therapeutic area"
          title="Five areas. A mix of NCEs and repurposed drugs."
          lede="We develop across five therapeutic areas chosen for clinical relevance, unmet need, and potential for scalable innovation. Every program enters the clinic with a pre-defined responsive population and measurable biomarker."
        />
        <div className="ta-grid">
          {window.TA_PORTFOLIO.map(t=>(
            <div key={t.key} className="ta-card ta-card-lg">
              <div className="ta-card-head">
                <div className="ta-card-dot" style={{background:t.dot}}/>
                <div className="ta-card-name">{t.name}</div>
              </div>
              <p className="ta-card-desc">{t.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────── All candidates grid (filterable) ───────────
function AssetCard({a}){
  const taPrimary = window.TA_PORTFOLIO.find(t => t.key === a.ta[0]);
  const stage = window.stageOf(a.nextPhase);
  const stages = window.PIPELINE_STAGES;
  const stageIdx = stages.indexOf(stage);
  return (
    <article className={`rep-card asset-card${a.isLead ? " is-lead":""}`}>
      <div className="rep-card-top">
        <span className="rep-card-area">
          <span className="dot" style={{background:taPrimary?.dot}}/>{taPrimary?.name}
          {a.ta.length > 1 && <span className="asset-multi">+{a.ta.length-1}</span>}
        </span>
        <span className="rep-card-tag">{a.classification}</span>
      </div>
      <h3 className="rep-card-title">{a.code}</h3>
      <div className="rep-card-sub">{a.disease}</div>
      <div className="phase-bar" aria-label={`Stage: ${stage}`}>
        {stages.map((s,i)=>(
          <div key={s} className={`phase-cell${i < stageIdx ? " done":""}${i === stageIdx ? " current":""}`}/>
        ))}
      </div>
      <div className="phase-labels">
        {stages.map((s,i)=>(
          <span key={s} className={i === stageIdx ? "active" : ""}>{s.replace("Phase ","P")}</span>
        ))}
      </div>
      {a.long.map((p,i)=><p key={i} className="rep-card-desc">{p}</p>)}
      <div className="rep-card-meta">
        <div><span>Drug Type</span><b>{a.drugType}</b></div>
        <div><span>Next Phase</span><b>{a.nextPhase}</b></div>
      </div>
    </article>
  );
}

function AllAssets(){
  const [filter, setFilter] = useState("all");
  const [page, setPage] = useState(0);
  const PAGE_SIZE = 4;
  const tas = window.TA_PORTFOLIO;
  const all = window.PIPELINE_ASSETS;
  const visible = filter === "all" ? all : all.filter(a => a.ta.includes(filter));
  const totalPages = Math.max(1, Math.ceil(visible.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages - 1);
  const pageStart = safePage * PAGE_SIZE;
  const pageVisible = visible.slice(pageStart, pageStart + PAGE_SIZE);
  const counts = useMemo(() => {
    const c = { all: all.length };
    tas.forEach(t => { c[t.key] = all.filter(a => a.ta.includes(t.key)).length; });
    return c;
  }, []);
  // Reset to first page whenever the filter changes.
  useEffect(() => { setPage(0); }, [filter]);
  return (
    <section className="section section-light" id="assets">
      <div className="section-inner">
        <SectionHead
          eyebrow="Sample portfolio"
          title="A sample portfolio of 17 candidates."
          lede="A representative selection from our broader pipeline of 50+ active assets — each shown with its mechanism, indication, drug type, classification, and next-phase plan."
        />
        <div className="filter-bar" role="tablist" aria-label="Filter by therapeutic area">
          <span className="filter-lbl">Filter</span>
          <button
            className={`filter-chip${filter==="all"?" active":""}`}
            onClick={()=>setFilter("all")}
            role="tab" aria-selected={filter==="all"}
          >All <span className="filter-count">{counts.all}</span></button>
          {tas.map(t => (
            <button
              key={t.key}
              className={`filter-chip${filter===t.key?" active":""}`}
              onClick={()=>setFilter(t.key)}
              role="tab" aria-selected={filter===t.key}
            >
              <span className="filter-dot" style={{background:t.dot}}/>
              {t.name} <span className="filter-count">{counts[t.key]}</span>
            </button>
          ))}
        </div>
        <div className="rep-grid asset-grid">
          {pageVisible.map(a => <AssetCard key={a.code} a={a}/>)}
        </div>
        {totalPages > 1 && (
          <div className="asset-pager" role="navigation" aria-label="Candidate list pagination">
            <button
              className="asset-pager-btn"
              onClick={() => setPage(Math.max(0, safePage - 1))}
              disabled={safePage === 0}
              aria-label="Previous page"
            >← Prev</button>
            <div className="asset-pager-meta">
              Showing <b>{pageStart + 1}</b>–<b>{Math.min(pageStart + PAGE_SIZE, visible.length)}</b> of <b>{visible.length}</b>
            </div>
            <div className="asset-pager-dots" role="tablist">
              {Array.from({length: totalPages}).map((_, i) => (
                <button
                  key={i}
                  className={`asset-pager-dot${i === safePage ? " active" : ""}`}
                  onClick={() => setPage(i)}
                  aria-label={`Page ${i + 1}`}
                  aria-selected={i === safePage}
                  role="tab"
                />
              ))}
            </div>
            <button
              className="asset-pager-btn"
              onClick={() => setPage(Math.min(totalPages - 1, safePage + 1))}
              disabled={safePage >= totalPages - 1}
              aria-label="Next page"
            >Next →</button>
          </div>
        )}
        <p className="rep-note">
          Source of truth: the codes, classifications, and language above are reproduced from VivaMed's internal candidate dossier. Detailed program packages available to qualified partners under CDA.
        </p>
      </div>
      <style>{`
        .asset-pager {
          display: flex;
          align-items: center;
          gap: 18px;
          flex-wrap: wrap;
          justify-content: space-between;
          margin: 32px 0 16px;
          padding: 14px 18px;
          background: #fff;
          border: 1px solid #e3ebf4;
          border-radius: 10px;
        }
        .asset-pager-btn {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 8px 14px;
          border-radius: 999px;
          background: #fff;
          border: 1px solid #d4dde8;
          color: #0B1C2C;
          font-family: var(--mono, "IBM Plex Mono", monospace);
          font-size: 12px;
          letter-spacing: .04em;
          font-weight: 600;
          cursor: pointer;
          transition: border-color .15s ease, background .15s ease, color .15s ease;
        }
        .asset-pager-btn:hover:not(:disabled) {
          border-color: #004AAD;
          background: rgba(0,74,173,.05);
          color: #004AAD;
        }
        .asset-pager-btn:disabled {
          opacity: .4;
          cursor: not-allowed;
        }
        .asset-pager-meta {
          font-family: var(--mono, "IBM Plex Mono", monospace);
          font-size: 12px;
          letter-spacing: .04em;
          color: #6B8AAB;
        }
        .asset-pager-meta b {
          color: #0B1C2C;
          font-weight: 700;
        }
        .asset-pager-dots {
          display: inline-flex;
          gap: 6px;
        }
        .asset-pager-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          border: 0;
          padding: 0;
          background: #d4dde8;
          cursor: pointer;
          transition: background .15s ease, transform .15s ease;
        }
        .asset-pager-dot:hover { background: #99b3d3; }
        .asset-pager-dot.active {
          background: #004AAD;
          transform: scale(1.25);
        }
        @media (max-width: 640px) {
          .asset-pager { gap: 12px; padding: 12px 14px; }
          .asset-pager-meta { order: 3; width: 100%; text-align: center; }
        }
      `}</style>
    </section>
  );
}

// ─────────── Smarter model — 5 tenets ───────────
function SmarterModel(){
  return (
    <section className="section" id="model">
      <div className="section-inner">
        <SectionHead
          eyebrow="A smarter, faster pipeline model"
          title="AI at every stage — from candidate selection to IND."
          lede="We accelerate development using AI to model toxicity, optimize dosage, and draft regulatory and IP filings. We also prioritize repurposed drugs and novel formulations, leveraging existing safety data to cut time and cost from development timelines."
        />
        <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:16}}>
          {[
            {n:"01",t:"Candidate selection",d:"Our AI platform scans compound libraries, published literature, and clinical data to surface candidates with the strongest biological rationale against validated targets."},
            {n:"02",t:"Toxicity & dosage modeling",d:"In-silico models predict off-target effects, tissue exposure, and optimal dosing windows before a single in-vivo study is run — slashing preclinical attrition."},
            {n:"03",t:"Regulatory & IP drafting",d:"AI co-scientists draft IND packages, FTO analyses, and initial patent claims, which our scientists and counsel then refine — compressing months of paperwork into weeks."},
            {n:"04",t:"Repurposed-drug acceleration",d:"For approved molecules redirected to new indications, we leverage existing safety data to shortcut development — often entering the clinic on an 18-month timeline."},
          ].map(s=>(
            <div key={s.n} className="smart-step">
              <div className="smart-step-n">{s.n}</div>
              <div className="smart-step-t">{s.t}</div>
              <div className="smart-step-d">{s.d}</div>
            </div>
          ))}
        </div>

        <div className="smart-tenets smart-tenets-5">
          <div className="smart-tenet">
            <div className="smart-tenet-n">50+</div>
            <div className="smart-tenet-l">active drug assets in development</div>
          </div>
          <div className="smart-tenet">
            <div className="smart-tenet-n">150+</div>
            <div className="smart-tenet-l">licensed or developed to date</div>
          </div>
          <div className="smart-tenet">
            <div className="smart-tenet-n">39</div>
            <div className="smart-tenet-l">regulatory approvals supported</div>
          </div>
          <div className="smart-tenet">
            <div className="smart-tenet-n">AI</div>
            <div className="smart-tenet-l">AI-assisted development, from ideation to IND</div>
          </div>
          <div className="smart-tenet">
            <div className="smart-tenet-n">NCEs + Repurposed</div>
            <div className="smart-tenet-l">both breakthrough therapies and best-in-class repurposed drugs</div>
          </div>
        </div>
      </div>
    </section>
  );
}

function PipeFooterCTA(){
  return (
    <>
      <section className="footer-cta">
        <h2>Interested in partnering on a program?</h2>
        <p>We partner with pharma, biotech, academic medical centers, and patient foundations to accelerate promising assets — through licensing, co-development, and risk-sharing structures. Qualified partners can access more detailed program information under CDA.</p>
        <div className="footer-cta-actions">
          <a className="btn btn-dark" href="/partnerships">Explore partnerships →</a>
          <a className="btn btn-ghost" href="/platform" style={{borderColor:"rgba(255,255,255,.4)"}}>Read the platform</a>
        </div>
      </section>
      <SiteFooter/>
    </>
  );
}

function App(){
  return (
    <>
      <PipeHero/>
      <LeadAsset/>
      <PortfolioBuckets/>
      <AllAssets/>
      <PipeFooterCTA/>
    </>
  );
}

return App;
})();
