// Reference Library — Mendeley-like dapp.
// 3 screens: Library list / PDF reader / Citation export.

function LibraryRail({ active }) {
  return (
    <>
      <div style={{ padding: '12px 16px', borderBottom: `1px solid ${UB.rule2}`, marginBottom: 14 }}>
        <Btn small primary icon={Icon.plus} style={{ width: '100%', justifyContent: 'center' }}>Add references</Btn>
      </div>
      <NavGroup label="Library">
        <NavItem icon={Icon.book} label="All references" badge="1,418" active={active === 'all'} />
        <NavItem icon={Icon.bell} label="Reading queue" badge="14" />
        <NavItem icon={Icon.check} label="Annotated" badge="218" />
        <NavItem icon={Icon.flask} label="Cited in my work" badge="412" />
        <NavItem icon={Icon.plus} label="Recently added" badge="22" />
      </NavGroup>
      <NavGroup label="Folders">
        <NavItem icon={Icon.book} label="Astrocytes · sleep" badge="84" active={active === 'folder'} />
        <NavItem icon={Icon.book} label="Glia heterogeneity" badge="56" />
        <NavItem icon={Icon.book} label="Reproducibility" badge="38" />
        <NavItem icon={Icon.book} label="Open imaging" badge="62" />
        <NavItem icon={Icon.book} label="Reviews · 2025 cycle" badge="14" />
      </NavGroup>
      <NavGroup label="Group libraries">
        <NavItem icon={Icon.user} label="Harriot Lab" badge="318" />
        <NavItem icon={Icon.user} label="Glia Initiative · CZB" badge="186" />
        <NavItem icon={Icon.user} label="OpenImaging Consortium" badge="1.2K" />
      </NavGroup>
      <NavGroup label="Tags">
        <div style={{ padding: '0 16px', display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {['#astrocyte', '#review', '#methods', '#replication', '#negative-result', '#tooling', '#preprint'].map(t => (
            <span key={t} style={{ padding: '2px 6px', background: UB.paperDeep, fontFamily: UB.mono, fontSize: 9, color: UB.ink2, letterSpacing: '0.04em' }}>{t}</span>
          ))}
        </div>
      </NavGroup>
    </>
  );
}

function LibCrumb({ items }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: UB.mono, fontSize: 10, color: UB.ink3, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 6 }}>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          <span style={{ color: i === items.length - 1 ? UB.ink : UB.ink3 }}>{it}</span>
          {i < items.length - 1 && <span style={{ color: UB.ink4 }}>›</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

const LIB_PAPERS = [
  { star: true,  type: 'UB',   title: 'Astrocytic gating of slow-wave sleep across cortical depth', authors: 'Harriot M., Singh L., Okafor R. +4', venue: 'UB-Chain · dPID·a92f.04', year: 2025, tags: ['#astrocyte', '#sleep'], read: true,  cited: 12, annotations: 18 },
  { star: false, type: 'arXiv',title: 'Sparse decoding of cortical dynamics with scaled-attention transformers', authors: 'Patel A., Mehta R.', venue: 'arXiv:2503.18112', year: 2025, tags: ['#methods', '#ml'], read: false, cited: 0,  annotations: 0  },
  { star: true,  type: 'PDF',  title: 'A reproducibility-weighted citation index for neuroimaging', authors: 'Lin C., Harriot M.', venue: 'Cell Reports Methods · 5(11)', year: 2024, tags: ['#review', '#methods'], read: true, cited: 6, annotations: 22 },
  { star: false, type: 'bioRxiv', title: 'Glia heterogeneity beyond morphology: a single-cell atlas v2', authors: 'Singh L. +6 · OpenGlia Consortium', venue: 'bioRxiv 2024.11.08.621442', year: 2024, tags: ['#astrocyte', '#single-cell'], read: true, cited: 4, annotations: 11 },
  { star: false, type: 'DOI',  title: 'Sleep depth from astrocyte calcium dynamics — RIKEN replication', authors: 'Yamamoto K., Tanaka H., Mori J.', venue: 'Nature Neuroscience 28(4)', year: 2025, tags: ['#replication', '#astrocyte'], read: true, cited: 2, annotations: 14 },
  { star: true,  type: 'UB',   title: 'Open-source 2-photon rig: BoM v3 + reproducible build', authors: 'Harriot M., Mwangi A.', venue: 'UB-Chain · dPID·56dd.01', year: 2024, tags: ['#tooling'], read: true, cited: 8, annotations: 5 },
  { star: false, type: 'PDF',  title: 'Negative result: μ-glia ablation does not impair LTP recall', authors: 'Yamamoto K., Mori J.', venue: 'eLife 14:e98821', year: 2025, tags: ['#negative-result', '#astrocyte'], read: false, cited: 0, annotations: 0 },
  { star: false, type: 'arXiv',title: 'Compositional generalisation in dendritic computation models', authors: 'Ortega B., Stein-Lopez M.', venue: 'arXiv:2412.07719', year: 2024, tags: ['#theory', '#dendrite'], read: false, cited: 0, annotations: 0 },
  { star: true,  type: 'UB',   title: 'Cortical microcircuit motifs across 14 species', authors: 'Harriot M. +6', venue: 'UB-Chain · dPID·17c0.03', year: 2024, tags: ['#comparative'], read: true, cited: 3, annotations: 9 },
  { star: false, type: 'DOI',  title: 'Astrocyte calcium signalling encodes sleep depth', authors: 'Lin C., Park S.', venue: 'Cell 188(7)', year: 2024, tags: ['#astrocyte', '#sleep'], read: true, cited: 22, annotations: 31 },
  { star: false, type: 'bioRxiv', title: 'Open imaging benchmark v3 · 14 sites · ~482 GB', authors: 'OpenImaging Consortium', venue: 'bioRxiv 2025.02.14.611042', year: 2025, tags: ['#tooling', '#benchmark'], read: false, cited: 0, annotations: 0 },
  { star: false, type: 'PDF',  title: 'Reviewer behaviour in distributed peer review platforms', authors: 'Kim J., Patel A.', venue: 'PNAS 121(38)', year: 2024, tags: ['#review', '#meta'], read: true, cited: 1, annotations: 4 },
];

function TypeChip({ t }) {
  const map = {
    UB:      { bg: UB.accent, fg: UB.ink },
    arXiv:   { bg: 'oklch(0.66 0.13 240 / 0.18)', fg: 'oklch(0.40 0.13 240)' },
    bioRxiv: { bg: 'oklch(0.72 0.13 155 / 0.18)', fg: 'oklch(0.42 0.13 155)' },
    DOI:     { bg: UB.paperDeep, fg: UB.ink2 },
    PDF:     { bg: 'oklch(0.78 0.16 70 / 0.20)', fg: 'oklch(0.45 0.16 70)' },
  };
  const c = map[t] || map.PDF;
  return <span style={{ fontFamily: UB.mono, fontSize: 9, padding: '2px 5px', background: c.bg, color: c.fg, letterSpacing: '0.06em' }}>{t}</span>;
}

// ─────────────────────────────────────────────── LIBRARY · LIST VIEW ─────────
function ReferenceLibraryDapp() {
  return (
    <Dapp>
      <ChromeBar dapp="REFERENCE" code="LIB / ALL · 1,418" />
      <Layout rail={<LibraryRail active="all" />}>
        <PageHead
          eyebrow={<LibCrumb items={['Reference Library', 'All references']} />}
          title="Reference Library"
          sub="Every paper, preprint and dataset you've read, cited, or filed away. Imported from UB-Chain, arXiv, bioRxiv, DOI, or your own drafts."
          actions={<>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, height: 32, padding: '0 12px', border: `1px solid ${UB.rule2}`, background: '#fff', minWidth: 280 }}>
              <span style={{ color: UB.ink4 }}>{Icon.search}</span>
              <span style={{ fontFamily: UB.mono, fontSize: 11, color: UB.ink3 }}>Search title · author · DOI · #tag</span>
            </div>
            <Btn small icon={Icon.doc}>Export BibTeX</Btn>
            <Btn small primary icon={Icon.plus}>Add references</Btn>
          </>}
        />

        <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
          {/* Main list */}
          <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
            {/* filter bar */}
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', padding: '12px 24px', borderBottom: `1px solid ${UB.rule2}`, flexWrap: 'wrap' }}>
              <span style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.18em', marginRight: 4 }}>FILTER</span>
              {['All · 1,418', '★ Starred · 84', 'Read · 612', 'Unread · 806', 'With annotations · 218', 'Cited by me · 412'].map((c, i) => (
                <span key={c} style={{ padding: '4px 10px', border: `1px solid ${i === 0 ? UB.ink : UB.rule2}`, background: i === 0 ? UB.ink : '#fff', color: i === 0 ? UB.paper : UB.ink2, fontFamily: UB.mono, fontSize: 10, letterSpacing: '0.04em', cursor: 'pointer' }}>{c}</span>
              ))}
              <span style={{ flex: 1 }} />
              <span style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3 }}>Sort: <span style={{ color: UB.ink }}>Date added ↓</span></span>
              <Tag tone="ink">LIST</Tag>
              <Tag>GRID</Tag>
            </div>

            {/* table */}
            <div style={{ flex: 1, overflow: 'auto' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '24px 70px 2fr 1fr 60px 80px 90px 60px', gap: 10, padding: '8px 24px', fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.14em', textTransform: 'uppercase', borderBottom: `1px solid ${UB.rule2}`, background: UB.paperDeep, position: 'sticky', top: 0 }}>
                <span></span><span>Type</span><span>Title</span><span>Authors</span><span>Year</span><span>Venue</span><span>Annot · Cite</span><span></span>
              </div>
              {LIB_PAPERS.map((p, i) => (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '24px 70px 2fr 1fr 60px 80px 90px 60px',
                  gap: 10, padding: '12px 24px', alignItems: 'center',
                  borderBottom: `1px solid ${UB.rule3}`,
                  background: i === 2 ? UB.accentDim : 'transparent',
                  cursor: 'pointer',
                }}>
                  <span style={{ color: p.star ? UB.accent : UB.ink4, fontSize: 14, lineHeight: 1 }}>★</span>
                  <TypeChip t={p.type} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: UB.ink, lineHeight: 1.3 }}>{p.title}</div>
                    <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>
                      {p.tags.map(t => <span key={t} style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, padding: '1px 4px', background: UB.paperDeep, letterSpacing: '0.04em' }}>{t}</span>)}
                      {!p.read && <Tag tone="warn">UNREAD</Tag>}
                    </div>
                  </div>
                  <span style={{ fontSize: 11, color: UB.ink3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.authors}</span>
                  <span style={{ fontFamily: UB.mono, fontSize: 11, color: UB.ink3 }}>{p.year}</span>
                  <span style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.venue.split(' · ')[0]}</span>
                  <span style={{ fontFamily: UB.mono, fontSize: 11, color: UB.ink2 }}>
                    {p.annotations > 0 ? <span style={{ color: UB.accent }}>{p.annotations}</span> : '—'} · {p.cited}
                  </span>
                  <span style={{ color: UB.ink4, fontSize: 14 }}>›</span>
                </div>
              ))}
            </div>

            {/* footer */}
            <div style={{ padding: '10px 24px', borderTop: `1px solid ${UB.rule2}`, display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 10, color: UB.ink3 }}>
              <span>Showing 12 of 1,418 · 218 annotated · 412 cited</span>
              <span>Last sync 2 min ago · IPFS + ORCID + arXiv</span>
            </div>
          </div>

          {/* Right inspector */}
          <div style={{ width: 320, borderLeft: `1px solid ${UB.rule2}`, background: '#fff', overflow: 'auto', flexShrink: 0 }}>
            <div style={{ padding: 18 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <span style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.16em' }}>SELECTION · 1</span>
                <Btn small ghost>×</Btn>
              </div>
              <TypeChip t="PDF" />
              <h3 style={{ fontFamily: UB.serif, fontSize: 22, lineHeight: 1.15, margin: '8px 0 6px', fontWeight: 400 }}>
                A reproducibility-weighted citation index for neuroimaging
              </h3>
              <div style={{ fontSize: 11, color: UB.ink2, marginBottom: 4 }}>Lin C., Harriot M.</div>
              <div style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3 }}>Cell Reports Methods · 5(11) · 2024</div>
              <div style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3, marginTop: 2 }}>doi:10.1016/j.crmeth.2024.0918</div>

              <div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
                <Btn small primary icon={Icon.book}>Open PDF</Btn>
                <Btn small icon={Icon.doc}>Cite</Btn>
                <Btn small icon={Icon.arrow}>Download</Btn>
              </div>

              <div style={{ marginTop: 18, fontSize: 12, lineHeight: 1.55, color: UB.ink2 }}>
                <strong style={{ fontWeight: 600 }}>Abstract.</strong> We propose RW-IF, a citation metric that down-weights citations from un-replicated work and up-weights replications, code release, and shared data. Across 14,000 neuroscience papers (2010–2023), RW-IF correlates ρ=0.71 with later replication outcomes and is robust to citation-ring inflation…
              </div>

              <div style={{ marginTop: 16 }}>
                <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.16em', marginBottom: 6 }}>YOUR ANNOTATIONS · 22</div>
                {[
                  ['Highlight · §3.2', 'Down-weighting works as a Bayes prior on citation utility…'],
                  ['Note · Fig 4',     'Use this framing in DRAFT·219 intro.'],
                  ['Highlight · §5.4', '…RW-IF correlates ρ=0.71 with replication.'],
                ].map(([k, v], i) => (
                  <div key={i} style={{ padding: '8px 0', borderTop: `1px solid ${UB.rule3}` }}>
                    <div style={{ fontFamily: UB.mono, fontSize: 10, color: UB.accent, marginBottom: 2, letterSpacing: '0.06em' }}>{k}</div>
                    <div style={{ fontSize: 11, color: UB.ink2, lineHeight: 1.5 }}>{v}</div>
                  </div>
                ))}
              </div>

              <div style={{ marginTop: 18 }}>
                <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.16em', marginBottom: 6 }}>FOLDERS · TAGS</div>
                <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                  <Tag>Reproducibility</Tag>
                  <Tag>Reviews · 2025 cycle</Tag>
                  <span style={{ fontFamily: UB.mono, fontSize: 9, padding: '2px 5px', background: UB.paperDeep, color: UB.ink2 }}>#review</span>
                  <span style={{ fontFamily: UB.mono, fontSize: 9, padding: '2px 5px', background: UB.paperDeep, color: UB.ink2 }}>#methods</span>
                  <Btn small ghost>+ tag</Btn>
                </div>
              </div>

              <div style={{ marginTop: 18 }}>
                <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.16em', marginBottom: 6 }}>CITED IN MY DRAFTS · 4</div>
                {['DRAFT·219 · §1.4', 'DRAFT·220 · §6.1', 'NB-204 · cell 2.3', 'dPID·81b3 · §intro'].map((c, i) => (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontFamily: UB.mono, fontSize: 11, color: UB.ink2 }}>
                    <span>{c}</span><span style={{ color: UB.ink4 }}>↗</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </Layout>
    </Dapp>
  );
}

