// TrialNexus — Home page content
// Three hero variants (typographic / product-mock / pipeline) controlled by Tweaks.

function HomeHero({ variant, onPilot, onTour }) {
  if (variant === 'product') return <HomeHeroProduct onPilot={onPilot}/>;
  if (variant === 'pipeline') return <HomeHeroPipeline onPilot={onPilot}/>;
  return <HomeHeroTypographic onPilot={onPilot} onTour={onTour}/>;
}

function HomeHeroTypographic({ onPilot, onTour }) {
  return (
    <section className="tn-hero" style={{minHeight:'100svh',display:'flex',alignItems:'center'}}>
      <TnOrbs/>
      <TnConstellation/>
      <div className="tn-hero-inner" style={{width:'100%'}}>
        <div className="tn-pre-dot tn-reveal" style={{marginBottom:28}}>
          <span className="tn-dot"/>Generally available · CDISC-native
        </div>
        <h1>Protocol to submission, <em className="tn-grad">without the middleware.</em></h1>
        <p className="tn-hero-sub">Sponsors and CROs close study builds in under two weeks — not 68 days. Every artifact carries an audit trail your regulatory reviewer can follow without a guide.</p>
        <div className="tn-hero-ctas">
          <button className="tn-btn tn-btn-primary tn-btn-lg" onClick={onPilot}>Book a demo <span className="tn-arrow">→</span></button>
          <button className="tn-btn tn-btn-secondary tn-btn-lg on-dark" onClick={onTour}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{flexShrink:0}}><path d="M8 5v14l11-7z"/></svg>
            Watch the tour
          </button>
        </div>
      </div>
    </section>
  );
}

function PlatformTour() {
  const [step, setStep] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const steps = [
    { k:'protocol', label:'Protocol PDF' },
    { k:'usdm',     label:'USDM v4.0' },
    { k:'ecrf',     label:'eCRF + DMP' },
    { k:'sdtm',     label:'SDTM + ADaM' },
    { k:'define',   label:'Define-XML' },
    { k:'signal',   label:'Signal narrative' },
  ];
  React.useEffect(() => {
    if (paused) return;
    const t = setTimeout(() => setStep(s => (s+1) % steps.length), step===0 ? 2800 : 3200);
    return () => clearTimeout(t);
  }, [step, paused]);
  const cur = steps[step];
  return (
    <div className="tn-tour" onMouseEnter={()=>setPaused(true)} onMouseLeave={()=>setPaused(false)}>
      <div className="tn-tour-chrome">
        <span style={{width:8,height:8,borderRadius:'50%',background:'#f87171'}}/>
        <span style={{width:8,height:8,borderRadius:'50%',background:'#fbbf24'}}/>
        <span style={{width:8,height:8,borderRadius:'50%',background:'#4ade80'}}/>
        <span className="tn-tour-url">app.trialnexus.ai · STUDY-A4471 · <em>{cur.label}</em></span>
        <span className="tn-tour-live"><span className="tn-dot"/>Live</span>
      </div>
      <div className="tn-tour-body">
        <div className="tn-tour-rail" aria-hidden="true">
          {steps.map((s,i)=>(
            <button key={s.k} className={`tn-tour-pip ${i===step?'active':''} ${i<step?'done':''}`} onClick={()=>{setStep(i);setPaused(true)}}>
              <span className="tn-tour-pip-num">{String(i+1).padStart(2,'0')}</span>
              <span className="tn-tour-pip-label">{s.label}</span>
            </button>
          ))}
        </div>
        <div className="tn-tour-stage">
          {cur.k==='protocol' && <TourStageProtocol/>}
          {cur.k==='usdm'     && <TourStageUsdm/>}
          {cur.k==='ecrf'     && <TourStageEcrf/>}
          {cur.k==='sdtm'     && <TourStageSdtm/>}
          {cur.k==='define'   && <TourStageDefine/>}
          {cur.k==='signal'   && <TourStageSignal/>}
        </div>
      </div>
      <div className="tn-tour-progress">
        <div className="tn-tour-progress-bar" style={{animation:paused?'none':`tnTourFill 3.2s linear forwards`}} key={step+'-'+paused}/>
      </div>
    </div>
  );
}

function TourFrame({ title, children }) {
  return (
    <div className="tn-tour-frame" key={title}>
      <div className="tn-tour-frame-title">{title}</div>
      {children}
    </div>
  );
}

