
const { useState, useEffect, useRef } = React;
const { SectionHeader, useReveal } = window;

/* ── Abstract ── */
function AbstractSection() {
  const keywords = ['LoRA','adapter merging','static code analysis','vulnerability detection','multi-task learning','large language models','linear combination','task interference','PrimeVul'];
  const contributions = [
    { n: '01', text: 'Empirical study of LoRA adapter merging for code analysis — 19 lambda configurations across two structurally dissimilar tasks (SCA and VD).' },
    { n: '02', text: 'Dense 4×4 interference characterisation showing merged adapters retain up to 98% of solo VD and 91% of solo SCA performance.' },
    { n: '03', text: 'Three-tier SCA evaluation with Hungarian algorithm assignment providing partial credit for near-miss detections.' },
    { n: '04', text: 'Evidence that switching from BigVul to PrimeVul (F1: +0.249) outperforms model scaling from Qwen-3B to Llama-8B (F1: +0.078).' },
  ];
  const r1 = useReveal(), r2 = useReveal();

  return (
    <section id="abstract" className="sec">
      <div className="wrap">
        <SectionHeader label="§1 — Abstract" title="What We Studied and Found"
          desc="Can task-specific LoRA adapters be merged post-hoc into a single model that preserves performance on both tasks? We ran the numbers." />

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }} className="mobile-stack">
          {/* Abstract prose */}
          <div ref={r1} className="reveal glass" style={{ padding: '32px 32px' }}>
            <p style={{ color: 'var(--t2)', fontSize: 15, lineHeight: 1.85, marginBottom: 18 }}>
              We investigate whether task-specific LoRA adapters — each fine-tuned independently on{' '}
              <span style={{ color: 'var(--t1)', fontWeight: 500 }}>Meta-Llama-3.1-8B-Instruct</span>{' '}
              — can be merged via weighted linear combination into a single adapter that preserves performance on both tasks.
            </p>
            <p style={{ color: 'var(--t2)', fontSize: 15, lineHeight: 1.85, marginBottom: 18 }}>
              We evaluate <span style={{ color: 'var(--t1)' }}>19 configurations</span>: a <span style={{ color: 'var(--t1)' }}>4×4 lambda grid</span>{' '}
              (λ<sub>SCA</sub>, λ<sub>VD</sub> ∈ {'{0.3, 0.5, 0.7, 1.0}'}) plus three baselines, on synthetic SCA data
              (3,463 samples) and PrimeVul vulnerability data (9,858 expert-verified C/C++ samples).
            </p>
            <p style={{ color: 'var(--t2)', fontSize: 15, lineHeight: 1.85, marginBottom: 24 }}>
              The best merged configuration retains{' '}
              <span style={{ color: 'var(--accent)', fontWeight: 600 }}>98% of solo VD performance</span> while gaining SCA capability,
              and <span style={{ color: 'var(--accent)', fontWeight: 600 }}>91% of solo SCA performance</span> while gaining VD capability.
              Interference is asymmetric: VD is more sensitive to SCA adapter weight than vice versa.
            </p>
            <div style={{ borderTop: '1px solid var(--bdr)', paddingTop: 18 }}>
              <p style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.12em', marginBottom: 12 }}>KEYWORDS</p>
              <p style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--t2)', lineHeight: 2 }}>
                {keywords.join(' · ')}
              </p>
            </div>
          </div>

          {/* Contributions */}
          <div ref={r2} className="reveal" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <p style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.14em', marginBottom: 4 }}>KEY CONTRIBUTIONS</p>
            {contributions.map(c => (
              <div key={c.n} style={{
                padding: '20px 22px',
                borderLeft: '2px solid var(--accent)',
                background: 'var(--card)',
                display: 'flex', gap: 16, alignItems: 'flex-start',
              }}>
                <span style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--accent)', flexShrink: 0, marginTop: 1 }}>{c.n}</span>
                <p style={{ fontSize: 14, color: 'var(--t2)', lineHeight: 1.7 }}>{c.text}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ── Problem ── */
function ProblemSection() {
  const problems = [
    { n: '1', title: 'Memory Overhead', desc: 'Separate specialised models for each task multiply VRAM requirements. A 8B model at 4-bit precision consumes 5–8 GB per task.' },
    { n: '2', title: 'Latency Multiplication', desc: 'Running independent inference passes per task adds unacceptable latency when simultaneous SCA and VD are required in production.' },
    { n: '3', title: 'Unknown Task Interference', desc: 'Adapter merging for code has never been studied. SCA (JSON arrays) and VD (binary labels) have fundamentally different output structures — interference dynamics are unknown.' },
  ];
  const gapItems = [
    { label: 'NLP adapter merging',         status: 'Prior work', dim: true },
    { label: 'Code LLM fine-tuning',        status: 'Prior work', dim: true },
    { label: 'Code adapter merging',        status: 'This paper', dim: false },
    { label: 'Heterogeneous-output merging',status: 'This paper', dim: false },
    { label: 'Per-layer adaptive merge',    status: 'Future work', dim: true },
  ];
  const r1 = useReveal(), r2 = useReveal();

  return (
    <section className="sec sec-alt">
      <div className="wrap">
        <SectionHeader label="§2 — Problem Statement" title="The Multi-Task Deployment Challenge"
          desc="Organisations need static code analysis and vulnerability detection simultaneously. Separate models are impractical. Can one merged adapter handle both?" />

        <div ref={r1} className="reveal" style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16, marginBottom: 40 }} >
          {problems.map(p => (
            <div key={p.n} style={{
              padding: '28px 24px',
              background: 'var(--card)', border: '1px solid var(--bdr)',
              borderTop: '2px solid var(--accent)',
            }}>
              <div style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.1em', marginBottom: 14 }}>CHALLENGE {p.n}</div>
              <h3 style={{ fontFamily: 'var(--fh)', fontSize: 16, fontWeight: 600, color: 'var(--t1)', marginBottom: 10 }}>{p.title}</h3>
              <p style={{ fontSize: 14, color: 'var(--t2)', lineHeight: 1.7 }}>{p.desc}</p>
            </div>
          ))}
        </div>

        <div ref={r2} className="reveal glass" style={{ padding: '28px 32px' }}>
          <p style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.14em', marginBottom: 18 }}>RESEARCH LANDSCAPE</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
            {gapItems.map(g => (
              <div key={g.label} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '9px 18px', border: '1px solid var(--bdr)',
                background: g.dim ? 'transparent' : 'rgba(168,139,90,0.06)',
                borderColor: g.dim ? 'var(--bdr)' : 'rgba(168,139,90,0.3)',
              }}>
                <span style={{ width: 5, height: 5, borderRadius: '50%', background: g.dim ? 'var(--t3)' : 'var(--accent)', flexShrink: 0 }}></span>
                <span style={{ fontSize: 13, color: g.dim ? 'var(--t2)' : 'var(--t1)' }}>{g.label}</span>
                <span style={{ fontFamily: 'var(--fm)', fontSize: 10, color: g.dim ? 'var(--t3)' : 'var(--accent)', marginLeft: 4 }}>{g.status}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ── Methodology ── */
function MethodologySection() {
  const formula = window.katex ? window.katex.renderToString(
    '\\Delta W_{\\text{merged}} = \\lambda_{\\text{SCA}} \\cdot \\Delta W_{\\text{SCA}} \\;+\\; \\lambda_{\\text{VD}} \\cdot \\Delta W_{\\text{VD}}',
    { displayMode: true, throwOnError: false }
  ) : '<code>ΔW_merged = λ_SCA·ΔW_SCA + λ_VD·ΔW_VD</code>';

  const loraFormula = window.katex ? window.katex.renderToString(
    'W = W_0 + B \\cdot A \\qquad B \\in \\mathbb{R}^{d \\times r},\\; A \\in \\mathbb{R}^{r \\times d},\\; r=16',
    { displayMode: true, throwOnError: false }
  ) : '<code>W = W₀ + BA</code>';

  const steps = [
    { n: '1', title: 'Independent Fine-tuning', desc: 'Train SCA and VD adapters separately on Meta-Llama-3.1-8B-Instruct. Identical LoRA config: r=16, α=16, 7 modules/layer, 42M trainable params.', accent: 'var(--blue)' },
    { n: '2', title: 'Post-hoc Merging',         desc: 'Combine weight deltas via PEFT\'s add_weighted_adapter (combination_type="linear"). Weights are not normalised — deliberate design choice.', accent: 'var(--accent)' },
    { n: '3', title: 'Grid Search',              desc: 'Evaluate 16 merged configs (4×4 lambda grid) plus 3 baselines = 19 total. Full test-set inference on both SCA and VD per config.', accent: 'var(--green)' },
    { n: '4', title: 'Pareto Analysis',          desc: 'Identify Pareto-optimal configs spanning the VD–SCA performance trade-off for practical deployment guidance.', accent: 'var(--purple)' },
  ];
  const rArch = useReveal(), rData = useReveal(), rForm = useReveal();

  return (
    <section id="methodology" className="sec">
      <div className="wrap">
        <SectionHeader label="§3 — Methodology" title="Approach and Experimental Design"
          desc="Two structurally dissimilar tasks, two independently trained adapters, one post-hoc linear merge evaluated across 19 configurations." />

        {/* Steps */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 1, marginBottom: 48, border: '1px solid var(--bdr)' }} className="mobile-stack">
          {steps.map((s, i) => (
            <div key={i} style={{ padding: '24px 22px', background: 'var(--card)', borderRight: i < 3 ? '1px solid var(--bdr)' : 'none' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
                <span style={{ fontFamily: 'var(--fm)', fontSize: 10, color: s.accent, fontWeight: 700 }}>{s.n}</span>
                <div style={{ flex: 1, height: 1, background: `linear-gradient(to right, ${s.accent}40, transparent)` }} />
              </div>
              <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--t1)', marginBottom: 10 }}>{s.title}</div>
              <p style={{ fontSize: 13, color: 'var(--t2)', lineHeight: 1.65 }}>{s.desc}</p>
            </div>
          ))}
        </div>

        {/* Architecture diagram */}
        <div ref={rArch} className="reveal" style={{ marginBottom: 36 }}>
          <p style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.14em', marginBottom: 18 }}>ADAPTER ARCHITECTURE</p>
          <div style={{ maxWidth: 820, margin: '0 auto' }}>
            {/* Base model */}
            <div style={{ padding: '18px 28px', textAlign: 'center', border: '1px solid var(--bdr)', background: 'var(--card)', marginBottom: 1 }}>
              <div style={{ fontFamily: 'var(--fm)', fontSize: 9, color: 'var(--t3)', letterSpacing: '0.18em', marginBottom: 6 }}>FROZEN BASE MODEL</div>
              <div style={{ fontWeight: 700, fontSize: 17, color: 'var(--t1)' }}>Meta-Llama-3.1-8B-Instruct &nbsp; W₀</div>
              <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--t3)', marginTop: 5 }}>32 layers · 4096 dims · ~8B frozen parameters · 4-bit NF4</div>
            </div>

            <div style={{ textAlign: 'center', padding: '8px 0', fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--t3)' }}>+</div>

            {/* Two adapters */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, marginBottom: 1 }}>
              {[
                { tag: 'SCA ADAPTER', accent: 'var(--blue)', task: 'Static Code Analysis', params: 'A_SCA · B_SCA', io: 'Python → JSON array of issues', f1: 'F1 = 0.994', note: '~1.6h · 800 steps · r=16' },
                { tag: 'VD ADAPTER',  accent: 'var(--purple)', task: 'Vulnerability Detection', params: 'A_VD · B_VD', io: 'C/C++ → "vulnerable" | "safe"', f1: 'F1 = 0.732', note: '~3.9h · 1100 steps · r=16' },
              ].map((a, i) => (
                <div key={i} style={{ padding: '20px 24px', background: 'var(--card)', border: '1px solid var(--bdr)', borderTop: `2px solid ${a.accent}` }}>
                  <div style={{ fontFamily: 'var(--fm)', fontSize: 9, color: a.accent, letterSpacing: '0.15em', marginBottom: 10 }}>{a.tag}</div>
                  <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6 }}>{a.task}</div>
                  <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--t3)', marginBottom: 6 }}>{a.params} &nbsp;(42M trainable params)</div>
                  <div style={{ fontSize: 13, color: 'var(--t2)', marginBottom: 8 }}>{a.io}</div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ fontFamily: 'var(--fm)', fontSize: 14, fontWeight: 700, color: a.accent }}>{a.f1}</span>
                    <span style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)' }}>{a.note}</span>
                  </div>
                </div>
              ))}
            </div>

            <div style={{ textAlign: 'center', padding: '8px 0', fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.12em' }}>
              ↓ &nbsp; WEIGHTED LINEAR COMBINATION &nbsp; ↓
            </div>

            {/* Merged */}
            <div style={{ padding: '22px 28px', textAlign: 'center', border: '1px solid var(--bdr)', borderTop: '2px solid var(--accent)', background: 'var(--card)' }}>
              <div style={{ fontFamily: 'var(--fm)', fontSize: 9, color: 'var(--accent)', letterSpacing: '0.18em', marginBottom: 12 }}>MERGED MULTI-TASK ADAPTER</div>
              <div dangerouslySetInnerHTML={{ __html: formula }} />
              <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--t3)', marginTop: 10 }}>
                λ ∈ {'{0.3, 0.5, 0.7, 1.0}'} &nbsp;·&nbsp; 16 merged configurations &nbsp;+&nbsp; 3 baselines = 19 total
              </div>
            </div>
          </div>
        </div>

        {/* Data pipeline + hyperparams */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }} className="mobile-stack">
          <div ref={rData} className="reveal glass" style={{ padding: '28px 28px' }}>
            <p style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.14em', marginBottom: 20 }}>DATASETS</p>
            {[
              { label: 'SCA', accent: 'var(--blue)', steps: ['35 Python templates', '→ AST-validated generation', '→ xxhash deduplication', '→ 3,463 unique samples'], note: '11 categories · stratified train/val/test splits' },
              { label: 'VD',  accent: 'var(--purple)', steps: ['PrimeVul (expert-verified labels)', '→ Filter 3–200 line functions', '→ 50/50 undersampling', '→ 9,858 samples'], note: 'C/C++ · pre-defined splits · MAX_SEQ=512 tokens' },
            ].map(d => (
              <div key={d.label} style={{ marginBottom: 24 }}>
                <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: d.accent, marginBottom: 10 }}>{d.label} Dataset</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                  {d.steps.map((s, i) => (
                    <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                      <span style={{ width: 4, height: 4, borderRadius: '50%', background: 'var(--t3)', flexShrink: 0, marginTop: 7 }} />
                      <span style={{ fontSize: 13, color: 'var(--t2)' }}>{s}</span>
                    </div>
                  ))}
                </div>
                <div style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', marginTop: 8 }}>{d.note}</div>
              </div>
            ))}
          </div>

          <div ref={rForm} className="reveal glass" style={{ padding: '28px 28px' }}>
            <p style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.14em', marginBottom: 20 }}>LORA FORMULATION</p>
            <div style={{ padding: '16px', border: '1px solid var(--bdr)', marginBottom: 24, overflowX: 'auto' }}>
              <div dangerouslySetInnerHTML={{ __html: loraFormula }} />
            </div>
            <p style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--t3)', letterSpacing: '0.14em', marginBottom: 14 }}>SHARED HYPERPARAMETERS</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
              {[
                ['LoRA rank r','16'],['LoRA alpha α','16'],['Target modules','7/layer'],
                ['Learning rate','2×10⁻⁴'],['LR schedule','Cosine'],['Optimizer','AdamW 8-bit'],
                ['Max seq length','512 tokens'],['Precision','BF16'],
              ].map(([k,v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 12px', border: '1px solid var(--bdr)', background: 'rgba(255,255,255,0.02)' }}>
                  <span style={{ fontSize: 12, color: 'var(--t2)' }}>{k}</span>
                  <span style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--accent)' }}>{v}</span>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 14, padding: '12px 14px', border: '1px solid rgba(168,139,90,0.2)', background: 'rgba(168,139,90,0.05)', fontSize: 12, color: 'var(--t2)' }}>
              Hardware: NVIDIA RTX 3060 Ti (8 GB VRAM) · 32 GB RAM · Windows 11 · Single GPU
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { AbstractSection, ProblemSection, MethodologySection });