// ────────────────────────────────────────────── LIBRARY · PDF READER ─────────
function ReferenceReaderDapp() {
  return (
    <Dapp>
      <ChromeBar dapp="REFERENCE" code="LIB / READER · doi:10.1016/j.crmeth.2024.0918" />
      <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
        {/* Toolbar */}
        <div style={{ width: 56, borderRight: `1px solid ${UB.rule2}`, background: UB.paperDeep, display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '14px 0', gap: 6, flexShrink: 0 }}>
          {[Icon.arrow, Icon.search, Icon.book, Icon.doc, Icon.flask, Icon.user, Icon.cog].map((ic, i) => (
            <div key={i} style={{
              width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: i === 2 ? UB.ink : 'transparent', color: i === 2 ? UB.accent : UB.ink2,
              cursor: 'pointer',
            }}>{ic}</div>
          ))}
          <div style={{ flex: 1 }} />
          <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.18em', writingMode: 'vertical-rl', transform: 'rotate(180deg)', padding: '8px 0' }}>READER · v3</div>
        </div>

        {/* Page thumbnails */}
        <div style={{ width: 110, borderRight: `1px solid ${UB.rule2}`, padding: 10, overflow: 'auto', flexShrink: 0 }}>
          {[1,2,3,4,5,6,7,8].map(n => (
            <div key={n} style={{ marginBottom: 8, position: 'relative' }}>
              <div style={{
                width: 90, height: 116,
                background: '#fff', border: `1px solid ${n === 4 ? UB.ink : UB.rule2}`,
                position: 'relative', padding: 6,
              }}>
                <div style={{ height: 4, background: UB.ink2, marginBottom: 3 }} />
                <div style={{ height: 2, background: UB.ink3, marginBottom: 2, width: '88%' }} />
                {Array.from({length: 14}).map((_, i) => <div key={i} style={{ height: 1.4, background: UB.ink4, marginBottom: 1.6, width: `${70 + Math.sin(i + n) * 18}%` }} />)}
                {n === 4 && <div style={{ position: 'absolute', left: 4, right: 4, top: 32, height: 16, background: UB.accent, opacity: 0.55 }} />}
                {n === 4 && <div style={{ position: 'absolute', left: 4, right: 4, top: 64, height: 8, background: UB.accent, opacity: 0.4 }} />}
              </div>
              <div style={{ textAlign: 'center', fontFamily: UB.mono, fontSize: 9, color: n === 4 ? UB.ink : UB.ink3, marginTop: 3 }}>{n}</div>
            </div>
          ))}
        </div>

        {/* Page surface */}
        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', background: UB.paperDeep }}>
          <div style={{ height: 38, borderBottom: `1px solid ${UB.rule2}`, background: '#fff', display: 'flex', alignItems: 'center', padding: '0 18px', gap: 12, fontFamily: UB.mono, fontSize: 11 }}>
            <span style={{ color: UB.ink3 }}>p.</span><span>4</span><span style={{ color: UB.ink3 }}>/ 18</span>
            <span style={{ width: 1, height: 18, background: UB.rule2 }} />
            <span style={{ color: UB.ink3 }}>zoom</span><span>112%</span>
            <span style={{ flex: 1 }} />
            <Tag tone="accent">22 ANNOTATIONS</Tag>
            <Btn small ghost>{'<'}</Btn>
            <Btn small ghost>{'>'}</Btn>
            <Btn small primary>Highlight</Btn>
          </div>

          <div style={{ flex: 1, overflow: 'auto', padding: '24px 32px', display: 'flex', justifyContent: 'center' }}>
            <div style={{
              width: 640, background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,.1)',
              padding: '56px 64px', fontFamily: UB.serif, fontSize: 13, lineHeight: 1.6, color: UB.ink2,
              position: 'relative',
            }}>
              <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.2em', marginBottom: 4 }}>HARRIOT & LIN · 2024 · CELL REPORTS METHODS · 4</div>
              <h2 style={{ fontFamily: UB.serif, fontSize: 19, fontWeight: 600, margin: '12px 0 18px', color: UB.ink }}>3.2 · Down-weighting un-replicated citations as a Bayes prior</h2>

              <p style={{ marginBottom: 14, textIndent: 18 }}>
                We model the contribution of citation <em>c<sub>ij</sub></em> from paper <em>i</em> to paper <em>j</em> as a Bernoulli draw whose success rate <em>π<sub>j</sub></em> reflects the latent reliability of <em>j</em>. Under the prior that{' '}
                <span style={{ background: UB.accent, padding: '0 1px' }}>down-weighting works as a Bayes prior on citation utility, with the replication rate τ<sub>j</sub> as a sufficient statistic for π<sub>j</sub></span>, we obtain the closed-form posterior in Equation (4).
              </p>
              <p style={{ marginBottom: 14, textIndent: 18 }}>
                Empirically, this re-weighting redistributes ≈18.6% of cumulative citation mass away from the long tail of un-replicated, low-tau papers. Section 4 evaluates the metric on a held-out set of 14,000 neuroscience papers spanning 2010–2023.
              </p>
              <p style={{ marginBottom: 8 }}>
                <strong style={{ fontFamily: UB.sans, fontWeight: 600, color: UB.ink, fontSize: 12 }}>Edge cases.</strong>{' '}
                Two pathologies require explicit handling: <span style={{ background: 'oklch(0.78 0.16 70 / 0.45)', padding: '0 1px' }}>(i) self-citation chains within a single lab, and (ii) citation rings that arise from venue-specific norms</span>. We treat both as structured covariates rather than removing them outright.
              </p>

              {/* Margin pin */}
              <div style={{
                position: 'absolute', right: -210, top: 110,
                width: 180, padding: 10,
                border: `1px solid ${UB.accent}`, background: '#fff',
                fontFamily: UB.sans, fontSize: 11, lineHeight: 1.45,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.1em', marginBottom: 4 }}>
                  <span>NOTE · 04 MAY</span>
                  <span style={{ color: UB.accent }}>● m.harriot</span>
                </div>
                <div style={{ color: UB.ink2 }}>Use this framing in DRAFT·219 intro — Bayes-prior re-weighting motivates Section 1.4.</div>
              </div>
              <div style={{
                position: 'absolute', right: -210, top: 250,
                width: 180, padding: 10,
                border: `1px solid ${UB.warn}`, background: '#fff',
                fontFamily: UB.sans, fontSize: 11, lineHeight: 1.45,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.1em', marginBottom: 4 }}>
                  <span>FLAG · 02 MAY</span>
                  <span style={{ color: UB.warn }}>● l.singh</span>
                </div>
                <div style={{ color: UB.ink2 }}>Pathology (ii) — citation rings — overlaps with §6 in Lin 2023. Worth a footnote?</div>
              </div>
            </div>
          </div>
        </div>

        {/* Right pane — outline + annotations */}
        <div style={{ width: 280, borderLeft: `1px solid ${UB.rule2}`, background: '#fff', display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
          <div style={{ padding: '14px 16px', borderBottom: `1px solid ${UB.rule2}` }}>
            <div style={{ fontFamily: UB.mono, fontSize: 9, letterSpacing: '0.2em', color: UB.ink3, marginBottom: 4 }}>READING</div>
            <div style={{ fontFamily: UB.serif, fontSize: 16, lineHeight: 1.2, fontWeight: 400 }}>A reproducibility-weighted citation index for neuroimaging</div>
            <div style={{ fontSize: 11, color: UB.ink3, marginTop: 4 }}>Lin C., Harriot M. · 2024</div>
          </div>

          <div style={{ flex: 1, overflow: 'auto' }}>
            <div style={{ padding: '12px 16px', borderBottom: `1px solid ${UB.rule3}` }}>
              <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.16em', marginBottom: 8 }}>OUTLINE</div>
              {[
                ['1', 'Introduction', false],
                ['2', 'Prior art & limitations', false],
                ['3', 'A weighted citation model', false],
                ['3.1', '— Notation', false],
                ['3.2', '— Bayes prior reformulation', true],
                ['3.3', '— Edge cases', false],
                ['4', 'Empirical evaluation', false],
                ['5', 'Discussion', false],
                ['6', 'Methods', false],
              ].map(([n, t, on], i) => (
                <div key={i} style={{ display: 'flex', gap: 10, padding: '4px 0', fontSize: 11, color: on ? UB.ink : UB.ink3, fontWeight: on ? 600 : 400, paddingLeft: n.includes('.') ? 18 : 0, borderLeft: on ? `2px solid ${UB.accent}` : '2px solid transparent', marginLeft: -16, paddingLeftActual: 16 }}>
                  <span style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3, width: 22, paddingLeft: on ? 14 : 16 }}>{n}</span>
                  <span>{t}</span>
                </div>
              ))}
            </div>

            <div style={{ padding: '12px 16px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                <span style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.16em' }}>ANNOTATIONS · 22</span>
                <span style={{ fontFamily: UB.mono, fontSize: 9, color: UB.accent }}>3 NEW</span>
              </div>
              {[
                { p: 'p.4 §3.2', tone: UB.accent, txt: 'down-weighting works as a Bayes prior…', who: 'highlight' },
                { p: 'p.4 §3.2', tone: UB.accent, txt: 'Use this framing in DRAFT·219 intro.', who: 'note · m.harriot' },
                { p: 'p.4 §3.2', tone: UB.warn,   txt: 'Pathology (ii) overlaps with §6 in Lin 2023.', who: 'flag · l.singh' },
                { p: 'p.7 §4.3', tone: UB.accent, txt: 'ρ=0.71 with later replication outcomes.', who: 'highlight' },
                { p: 'p.9 fig.4', tone: UB.ok,    txt: 'Replication-rate × cite-mass — print this for offsite.', who: 'note · m.harriot' },
                { p: 'p.12 §5',  tone: UB.accent, txt: 'venue-specific citation norms…', who: 'highlight' },
              ].map((a, i) => (
                <div key={i} style={{ padding: '8px 0', borderTop: i > 0 ? `1px solid ${UB.rule3}` : 'none' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.06em', marginBottom: 3 }}>
                    <span>{a.p}</span>
                    <span style={{ color: a.tone }}>● {a.who}</span>
                  </div>
                  <div style={{ fontSize: 11, color: UB.ink2, lineHeight: 1.45, paddingLeft: 8, borderLeft: `2px solid ${a.tone}` }}>{a.txt}</div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ borderTop: `1px solid ${UB.rule2}`, padding: 12, display: 'flex', gap: 6 }}>
            <Btn small ghost>Cite</Btn>
            <Btn small ghost>Share</Btn>
            <Btn small primary style={{ flex: 1, justifyContent: 'center' }}>Add to draft</Btn>
          </div>
        </div>
      </div>
    </Dapp>
  );
}

// ──────────────────────────────────────── LIBRARY · CITATION EXPORT ──────────
function CitationExportDapp() {
  return (
    <Dapp>
      <ChromeBar dapp="REFERENCE" code="LIB / CITE · 412 SELECTED" />
      <Layout rail={<LibraryRail active="all" />}>
        <PageHead
          eyebrow={<LibCrumb items={['Reference Library', 'Cite & export']} />}
          title="Cite & export"
          sub="Generate citations, export bibliographies, and sync references back to your active drafts. Format-aware — switch CSL styles and the previews update."
          actions={<>
            <Btn small icon={Icon.doc}>Copy to clipboard</Btn>
            <Btn small primary icon={Icon.arrow}>Export · BibTeX</Btn>
          </>}
        />

        <div style={{ flex: 1, padding: 24, overflow: 'auto', display: 'grid', gridTemplateColumns: '320px 1fr 320px', gap: 18 }}>

          {/* Left — selection + format picker */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Card title="Selection" code="412 REFERENCES" pad={false}>
              <div style={{ padding: '12px 14px', borderBottom: `1px solid ${UB.rule3}`, fontSize: 11, color: UB.ink2 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                  <span>Cited in DRAFT·219</span>
                  <span style={{ fontFamily: UB.mono, color: UB.accent }}>184</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                  <span>Folder · Astrocytes · sleep</span>
                  <span style={{ fontFamily: UB.mono, color: UB.ink3 }}>84</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                  <span>Folder · Reproducibility</span>
                  <span style={{ fontFamily: UB.mono, color: UB.ink3 }}>38</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span>Tagged · #replication</span>
                  <span style={{ fontFamily: UB.mono, color: UB.ink3 }}>106</span>
                </div>
              </div>
              <div style={{ padding: 12, fontFamily: UB.mono, fontSize: 10, color: UB.ink3 }}>
                Dedupe by DOI · merged 14 · resolved 8 unknown
              </div>
            </Card>

            <Card title="Citation style" code="CSL">
              {[
                ['Nature', true],
                ['APA · 7th ed.', false],
                ['Cell', false],
                ['IEEE', false],
                ['ACM', false],
                ['Vancouver', false],
                ['UB-Chain Open · v1', false],
                ['+ import .csl', false],
              ].map(([k, on], i) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: i < 7 ? `1px solid ${UB.rule3}` : 'none', fontSize: 12, color: on ? UB.ink : UB.ink2, fontWeight: on ? 600 : 400, cursor: 'pointer' }}>
                  <span>{k}</span>
                  {on && <Tag tone="accent">ACTIVE</Tag>}
                </div>
              ))}
            </Card>

            <Card title="Locale" code="EN-GB">
              <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                {['en-GB', 'en-US', 'de-DE', 'fr-FR', 'ja-JP', 'zh-CN'].map((l, i) => (
                  <Tag key={l} tone={i === 0 ? 'ink' : 'default'}>{l}</Tag>
                ))}
              </div>
            </Card>
          </div>

          {/* Center — formatted preview + raw outputs */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Card title="Formatted preview · Nature" code="FIRST 6 OF 412" pad={false}>
              <div style={{ padding: 18, fontFamily: UB.serif, fontSize: 13, lineHeight: 1.6, color: UB.ink2 }}>
                {[
                  '1.  Lin, C. & Harriot, M. A reproducibility-weighted citation index for neuroimaging. Cell Rep. Methods 5, 100918 (2024).',
                  '2.  Yamamoto, K., Tanaka, H. & Mori, J. Sleep depth from astrocyte calcium dynamics — RIKEN replication. Nat. Neurosci. 28, 411–423 (2025).',
                  '3.  Singh, L. et al. Glia heterogeneity beyond morphology: a single-cell atlas v2. bioRxiv 2024.11.08.621442 (2024).',
                  '4.  Harriot, M., Singh, L., Okafor, R. et al. Astrocytic gating of slow-wave sleep across cortical depth. UB-Chain dPID·a92f.04 (2025).',
                  '5.  Patel, A. & Mehta, R. Sparse decoding of cortical dynamics with scaled-attention transformers. arXiv:2503.18112 (2025).',
                  '6.  Harriot, M. & Mwangi, A. Open-source 2-photon rig: BoM v3 + reproducible build. UB-Chain dPID·56dd.01 (2024).',
                ].map((c, i) => (
                  <div key={i} style={{ marginBottom: 10, paddingLeft: 22, textIndent: -22 }}>{c}</div>
                ))}
                <div style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3, textAlign: 'center', paddingTop: 8, borderTop: `1px dashed ${UB.rule2}` }}>+ 406 more · scroll preview</div>
              </div>
            </Card>

            <Card title="BibTeX" code="*.bib · 412 ENTRIES" pad={false}>
              <pre style={{
                margin: 0, padding: 16, fontFamily: UB.mono, fontSize: 10.5, lineHeight: 1.55, color: UB.ink2,
                background: UB.paperDeep, overflow: 'auto', maxHeight: 220,
                whiteSpace: 'pre',
              }}>
{`@article{lin2024rwif,
  author    = {Lin, C. and Harriot, M.},
  title     = {A reproducibility-weighted citation index for neuroimaging},
  journal   = {Cell Reports Methods},
  volume    = {5}, number = {11}, pages = {100918},
  year      = {2024}, doi = {10.1016/j.crmeth.2024.0918}
}
@article{yamamoto2025sleep,
  author    = {Yamamoto, K. and Tanaka, H. and Mori, J.},
  title     = {Sleep depth from astrocyte calcium dynamics --- RIKEN replication},
  journal   = {Nature Neuroscience}, volume = {28}, pages = {411--423},
  year      = {2025}, doi = {10.1038/s41593-025-01882-1}
}
@misc{harriot2025astro,
  author    = {Harriot, M. and Singh, L. and Okafor, R. and others},
  title     = {Astrocytic gating of slow-wave sleep across cortical depth},
  howpublished = {UB-Chain dPID·a92f.04}, year = {2025}
}
@misc{patel2025sparse,
  author    = {Patel, A. and Mehta, R.},
  title     = {Sparse decoding of cortical dynamics with scaled-attention transformers},
  eprint    = {2503.18112}, archivePrefix = {arXiv}, year = {2025}
}`}
              </pre>
            </Card>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Card title="In-text · Nature" code="NUMERIC">
                <div style={{ fontFamily: UB.serif, fontSize: 13, lineHeight: 1.6, color: UB.ink2 }}>
                  Recent work has reframed citation utility as a Bayes prior over replication outcomes <sup>1</sup>, with later replication studies <sup>2</sup> confirming the predictive validity. The astrocyte-gating hypothesis <sup>4</sup> extends this to sleep-state classification.
                </div>
                <Btn small style={{ marginTop: 10 }}>Insert at cursor →</Btn>
              </Card>
              <Card title="In-text · APA 7" code="AUTHOR-DATE">
                <div style={{ fontFamily: UB.serif, fontSize: 13, lineHeight: 1.6, color: UB.ink2 }}>
                  Recent work (Lin &amp; Harriot, 2024) has reframed citation utility as a Bayes prior over replication outcomes, with later replication studies (Yamamoto et&nbsp;al., 2025) confirming predictive validity. The astrocyte-gating hypothesis (Harriot et&nbsp;al., 2025) extends this…
                </div>
                <Btn small style={{ marginTop: 10 }}>Switch style →</Btn>
              </Card>
            </div>
          </div>

          {/* Right — destinations + history */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Card title="Send to…" code="DESTINATIONS">
              {[
                ['DRAFT·219 · LaTeX',         'auto-merge · 184 already cited', Icon.doc, 'accent'],
                ['DRAFT·220 · LaTeX',         'merge · 92 new entries',         Icon.doc, 'ok'],
                ['Notebook · NB-219',         'append to bib block',            Icon.book, 'ok'],
                ['Overleaf · /harriot-glia/', 'OAuth synced · 4 min ago',       Icon.arrow, 'info'],
                ['Zotero · group-czb',        'mirror selection',                Icon.arrow, 'info'],
              ].map(([k, s, ic, t], i, arr) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '20px 1fr 60px', gap: 8, alignItems: 'center', padding: '9px 0', borderBottom: i < arr.length - 1 ? `1px solid ${UB.rule3}` : 'none' }}>
                  <span>{ic}</span>
                  <div>
                    <div style={{ fontSize: 12 }}>{k}</div>
                    <div style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3 }}>{s}</div>
                  </div>
                  <Btn small primary>Send</Btn>
                </div>
              ))}
            </Card>

            <Card title="Export formats" code="OUTPUT">
              {[
                ['BibTeX', '.bib', 'recommended', 'accent'],
                ['BibLaTeX', '.bib', 'with @misc + @online', 'ok'],
                ['CSL JSON', '.json', 'for Pandoc / Quarto', 'ok'],
                ['RIS', '.ris', 'EndNote · ProCite', 'default'],
                ['Citation list', '.txt', 'plain Nature', 'default'],
                ['Markdown footnotes', '.md', 'pandoc-cite', 'default'],
              ].map(([k, ext, s, t], i, arr) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 60px 60px', gap: 6, alignItems: 'center', padding: '7px 0', borderBottom: i < arr.length - 1 ? `1px solid ${UB.rule3}` : 'none' }}>
                  <div>
                    <span style={{ fontSize: 12 }}>{k}</span>
                    <span style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3, marginLeft: 6 }}>{ext}</span>
                    <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, marginTop: 1 }}>{s}</div>
                  </div>
                  <Tag tone={t}>{t === 'accent' ? 'TOP' : t === 'ok' ? 'OK' : 'STD'}</Tag>
                  <Btn small ghost>↓</Btn>
                </div>
              ))}
            </Card>

            <Card title="Recent exports" code="HISTORY">
              {[
                ['DRAFT·219.bib · 184 refs', '2 h'],
                ['Glia-2025-review.csl.json', 'yesterday'],
                ['Replication-set.ris', '3d'],
              ].map((r, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: i < 2 ? `1px solid ${UB.rule3}` : 'none', fontSize: 11 }}>
                  <span>{r[0]}</span>
                  <span style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3 }}>{r[1]}</span>
                </div>
              ))}
            </Card>
          </div>
        </div>
      </Layout>
    </Dapp>
  );
}

window.ReferenceLibraryDapp = ReferenceLibraryDapp;
window.ReferenceReaderDapp = ReferenceReaderDapp;
window.CitationExportDapp = CitationExportDapp;