function TourStageProtocol() {
  return (
    <TourFrame title="Parser Agent · reading protocol.pdf">
      <div className="tn-tour-pdf">
        <div className="tn-tour-pdf-line w60"/>
        <div className="tn-tour-pdf-line w90"/>
        <div className="tn-tour-pdf-line w40 hl"/>
        <div className="tn-tour-pdf-line w80"/>
        <div className="tn-tour-pdf-line w55 hl"/>
        <div className="tn-tour-pdf-line w70"/>
      </div>
      <div className="tn-tour-caret">
        <span className="tn-tour-caret-dot"/> extracting endpoints, arms, visit schedule…
      </div>
    </TourFrame>
  );
}
function TourStageUsdm() {
  return (
    <TourFrame title="USDM v4.0 · StudyDesign">
      <pre className="tn-tour-code">{`"studyVersion": {
  "studyTitle": "A Phase 2 study of…",
  "studyType": "Interventional",
  "studyDesign": {
    "studyPhase": "PHASE-2",
    "studyArms": [
      { "armId": "ARM-A", "armName": "Drug X 10mg" },
      { "armId": "ARM-B", "armName": "Placebo" }
    ],
    "studyEpochs": [ "Screening", "Treatment", "Follow-up" ]
  }
}`}</pre>
    </TourFrame>
  );
}
function TourStageEcrf() {
  return (
    <TourFrame title="eCRF Builder · Vital Signs form">
      <div className="tn-tour-form">
        <div className="tn-tour-field"><span>Systolic BP</span><em>mmHg · 80–200</em></div>
        <div className="tn-tour-field"><span>Diastolic BP</span><em>mmHg · 40–120</em></div>
        <div className="tn-tour-field"><span>Pulse</span><em>bpm · 30–180</em></div>
        <div className="tn-tour-field"><span>Temperature</span><em>°C · 35.0–40.0</em></div>
        <div className="tn-tour-field hl"><span>Position</span><em>SUPINE · SITTING · STANDING</em></div>
      </div>
    </TourFrame>
  );
}
function TourStageSdtm() {
  return (
    <TourFrame title="SDTM · VS domain · first rows">
      <table className="tn-tour-table">
        <thead><tr><th>USUBJID</th><th>VSTESTCD</th><th>VSORRES</th><th>VSORRESU</th><th>VISIT</th></tr></thead>
        <tbody>
          <tr><td>001-0012</td><td>SYSBP</td><td>128</td><td>mmHg</td><td>SCREEN</td></tr>
          <tr><td>001-0012</td><td>DIABP</td><td>82</td><td>mmHg</td><td>SCREEN</td></tr>
          <tr className="hl"><td>001-0012</td><td>PULSE</td><td>74</td><td>beats/min</td><td>SCREEN</td></tr>
          <tr><td>001-0013</td><td>SYSBP</td><td>134</td><td>mmHg</td><td>SCREEN</td></tr>
        </tbody>
      </table>
    </TourFrame>
  );
}
function TourStageDefine() {
  return (
    <TourFrame title="Define-XML v2.1 · ItemDef">
      <pre className="tn-tour-code">{`<ItemDef OID="IT.VS.VSORRES"
  Name="VSORRES"
  DataType="text"
  Length="200">
  <Description>
    <TranslatedText xml:lang="en">
      Result or Finding in Original Units
    </TranslatedText>
  </Description>
  <def:Origin Type="Collected"/>
</ItemDef>`}</pre>
    </TourFrame>
  );
}
function TourStageSignal() {
  return (
    <TourFrame title="Signal · Weekly briefing · Clinical Ops">
      <div className="tn-tour-narrative">
        <strong>Enrollment tracking 12% behind forecast.</strong> Sites 004 and 011 drove the gap — consent visits delayed by IRB amendment finalized Mar 28. Queue of 23 pre-screened candidates clears this week.
        <div className="tn-tour-narrative-cite">cited: <span>enrollment.rate</span> · <span>irb.amendment</span> · <span>site.004.screening</span></div>
      </div>
    </TourFrame>
  );
}

Object.assign(window, { PlatformTour });

function HomeHeroProduct({ onPilot }) {
  return (
    <section className="tn-hero">
      <TnOrbs/>
      <div className="tn-hero-grid">
        <div className="tn-hero-inner left">
          <h1 style={{fontSize:'clamp(36px,4.8vw,64px)'}}>The agents do the queries. <em className="tn-grad">You own the decisions.</em></h1>
          <p className="tn-hero-sub">Turn protocols into USDM. Generate DMP, eCRF, SDTM, ADaM and Define-XML with provenance on every field. Study builds in under two weeks. Humans approve what matters.</p>
          <div className="tn-hero-ctas">
            <button className="tn-btn tn-btn-primary tn-btn-lg" onClick={onPilot}>Book a demo <span className="tn-arrow">→</span></button>
            <a className="tn-btn tn-btn-secondary tn-btn-lg" href="data-management-agent.html">Meet Core</a>
          </div>
        </div>
        <div style={{position:'relative'}}>
          <ProductMock/>
        </div>
      </div>
    </section>
  );
}

function HomeHeroPipeline({ onPilot }) {
  return (
    <section className="tn-hero">
      <TnOrbs/>
      <div className="tn-hero-inner" style={{maxWidth:1040}}>
        <h1>From protocol PDF to <em className="tn-grad">Define-XML</em>, with audit on every step.</h1>
        <p className="tn-hero-sub">Seven specialized agents. One context. Every artifact carries its own reasoning trail. Regulators see the work, not just the output. Study builds in under two weeks.</p>
        <div className="tn-hero-ctas">
          <button className="tn-btn tn-btn-primary tn-btn-lg" onClick={onPilot}>Book a demo <span className="tn-arrow">→</span></button>
          <a className="tn-btn tn-btn-secondary tn-btn-lg" href="#os">Explore the OS</a>
        </div>
        <PipelineStrip light/>
      </div>
    </section>
  );
}

function ProductMock() {
  return (
    <div style={{background:'#fff',borderRadius:22,border:'1px solid var(--tn-border)',boxShadow:'0 40px 80px rgba(10,10,26,.12)',overflow:'hidden',fontSize:13}}>
      <div style={{display:'flex',gap:6,padding:'12px 16px',borderBottom:'1px solid var(--tn-border)',alignItems:'center'}}>
        <span style={{width:10,height:10,borderRadius:'50%',background:'#f87171'}}/>
        <span style={{width:10,height:10,borderRadius:'50%',background:'#fbbf24'}}/>
        <span style={{width:10,height:10,borderRadius:'50%',background:'#4ade80'}}/>
        <span style={{marginLeft:14,fontFamily:'var(--tn-font-mono)',fontSize:12,color:'var(--tn-fg-3)'}}>app.trialnexus.ai · STUDY-A4471</span>
      </div>
      <div style={{padding:'20px 22px'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
          <div>
            <div style={{fontSize:11,letterSpacing:'.12em',textTransform:'uppercase',color:'var(--tn-fg-3)',fontWeight:600}}>Decision Queue</div>
            <div style={{fontFamily:'var(--tn-font-heading)',fontSize:18,fontWeight:600,marginTop:4}}>Core · 12 awaiting review</div>
          </div>
          <span className="tn-tag live"><span style={{width:6,height:6,borderRadius:'50%',background:'#4ade80'}}/>Live</span>
        </div>
        {[
          { t: 'Map AE.AETERM → MedDRA PT', c: 94, tag: 'SDTM' },
          { t: 'Range check: VSORRES (systolic BP)', c: 87, tag: 'Edit check' },
          { t: 'Derivation: ADSL.AGEGR1', c: 76, tag: 'ADaM' },
        ].map((r,i) => (
          <div key={i} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'12px 0',borderTop:i?'1px solid var(--tn-border)':'none'}}>
            <div>
              <div style={{fontWeight:500,fontSize:13.5}}>{r.t}</div>
              <div style={{fontSize:11,color:'var(--tn-fg-3)',marginTop:2,fontFamily:'var(--tn-font-mono)'}}>{r.tag} · provenance attached</div>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:10}}>
              <div style={{fontFamily:'var(--tn-font-mono)',fontSize:12,color:r.c>=90?'#16a34a':r.c>=75?'#d97706':'#dc2626'}}>{r.c}%</div>
              <button style={{padding:'6px 12px',borderRadius:100,background:'var(--tn-fg-1)',color:'#fff',fontSize:11,fontWeight:600}}>Approve</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PipelineStrip({ light }) {
  const nodes = ['Parser', 'DMP', 'eCRF', 'SDTM', 'ADaM', 'Queries', 'Define-XML'];
  return (
    <div style={{marginTop:48,padding:'20px 24px',borderRadius:18,background:light?'rgba(255,255,255,.6)':'rgba(255,255,255,.04)',border:`1px solid ${light?'var(--tn-border)':'rgba(255,255,255,.08)'}`,display:'flex',alignItems:'center',gap:10,flexWrap:'wrap',justifyContent:'center',backdropFilter:'blur(10px)'}}>
      {nodes.map((n,i) => (
        <React.Fragment key={n}>
          <div style={{padding:'6px 14px',borderRadius:100,background:light?'#fff':'rgba(255,255,255,.06)',border:`1px solid ${light?'var(--tn-border)':'rgba(255,255,255,.08)'}`,fontSize:13,fontWeight:500,fontFamily:'var(--tn-font-heading)'}}>{n}</div>
          {i < nodes.length - 1 && <span style={{color:light?'var(--tn-fg-3)':'rgba(255,255,255,.3)'}}>→</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

const EXPERT_LOGOS = [
  { name: 'Komodo Health',       src: 'assets/logos/komodo-health.svg' },
  { name: 'Verily',              src: 'assets/logos/verily.svg' },
  { name: 'Takeda',             src: 'assets/logos/takeda.png' },
  { name: 'Accenture',          src: 'assets/logos/accenture.png' },
  { name: 'Revvity',            src: 'assets/logos/revvity.svg?v=2' },
  { name: 'Saama',              src: 'assets/logos/saama.svg?v=2' },
  { name: 'eClinical Solutions', src: 'assets/logos/eclinical.png' },
  { name: 'Cytel',              src: 'assets/logos/cytel.svg?v=3' },
  { name: 'Clario',             src: 'assets/logos/clario.svg' },
  { name: 'Tempus',             src: 'assets/logos/tempus.png' },
  { name: 'Oracle',             src: 'assets/logos/oracle.svg?v=2' },
  { name: 'Roche',              src: 'assets/logos/roche.svg?v=3' },
];

function ExpertStrip() {
  const items = [...EXPERT_LOGOS, ...EXPERT_LOGOS];
  return (
    <div className="tn-expert-strip">
      <div className="tn-expert-strip-label">Built by experts from leading life sciences and AI organizations</div>
      <div className="tn-expert-marquee">
        {items.map((logo, i) => (
          <span key={i} className="tn-expert-item" title={logo.name}>
            <img src={logo.src} alt={logo.name} className="tn-expert-logo" style={logo.scale ? {transform:`scale(${logo.scale})`} : undefined}/>
          </span>
        ))}
      </div>
    </div>
  );
}

function OsSection() {
  return (
    <section className="tn-section tn-section-dark" id="os">
      <div className="tn-container">
        <div className="tn-reveal tn-center" style={{textAlign:'center',maxWidth:820,margin:'0 auto'}}>
          <span className="tn-pre">The Operating System</span>
          <h2 className="tn-h2">Three products. <em className="tn-grad">One data layer. One audit trail.</em></h2>
          <p className="tn-sub" style={{marginInline:'auto'}}>Core writes every artifact a trial produces. Signal reads across every function that runs it. Agent Studio builds the workflows specific to yours. One data layer, one audit trail, across all three.</p>
        </div>

        <div className="tn-grid-3 tn-reveal tn-reveal-d2" style={{gap:24,marginTop:56}}>

          {/* Core — pink, write side */}
          <a href="data-management-agent.html" className="tn-os-card" style={{'--card-accent':'255,107,157'}} onMouseEnter={e=>e.currentTarget.classList.add('hover')} onMouseLeave={e=>e.currentTarget.classList.remove('hover')}>
            <div style={{marginBottom:28,position:'relative',display:'inline-flex',alignItems:'center',justifyContent:'center',width:64,height:64}}>
              <div style={{position:'absolute',width:128,height:128,borderRadius:'50%',background:'radial-gradient(circle, rgba(255,107,157,.2) 0%, rgba(255,107,157,.06) 50%, transparent 70%)',pointerEvents:'none'}}/>
              <TnIcon name="core" size={52} color="rgba(255,107,157,1)" strokeWidth={1.5}/>
            </div>
            <div className="tn-os-card-status"><span className="tn-dot-live"/>Write side</div>
            <h3 className="tn-os-card-title">Core</h3>
            <p className="tn-os-card-body">Seven specialized agents. Protocol → USDM → DMP → eCRF → SDTM → ADaM → Define-XML. Study builds in under two weeks. Every artifact carries its reasoning trail.</p>
            <div className="tn-os-card-tags">
              {['Protocol → USDM','SDTM + ADaM','Define-XML'].map(t => (
                <span key={t} className="tn-os-tag" style={{background:'rgba(255,107,157,.1)',borderColor:'rgba(255,107,157,.22)'}}>{t}</span>
              ))}
            </div>
            <div className="tn-os-card-cta">Explore Core <span>→</span></div>
          </a>

          {/* Signal — blue, read side */}
          <a href="signal.html" className="tn-os-card" style={{'--card-accent':'18,194,233'}} onMouseEnter={e=>e.currentTarget.classList.add('hover')} onMouseLeave={e=>e.currentTarget.classList.remove('hover')}>
            <div style={{marginBottom:28,position:'relative',display:'inline-flex',alignItems:'center',justifyContent:'center',width:64,height:64}}>
              <div style={{position:'absolute',width:128,height:128,borderRadius:'50%',background:'radial-gradient(circle, rgba(18,194,233,.2) 0%, rgba(18,194,233,.06) 50%, transparent 70%)',pointerEvents:'none'}}/>
              <TnIcon name="predict" size={52} color="rgba(18,194,233,1)" strokeWidth={1.5}/>
            </div>
            <div className="tn-os-card-status"><span className="tn-dot-live"/>Read side</div>
            <h3 className="tn-os-card-title">Signal</h3>
            <p className="tn-os-card-body">One data layer, six role-aware views. Every function opens Signal and finds the narrative already written. The Monday-morning briefing in 60 seconds, not two days.</p>
            <div className="tn-os-card-tags">
              {['Weekly narratives','Role-aware views','Provenance inline'].map(t => (
                <span key={t} className="tn-os-tag" style={{background:'rgba(18,194,233,.1)',borderColor:'rgba(18,194,233,.25)'}}>{t}</span>
              ))}
            </div>
            <div className="tn-os-card-cta">Explore Signal <span>→</span></div>
          </a>

          {/* Agent Studio — purple, build side */}
          <a href="agent-studio.html" className="tn-os-card" style={{'--card-accent':'196,113,237'}} onMouseEnter={e=>e.currentTarget.classList.add('hover')} onMouseLeave={e=>e.currentTarget.classList.remove('hover')}>
            <div style={{marginBottom:28,position:'relative',display:'inline-flex',alignItems:'center',justifyContent:'center',width:64,height:64}}>
              <div style={{position:'absolute',width:128,height:128,borderRadius:'50%',background:'radial-gradient(circle, rgba(196,113,237,.2) 0%, rgba(196,113,237,.06) 50%, transparent 70%)',pointerEvents:'none'}}/>
              <TnIcon name="studio" size={52} color="rgba(196,113,237,1)" strokeWidth={1.5}/>
            </div>
            <div className="tn-os-card-status"><span className="tn-dot-live"/>Build side</div>
            <h3 className="tn-os-card-title">Agent Studio</h3>
            <p className="tn-os-card-body">The agents your trial needs that Core doesn't cover. Build them in the same Part 11 runtime, with the same Decision Queue and the same audit trail. Your workflows. Your agents.</p>
            <div className="tn-os-card-tags">
              {['Custom agents','Token audit log','21 CFR runtime'].map(t => (
                <span key={t} className="tn-os-tag" style={{background:'rgba(196,113,237,.1)',borderColor:'rgba(196,113,237,.25)'}}>{t}</span>
              ))}
            </div>
            <div className="tn-os-card-cta">Explore Agent Studio <span>→</span></div>
          </a>

        </div>

      </div>
    </section>
  );
}

function EvidenceSection() {
  return (
    <section className="tn-section tn-section-alt">
      <div className="tn-container">
        <div className="tn-reveal">
          <span className="tn-pre">Why now</span>
          <h2 className="tn-h2">The people running your trials are exceptional. <em className="tn-grad">The tools they're using are not.</em></h2>
          <p className="tn-sub">Clinical-trial teams are some of the most rigorously trained professionals in medicine. They spend most of their day reconciling spreadsheets.</p>
        </div>
        <div className="tn-stats tn-reveal tn-reveal-d2">
          {[
            { n:'68 days', l:'average time to build a study database.', s:'Tufts CSDD, 2023', accent:'var(--tn-pink)' },
            { n:'85%',     l:'of trials miss enrollment timelines.',    s:'SCORR Marketing, 2022', accent:'var(--tn-blue)' },
            { n:'30%',     l:'annual turnover across mid-size CROs.',   s:'ACRP Workforce Report', accent:'var(--tn-purple)' },
          ].map(({n,l,s,accent}) => (
            <div key={n} style={{borderLeft:`3px solid ${accent}`,paddingLeft:28}}>
              <div className="tn-stat-num">{n}</div>
              <div className="tn-stat-label">{l}</div>
              <div className="tn-stat-src">{s}</div>
            </div>
          ))}
        </div>
        <div className="tn-reveal tn-reveal-d3" style={{marginTop:48,padding:'28px 32px',borderRadius:20,background:'#fff',borderLeft:'3px solid var(--tn-pink)',border:'1px solid var(--tn-border)',borderLeftWidth:3,borderLeftColor:'var(--tn-pink)',maxWidth:820}}>
          <p style={{fontSize:17,color:'var(--tn-fg-2)',lineHeight:1.75,margin:0}}>These are not abstract inefficiencies. A 68-day study build is a 68-day delay before your trial can generate safety data. An 85% miss rate on enrollment timelines means most trials cost more and take longer than planned. TrialNexus closes these gaps without asking your team to work harder.</p>
        </div>
      </div>
    </section>
  );
}

function FeaturesSection() {
  const feats = [
    { icon:'narratives', t:'Narratives, not dashboards', d:'Every view in Signal comes pre-read. Weekly briefings per study, ad-hoc answers to questions, citations back to the SDTM variable. The Monday-morning briefing in 60 seconds.' },
    { icon:'cdisc',      t:'CDISC-native architecture', d:'USDM-centric. CDASH, SDTM, ADaM and Define-XML are first-class citizens, not afterthoughts bolted onto a general ML stack. Define-XML that passes Pinnacle 21 on the first run.' },
    { icon:'audit',      t:'Audit trails built in', d:'Every decision logged with provenance and reasoning. 21 CFR Part 11 and ICH E6(R3) compliant by design. An audit trail your regulatory reviewer can follow without a guide.' },
    { icon:'dial',       t:'Human-agency control plane', d:'Augmented · full-oversight · autonomous. You set the boundaries per agent, per study. Context windows are scoped so agents only see what their task requires.' },
    { icon:'integrations',t:'Enterprise integrations', d:'Deploy into Medidata Rave (ODM XML) and Veeva Vault CDMS. Auth0 SSO. Query cycles that close in hours, not days.' },
    { icon:'explainable', t:'Explainable by default', d:'Every artifact carries a reasoning trail. Agents show their work: regulators see every step. Every decision your DM lead makes comes with the reasoning already written.' },
    { icon:'open',        t:'Open, not locked-in', d:'Your data stays in your systems. USDM makes protocols portable. If you leave, you leave with everything. Every artifact in open formats, no extraction fee.' },
  ];
  return (
    <section className="tn-section">
      <div className="tn-container">
        <div className="tn-reveal">
          <span className="tn-pre">Built for the work</span>
          <h2 className="tn-h2">Built for the people who actually <em className="tn-grad">run clinical trials.</em></h2>
          <p className="tn-sub">CDISC-native by design. Enterprise integrations built in. Every output traceable, every decision defensible.</p>
        </div>
        <div className="tn-feat-grid" style={{gridTemplateColumns:'repeat(auto-fill,minmax(260px,1fr))'}}>
          {feats.map((f,i) => {
            const colors = ['var(--tn-pink)','var(--tn-blue)','var(--tn-purple)','var(--tn-pink)','var(--tn-blue)','var(--tn-purple)','var(--tn-pink)'];
            const bgColors = ['rgba(255,107,157,.1)','rgba(18,194,233,.1)','rgba(196,113,237,.1)','rgba(255,107,157,.1)','rgba(18,194,233,.1)','rgba(196,113,237,.1)','rgba(255,107,157,.1)'];
            const borderColors = ['rgba(255,107,157,.18)','rgba(18,194,233,.18)','rgba(196,113,237,.18)','rgba(255,107,157,.18)','rgba(18,194,233,.18)','rgba(196,113,237,.18)','rgba(255,107,157,.18)'];
            return (
              <div className={`tn-card tn-feat tn-reveal tn-reveal-d${(i%4)+1}`} key={f.t} style={{borderTop:`2px solid ${borderColors[i]}`}}>
                <div className="tn-feat-icon" style={{color:colors[i],background:bgColors[i],border:`1px solid ${borderColors[i]}`}}>
                  <TnIcon name={f.icon} size={24}/>
                </div>
                <h3>{f.t}</h3>
                <p>{f.d}</p>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function AgencyDialSection() {
  const [mode, setMode] = React.useState('augmented');
  const modes = {
    oversight:  {
      label:'Full oversight',
      copy:'Every agent output requires human approval before it touches your EDC. The agents propose; you decide. The Decision Queue surfaces every item. Nothing executes without a sign-off. The right setting for first studies and Phase I oncology programs where every data point is under scrutiny.',
      queueLabel:'All 12 items awaiting review',
      queueItems:['Map AE.AETERM → MedDRA PT','Range check: VSORRES','Derivation: ADSL.AGEGR1'],
    },
    augmented:  {
      label:'Augmented',
      copy:'Routine actions auto-execute above your configured confidence threshold. Edge cases route to the Decision Queue. The default for most active studies: agents handle the routine they can do reliably, your team owns the decisions that require expertise.',
      queueLabel:'3 edge cases awaiting review',
      queueItems:['Derivation: ADSL.AGEGR1 (76%)'],
    },
    autonomous: {
      label:'Autonomous',
      copy:'Within guardrails you define, agents close loops without checking back. Every action is logged: the token trace, the confidence score, the model version. Nothing is invisible. You\'ve told the system which decisions it can make on its own.',
      queueLabel:'Queue clear',
      queueItems:[],
    },
  };
  const cur = modes[mode];
  return (
    <section className="tn-section tn-section-dark">
      <div className="tn-container">
        <div className="tn-reveal tn-center" style={{textAlign:'center',maxWidth:820,margin:'0 auto'}}>
          <span className="tn-pre">Control Plane</span>
          <h2 className="tn-h2" style={{maxWidth:720,marginInline:'auto'}}>You are in control. <em className="tn-grad">The agents work within the boundaries you define.</em></h2>
          <p className="tn-sub" style={{marginInline:'auto'}}>TrialNexus is built on a four-layer control architecture: CDISC-standards compliance enforced at the model level, context-window scoping so agents only see what they need, a human-approval gate at every decision point, and an immutable audit trail that shows regulators exactly what was automated and what was reviewed.</p>
        </div>
        <div className="tn-dial tn-reveal tn-reveal-d2" style={{marginTop:36}}>
          {Object.entries(modes).map(([k,v]) => (
            <button key={k} className={mode===k?'on':''} onClick={() => { setMode(k); window.tnTrack?.('agency_dial_click',{mode:k}); }}>{v.label}</button>
          ))}
        </div>
        <div className="tn-grid-2 tn-reveal tn-reveal-d3" style={{gap:32,marginTop:32,maxWidth:880,marginInline:'auto'}}>
          <div>
            <p style={{margin:0,fontSize:17,color:'rgba(255,255,255,.85)',lineHeight:1.75}}>{cur.copy}</p>
          </div>
          <div style={{background:'rgba(255,255,255,.04)',borderRadius:16,border:'1px solid rgba(255,255,255,.08)',overflow:'hidden',fontSize:13}}>
            <div style={{padding:'12px 16px',borderBottom:'1px solid rgba(255,255,255,.08)',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <span style={{fontSize:11,fontWeight:600,letterSpacing:'.1em',textTransform:'uppercase',color:'rgba(255,255,255,.5)'}}>Decision Queue</span>
              <span style={{fontSize:11,fontFamily:'var(--tn-font-mono)',color:cur.queueItems.length===0?'#4ade80':'rgba(255,255,255,.5)'}}>{cur.queueLabel}</span>
            </div>
            <div style={{padding:'8px 0'}}>
              {cur.queueItems.length > 0 ? cur.queueItems.map((item,i) => (
                <div key={i} style={{padding:'13px 16px',display:'flex',justifyContent:'space-between',alignItems:'center',borderBottom:i<cur.queueItems.length-1?'1px solid rgba(255,255,255,.05)':'none'}}>
                  <span style={{fontSize:14,color:'rgba(255,255,255,.85)',fontWeight:500}}>{item}</span>
                  <button style={{padding:'6px 14px',borderRadius:100,background:'rgba(255,255,255,.08)',border:'1px solid rgba(255,255,255,.1)',color:'rgba(255,255,255,.75)',fontSize:12,fontWeight:600,cursor:'pointer',flexShrink:0,marginLeft:12}}>Review</button>
                </div>
              )) : (
                <div style={{padding:'28px 16px',textAlign:'center',color:'rgba(255,255,255,.38)',fontSize:13,fontFamily:'var(--tn-font-mono)'}}>All outputs executed automatically</div>
              )}
            </div>
          </div>
        </div>
        <div className="tn-reveal tn-reveal-d4" style={{marginTop:40,padding:'28px 36px',borderRadius:20,background:'rgba(255,107,157,.06)',borderLeft:'3px solid rgba(255,107,157,.6)',border:'1px solid rgba(255,107,157,.18)',borderLeftWidth:3,borderLeftColor:'rgba(255,107,157,.6)',maxWidth:880,marginInline:'auto'}}>
          <p style={{margin:0,fontSize:17,color:'rgba(255,255,255,.82)',lineHeight:1.8}}>Most AI tools optimize for autonomy. We optimize for defensibility. In a regulated trial, the question is never "can the agent do this?" — it's "can you show the FDA exactly how this decision was made?" Our control plane answers that question before anyone asks.</p>
        </div>
      </div>
    </section>
  );
}

function IntegrationsSection() {
  const items = [
    ['Medidata Rave', 'ODM XML bidirectional'],
    ['Veeva Vault CDMS', 'JSON REST'],
    ['Auth0', 'Enterprise SSO · SAML'],
    ['CDISC Library', 'SDTM/CDASH/ADaM CT'],
    ['Major Frontier Models', 'BYO-API keys on Enterprise'],
    ['R · Python · SAS', 'Output delivered into your SCE'],
    ['USDM MDR systems', 'Standards-compliant metadata repositories'],
  ];
  return (
    <section className="tn-section tn-section-alt">
      <div className="tn-container">
        <div className="tn-reveal">
          <span className="tn-pre">Integrations</span>
          <h2 className="tn-h2">Drop into your stack. <em className="tn-grad">Leave it standing.</em></h2>
          <p className="tn-sub">TrialNexus is additive. We meet your EDC where it lives and keep the data where you keep it.</p>
        </div>
        <div className="tn-feat-grid cols-3 tn-reveal tn-reveal-d2">
          {items.map(([name,desc]) => (
            <div className="tn-card" key={name} style={{padding:20}}>
              <div style={{fontFamily:'var(--tn-font-heading)',fontSize:15,fontWeight:600,marginBottom:4,letterSpacing:'-.005em'}}>{name}</div>
              <div style={{fontSize:13,color:'var(--tn-fg-3)',fontFamily:'var(--tn-font-mono)'}}>{desc}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function EnterpriseLayerSection() {
  const [active, setActive] = React.useState(0);
  const prompts = [
    { tag:'DMP Writer',         user:'@TrialNexus draft a DMP for STUDY-A4471 using our standard SOP template and flag all open decisions.', reply:'DMP draft complete. 23 sections populated from protocol and USDM output. 4 decisions flagged for your DM lead: database lock date, query aging threshold, SAE reconciliation owner, discrepancy classification SOP reference. Ready in Decision Queue. · template: DMP-SOP-v4.1' },
    { tag:'SDTM Mapper',        user:'@TrialNexus map the AE dataset for Study A4471 — flag anything below 85% confidence.', reply:'AE domain mapped. 34 variables: 31 auto-mapped above threshold. 3 routed to Decision Queue — AEOUT value \'RECOVERING/RESOLVED\' split, sponsor-defined severity scale, AEACN multi-select field. Your DM lead has 3 decisions, not 34. · CT version: CDISC 2024-03-29' },
    { tag:'Query Scan',         user:'@TrialNexus run a data quality scan on Site 042 — last 30 days.', reply:'14 query candidates identified at Site 042. 6 high-confidence: 4 AE onset dates outside visit window, 2 vital sign values outside range. 8 medium-confidence: concomitant med coding, missing ECOG. Query text drafted, resolution suggested, routed to coordinator. No manual data review required.' },
    { tag:'Define-XML',         user:'@TrialNexus generate the Define-XML package for Study A4471 — we\'re submitting next week.', reply:'Define-XML v2.1 generated with cSDRG narrative. Pinnacle 21 validation: 0 errors, 2 warnings. Both documented and explained in cSDRG §3.2. Package staged for QC sign-off. · audit ref: define.run.2024-05-14T14:22Z' },
  ];
  const features = [
    { t:'Works where you already work', d:'Invoke @TrialNexus from Claude Enterprise, ChatGPT, or any MCP-compatible client. No new interface. Your team stays in the tools they know.' },
    { t:'Tasks base models cannot complete', d:'SDTM mapping, SoA extraction, EDC population — these require CDISC domain knowledge and multi-step workflow logic no frontier model carries natively.' },
    { t:'Audit trail on every call', d:'Every invocation logged at the token level: model version, inputs, outputs, agent version, human approval. The same immutable trail as the full Core pipeline.' },
  ];
  return (
    <section className="tn-section tn-section-dark">
      <div className="tn-container">
        <div className="tn-reveal tn-center" style={{textAlign:'center',maxWidth:760,margin:'0 auto'}}>
          <span className="tn-pre">MCP · Enterprise AI layer</span>
          <h2 className="tn-h2">@TrialNexus from the tools <em className="tn-grad">your team already uses.</em></h2>
          <p className="tn-sub" style={{marginInline:'auto'}}>Every agent available as an MCP endpoint. Invoke complex clinical workflows from Claude Enterprise, ChatGPT, or any MCP client — with full CDISC validation and an unbroken audit trail.</p>
        </div>

        <div className="tn-grid-side tn-reveal tn-reveal-d2" style={{marginTop:48,gap:32,alignItems:'center'}}>

          {/* Tabbed chat window */}
          <div style={{borderRadius:20,overflow:'hidden',border:'1px solid rgba(255,255,255,.1)',background:'rgba(255,255,255,.02)'}}>
            {/* Window chrome */}
            <div style={{display:'flex',alignItems:'center',gap:0,borderBottom:'1px solid rgba(255,255,255,.08)',background:'rgba(255,255,255,.03)'}}>
              <div style={{display:'flex',gap:6,padding:'12px 16px',borderRight:'1px solid rgba(255,255,255,.06)'}}>
                {['rgba(255,95,87,.7)','rgba(255,189,46,.7)','rgba(40,200,64,.7)'].map(c => (
                  <div key={c} style={{width:9,height:9,borderRadius:'50%',background:c}}/>
                ))}
              </div>
              <div style={{display:'flex',flex:1,overflowX:'auto'}}>
                {prompts.map((p,i) => (
                  <button key={i} onClick={() => setActive(i)} style={{padding:'10px 16px',background:'none',border:'none',borderBottom:`2px solid ${active===i?'var(--tn-pink)':'transparent'}`,cursor:'pointer',fontSize:11,fontFamily:'var(--tn-font-mono)',fontWeight:600,letterSpacing:'.06em',color:active===i?'var(--tn-pink)':'rgba(255,255,255,.3)',transition:'all .2s',whiteSpace:'nowrap'}}>
                    {p.tag}
                  </button>
                ))}
              </div>
            </div>

            {/* Chat content */}
            <div style={{padding:'20px 20px',display:'flex',flexDirection:'column',gap:16,minHeight:220}}>
              <div style={{display:'flex',gap:10,alignItems:'flex-start'}}>
                <div style={{width:26,height:26,borderRadius:'50%',background:'rgba(255,255,255,.08)',border:'1px solid rgba(255,255,255,.14)',flexShrink:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.45)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
                </div>
                <p style={{margin:0,fontSize:13,color:'rgba(255,255,255,.5)',lineHeight:1.65,fontStyle:'italic'}}>"{prompts[active].user}"</p>
              </div>
              <div style={{display:'flex',gap:10,alignItems:'flex-start'}}>
                <div style={{width:26,height:26,borderRadius:'50%',background:'rgba(10,10,26,.6)',border:'1px solid rgba(255,107,157,.25)',flexShrink:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
                  <TnMark size={18}/>
                </div>
                <div style={{flex:1}}>
                  <p style={{margin:'0 0 10px',fontSize:12,color:'rgba(255,255,255,.8)',lineHeight:1.75,fontFamily:'var(--tn-font-mono)'}}>{prompts[active].reply}</p>
                  <div style={{display:'inline-flex',alignItems:'center',gap:6,padding:'4px 10px',borderRadius:100,background:'rgba(255,107,157,.1)',border:'1px solid rgba(255,107,157,.2)'}}>
                    <span style={{width:5,height:5,borderRadius:'50%',background:'var(--tn-pink)',flexShrink:0}}/>
                    <span style={{fontSize:10,fontWeight:600,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--tn-pink)'}}>{prompts[active].tag}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Feature list */}
          <div style={{display:'flex',flexDirection:'column',gap:28}}>
            {features.map((f,i) => (
              <div key={f.t} style={{display:'flex',gap:14,alignItems:'flex-start'}}>
                <div style={{width:3,height:3,borderRadius:'50%',background:'var(--tn-pink)',marginTop:8,flexShrink:0}}/>
                <div>
                  <h3 style={{fontFamily:'var(--tn-font-heading)',fontSize:15,fontWeight:600,color:'#fff',margin:'0 0 6px',letterSpacing:'-.01em'}}>{f.t}</h3>
                  <p style={{fontSize:14,color:'rgba(255,255,255,.45)',lineHeight:1.65,margin:0}}>{f.d}</p>
                </div>
              </div>
            ))}
          </div>

        </div>
      </div>
    </section>
  );
}

function FaqSection() {
  const faqs = [
    { q:'What exactly do the agents do?', a:'Seven specialized agents cover the trial lifecycle: Parser (Protocol → USDM), DMP Writer, eCRF Builder, SDTM Mapper, ADaM Generator, Query Candidate, and Define-XML Generator. Each runs as an isolated activity with its own LLM call and its own audit trail. Study builds that used to take 68 days close in under two weeks.' },
    { q:'What has been the regulatory guidance on AI use in clinical trials?', a:'The FDA\'s 2023 discussion paper on AI/ML in drug development and the EMA\'s 2023 reflection paper both reach the same conclusion: AI-assisted processes are acceptable when they are transparent, validated, and human-supervised. The key requirement is that a qualified person reviews, understands, and takes accountability for every AI-generated output. That is exactly what the Decision Queue and audit trail provide: not AI replacing the DM lead, but AI doing the drafting work so the DM lead can focus on the review.' },
    { q:'How do we trust AI-generated trial artifacts?', a:'Every artifact carries a provenance record: which agent, which prompt, which source passages, which human approval. Outputs are gated by confidence thresholds you configure. Nothing lands in your EDC without a human-in-the-loop step unless you explicitly allow it. Define-XML is validated against Pinnacle 21 rules inline, before it leaves the pipeline.' },
    { q:'Is this 21 CFR Part 11 compliant?', a:'We are architected for Part 11 and ICH E6(R3): immutable audit logs, e-signature on approvals, versioning on every artifact, role-based access. Validation packages are part of the pilot engagement. See our Security page for the current state of third-party attestations.' },
    { q:'How long is a pilot?', a:'Four weeks. One protocol, end-to-end: Parser → USDM → DMP → eCRF → Query Candidate → SDTM. We configure the agency dial with your team, run the pipeline, and hand over the artifacts plus the reasoning trail.' },
    { q:'Does my data leave my infrastructure?', a:'It depends on the tenant model. Shared cloud tenants run in our Supabase-managed Postgres. Enterprise tenants get isolated databases with customer-held encryption keys. LLM calls go through tenant-scoped providers; we do not train on your data.' },
    { q:'What EDCs do you support?', a:'Medidata Rave (ODM XML) and Veeva Vault CDMS today. Oracle InForm on the roadmap. We can export ODM-XML for any system that imports it.' },
  ];
  return (
    <section className="tn-section">
      <div className="tn-container-narrow">
        <div className="tn-reveal">
          <span className="tn-pre">Common questions</span>
          <h2 className="tn-h2">Questions we hear <em className="tn-grad">on every call.</em></h2>
        </div>
        <div className="tn-faq tn-reveal tn-reveal-d2" style={{marginTop:48}}>
          {faqs.map((f,i) => <FaqItem key={i} {...f}/>)}
        </div>
      </div>
    </section>
  );
}

function FaqItem({ q, a }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div className={`tn-faq-item ${open?'open':''}`}>
      <button className="tn-faq-q" onClick={() => { setOpen(o=>!o); window.tnTrack?.('faq_open',{q}); }}>
        <span>{q}</span>
        <span className="tn-faq-plus">+</span>
      </button>
      <div className="tn-faq-a"><div className="tn-faq-a-inner">{a}</div></div>
    </div>
  );
}

function HomeCta({ onPilot }) {
  return (
    <section className="tn-cta tn-section-dark" style={{textAlign:'center',padding:'120px 32px',position:'relative',overflow:'hidden'}}>
      <div style={{position:'absolute',top:0,left:0,right:0,height:2,background:'var(--tn-gradient-primary)'}}/>
      <TnOrbs/>
      <div className="tn-container tn-reveal">
        <h2 className="tn-h2" style={{maxWidth:820,marginInline:'auto',fontSize:'clamp(32px,4vw,56px)'}}>A <em className="tn-grad">better way</em> is here.</h2>
        <p className="tn-sub" style={{marginInline:'auto',marginTop:16,marginBottom:36}}>See TrialNexus in a 30-minute working session. Bring your protocol. We'll build from it.</p>
        <div className="tn-hero-ctas" style={{justifyContent:'center'}}>
          <button className="tn-btn tn-btn-primary tn-btn-lg" onClick={onPilot}>Book a demo <span className="tn-arrow">→</span></button>
          <a className="tn-btn tn-btn-secondary tn-btn-lg on-dark" href="contact.html">Talk to us</a>
        </div>
      </div>
    </section>
  );
}

function HomePage() {
  const [tour, setTour] = React.useState(false);
  const tweakSchema = [
    { key:'hero', label:'Hero variant', type:'segmented', options:[
      {value:'typographic',label:'Typographic'},
      {value:'product',label:'Product'},
      {value:'pipeline',label:'Pipeline'},
    ]},
  ];
  return (
    <TnPage path="index.html" onDarkNav={true} tweakSchema={tweakSchema} tweakInitial={{ hero:'typographic' }}>
      {({ tweaks, openPilot }) => (
        <main data-screen-label="01 Home">
          <HomeHero variant={tweaks.hero} onPilot={openPilot} onTour={() => setTour(true)}/>
          <ExpertStrip/>
          <OsSection/>
          <EvidenceSection/>
          <FeaturesSection/>
          <AgencyDialSection/>
          <IntegrationsSection/>
          <EnterpriseLayerSection/>
          <FaqSection/>
          <HomeCta onPilot={openPilot}/>
          <TnTourModal open={tour} onClose={() => setTour(false)}>
            <PlatformTour key={tour ? 'open' : 'closed'}/>
          </TnTourModal>
        </main>
      )}
    </TnPage>
  );
}

Object.assign(window, { HomePage, HomeCta, ProductMock });
