#!/usr/bin/env python3
"""Build NSF HERD Dashboard v5 — Round 5 changes."""
import json, sys, os

base = "/Users/leisanyumac.com/Documents/Claude Code Projects"
with open(f"{base}/nsf_data.json") as f:
    D = json.load(f)
with open(f"{base}/nsf_q9q11_data.json") as f:
    D2 = json.load(f)
with open("/tmp/peer_chart2_data.json") as f:
    PEER = json.load(f)
with open("/tmp/nat_q11_corrected.json") as f:
    NAT_Q11_DATA = json.load(f)
with open("/tmp/fed_agency_data.json") as f:
    FED_AG = json.load(f)
with open("/tmp/sub_type_ranks.json") as f:
    SUB_RANKS = json.load(f)

D_js  = json.dumps(D,  separators=(',',':'))
D2_js = json.dumps(D2, separators=(',',':'))
PEER_js = json.dumps(PEER, separators=(',',':'))
NAT_Q11_js = json.dumps(NAT_Q11_DATA, separators=(',',':'))
FED_AG_js = json.dumps(FED_AG, separators=(',',':'))
SUB_RANKS_js = json.dumps(SUB_RANKS, separators=(',',':'))

# ── CSS ──────────────────────────────────────────────────────────────────────
CSS = """
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-size:16px;background:#f5f4f0;color:#2E2D29;display:flex;min-height:100vh}
#sidebar{width:265px;min-width:265px;background:#8C1515;color:#fff;display:flex;flex-direction:column;position:fixed;top:0;left:0;height:100vh;z-index:100;overflow-y:auto}
/* Logo */
.sidebar-logo{padding:20px 20px 14px;border-bottom:1px solid rgba(255,255,255,.18)}
.logo-name{font-family:'Source Serif Pro','Georgia','Times New Roman',serif;font-size:26px;font-weight:600;letter-spacing:-.2px;color:#fff;line-height:1.1;padding-bottom:6px}
.logo-line{width:140px;height:1px;background:rgba(255,255,255,.35);margin:0}
.logo-dept{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1.8px;color:rgba(255,255,255,.88);margin-top:6px;line-height:1.4}
/* Nav */
.sidebar-section{padding:14px 0 6px 20px;font-size:16px;font-weight:700;text-transform:uppercase;letter-spacing:1.5px;color:rgba(255,255,255,.5)}
.nav-item{display:flex;align-items:flex-start;padding:10px 20px;cursor:pointer;border-left:3px solid transparent;transition:all .15s}
.nav-item:hover{background:rgba(255,255,255,.1);border-left-color:rgba(255,255,255,.4)}
.nav-item.active{background:rgba(255,255,255,.15);border-left-color:#fff}
.nav-label{font-size:15px;font-weight:500;color:#fff;line-height:1.4}
.nav-item.active .nav-label{font-weight:700}
/* Counter */
#interaction-counter{padding:8px 20px;font-size:10px;color:rgba(255,255,255,.45);font-style:italic}
.sidebar-footer{padding:6px 20px 14px;font-size:10px;color:rgba(255,255,255,.32);line-height:1.6}
/* Main content */
#main{margin-left:265px;flex:1;overflow-y:auto;max-width:1400px}
.view{display:none;padding:28px 32px 40px}
.view.active{display:block}
.view-header{margin-bottom:22px}
.view-title{font-size:24px;font-weight:700;color:#2E2D29;letter-spacing:-.3px}
.view-subtitle{font-size:15px;color:#666;margin-top:4px}
/* KPI cards */
.kpi-row{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:26px}
.kpi-card{background:#fff;border-radius:10px;padding:18px 20px;border:1px solid #E8E4DF;box-shadow:0 1px 4px rgba(0,0,0,.06);display:flex;flex-direction:column}
.kpi-label{font-size:16px;font-weight:700;color:#666;text-transform:uppercase;letter-spacing:.8px;line-height:1.35;margin-bottom:8px;min-height:66px}
.kpi-value-area{min-height:48px;display:flex;align-items:center}
.kpi-value{font-size:40px;font-weight:800;color:#8C1515;letter-spacing:-1.5px;line-height:1}
.kpi-rank-area{min-height:48px;display:flex;align-items:center}
.kpi-rank{font-size:40px;font-weight:800;color:#8C1515;letter-spacing:-2px;line-height:1}
.kpi-line{height:1px;background:#eee;margin:10px 0}
.kpi-yoy{display:flex;align-items:center;gap:6px;margin-bottom:6px;flex-wrap:wrap}
.kpi-yoy-delta{font-size:13px;font-weight:700;color:#175E54}
.kpi-yoy-pct{font-size:13px;font-weight:700;color:#175E54}
.kpi-yoy-label{font-size:13px;color:#999;font-weight:600}
.kpi-neg .kpi-yoy-delta,.kpi-neg .kpi-yoy-pct{color:#8C1515}
.kpi-cagr{font-size:13px;color:#555;line-height:2}
.kpi-cagr span{font-weight:700;color:#2E2D29}
.kpi-rank-move{font-size:13px;font-weight:600;margin-top:6px;line-height:1.6}
.kpi-rank-move.up{color:#175E54}
.kpi-rank-move.down{color:#8C1515}
.kpi-rank-move.same{color:#888}
/* Chart cards */
.chart-card{background:#fff;border-radius:10px;padding:22px;border:1px solid #E8E4DF;box-shadow:0 1px 4px rgba(0,0,0,.06);margin-bottom:22px}
.chart-header{display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:14px;flex-wrap:wrap;gap:10px}
.chart-title{font-size:18px;font-weight:700;color:#2E2D29}
.chart-subtitle{font-size:14px;color:#888;margin-top:2px}
.chart-controls{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.ctrl-group{display:flex;align-items:center;gap:6px}
.ctrl-label{font-size:15px;font-weight:600;color:#666;white-space:nowrap}
select.ctrl-select{font-size:15px;padding:5px 8px;border:1px solid #D0CCC7;border-radius:6px;background:#fff;color:#2E2D29;cursor:pointer;outline:none}
select.ctrl-select:focus{border-color:#8C1515}
.multiselect-dropdown{position:relative;display:inline-block}
.multiselect-btn{font-size:15px;padding:5px 10px;border:1px solid #D0CCC7;border-radius:6px;background:#fff;color:#2E2D29;cursor:pointer;white-space:nowrap;min-width:130px;display:flex;align-items:center;justify-content:space-between;gap:4px}
.multiselect-btn:hover{border-color:#8C1515}
.multiselect-menu{display:none;position:absolute;right:0;top:calc(100% + 4px);background:#fff;border:1px solid #D0CCC7;border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.12);z-index:200;min-width:180px;padding:6px 0}
.multiselect-menu.open{display:block}
.multiselect-opt{display:flex;align-items:center;gap:8px;padding:7px 14px;cursor:pointer;font-size:15px;color:#2E2D29}
.multiselect-opt:hover{background:#f5f4f0}
.multiselect-opt input{accent-color:#8C1515;width:14px;height:14px;cursor:pointer}
.chart-scroll-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}
.chart-wrap{position:relative;height:380px}
.chart-wrap.tall{height:560px}
.chart-wrap.bump{height:580px}
.chart-wrap.horiz{height:420px}
.chart-wrap.horiz-sm{height:180px}
.chart-wrap canvas{height:100%!important}
.chart-legend{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:10px}
.legend-item{display:flex;align-items:center;gap:6px;font-size:14px;color:#555}
.legend-dot{width:12px;height:12px;border-radius:3px;flex-shrink:0}
.mini-charts-row{display:flex;gap:16px;overflow-x:auto;padding-bottom:4px}
.mini-chart-card{flex:1;min-width:160px;background:#f9f8f6;border-radius:8px;padding:14px 12px;border:1px solid #E8E4DF}
.mini-chart-title{font-size:14px;font-weight:700;color:#2E2D29;margin-bottom:8px;text-align:center}
.mini-chart-wrap{position:relative;height:200px}
.mini-chart-wrap canvas{height:100%!important}
/* Sponsor Group Filter */
.sg-filter-wrap{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.sg-btns{display:flex;border:1px solid #D0CCC7;border-radius:7px;overflow:hidden}
.sg-btn{padding:5px 12px;font-size:15px;font-weight:600;border:none;border-right:1px solid #D0CCC7;background:#fff;color:#555;cursor:pointer;transition:background .12s,color .12s}
.sg-btn:last-child{border-right:none}
.sg-btn.active{background:#8C1515;color:#fff}
.sg-btn:hover:not(.active){background:#f5f4f0}
/* Non-Federal Drill-down */
.nf-drill-row{margin-top:8px}
.nf-expand-btn{font-size:14px;padding:4px 12px;border:1px dashed #8C1515;border-radius:6px;background:transparent;color:#8C1515;cursor:pointer}
.nf-expand-btn:hover{background:#fff8f8}
.nf-chart-card{background:#f9f8f6;border-radius:8px;padding:16px;border:1px solid #E8E4DF;margin-top:10px}
.nf-chart-title{font-size:14px;font-weight:700;color:#2E2D29;margin-bottom:8px}
.nf-chart-legend{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:8px}
.nf-chart-wrap{position:relative;height:220px}
.nf-chart-wrap canvas{height:100%!important}
/* Introduction page */
.intro-header{margin-bottom:28px}
.intro-title{font-size:26px;font-weight:700;color:#2E2D29;letter-spacing:-.3px}
.intro-subtitle{font-size:15px;color:#888;margin-top:4px}
.intro-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:30px}
.intro-stat{background:#fff;border-radius:10px;padding:20px;border:1px solid #E8E4DF;box-shadow:0 1px 4px rgba(0,0,0,.06);text-align:center}
.intro-stat-value{font-size:30px;font-weight:800;color:#8C1515;letter-spacing:-1px;line-height:1.2}
.intro-stat-label{font-size:13px;font-weight:600;color:#666;text-transform:uppercase;letter-spacing:.6px;margin-top:6px}
.intro-section{background:#fff;border-radius:10px;padding:22px 24px;border:1px solid #E8E4DF;box-shadow:0 1px 4px rgba(0,0,0,.06);margin-bottom:18px}
.intro-section h3{font-size:17px;font-weight:700;color:#8C1515;margin-bottom:10px;letter-spacing:-.2px}
.intro-section p{font-size:14.5px;color:#2E2D29;line-height:1.7;margin-bottom:8px}
.intro-section p:last-child{margin-bottom:0}
.intro-list{list-style:none;padding:0;margin:0}
.intro-list li{font-size:14.5px;color:#2E2D29;line-height:1.7;padding:4px 0 4px 20px;position:relative}
.intro-list li::before{content:'\\2022';color:#8C1515;font-weight:700;position:absolute;left:4px;top:4px}
.intro-cols{display:grid;grid-template-columns:1fr 1fr;gap:18px}
.intro-cols>div{display:flex;flex-direction:column;gap:18px}
.intro-cols>div>.intro-section{flex:1;margin-bottom:0}
.intro-note{font-size:12.5px;color:#888;line-height:1.6;margin-top:24px;padding-top:14px;border-top:1px solid #E8E4DF}
/* Field label tooltip */
.field-tooltip{position:fixed;z-index:9999;background:#2E2D29;color:#fff;font-size:12.5px;line-height:1.55;padding:10px 14px;border-radius:8px;max-width:340px;pointer-events:none;opacity:0;transition:opacity .15s;box-shadow:0 4px 16px rgba(0,0,0,.25)}
.field-tooltip.visible{opacity:1}
.field-tooltip-title{font-weight:700;font-size:13px;margin-bottom:4px;color:#F4D03F}
@media(max-width:900px){.kpi-row{grid-template-columns:1fr 1fr}.intro-grid{grid-template-columns:1fr 1fr}.intro-cols{grid-template-columns:1fr}}
@media(max-width:600px){.kpi-row{grid-template-columns:1fr}.intro-grid{grid-template-columns:1fr}}
"""

# ── SIDEBAR ──────────────────────────────────────────────────────────────────
SIDEBAR = """
<aside id="sidebar">
  <div class="sidebar-logo">
    <div class="logo-name">Stanford</div>
    <div class="logo-line"></div>
    <div class="logo-dept">Office of Research<br>Administration</div>
  </div>
  <div class="sidebar-section">NSF HERD Dashboard</div>
  <div class="nav-item active" data-view="intro">
    <span class="nav-label">Introduction</span>
  </div>
  <div class="nav-item" data-view="q1">
    <span class="nav-label">R&amp;D Expenditures by Funding Source</span>
  </div>
  <div class="nav-item" data-view="q9q11">
    <span class="nav-label">R&amp;D Expenditures by R&amp;D Field</span>
  </div>
  <div class="nav-item" data-view="q12">
    <span class="nav-label">R&amp;D Expenditures by Expenditure Category</span>
  </div>
  <div class="nav-item" data-view="q2">
    <span class="nav-label">R&amp;D Expenditures from Foreign Source</span>
  </div>
  <div class="nav-item" data-view="q4">
    <span class="nav-label">R&amp;D Expenditures in Medical School</span>
  </div>
  <div class="nav-item" data-view="q15">
    <span class="nav-label">Research Headcount</span>
  </div>
  <div style="flex:1"></div>
  <div id="interaction-counter">0 interactions&nbsp;|&nbsp;0:00 elapsed</div>
  <div class="sidebar-footer">NSF HERD Survey FY14–FY24<br>National Science Foundation</div>
</aside>
"""

# ── INTRO VIEW ───────────────────────────────────────────────────────────────
INTRO_VIEW = """
<div id="view-intro" class="view active">
  <div class="intro-header">
    <div class="intro-title">About the NSF HERD Survey</div>
    <div class="intro-subtitle">Higher Education Research and Development Survey</div>
  </div>

  <!-- Key Stats Banner -->
  <div class="kpi-row">
    <div class="kpi-card">
      <div class="kpi-label">Institutions Surveyed (FY24)</div>
      <div class="kpi-value-area"><div class="kpi-value">925</div></div>
    </div>
    <div class="kpi-card">
      <div class="kpi-label">Response Rate (FY24)</div>
      <div class="kpi-value-area"><div class="kpi-value">95%</div></div>
    </div>
    <div class="kpi-card">
      <div class="kpi-label">Annual Survey</div>
      <div class="kpi-value-area"><div class="kpi-value">Since 1972</div></div>
    </div>
    <div class="kpi-card">
      <div class="kpi-label">Higher Ed R&amp;D Exp. (FY24)</div>
      <div class="kpi-value-area"><div class="kpi-value">$117.6B</div></div>
    </div>
  </div>

  <!-- What is the HERD Survey -->
  <div class="intro-section">
    <h3>What Is the HERD Survey?</h3>
    <p>The Higher Education Research and Development (HERD) Survey is the primary source of information on R&amp;D expenditures at U.S. colleges and universities. It collects detailed data on R&amp;D spending by field of research, source of funding, and type of expenditure. The survey is conducted annually and provides comprehensive, institution-level data that enables national benchmarking and trend analysis.</p>
  </div>

  <!-- Who Conducts It -->
  <div class="intro-section">
    <h3>Who Conducts It?</h3>
    <p>The HERD Survey is conducted by the <strong>National Center for Science and Engineering Statistics (NCSES)</strong>, a statistical agency within the <strong>National Science Foundation (NSF)</strong>. NCSES is one of 13 principal federal statistical agencies in the United States and is responsible for providing data on the state of science, engineering, and technology in the U.S.</p>
  </div>

  <!-- Eligibility & What's Included/Excluded -->
  <div class="intro-cols">
    <div>
      <!-- Eligibility Criteria -->
      <div class="intro-section">
        <h3>Who Is Included?</h3>
        <p>Institutions must meet all of the following criteria:</p>
        <ul class="intro-list">
          <li>U.S.-based institution (including territories)</li>
          <li>Grants bachelor&rsquo;s degrees or higher in science, engineering, or health fields</li>
          <li>Expended at least $150,000 in separately accounted-for R&amp;D in the fiscal year</li>
        </ul>
      </div>

      <!-- What's Included -->
      <div class="intro-section">
        <h3>What&rsquo;s Included in the Data?</h3>
        <ul class="intro-list">
          <li>Basic research, applied research, and experimental development</li>
          <li>R&amp;D funded by external sponsors &mdash; federal, state &amp; local government, corporations (businesses), non-profits, and other non-federal sources</li>
          <li>R&amp;D funded by institution &mdash; institutionally financed research, committed cost sharing, and unrecovered indirect costs (prescribed calculation methodology)</li>
          <li>Subawards (pass-through funding to other institutions)</li>
          <li>Indirect costs (facilities &amp; administrative costs)</li>
          <li>R&amp;D expenditures across all fields of science, engineering, and non-S&amp;E fields</li>
        </ul>
      </div>
    </div>

    <div>
      <!-- What's Excluded -->
      <div class="intro-section">
        <h3>What&rsquo;s Excluded in the Data?</h3>
        <ul class="intro-list">
          <li>Public service activities (non-research community engagement)</li>
          <li>Curriculum development and course preparation</li>
          <li>Training grants and fellowships (unless tied to specific research)</li>
          <li>Capital projects and construction costs</li>
          <li>Departmental research that is not separately budgeted</li>
          <li>Routine testing and quality control</li>
          <li>Federally funded R&amp;D centers (FFRDCs) e.g., SLAC</li>
        </ul>
      </div>

      <!-- Why It Matters -->
      <div class="intro-section">
        <h3>Why Does It Matter?</h3>
        <ul class="intro-list">
          <li><strong>Benchmarking</strong> &mdash; Enables universities to compare their R&amp;D performance against national averages and peer institutions</li>
          <li><strong>Carnegie Classification</strong> &mdash; HERD data informs the research activity classification (R1/R2) used by the Carnegie Classification system</li>
          <li><strong>Federal funding decisions</strong> &mdash; Policymakers and agencies use HERD data to assess the distribution and impact of federal research investment</li>
          <li><strong>Institutional strategy</strong> &mdash; Senior leaders use HERD data to identify growth areas, evaluate portfolio balance, and inform resource allocation</li>
        </ul>
      </div>
    </div>
  </div>

  <!-- About This Dashboard -->
  <div class="intro-section">
    <h3>About This Dashboard</h3>
    <p>This dashboard presents NSF HERD data from <strong>FY2014 through FY2024</strong>, comparing Stanford University&rsquo;s research expenditures against national totals and peer institutions. Data is organized across selected questionnaire-based views:</p>
    <ul class="intro-list">
      <li><strong>R&amp;D Expenditures by Funding Source</strong> (Q1) &mdash; Federal, non-federal, and institutional funding trends</li>
      <li><strong>R&amp;D Expenditures by R&amp;D Field</strong> (Q9/Q11) &mdash; Spending by discipline (life sciences, engineering, physical sciences, etc.)</li>
      <li><strong>R&amp;D Expenditures by Expenditure Category</strong> (Q12) &mdash; How funds are spent (salaries, equipment, subawards, indirect costs, etc.)</li>
      <li><strong>R&amp;D Expenditures from Foreign Source</strong> (Q2) &mdash; Foreign-sourced R&amp;D funding trends</li>
      <li><strong>R&amp;D Expenditures in Medical School</strong> (Q4) &mdash; Medical school-specific R&amp;D expenditures</li>
      <li><strong>Research Headcount</strong> (Q15) &mdash; Number of researchers, technicians, and support staff</li>
    </ul>
    <p>Each view includes national trend charts and Stanford-specific comparisons with peer rankings where available.</p>
  </div>

  <div class="intro-note">
    Source: National Center for Science and Engineering Statistics (NCSES), National Science Foundation. Higher Education Research and Development (HERD) Survey, FY 2014&ndash;2024. All dollar values are reported in current (nominal) dollars as collected by the survey. Some data points may be unavailable for certain years due to survey methodology changes.
  </div>
</div>
"""

# ── Q1 VIEW ──────────────────────────────────────────────────────────────────
Q1_VIEW = """
<div id="view-q1" class="view">
  <div class="view-header">

    <div class="view-title">R&amp;D Expenditures by Funding Source</div>
    <div class="view-subtitle">NSF Higher Education R&amp;D (HERD) Survey</div>
  </div>
  <div class="kpi-row" id="q1-kpis"></div>

  <!-- Chart 1: National bars by Sponsor Group -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Higher Ed R&amp;D Expenditures by Funding Source</div>
        <div class="chart-subtitle">All U.S. Higher Education Institutions</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">View:</span>
          <select class="ctrl-select" id="c1-year-filter" onchange="rebuildChart1()">
            <option value="5">5-Year (FY20–FY24)</option>
            <option value="10">10-Year (FY15–FY24)</option>
          </select>
        </div>
        <div class="sg-filter-wrap">
          <span class="ctrl-label">Sponsor Type Group:</span>
          <div class="sg-btns" id="sg-c1">
            <button class="sg-btn active" data-group="Total" onclick="setSG('c1','Total',rebuildChart1)">Total</button>
            <button class="sg-btn" data-group="Federal" onclick="setSG('c1','Federal',rebuildChart1)">Federal</button>
            <button class="sg-btn" data-group="NonFederal" onclick="setSG('c1','NonFederal',rebuildChart1)">Non-Federal</button>
            <button class="sg-btn" data-group="Institutional" onclick="setSG('c1','Institutional',rebuildChart1)">Institutional Funds</button>
          </div>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:500px"><canvas id="chart1"></canvas></div></div>
  </div>

  <!-- Chart 2: Stanford horizontal bar + ranking -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Stanford R&amp;D Expenditures and Ranking</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">View:</span>
          <select class="ctrl-select" id="c2-year-filter" onchange="rebuildChart2()">
            <option value="5">5-Year (FY20–FY24)</option>
            <option value="10">10-Year (FY15–FY24)</option>
          </select>
        </div>
        <div class="ctrl-group">
          <span class="ctrl-label">Sponsor Type Group:</span>
          <select class="ctrl-select" id="sg-c2-select" onchange="onC2SponsorChange()">
            <option value="Total">Total</option>
            <option value="Federal" selected>Federal</option>
            <option value="NonFederal">Non-Federal</option>
            <option value="Institutional">Institutional Funds</option>
          </select>
        </div>
        <div class="ctrl-group" id="c2-sub-group" style="display:none">
          <span class="ctrl-label" id="c2-sub-label">Federal Agency:</span>
          <div class="multiselect-dropdown" id="c2-sub-dd">
            <div class="multiselect-btn" onclick="toggleDD('c2-sub-dd')">
              <span id="c2-sub-label-val">Total</span><span>&#9662;</span>
            </div>
            <div class="multiselect-menu" id="c2-sub-menu" style="min-width:220px"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap horiz" style="min-width:400px;height:500px"><canvas id="chart2"></canvas></div></div>
  </div>
</div>
"""

# ── Q9/Q11 VIEW ───────────────────────────────────────────────────────────────
Q9_VIEW = """
<div id="view-q9q11" class="view">
  <div class="view-header">

    <div class="view-title">R&amp;D Expenditures by R&amp;D Field</div>
    <div class="view-subtitle">NSF HERD Survey — Questionnaires 9 &amp; 11</div>
  </div>

  <!-- Chart 1: National stacked bar by field -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">HigherEd R&amp;D Expenditures by R&amp;D Field</div>
        <div class="chart-subtitle">All U.S. Higher Education Institutions</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">View:</span>
          <select class="ctrl-select" id="c3-year-filter" onchange="rebuildQ9Chart1()">
            <option value="5">5-Year (FY20–FY24)</option>
            <option value="10">10-Year (FY15–FY24)</option>
          </select>
        </div>
        <div class="ctrl-group">
          <span class="ctrl-label">Field:</span>
          <div class="multiselect-dropdown" id="c3-field-dd">
            <div class="multiselect-btn" onclick="toggleDD('c3-field-dd')">
              <span id="c3-field-label">All Fields</span><span>&#9662;</span>
            </div>
            <div class="multiselect-menu" id="c3-field-menu" style="min-width:220px">
              <label class="multiselect-opt" style="border-bottom:1px solid #ddd;padding-bottom:6px;margin-bottom:2px"><input type="checkbox" value="Total" onchange="onC3FieldToggle(this)"> Total (All Fields)</label>
              <label class="multiselect-opt"><input type="checkbox" value="A" checked onchange="onC3FieldToggle(this)"> A — Computer &amp; Info Sci</label>
              <label class="multiselect-opt"><input type="checkbox" value="B" checked onchange="onC3FieldToggle(this)"> B — Engineering</label>
              <label class="multiselect-opt"><input type="checkbox" value="C" checked onchange="onC3FieldToggle(this)"> C — Geosciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="D" checked onchange="onC3FieldToggle(this)"> D — Life Sciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="E" checked onchange="onC3FieldToggle(this)"> E — Math &amp; Stats</label>
              <label class="multiselect-opt"><input type="checkbox" value="F" checked onchange="onC3FieldToggle(this)"> F — Physical Sciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="G" checked onchange="onC3FieldToggle(this)"> G — Psychology</label>
              <label class="multiselect-opt"><input type="checkbox" value="H" checked onchange="onC3FieldToggle(this)"> H — Social Sciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="I" checked onchange="onC3FieldToggle(this)"> I — Other Sciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="J" checked onchange="onC3FieldToggle(this)"> J — Non-S&amp;E</label>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap tall" style="min-width:500px"><canvas id="chart3"></canvas></div></div>
  </div>

  <!-- Chart 2: Bump/rank chart -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Stanford and Peers — Ranking by R&amp;D Field</div>
        <div class="chart-subtitle">Stanford and Peers ranking against all HigherEds</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">View:</span>
          <select class="ctrl-select" id="c4-year-filter" onchange="rebuildQ9Chart2()">
            <option value="5">5-Year (FY20–FY24)</option>
            <option value="10">10-Year (FY15–FY24)</option>
          </select>
        </div>
        <div class="ctrl-group">
          <span class="ctrl-label">Field:</span>
          <div class="multiselect-dropdown" id="c4-field-dd">
            <div class="multiselect-btn" onclick="toggleDD('c4-field-dd')">
              <span id="c4-field-label">Total</span><span>&#9662;</span>
            </div>
            <div class="multiselect-menu" id="c4-field-menu" style="min-width:220px">
              <label class="multiselect-opt" style="border-bottom:1px solid #ddd;padding-bottom:6px;margin-bottom:2px"><input type="checkbox" value="Total" checked onchange="onC4FieldToggle(this)"> Total (All Fields)</label>
              <label class="multiselect-opt"><input type="checkbox" value="A" onchange="onC4FieldToggle(this)"> A — Computer &amp; Info Sci</label>
              <label class="multiselect-opt"><input type="checkbox" value="B" onchange="onC4FieldToggle(this)"> B — Engineering</label>
              <label class="multiselect-opt"><input type="checkbox" value="C" onchange="onC4FieldToggle(this)"> C — Geosciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="D" onchange="onC4FieldToggle(this)"> D — Life Sciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="E" onchange="onC4FieldToggle(this)"> E — Math &amp; Stats</label>
              <label class="multiselect-opt"><input type="checkbox" value="F" onchange="onC4FieldToggle(this)"> F — Physical Sciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="G" onchange="onC4FieldToggle(this)"> G — Psychology</label>
              <label class="multiselect-opt"><input type="checkbox" value="H" onchange="onC4FieldToggle(this)"> H — Social Sciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="I" onchange="onC4FieldToggle(this)"> I — Other Sciences</label>
              <label class="multiselect-opt"><input type="checkbox" value="J" onchange="onC4FieldToggle(this)"> J — Non-S&amp;E</label>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap bump" style="min-width:520px"><canvas id="chart4"></canvas></div></div>
  </div>
</div>
"""

# ── Q12 VIEW ──────────────────────────────────────────────────────────────────
Q12_VIEW = """
<div id="view-q12" class="view">
  <div class="view-header">

    <div class="view-title">R&amp;D Expenditures by Expenditure Category</div>
    <div class="view-subtitle">NSF HERD Survey — Questionnaire 12</div>
  </div>

  <!-- Chart 1 -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">R&amp;D Expenditures by Expenditure Category</div>
        <div class="chart-subtitle">All U.S. Higher Education Institutions</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">View:</span>
          <select class="ctrl-select" id="c5-year-filter" onchange="rebuildQ12Chart1()">
            <option value="5">5-Year (FY20–FY24)</option>
            <option value="10">10-Year (FY15–FY24)</option>
          </select>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:500px"><canvas id="chart5"></canvas></div></div>
  </div>

  <!-- Chart 2: IC% by institution for selected FY -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Stanford and Peers — Indirect Cost Proportion of Total Expenditures</div>
        <div class="chart-subtitle">Indirect costs as % of total R&amp;D expenditures</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">Fiscal Year:</span>
          <select class="ctrl-select" id="c5c-fy" onchange="rebuildQ12Chart3()">
            <option value="2024" selected>FY24</option>
            <option value="2023">FY23</option>
            <option value="2022">FY22</option>
            <option value="2021">FY21</option>
            <option value="2020">FY20</option>
            <option value="2019">FY19</option>
            <option value="2018">FY18</option>
            <option value="2017">FY17</option>
            <option value="2016">FY16</option>
            <option value="2015">FY15</option>
            <option value="2014">FY14</option>
          </select>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:700px;height:400px"><canvas id="chart5c"></canvas></div></div>
  </div>
</div>
"""

# ── Q2 VIEW ───────────────────────────────────────────────────────────────────
Q2_VIEW = """
<div id="view-q2" class="view">
  <div class="view-header">

    <div class="view-title">R&amp;D Expenditures from Foreign Source</div>
    <div class="view-subtitle">NSF HERD Survey — Questionnaire 2</div>
  </div>

  <!-- Chart 1: National total foreign-source R&D -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Foreign-Source R&amp;D Expenditures</div>
        <div class="chart-subtitle">All U.S. Higher Education Institutions</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">View:</span>
          <select class="ctrl-select" id="c6-year-filter" onchange="rebuildQ2Chart1()">
            <option value="5">5-Year (FY20–FY24)</option>
            <option value="10">10-Year (FY15–FY24)</option>
          </select>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:500px"><canvas id="chart6"></canvas></div></div>
  </div>

  <!-- Chart 2: Stanford and Peers for selected FY -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Stanford and Peers — Foreign-sourced R&amp;D Expenditures</div>
        <div class="chart-subtitle">Stanford and peers</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">Fiscal Year:</span>
          <select class="ctrl-select" id="c6b-fy" onchange="rebuildQ2Chart2()">
            <option value="2024" selected>FY24</option>
            <option value="2023">FY23</option>
            <option value="2022">FY22</option>
            <option value="2021">FY21</option>
            <option value="2020">FY20</option>
            <option value="2019">FY19</option>
            <option value="2018">FY18</option>
            <option value="2017">FY17</option>
            <option value="2016">FY16</option>
            <option value="2015">FY15</option>
            <option value="2014">FY14</option>
          </select>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:700px;height:400px"><canvas id="chart6b"></canvas></div></div>
  </div>
</div>
"""

# ── Q4 VIEW ───────────────────────────────────────────────────────────────────
Q4_VIEW = """
<div id="view-q4" class="view">
  <div class="view-header">

    <div class="view-title">R&amp;D Expenditures in Medical School</div>
    <div class="view-subtitle">NSF HERD Survey — Questionnaire 4</div>
  </div>

  <!-- Chart 1: National vs Stanford grouped bar -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Medical School R&amp;D Expenditures</div>
        <div class="chart-subtitle">All U.S. Higher Education Institutions</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">View:</span>
          <select class="ctrl-select" id="c7-year-filter" onchange="rebuildQ4Chart1()">
            <option value="5">5-Year (FY20–FY24)</option>
            <option value="10">10-Year (FY15–FY24)</option>
          </select>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:500px"><canvas id="chart7"></canvas></div></div>
  </div>

  <!-- Chart 2: Stanford and Peers for selected FY -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Stanford and Peers — R&amp;D Expenditures in Medical School</div>
        <div class="chart-subtitle">Stanford and peers</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">Fiscal Year:</span>
          <select class="ctrl-select" id="c7b-fy" onchange="rebuildQ4Chart2()">
            <option value="2024" selected>FY24</option>
            <option value="2023">FY23</option>
            <option value="2022">FY22</option>
            <option value="2021">FY21</option>
            <option value="2020">FY20</option>
            <option value="2019">FY19</option>
            <option value="2018">FY18</option>
            <option value="2017">FY17</option>
            <option value="2016">FY16</option>
            <option value="2015">FY15</option>
            <option value="2014">FY14</option>
          </select>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:700px;height:400px"><canvas id="chart7b"></canvas></div></div>
  </div>
</div>
"""

# ── Q15 VIEW ──────────────────────────────────────────────────────────────────
Q15_VIEW = """
<div id="view-q15" class="view">
  <div class="view-header">

    <div class="view-title">Research Headcount</div>
    <div class="view-subtitle">NSF HERD Survey — Questionnaire 15 &nbsp;|&nbsp; Researchers, R&amp;D Technicians &amp; R&amp;D Support Staff</div>
  </div>

  <!-- Chart 1: National headcount over time -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Research Headcount</div>
        <div class="chart-subtitle">All U.S. Higher Education Institutions</div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:400px"><canvas id="chart8"></canvas></div></div>
    <div style="padding:4px 16px 8px;font-size:12px;color:#888;font-style:italic">FY22 is the earliest available year for this data</div>
  </div>

  <!-- Chart 2: Stanford and Peers headcount -->
  <div class="chart-card">
    <div class="chart-header">
      <div>
        <div class="chart-title">Stanford and Peers — Research Headcount</div>
        <div class="chart-subtitle">Stanford and peers</div>
      </div>
      <div class="chart-controls">
        <div class="ctrl-group">
          <span class="ctrl-label">Fiscal Year:</span>
          <select class="ctrl-select" id="c8c-fy" onchange="rebuildQ15PeerChart()">
            <option value="2024" selected>FY24</option>
            <option value="2023">FY23</option>
            <option value="2022">FY22</option>
          </select>
        </div>
      </div>
    </div>
    <div class="chart-scroll-wrap"><div class="chart-wrap" style="min-width:500px"><canvas id="chart8c"></canvas></div></div>
  </div>

</div>
"""

# ── JAVASCRIPT ────────────────────────────────────────────────────────────────
JS = r"""
// ── Data references
const D_NAT_Q1  = D.q1_national;
const D_STA_Q1  = D.stanford_q1;
const D_RANKS   = D.stanford_rankings;
const D_NAT_Q2  = D.national_q2;
const D_STA_Q2  = D.stanford_q2;
const D_NAT_Q4  = D.national_q4;
const D_STA_Q4  = D.stanford_q4;
const D_Q4_RNK  = D.stanford_q4_rankings;
const D_NAT_Q12 = D.national_q12;
const D_STA_Q12 = D.stanford_q12;
const D_STA_Q15 = D.stanford_q15;
const D_NAT_Q15 = D.national_q15;
const D_STA_Q15D= D.stanford_q15_detail;
const D_NAT_Q9  = D.national_q9;
const D_STA_Q9  = D.stanford_q9;

// ── Colors
const SPONSOR_COLORS = {
  Federal:'#003087', StateLocal:'#4B8BBE', Business:'#2E8B57',
  Nonprofit:'#8B6914', Institutional:'#6A1D8A', Other:'#888888'
};
const SPONSOR_GROUP_COLORS = { Total:'#8C1515', Federal:'#003087', NonFederal:'#2E8B57', Institutional:'#6A1D8A' };
const SPONSOR_GROUP_LABELS = { Total:'Total', Federal:'Federal', NonFederal:'Non-Federal', Institutional:'Institutional Funds' };
const FIELD_COLORS = {
  J:'#78909C', I:'#26A69A', H:'#512DA8', G:'#FF7043',
  F:'#880E4F', E:'#EF6C00', D:'#F9A825', C:'#2E7D32', B:'#0F8B8D', A:'#1A4799'
};
const FIELD_LABELS_SHORT = {
  A:'Computer & Info Sci', B:'Engineering', C:'Geosciences', D:'Life Sciences',
  E:'Math & Stats', F:'Physical Sciences', G:'Psychology', H:'Social Sciences',
  I:'Other Sciences', J:'Non-S&E'
};
const Q12_CATS   = ['Salaries & Benefits','Software (non-cap)','Software (cap)','Equipment','Subawards','Other Direct','Indirect Costs'];
const Q12_COLORS = ['#1565C0','#90A4AE','#CFD8DC','#6A1D8A','#2E7D32','#F9A825','#8C1515'];
const INST_COLORS = {
  'Stanford':'#8C1515','Johns Hopkins':'#002D72','MIT':'#E77500',
  'Harvard':'#A51C30','UC Berkeley':'#FDB515','UCSF':'#058488',
  'UCLA':'#2774AE','UCSD':'#00629B','Columbia':'#6A5ACD',
  'Cornell':'#D47500','Duke':'#012169','Penn':'#40826D','Yale':'#B8860B'
};
const NF_BREAKDOWN_COLORS = { Business:'#2E8B57', Nonprofit:'#8B6914', StateLocal:'#4B8BBE', Other:'#888888' };
const NF_BREAKDOWN_LABELS = { Business:'Corporation', Nonprofit:'Non-Profit', StateLocal:'State & Local Govt', Other:'Other Non-Federal' };

// ── Tooltip text for Institutional Funds legend
const INST_FUNDS_TIP = '<div class="field-tooltip-title">Institutional Funds</div>Includes institutionally financed research, committed cost sharing, and unrecovered indirect costs (prescribed calculation methodology)';

// ── Tooltip text for R&D field legends (Q9/Q11)
const FIELD_TIPS = {
  A:'<div class="field-tooltip-title">A: Computer & Information Sciences</div>AI & machine learning, cybersecurity & information assurance, data science, human-computer interaction (HCI), information science, software engineering',
  B:'<div class="field-tooltip-title">B: Engineering</div>Aerospace, bioengineering & biomedical, chemical, civil, electrical/electronic & communications, industrial & manufacturing, mechanical, metallurgical & materials, other engineering',
  C:'<div class="field-tooltip-title">C: Geosciences, Atmospheric & Ocean Sciences</div>Atmospheric science & meteorology, geological & earth sciences, ocean sciences & marine sciences, other geosciences',
  D:'<div class="field-tooltip-title">D: Life Sciences</div>Agricultural sciences, biological & biomedical sciences, health sciences, natural resources & conservation, other life sciences',
  E:'<div class="field-tooltip-title">E: Math & Statistics</div>Mathematics and statistics',
  F:'<div class="field-tooltip-title">F: Physical Sciences</div>Astronomy & astrophysics, chemistry, materials science, physics, other physical sciences',
  G:'<div class="field-tooltip-title">G: Psychology</div>Psychology',
  H:'<div class="field-tooltip-title">H: Social Sciences</div>Anthropology, economics, political science & government, sociology/demography & population studies, other social sciences',
  I:'<div class="field-tooltip-title">I: Other Sciences</div>Multidisciplinary & interdisciplinary studies, other sciences n.e.c.',
  J:'<div class="field-tooltip-title">J: Non-S&E Fields</div>Business & management, communication & communications technologies, education, humanities, law, social work, visual & performing arts, other non-S&E'
};

// ── Stanford Tree SVG (inline, data URI)
const TREE_SVG_URI = "data:image/svg+xml," + encodeURIComponent(
  '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 55">' +
  '<polygon points="20,2 38,44 2,44" fill="#8C1515"/>' +
  '<polygon points="20,14 34,44 6,44" fill="#A61C24" opacity="0.5"/>' +
  '<rect x="16" y="44" width="8" height="11" fill="#8C1515"/>' +
  '</svg>'
);
const TREE_IMG = new Image(18, 25);
TREE_IMG.src = TREE_SVG_URI;

// ── Chart.js global font defaults
Chart.defaults.font.size = 13;
Chart.defaults.font.family = "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif";
Chart.defaults.plugins.tooltip.bodyFont = { size: 13 };
Chart.defaults.plugins.tooltip.titleFont = { size: 13 };
Chart.defaults.plugins.legend.labels.font = { size: 14 };
Chart.defaults.scale.ticks.font = { size: 13 };

// ── Peer data & corrected Q11 national data
const PEER_Q12 = PEER.q12_ic;
const PEER_Q2  = PEER.q2_foreign;
const PEER_Q4  = PEER.q4_medschool;
const PEER_Q15 = PEER.q15_headcount;

// ── State
let interactionCount = 0, sessionStart = null, timerInterval = null;
const charts = {};
const sgState  = {};   // sponsor group: {chartId: 'Federal'|'NonFederal'|'Institutional'}
const nfdState = {};   // non-fed drill: {chartId: true|false}

// ── Helpers
function fmtDollars(v) {
  if (v >= 1e9) return '$' + (v / 1e9).toFixed(1) + 'B';
  if (v >= 1e6) return '$' + Math.round(v / 1e6) + 'M';
  if (v >= 1e5) return '$' + (v / 1e6).toFixed(1) + 'M';
  if (v >= 1e3) return '$' + Math.round(v / 1e3) + 'K';
  return '$' + Math.round(v);
}
function fmtDollarsND(v) {
  return fmtDollars(v);
}
function fmtYOY(cur, prev) {
  if (!prev || prev === 0) return null;
  const delta = cur - prev, pct = (delta / Math.abs(prev)) * 100, pos = delta >= 0;
  const tri = pos ? '▲' : '▼';
  return { delta: tri + fmtDollars(Math.abs(delta)), pct: tri + Math.abs(pct).toFixed(1) + '%', pos,
           combined: tri + fmtDollars(Math.abs(delta)) + '  ' + tri + Math.abs(pct).toFixed(1) + '%' };
}
function cagr(v0, v1, n) {
  if (!v0 || !v1 || n <= 0) return 0;
  return (Math.pow(v1 / v0, 1 / n) - 1) * 100;
}
function fy(y)  { return 'FY' + String(y).slice(-2); }
function pad(n) { return String(n).padStart(2, '0'); }
function getYears(filter, all) {
  const last = all[all.length - 1];
  if (filter === '5')  return all.filter(y => y >= last - 4);
  if (filter === '10') return all.filter(y => y >= last - 9);
  return all;
}
function destroyChart(id) { if (charts[id]) { charts[id].destroy(); delete charts[id]; } }

// ── Sponsor Group helpers
function getSponsorGroupVal(row, group) {
  if (group === 'Federal')       return row.Federal || 0;
  if (group === 'NonFederal')    return (row.StateLocal||0) + (row.Business||0) + (row.Nonprofit||0) + (row.Other||0);
  if (group === 'Institutional') return row.Institutional || 0;
  return row.Total || 0;
}
function setSG(id, group, rebuild) {
  sgState[id] = group;
  document.querySelectorAll('#sg-' + id + ' .sg-btn').forEach(b =>
    b.classList.toggle('active', b.dataset.group === group)
  );
  const nfRow = document.getElementById('nfd-' + id);
  if (nfRow) nfRow.style.display = group === 'NonFederal' ? 'block' : 'none';
  if (group !== 'NonFederal') {
    nfdState[id] = false;
    const nfc = document.getElementById('nfc-' + id);
    if (nfc) nfc.style.display = 'none';
    const btn = document.getElementById('nfbtn-' + id);
    if (btn) btn.textContent = 'Break down Non-Federal';
  }
  rebuild();
}
// ── Interaction counter
function trackInteraction() {
  if (!sessionStart) {
    sessionStart = Date.now();
    timerInterval = setInterval(updateCounter, 1000);
  }
  interactionCount++;
  updateCounter();
}
function updateCounter() {
  const el = document.getElementById('interaction-counter');
  if (!el) return;
  const secs = sessionStart ? Math.floor((Date.now() - sessionStart) / 1000) : 0;
  const m = Math.floor(secs / 60), s = secs % 60;
  const n = interactionCount;
  el.textContent = `${n} interaction${n !== 1 ? 's' : ''}\u00a0|\u00a0${m}:${pad(s)} elapsed`;
}

// ── Dropdown helpers
function toggleDD(id) {
  document.getElementById(id).querySelector('.multiselect-menu').classList.toggle('open');
}
document.addEventListener('click', e => {
  document.querySelectorAll('.multiselect-menu.open').forEach(m => {
    if (!m.closest('.multiselect-dropdown').contains(e.target)) m.classList.remove('open');
  });
});
function getChecked(menuId) {
  return [...document.querySelectorAll('#' + menuId + ' input:checked')].map(i => i.value);
}
function updateLabel(labelId, checked, allLabel) {
  const el = document.getElementById(labelId);
  const opts = document.querySelectorAll('#' + labelId.replace('label', 'menu') + ' input');
  if (!el) return;
  if (checked.length === opts.length) el.textContent = allLabel;
  else el.textContent = checked.length + ' Selected';
}

// ── topBarPlugin (Total on top, Change $ line, Change % line)
const topBarPlugin = {
  id: 'topBarLabels',
  afterDatasetsDraw(chart, _, opts) {
    if (!opts || !opts.labels) return;
    const { ctx } = chart;
    const lastDS = chart.data.datasets.length - 1;
    const meta = chart.getDatasetMeta(lastDS);
    meta.data.forEach((bar, i) => {
      const lbl = opts.labels[i];
      if (!lbl) return;
      ctx.save();
      ctx.textAlign = 'center';
      ctx.font = 'bold 14px -apple-system,sans-serif';
      ctx.fillStyle = '#2E2D29';
      ctx.textBaseline = 'bottom';
      ctx.fillText(lbl.total, bar.x, bar.y - 6);
      if (lbl.changePct) {
        const chColor = lbl.up ? '#175E54' : '#8C1515';
        ctx.fillStyle = chColor;
        ctx.font = 'bold 13px -apple-system,sans-serif';
        ctx.fillText(lbl.changePct, bar.x, bar.y - 22);
        if (lbl.changeDollar) {
          ctx.fillText(lbl.changeDollar, bar.x, bar.y - 37);
        }
      }
      ctx.restore();
    });
  }
};
Chart.register(topBarPlugin);

// ── rankCirclePlugin (Stanford cardinal, positioned closer to bars)
const rankCirclePlugin = {
  id: 'rankCircles',
  afterDraw(chart) {
    const cfg = chart.config._config || chart.config;
    const rdata = cfg._rankData;
    if (!rdata) return;
    const { ctx } = chart;
    const meta = chart.getDatasetMeta(0);
    // Position circles just right of chart area
    const circleX = chart.chartArea.right + 32;

    // "Stanford's Ranking" label above circles
    if (cfg._showRankLabel !== false && meta.data.length > 0) {
      ctx.save();
      ctx.font = 'bold 12px -apple-system,sans-serif';
      ctx.fillStyle = '#555';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';
      ctx.fillText("Stanford's", circleX, chart.chartArea.top - 8);
      ctx.fillText("Ranking",    circleX, chart.chartArea.top + 6);
      ctx.restore();
    }

    meta.data.forEach((bar, i) => {
      const rank = rdata[i];
      if (!rank) return;
      ctx.save();
      ctx.beginPath();
      ctx.arc(circleX, bar.y, 18, 0, Math.PI * 2);
      ctx.fillStyle = '#8C1515';
      ctx.fill();
      ctx.fillStyle = '#fff';
      ctx.font = 'bold 14px -apple-system,sans-serif';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('#' + rank, circleX, bar.y);
      ctx.restore();
    });
  }
};

// ── fieldRightLabelPlugin (labels to right of FY24 bar, supports color objects + hover tooltips)
const fieldRightLabelPlugin = {
  id: 'fieldRightLabels',
  afterDraw(chart) {
    const fLabels = (chart.config._config || chart.config)._fieldRightLabels;
    if (!fLabels) return;
    const { ctx, chartArea } = chart;
    const lastIdx = chart.data.labels.length - 1;
    chart._fieldLabelBounds = [];
    fLabels.forEach((labelObj, dsIdx) => {
      const meta = chart.getDatasetMeta(dsIdx);
      const bar = meta.data[lastIdx];
      if (!bar) return;
      const barTop = bar.y, barBase = bar.base, barH = barBase - barTop;
      if (barH < 12) return;
      const midY = barTop + barH / 2;
      const labelText  = typeof labelObj === 'string' ? labelObj : labelObj.label;
      const labelColor = typeof labelObj === 'string' ? '#333' : (labelObj.color || '#333');
      ctx.save();
      ctx.font = 'bold 14px -apple-system,sans-serif';
      ctx.fillStyle = labelColor;
      ctx.textAlign = 'left';
      ctx.textBaseline = 'middle';
      ctx.fillText(labelText, chartArea.right + 8, midY);
      const tw = ctx.measureText(labelText).width;
      chart._fieldLabelBounds.push({ x: chartArea.right + 8, y: midY - 9, w: tw, h: 18, dsIdx });
      ctx.restore();
    });
  },
  afterEvent(chart, args) {
    const tooltips = (chart.config._config || chart.config)._fieldRightTooltips;
    if (!tooltips || !chart._fieldLabelBounds) return;
    const e = args.event;
    if (e.type === 'mouseout') { const t = document.getElementById('field-tooltip'); if (t) t.classList.remove('visible'); chart.canvas.style.cursor = 'default'; return; }
    if (e.type !== 'mousemove') return;
    const tipEl = document.getElementById('field-tooltip');
    if (!tipEl) return;
    const mx = e.x, my = e.y;
    let hit = null;
    for (const b of chart._fieldLabelBounds) {
      if (mx >= b.x && mx <= b.x + b.w && my >= b.y && my <= b.y + b.h) { hit = b; break; }
    }
    if (hit && tooltips[hit.dsIdx]) {
      const tt = tooltips[hit.dsIdx];
      tipEl.innerHTML = tt;
      const rect = chart.canvas.getBoundingClientRect();
      let px = rect.left + hit.x - 350;
      if (px < 8) px = rect.left + hit.x + hit.w + 8;
      const py = rect.top + hit.y;
      tipEl.style.left = px + 'px';
      tipEl.style.top = Math.max(py, 8) + 'px';
      tipEl.classList.add('visible');
      chart.canvas.style.cursor = 'help';
    } else {
      tipEl.classList.remove('visible');
      chart.canvas.style.cursor = 'default';
    }
  }
};

// ── bumpLabelPlugin (left labels at first year + right labels at last year + Stanford tree)
const bumpLabelPlugin = {
  id: 'bumpLabels',
  afterDraw(chart) {
    const cfg = chart.config._config || chart.config;
    const { ctx, chartArea, scales } = chart;
    const yScale = scales.y;
    if (!yScale) return;

    // Right labels (at last year position)
    const rdata = cfg._bumpRightLabels;
    if (rdata) {
      rdata.forEach(({ inst, rank, color }) => {
        const y = yScale.getPixelForValue(rank);
        if (y < chartArea.top - 2 || y > chartArea.bottom + 2) return;
        ctx.save();
        const isS = inst === 'Stanford';
        ctx.font = isS ? 'bold 14px -apple-system,sans-serif' : '13px -apple-system,sans-serif';
        ctx.fillStyle = color;
        ctx.textAlign = 'left';
        ctx.textBaseline = 'middle';
        ctx.fillText(inst, chartArea.right + 26, y);
        ctx.restore();
      });
    }

    // Left labels (at first year position)
    const ldata = cfg._bumpLeftLabels;
    if (ldata) {
      ldata.forEach(({ inst, rank, color }) => {
        const y = yScale.getPixelForValue(rank);
        if (y < chartArea.top - 2 || y > chartArea.bottom + 2) return;
        ctx.save();
        const isS = inst === 'Stanford';
        ctx.font = isS ? 'bold 14px -apple-system,sans-serif' : '13px -apple-system,sans-serif';
        ctx.fillStyle = color;
        ctx.textAlign = 'right';
        ctx.textBaseline = 'middle';
        ctx.fillText(inst, chartArea.left - 26, y);
        ctx.restore();
      });
    }
  }
};

// ── stanfordBarPlugin (draws tree icon at Stanford label on Y-axis of horizontal bar charts)
const stanfordBarPlugin = {
  id: 'stanfordBar',
  afterDraw(chart) {
    // Tree icon removed
  }
};

// ─────────────── Q1: KPIs ────────────────────────────────────────────────────
function buildQ1KPIs() {
  const natRows = D_NAT_Q1;
  const latest   = natRows[natRows.length - 1];
  const prev     = natRows[natRows.length - 2];
  const fiveAgo  = natRows.find(r => r.year === latest.year - 5) || natRows[0];
  const tenAgo   = natRows.find(r => r.year === latest.year - 10) || natRows[0];

  const rTotal   = D_RANKS['Total'] || [];
  const rFed     = D_RANKS['Federal'] || [];
  const rLatestT = rTotal.find(r => r.year === latest.year);
  const rPrevT   = rTotal.find(r => r.year === latest.year - 1);
  const rLatestF = rFed.find(r => r.year === latest.year);
  const rPrevF   = rFed.find(r => r.year === latest.year - 1);

  function kpiDollar(label, val, prevVal, v5, v10) {
    const yoy = fmtYOY(val, prevVal);
    const c5  = cagr(v5,  val, 5);
    const c10 = cagr(v10, val, 10);
    const neg = yoy && !yoy.pos;
    return `<div class="kpi-card${neg ? ' kpi-neg' : ''}">
      <div class="kpi-label">${label}</div>
      <div class="kpi-value-area"><div class="kpi-value">${fmtDollars(val)}</div></div>
      <div class="kpi-line"></div>
      <div class="kpi-yoy">
        <span class="kpi-yoy-delta">${yoy ? yoy.delta : '—'}</span>
        <span class="kpi-yoy-pct">${yoy ? yoy.pct : ''}</span>
        <span class="kpi-yoy-label">vs FY${String(prev.year).slice(-2)}</span>
      </div>
      <div class="kpi-cagr">5-Yr CAGR: <span>${c5 >= 0 ? '▲' : '▼'}${Math.abs(c5).toFixed(1)}%</span></div>
      <div class="kpi-cagr">10-Yr CAGR: <span>${c10 >= 0 ? '▲' : '▼'}${Math.abs(c10).toFixed(1)}%</span></div>
    </div>`;
  }

  function kpiRank(label, rLatest, rPrev) {
    const rank = rLatest ? rLatest.rank : '—';
    const delta = rLatest && rPrev ? rPrev.rank - rLatest.rank : 0;
    const cls = delta > 0 ? 'up' : delta < 0 ? 'down' : 'same';
    const tri = delta > 0 ? '▲' : delta < 0 ? '▼' : '—';
    const prevRank = rPrev ? rPrev.rank : '?';
    return `<div class="kpi-card">
      <div class="kpi-label">${label}</div>
      <div class="kpi-rank-area"><div class="kpi-rank">#${rank}</div></div>
      <div class="kpi-line"></div>
      <div class="kpi-rank-move ${cls}">
        ${tri} ${Math.abs(delta) > 0 ? Math.abs(delta) + ' spot' + (Math.abs(delta) > 1 ? 's' : '') : 'Unchanged'}<br>
        from #${prevRank} in FY${String(latest.year - 1).slice(-2)}
      </div>
    </div>`;
  }

  let html = '';
  html += kpiDollar('Higher Ed R&amp;D Exp. (FY' + String(latest.year).slice(-2) + ')',
    latest.Total, prev.Total, fiveAgo.Total, tenAgo.Total);
  html += kpiDollar('Higher Ed Federal R&amp;D Exp. (FY' + String(latest.year).slice(-2) + ')',
    latest.Federal, prev.Federal, fiveAgo.Federal, tenAgo.Federal);
  html += kpiRank('Stanford Total R&amp;D Exp. Ranking', rLatestT, rPrevT);
  html += kpiRank('Stanford Federal R&amp;D Exp. Ranking', rLatestF, rPrevF);

  document.getElementById('q1-kpis').innerHTML = html;
}

// ─────────────── Q1: Chart 1 (National by Sponsor Group) ─────────────────────
const FED_AGENCY_KEYS   = ['DHHS','DOD','NSF','DOE','NASA','Other Fed'];
const FED_AGENCY_COLORS = { DHHS:'#1565C0', DOD:'#6A1D8A', NSF:'#2E8B57', DOE:'#EF6C00', NASA:'#003087', 'Other Fed':'#888888' };
const FED_AGENCY_LABELS = { DHHS:'DHHS (NIH)', DOD:'DOD', NSF:'NSF', DOE:'DOE', NASA:'NASA', 'Other Fed':'Other Federal' };

function rebuildChart1() { trackInteraction(); buildChart1(); }
function buildChart1() {
  destroyChart('chart1');
  const yf    = document.getElementById('c1-year-filter').value;
  const group = sgState['c1'] || 'Total';

  const allYears = D_NAT_Q1.map(r => r.year);
  const years    = getYears(yf, allYears);
  const rows     = D_NAT_Q1.filter(r => years.includes(r.year));
  const ctx      = document.getElementById('chart1').getContext('2d');
  // Common datalabel config: always show, $ on line 1 and % on line 2
  function stackedDL(totalsArr) {
    return {
      display: true,
      formatter: (val, ctx2) => {
        if (!val) return '';
        const t = totalsArr[ctx2.dataIndex] || 1;
        const pct = Math.round(val / t * 100);
        return [fmtDollars(val), pct + '%'];
      },
      color: '#fff', font: { size: 12, weight: 'bold' },
      anchor: 'center', align: 'center', textAlign: 'center'
    };
  }

  if (group === 'Total') {
    // ── Stacked bar: Federal, Non-Federal, Institutional Funds
    const TOTAL_KEYS   = ['Federal','NonFederal','Institutional'];
    const TOTAL_LABELS = { Federal:'Federal', NonFederal:'Non-Federal', Institutional:'Institutional Funds' };
    const TOTAL_COLORS = { Federal:'#003087', NonFederal:'#2E8B57', Institutional:'#B07A00' };
    const getNF = r => (r.StateLocal||0)+(r.Business||0)+(r.Nonprofit||0)+(r.Other||0);
    const getVal = (r,k) => k==='Federal' ? r.Federal||0 : k==='NonFederal' ? getNF(r) : r.Institutional||0;
    const totals = rows.map(r => (r.Federal||0) + getNF(r) + (r.Institutional||0));
    const topLabels = totals.map((val, i) => {
      const prev = i > 0 ? totals[i - 1] : null;
      const yoy  = prev ? fmtYOY(val, prev) : null;
      return { total: fmtDollars(val), changeDollar: yoy ? yoy.delta : null, changePct: yoy ? yoy.pct : null, up: yoy ? yoy.pos : true };
    });
    const datasets = TOTAL_KEYS.map(k => ({
      label: TOTAL_LABELS[k],
      data: rows.map(r => getVal(r, k)),
      backgroundColor: TOTAL_COLORS[k], stack: 'main'
    }));
    const rightLabels = TOTAL_KEYS.map(k => ({ label: TOTAL_LABELS[k], color: TOTAL_COLORS[k] }));
    const cfg = {
      type: 'bar',
      data: { labels: years.map(fy), datasets },
      options: {
        responsive: true, maintainAspectRatio: false,
        layout: { padding: { top: 52, right: 185 } },
        scales: {
          x: { stacked: true, grid: { display: false } },
          y: { stacked: true, ticks: { callback: v => fmtDollarsND(v) }, grid: { color: '#f0eeec' } }
        },
        plugins: { legend: { display: false }, topBarLabels: { labels: topLabels }, datalabels: stackedDL(totals) }
      },
      plugins: [ChartDataLabels, topBarPlugin, fieldRightLabelPlugin]
    };
    cfg._fieldRightLabels = rightLabels;
    cfg._fieldRightTooltips = { 2: INST_FUNDS_TIP };
    charts.chart1 = new Chart(ctx, cfg);

  } else if (group === 'NonFederal') {
    // ── Stacked bar with 4 Non-Federal sub-categories
    const keys   = ['Business', 'Nonprofit', 'StateLocal', 'Other'];
    const totals = rows.map(r => keys.reduce((s, k) => s + (r[k] || 0), 0));
    const topLabels = totals.map((val, i) => {
      const prev = i > 0 ? totals[i - 1] : null;
      const yoy  = prev ? fmtYOY(val, prev) : null;
      return { total: fmtDollars(val), changeDollar: yoy ? yoy.delta : null, changePct: yoy ? yoy.pct : null, up: yoy ? yoy.pos : true };
    });
    const datasets = keys.map(k => ({
      label: NF_BREAKDOWN_LABELS[k],
      data: rows.map(r => r[k] || 0),
      backgroundColor: NF_BREAKDOWN_COLORS[k], borderRadius: 0, stack: 'nf'
    }));
    const rightLabels = keys.map(k => ({ label: NF_BREAKDOWN_LABELS[k], color: NF_BREAKDOWN_COLORS[k] }));
    const cfg = {
      type: 'bar',
      data: { labels: years.map(fy), datasets },
      options: {
        responsive: true, maintainAspectRatio: false,
        layout: { padding: { top: 52, right: 140 } },
        scales: {
          x: { stacked: true, grid: { display: false } },
          y: { stacked: true, ticks: { callback: v => fmtDollarsND(v) }, grid: { color: '#f0eeec' } }
        },
        plugins: { legend: { display: false }, topBarLabels: { labels: topLabels }, datalabels: stackedDL(totals) }
      },
      plugins: [ChartDataLabels, topBarPlugin, fieldRightLabelPlugin]
    };
    cfg._fieldRightLabels = rightLabels;
    charts.chart1 = new Chart(ctx, cfg);

  } else {
    // ── Single bar (Federal or Institutional)
    const vals  = rows.map(r => getSponsorGroupVal(r, group));
    const color = SPONSOR_GROUP_COLORS[group];
    const label = SPONSOR_GROUP_LABELS[group];
    const topLabels = rows.map((r, i) => {
      const val  = vals[i];
      const prev = i > 0 ? vals[i - 1] : null;
      const yoy  = prev ? fmtYOY(val, prev) : null;
      return { total: fmtDollars(val), changeDollar: yoy ? yoy.delta : null, changePct: yoy ? yoy.pct : null, up: yoy ? yoy.pos : true };
    });
    const cfg = {
      type: 'bar',
      data: { labels: years.map(fy), datasets: [{ label, data: vals, backgroundColor: color, borderRadius: 2 }] },
      options: {
        responsive: true, maintainAspectRatio: false,
        layout: { padding: { top: 52, right: 155 } },
        scales: {
          x: { grid: { display: false } },
          y: { ticks: { callback: v => fmtDollarsND(v) }, grid: { color: '#f0eeec' } }
        },
        plugins: {
          legend: { display: false },
          topBarLabels: { labels: topLabels },
          datalabels: {
            display: true,
            formatter: (val) => {
              const d = val >= 1e9 ? (val/1e9).toFixed(1)+'B' : Math.round(val/1e6)+'M';
              return '$' + d;
            },
            color: '#fff', font: { size: 13, weight: 'bold' },
            anchor: 'center', align: 'center', textAlign: 'center',
          }
        }
      },
      plugins: [ChartDataLabels, topBarPlugin, fieldRightLabelPlugin]
    };
    cfg._fieldRightLabels = [{ label, color }];
    if (group === 'Institutional') cfg._fieldRightTooltips = { 0: INST_FUNDS_TIP };
    charts.chart1 = new Chart(ctx, cfg);
  }
}

// ─────────────── Q1: Chart 2 (Stanford Horizontal + Ranking) ─────────────────
function rebuildChart2() { trackInteraction(); buildChart2(); }

// Toggle handler for Q1 Chart 2 sub-type multiselect
function onC2SubToggle(el) {
  const menu = document.getElementById('c2-sub-menu');
  const totalCb = menu.querySelector('input[value="Total"]');
  const itemCbs = [...menu.querySelectorAll('input:not([value="Total"])')];
  if (el.value === 'Total' && el.checked) {
    itemCbs.forEach(cb => cb.checked = false);
  } else if (el.value !== 'Total' && el.checked) {
    totalCb.checked = false;
  }
  const anyItem = itemCbs.some(cb => cb.checked);
  if (!anyItem && !totalCb.checked) { el.checked = true; }
  // Update display label
  const lbl = document.getElementById('c2-sub-label-val');
  const sel = getChecked('c2-sub-menu');
  if (sel.includes('Total')) lbl.textContent = 'Total';
  else if (sel.length === 1) {
    const group = document.getElementById('sg-c2-select').value;
    if (group === 'Federal') lbl.textContent = FED_AGENCY_LABELS[sel[0]] || sel[0];
    else lbl.textContent = NF_BREAKDOWN_LABELS[sel[0]] || sel[0];
  } else lbl.textContent = sel.length + ' Selected';
  rebuildChart2();
}

// Handler for main sponsor type dropdown change
function onC2SponsorChange() {
  const group = document.getElementById('sg-c2-select').value;
  const subGrp = document.getElementById('c2-sub-group');
  const subMenu = document.getElementById('c2-sub-menu');
  const subLbl = document.getElementById('c2-sub-label');
  const subValLbl = document.getElementById('c2-sub-label-val');

  if (group === 'Federal') {
    subGrp.style.display = '';
    if (subLbl) subLbl.textContent = 'Federal Agency:';
    subMenu.innerHTML =
      '<label class="multiselect-opt" style="border-bottom:1px solid #ddd;padding-bottom:6px;margin-bottom:2px"><input type="checkbox" value="Total" checked onchange="onC2SubToggle(this)"> Total (All Agencies)</label>' +
      FED_AGENCY_KEYS.map(k =>
        `<label class="multiselect-opt"><input type="checkbox" value="${k}" onchange="onC2SubToggle(this)"> ${FED_AGENCY_LABELS[k]}</label>`
      ).join('');
    if (subValLbl) subValLbl.textContent = 'Total';
  } else if (group === 'NonFederal') {
    subGrp.style.display = '';
    if (subLbl) subLbl.textContent = 'Non-Fed Sponsor Type:';
    const nfKeys = [
      {v:'Business',l:'Corporation'},{v:'Nonprofit',l:'Non-Profit'},
      {v:'StateLocal',l:'State \\x26 Local Govt'},{v:'Other',l:'Other Non-Federal'}
    ];
    subMenu.innerHTML =
      '<label class="multiselect-opt" style="border-bottom:1px solid #ddd;padding-bottom:6px;margin-bottom:2px"><input type="checkbox" value="Total" checked onchange="onC2SubToggle(this)"> Total (All Non-Fed)</label>' +
      nfKeys.map(k =>
        `<label class="multiselect-opt"><input type="checkbox" value="${k.v}" onchange="onC2SubToggle(this)"> ${k.l}</label>`
      ).join('');
    if (subValLbl) subValLbl.textContent = 'Total';
  } else {
    subGrp.style.display = 'none';
  }
  rebuildChart2();
}

function buildChart2() {
  destroyChart('chart2');
  const yf    = document.getElementById('c2-year-filter').value;
  const group = document.getElementById('sg-c2-select').value;
  const subChecked = (group === 'Federal' || group === 'NonFederal') ? getChecked('c2-sub-menu') : [];
  const isTotal = subChecked.includes('Total') || subChecked.length === 0;

  const allYears = D_STA_Q1.map(r => r.year);
  const years    = getYears(yf, allYears);
  const rows     = D_STA_Q1.filter(r => years.includes(r.year));

  // Determine values based on selection
  let vals, color, barLabel;
  if (group === 'Federal' && !isTotal) {
    // Federal sub-agencies from FED_AG data (sum selected)
    const staFed = FED_AG.stanford_fed_agency;
    const agencies = subChecked.filter(k => FED_AGENCY_KEYS.includes(k));
    vals = years.map(y => agencies.reduce((s, k) => s + (((staFed[String(y)] || {})[k]) || 0), 0));
    if (agencies.length === 1) {
      color = FED_AGENCY_COLORS[agencies[0]] || '#003087';
      barLabel = FED_AGENCY_LABELS[agencies[0]] || agencies[0];
    } else {
      color = '#003087';
      barLabel = agencies.length + ' agencies';
    }
  } else if (group === 'NonFederal' && !isTotal) {
    // Non-Federal sub-categories from Q1 data (sum selected)
    const nfKeys = subChecked.filter(k => k !== 'Total');
    vals = rows.map(r => nfKeys.reduce((s, k) => s + (r[k] || 0), 0));
    if (nfKeys.length === 1) {
      color = NF_BREAKDOWN_COLORS[nfKeys[0]] || '#2E8B57';
      barLabel = NF_BREAKDOWN_LABELS[nfKeys[0]] || nfKeys[0];
    } else {
      color = '#2E8B57';
      barLabel = nfKeys.length + ' non-fed types';
    }
  } else {
    // Total or Institutional — use standard Q1 data
    vals = rows.map(r => getSponsorGroupVal(r, group));
    color = SPONSOR_GROUP_COLORS[group] || '#8C1515';
    barLabel = SPONSOR_GROUP_LABELS[group] || group;
  }

  // Reversed: FY24 at top
  const revYears = [...years].reverse();
  const revVals  = [...vals].reverse();

  // Rank data — use sub-type rankings for specific agencies/categories, group-level for totals/multi
  let rankRows;
  if (group === 'Federal' && !isTotal) {
    const agencies = subChecked.filter(k => k !== 'Total');
    if (agencies.length === 1 && SUB_RANKS[agencies[0]]) {
      rankRows = SUB_RANKS[agencies[0]];
    } else {
      rankRows = D_RANKS.Federal;
    }
  } else if (group === 'NonFederal' && !isTotal) {
    const nfSel = subChecked.filter(k => k !== 'Total');
    if (nfSel.length === 1 && SUB_RANKS[nfSel[0]]) {
      rankRows = SUB_RANKS[nfSel[0]];
    } else {
      rankRows = D_RANKS.NonFederal;
    }
  } else if (group === 'Institutional') {
    rankRows = D_RANKS.Institutional;
  } else if (group === 'Federal') {
    rankRows = D_RANKS.Federal;
  } else if (group === 'NonFederal') {
    rankRows = D_RANKS.NonFederal;
  } else {
    rankRows = D_RANKS.Total;
  }
  const revRanks = revYears.map(y => { const rr = rankRows.find(r => r.year === y); return rr ? rr.rank : null; });

  const thick = years.length <= 5 ? 34 : 22;

  const ctx  = document.getElementById('chart2').getContext('2d');
  const cfg2 = {
    type: 'bar',
    data: {
      labels: revYears.map(fy),
      datasets: [{ data: revVals, backgroundColor: color, borderRadius: 4, barThickness: thick }]
    },
    options: {
      indexAxis: 'y', responsive: true, maintainAspectRatio: false,
      layout: { padding: { right: 76, top: 28 } },
      scales: {
        x: { ticks: { callback: v => fmtDollarsND(v) }, grid: { color: '#f0eeec' } },
        y: { grid: { display: false } }
      },
      plugins: {
        legend: { display: false },
        datalabels: {
          anchor: 'center', align: 'center',
          formatter: v => fmtDollarsND(v),
          color: '#fff', font: { size: 14, weight: 'bold' }
        }
      }
    },
    plugins: [ChartDataLabels, rankCirclePlugin]
  };
  cfg2._rankData = revRanks;
  cfg2._showRankLabel = true;
  charts.chart2 = new Chart(ctx, cfg2);
}

// ─────────────── Q1: init ────────────────────────────────────────────────────
let q1Inited = false;
function initQ1() { buildQ1KPIs(); buildChart1(); onC2SponsorChange(); q1Inited = true; }

// ─────────────── Q9/Q11: Chart 1 ─────────────────────────────────────────────
function onC3FieldToggle(el) {
  const menu = document.getElementById('c3-field-menu');
  const totalCb = menu.querySelector('input[value="Total"]');
  const fieldCbs = [...menu.querySelectorAll('input:not([value="Total"])')];
  if (el.value === 'Total' && el.checked) {
    fieldCbs.forEach(cb => cb.checked = false);
  } else if (el.value !== 'Total' && el.checked) {
    totalCb.checked = false;
  }
  // ensure at least one is checked
  const anyField = fieldCbs.some(cb => cb.checked);
  if (!anyField && !totalCb.checked) { el.checked = true; }
  rebuildQ9Chart1();
}
function rebuildQ9Chart1() { trackInteraction(); buildQ9Chart1(); }
function buildQ9Chart1() {
  destroyChart('chart3');
  const yf       = document.getElementById('c3-year-filter').value;
  const selFields = getChecked('c3-field-menu');
  const isTotal   = selFields.includes('Total');

  // Update label
  const lbl = document.getElementById('c3-field-label');
  if (lbl) {
    if (isTotal) lbl.textContent = 'Total';
    else {
      const allFieldCbs = document.querySelectorAll('#c3-field-menu input:not([value="Total"])');
      const fieldChecked = selFields.filter(v => v !== 'Total');
      if (fieldChecked.length === allFieldCbs.length) lbl.textContent = 'All Fields';
      else lbl.textContent = fieldChecked.length + ' Selected';
    }
  }

  const allYears = Object.keys(NAT_Q11.Total).map(Number).sort();
  const years    = getYears(yf, allYears);

  function getNatVal(fk, year) {
    return (NAT_Q11[fk] || {})[String(year)] || 0;
  }

  const ctx = document.getElementById('chart3').getContext('2d');
  let datasets, topLabels, rightLabels, layoutRight;

  if (isTotal) {
    // Single bar per year using NAT_Q11.Total
    const vals = years.map(y => getNatVal('Total', y));
    datasets = [{ label: 'Total', data: vals, backgroundColor: '#003087', stack: 'main' }];
    topLabels = years.map((y, i) => {
      const val = getNatVal('Total', y);
      const prevY = i > 0 ? years[i - 1] : null;
      const prevV = prevY ? getNatVal('Total', prevY) : null;
      const yoy = prevV ? fmtYOY(val, prevV) : null;
      return { total: fmtDollars(val), changeDollar: yoy ? yoy.delta : null, changePct: yoy ? yoy.pct : null, up: yoy ? yoy.pos : true };
    });
    rightLabels = [];
    layoutRight = 20;
  } else {
    const FIELD_ORDER = ['J','I','H','G','F','E','D','C','B','A'];
    const active = FIELD_ORDER.filter(f => selFields.includes(f));
    datasets = active.map(fk => ({
      label: fk + ': ' + FIELD_LABELS_SHORT[fk],
      data: years.map(y => getNatVal(fk, y)),
      backgroundColor: FIELD_COLORS[fk],
      stack: 'main',
    }));
    topLabels = years.map((y, i) => {
      const total  = active.reduce((s, fk) => s + getNatVal(fk, y), 0);
      const prevY  = i > 0 ? years[i - 1] : null;
      const prevT  = prevY ? active.reduce((s, fk) => s + getNatVal(fk, prevY), 0) : null;
      const yoy    = prevT ? fmtYOY(total, prevT) : null;
      return { total: fmtDollars(total), changeDollar: yoy ? yoy.delta : null, changePct: yoy ? yoy.pct : null, up: yoy ? yoy.pos : true };
    });
    rightLabels = active.map(fk => ({ label: fk + ': ' + FIELD_LABELS_SHORT[fk], color: FIELD_COLORS[fk] }));
    layoutRight = 200;
  }

  const cfg3 = {
    type: 'bar',
    data: { labels: years.map(fy), datasets },
    options: {
      responsive: true, maintainAspectRatio: false,
      animation: false,
      layout: { padding: { top: 52, right: layoutRight } },
      scales: {
        x: { stacked: true, grid: { display: false } },
        y: { stacked: true, ticks: { callback: v => fmtDollars(v) }, grid: { color: '#f0eeec' } }
      },
      plugins: {
        legend: { display: false },
        topBarLabels: { labels: topLabels },
        datalabels: {
          display: ctx2 => {
            if (isTotal) return false;
            const bar = ctx2.chart.getDatasetMeta(ctx2.datasetIndex).data[ctx2.dataIndex];
            return bar ? (bar.base - bar.y) > 28 : false;
          },
          formatter: (val, ctx2) => {
            const total = ctx2.chart.data.datasets.reduce((s, ds) => s + (ds.data[ctx2.dataIndex]||0), 0);
            const pct   = total > 0 ? Math.round(val / total * 100) : 0;
            return fmtDollars(val) + '\n' + pct + '%';
          },
          color: '#fff', font: { size: 13, weight: 'bold' },
          anchor: 'center', align: 'center', textAlign: 'center',
        }
      }
    },
    plugins: [ChartDataLabels, topBarPlugin, fieldRightLabelPlugin]
  };
  cfg3._fieldRightLabels = rightLabels;
  if (!isTotal) {
    const FIELD_ORDER = ['J','I','H','G','F','E','D','C','B','A'];
    const activeF = FIELD_ORDER.filter(f => selFields.includes(f));
    const tips = {};
    activeF.forEach((fk, i) => { if (FIELD_TIPS[fk]) tips[i] = FIELD_TIPS[fk]; });
    cfg3._fieldRightTooltips = tips;
  }
  charts.chart3 = new Chart(ctx, cfg3);
}

// ─────────────── Q9/Q11: Chart 2 (Bump Chart) ────────────────────────────────
function onC4FieldToggle(el) {
  const menu = document.getElementById('c4-field-menu');
  const totalCb = menu.querySelector('input[value="Total"]');
  const fieldCbs = [...menu.querySelectorAll('input:not([value="Total"])')];
  if (el.value === 'Total' && el.checked) {
    fieldCbs.forEach(cb => cb.checked = false);
  } else if (el.value !== 'Total' && el.checked) {
    totalCb.checked = false;
  }
  const anyField = fieldCbs.some(cb => cb.checked);
  if (!anyField && !totalCb.checked) { el.checked = true; }
  // Update label
  const lbl = document.getElementById('c4-field-label');
  const sel = getChecked('c4-field-menu');
  if (sel.includes('Total')) lbl.textContent = 'Total';
  else if (sel.length === fieldCbs.length) lbl.textContent = 'All Fields';
  else if (sel.length === 1) {
    const fk = sel[0];
    lbl.textContent = fk + ': ' + (FIELD_LABELS_SHORT[fk] || fk);
  } else lbl.textContent = sel.length + ' Selected';
  rebuildQ9Chart2();
}
function rebuildQ9Chart2() { trackInteraction(); buildQ9Chart2(); }
function buildQ9Chart2() {
  destroyChart('chart4');
  const yf   = document.getElementById('c4-year-filter').value;
  const selFields = getChecked('c4-field-menu');
  const fKey = selFields.includes('Total') ? 'Total' : (selFields.length === 1 ? selFields[0] : 'Total');

  const allYears  = Object.keys(D2.rankings_combined.Stanford.Total).map(Number).sort();
  const years     = getYears(yf, allYears);
  const allInsts  = ['Stanford', ...D2.peers_list];
  const firstYear = String(years[0]);
  const lastYear  = String(years[years.length - 1]);

  // Use national rank directly (ranking against all HigherEds)
  function getNatRank(inst, yr) {
    return ((D2.rankings_combined[inst] || {})[fKey] || {})[String(yr)] || null;
  }

  // Find the max rank across all institutions and years for Y-axis range
  let maxRank = 0;
  allInsts.forEach(inst => {
    years.forEach(y => {
      const r = getNatRank(inst, y);
      if (r != null && r > maxRank) maxRank = r;
    });
  });
  maxRank = Math.max(maxRank, 10); // at least show top 10

  // Right labels at last year national rank
  const lastYearRanks = {};
  allInsts.forEach(inst => { lastYearRanks[inst] = getNatRank(inst, years[years.length - 1]) || 999; });
  const sortedByLast = [...allInsts].sort((a, b) => lastYearRanks[a] - lastYearRanks[b]);
  const bumpRightLabels = sortedByLast.map(inst => ({
    inst, rank: lastYearRanks[inst], color: INST_COLORS[inst] || '#aaa'
  }));

  // Left labels at first year national rank
  const firstYearRanks = {};
  allInsts.forEach(inst => { firstYearRanks[inst] = getNatRank(inst, years[0]) || 999; });
  const sortedByFirst = [...allInsts].sort((a, b) => firstYearRanks[a] - firstYearRanks[b]);
  const bumpLeftLabels = sortedByFirst.map(inst => ({
    inst, rank: firstYearRanks[inst], color: INST_COLORS[inst] || '#aaa'
  }));

  const datasets = allInsts.map(inst => {
    return {
      label: inst,
      data: years.map(y => getNatRank(inst, y)),
      borderColor: INST_COLORS[inst] || '#aaa',
      backgroundColor: INST_COLORS[inst] || '#aaa',
      borderWidth: inst === 'Stanford' ? 3 : 1.5,
      pointRadius: inst === 'Stanford' ? 7 : 5,
      pointHoverRadius: 9,
      tension: 0.3, fill: false,
      order: inst === 'Stanford' ? 0 : 1,
    };
  });

  const ctx = document.getElementById('chart4').getContext('2d');
  const cfg4 = {
    type: 'line',
    data: { labels: years.map(fy), datasets },
    options: {
      responsive: true, maintainAspectRatio: false,
      layout: { padding: { left: 120, right: 120, bottom: 4 } },
      scales: {
        y: {
          reverse: true, min: 0.5, max: maxRank + 0.5,
          ticks: { stepSize: 1, display: false },
          grid: { color: '#eee' }
        },
        x: { grid: { color: '#f0eeec' } }
      },
      plugins: {
        legend: { display: false },
        datalabels: {
          display: (ctx2) => {
            const v = ctx2.dataset.data[ctx2.dataIndex];
            if (v == null) return false;
            const chart = ctx2.chart;
            const y = chart.scales.y.getPixelForValue(v);
            return y >= chart.chartArea.top - 2 && y <= chart.chartArea.bottom + 2;
          },
          formatter: (val) => val,
          color: '#fff',
          backgroundColor: ctx2 => INST_COLORS[ctx2.dataset.label] || '#aaa',
          borderRadius: 10,
          padding: { top: 2, bottom: 2, left: 4, right: 4 },
          font: { size: 13, weight: 'bold' },
        }
      }
    },
    plugins: [ChartDataLabels, bumpLabelPlugin]
  };
  cfg4._bumpRightLabels = bumpRightLabels;
  cfg4._bumpLeftLabels  = bumpLeftLabels;
  charts.chart4 = new Chart(ctx, cfg4);
}

// ─────────────── Q9/Q11: init ────────────────────────────────────────────────
let q9Inited = false;
function initQ9Q11() { buildQ9Chart1(); buildQ9Chart2(); q9Inited = true; }

// ─────────────── Peer Bar Chart Helper ────────────────────────────────────────
// Builds a vertical bar chart for Stanford + 12 peers, sorted desc
// valFn(inst, year) → number;  fmtFn(v) → string for label
function buildPeerBar(chartId, canvasId, year, valFn, fmtFn, customInsts) {
  destroyChart(chartId);
  const allInsts = customInsts || ['Stanford', ...D2.peers_list];
  const pts = allInsts.map(inst => ({ inst, val: valFn(inst, year) }))
    .sort((a, b) => b.val - a.val);

  const colors = pts.map(p => p.inst === 'Stanford' ? '#8C1515' : '#4B8BBE');
  const ctx = document.getElementById(canvasId).getContext('2d');
  const cfg = {
    type: 'bar',
    data: {
      labels: pts.map(p => p.inst),
      datasets: [{ data: pts.map(p => p.val), backgroundColor: colors, borderRadius: 3 }]
    },
    options: {
      responsive: true, maintainAspectRatio: false,
      layout: { padding: { top: 20 } },
      scales: {
        x: {
          grid: { display: false },
          ticks: {
            font: (ctx2) => {
              if (ctx2.index == null) return { size: 13, weight: 'normal' };
              const inst = pts[ctx2.index]?.inst;
              return { size: 13, weight: inst === 'Stanford' ? 'bold' : 'normal' };
            },
            color: (ctx2) => {
              if (ctx2.index == null) return '#555';
              return pts[ctx2.index]?.inst === 'Stanford' ? '#8C1515' : '#555';
            },
            maxRotation: 45, minRotation: 25
          }
        },
        y: { ticks: { callback: v => fmtFn(v) }, grid: { color: '#f0eeec' } }
      },
      plugins: {
        legend: { display: false },
        datalabels: {
          anchor: 'end', align: 'top', clamp: true,
          formatter: v => fmtFn(v),
          color: (ctx2) => (ctx2.dataIndex != null && pts[ctx2.dataIndex]?.inst === 'Stanford') ? '#8C1515' : '#2E2D29',
          font: (ctx2) => ({ size: 13, weight: (ctx2.dataIndex != null && pts[ctx2.dataIndex]?.inst === 'Stanford') ? 'bold' : 'normal' })
        }
      }
    },
    plugins: [ChartDataLabels]
  };
  charts[chartId] = new Chart(ctx, cfg);
}

// ─────────────── Q12: Chart 1 ────────────────────────────────────────────────
function rebuildQ12Chart1() { trackInteraction(); buildQ12Chart1(); }
function buildQ12Chart1() {
  destroyChart('chart5');
  const yf  = document.getElementById('c5-year-filter').value;
  const src = D_NAT_Q12;

  const allYears = Object.keys(src).map(Number).sort();
  const years    = getYears(yf, allYears);

  const datasets = Q12_CATS.map((cat, ci) => ({
    label: cat,
    data: years.map(y => (src[String(y)] || {})[cat] || 0),
    backgroundColor: Q12_COLORS[ci], stack: 'main',
  }));

  const topLabels = years.map((y, i) => {
    const total = Q12_CATS.reduce((s, c) => s + ((src[String(y)] || {})[c] || 0), 0);
    const prevY = i > 0 ? years[i-1] : null;
    const prevT = prevY ? Q12_CATS.reduce((s, c) => s + ((src[String(prevY)] || {})[c] || 0), 0) : null;
    const yoy   = prevT ? fmtYOY(total, prevT) : null;
    return { total: fmtDollars(total), changeDollar: yoy ? yoy.delta : null, changePct: yoy ? yoy.pct : null, up: yoy ? yoy.pos : true };
  });

  const rightLabels = Q12_CATS.map((cat, ci) => ({ label: cat, color: Q12_COLORS[ci] }));

  const ctx  = document.getElementById('chart5').getContext('2d');
  const cfg5 = {
    type: 'bar',
    data: { labels: years.map(fy), datasets },
    options: {
      responsive: true, maintainAspectRatio: false,
      animation: false,
      layout: { padding: { top: 52, right: 140 } },
      scales: {
        x: { stacked: true, grid: { display: false } },
        y: { stacked: true, ticks: { callback: v => fmtDollars(v) }, grid: { color: '#f0eeec' } }
      },
      plugins: {
        legend: { display: false },
        topBarLabels: { labels: topLabels },
        datalabels: {
          display: ctx2 => {
            const bar = ctx2.chart.getDatasetMeta(ctx2.datasetIndex).data[ctx2.dataIndex];
            return bar ? (bar.base - bar.y) > 28 : false;
          },
          formatter: (val, ctx2) => {
            const total = ctx2.chart.data.datasets.reduce((s, ds) => s + (ds.data[ctx2.dataIndex]||0), 0);
            const isIC  = ctx2.datasetIndex === Q12_CATS.length - 1; // last dataset = Indirect Costs
            const pct   = total > 0 ? (isIC ? (val/total*100).toFixed(1) : Math.round(val/total*100)) : '0';
            return fmtDollars(val) + '\n' + pct + '%';
          },
          color: '#fff', font: { size: 13, weight: 'bold' },
          anchor: 'center', align: 'center', textAlign: 'center',
        }
      }
    },
    plugins: [ChartDataLabels, topBarPlugin, fieldRightLabelPlugin]
  };
  cfg5._fieldRightLabels = rightLabels;
  charts.chart5 = new Chart(ctx, cfg5);
}

// ─────────────── Q12: Chart 2 (IC% Mini Charts) ──────────────────────────────
function buildQ12MiniCharts() {
  ['q12mini20','q12mini21','q12mini22','q12mini23','q12mini24'].forEach(id => {
    if (charts[id]) { charts[id].destroy(); delete charts[id]; }
  });
  const fyList = [2020, 2021, 2022, 2023, 2024];
  const container = document.getElementById('q12-mini-charts');
  container.innerHTML = '';

  fyList.forEach((year, fi) => {
    const s = D_STA_Q12[String(year)] || {};
    const n = D_NAT_Q12[String(year)] || {};
    const sTotal = Q12_CATS.reduce((a, c) => a + (s[c]||0), 0);
    const nTotal = Q12_CATS.reduce((a, c) => a + (n[c]||0), 0);
    const sPct = sTotal > 0 ? s['Indirect Costs']/sTotal*100 : 0;
    const nPct = nTotal > 0 ? n['Indirect Costs']/nTotal*100 : 0;

    const id   = 'q12mini' + String(year).slice(-2);
    const card = document.createElement('div');
    card.className = 'mini-chart-card';
    card.innerHTML = `<div class="mini-chart-title">FY${String(year).slice(-2)}</div><div class="mini-chart-wrap"><canvas id="${id}"></canvas></div>`;
    container.appendChild(card);

    setTimeout(() => {
      const ctx2 = document.getElementById(id).getContext('2d');
      charts[id] = new Chart(ctx2, {
        type: 'bar',
        data: {
          labels: ['Stanford', 'National Avg'],
          datasets: [{ data: [+sPct.toFixed(1), +nPct.toFixed(1)], backgroundColor: ['#8C1515','#4B8BBE'], borderRadius: 4 }]
        },
        options: {
          responsive: true, maintainAspectRatio: false,
          scales: {
            y: { min: 0, max: 40, ticks: { callback: v => v + '%' }, grid: { color: '#eee' } },
            x: { grid: { display: false } }
          },
          plugins: {
            legend: { display: false },
            datalabels: { anchor: 'center', align: 'center', formatter: v => v.toFixed(1)+'%', color: '#fff', font: { size: 13, weight: 'bold' } }
          }
        },
        plugins: [ChartDataLabels]
      });
    }, fi * 30);
  });
}

// ─────────────── Q12: Chart 3 (IC% by Institution for selected FY) ───────────
function rebuildQ12Chart3() { trackInteraction(); buildQ12Chart3(); }
function buildQ12Chart3() {
  const year = parseInt(document.getElementById('c5c-fy').value);
  buildPeerBar('chart5c', 'chart5c', year,
    (inst, yr) => (PEER_Q12[inst] || {})[String(yr)] || 0,
    v => v.toFixed(1) + '%');
}

// ─────────────── Q12: init ───────────────────────────────────────────────────
let q12Inited = false;
function initQ12() { buildQ12Chart1(); buildQ12Chart3(); q12Inited = true; }

// ─────────────── Q2: Chart 1 (National total foreign-source) ─────────────────
function rebuildQ2Chart1() { trackInteraction(); buildQ2Chart1(); }
function buildQ2Chart1() {
  destroyChart('chart6');
  const yf       = document.getElementById('c6-year-filter').value;
  const allYears = Object.keys(D_NAT_Q2).map(Number).sort();
  const years    = getYears(yf, allYears);

  const Q2_CATS   = ['Foreign Governments','Foreign Business','Foreign Nonprofit','Foreign Higher Ed','Other Foreign'];
  const Q2_COLORS = ['#1565C0','#2E8B57','#8B6914','#6A1D8A','#888888'];

  // Build stacked datasets — years before 2016 only have Total (show as single bar)
  const datasets = Q2_CATS.map((cat, ci) => ({
    label: cat,
    data: years.map(y => {
      const row = D_NAT_Q2[String(y)] || {};
      if (Object.keys(row).length <= 2) return ci === 0 ? (row.Total || 0) : 0; // pre-2016: put total in first cat
      return row[cat] || 0;
    }),
    backgroundColor: Q2_COLORS[ci], stack: 'main',
  }));

  const topLabels = years.map((y, i) => {
    const total = (D_NAT_Q2[String(y)] || {}).Total || 0;
    const prevY = i > 0 ? years[i-1] : null;
    const prevT = prevY ? ((D_NAT_Q2[String(prevY)] || {}).Total || 0) : null;
    const yoy   = prevT ? fmtYOY(total, prevT) : null;
    return { total: fmtDollars(total), changeDollar: yoy ? yoy.delta : null, changePct: yoy ? yoy.pct : null, up: yoy ? yoy.pos : true };
  });

  const rightLabels = Q2_CATS.map((cat, ci) => ({ label: cat, color: Q2_COLORS[ci] }));

  const ctx  = document.getElementById('chart6').getContext('2d');
  const cfg6 = {
    type: 'bar',
    data: { labels: years.map(fy), datasets },
    options: {
      responsive: true, maintainAspectRatio: false,
      animation: false,
      layout: { padding: { top: 52, right: 160 } },
      scales: {
        x: { stacked: true, grid: { display: false } },
        y: { stacked: true, ticks: { callback: v => fmtDollarsND(v) }, grid: { color: '#f0eeec' } }
      },
      plugins: {
        legend: { display: false },
        topBarLabels: { labels: topLabels },
        datalabels: {
          display: ctx2 => {
            const bar = ctx2.chart.getDatasetMeta(ctx2.datasetIndex).data[ctx2.dataIndex];
            return bar ? Math.abs(bar.base - bar.y) > 28 : false;
          },
          formatter: (val, ctx2) => {
            if (!val) return '';
            const total = (D_NAT_Q2[String(years[ctx2.dataIndex])] || {}).Total || 1;
            const pct = Math.round(val / total * 100);
            return fmtDollarsND(val) + '\n' + pct + '%';
          },
          color: '#fff', font: { size: 13, weight: 'bold' },
          anchor: 'center', align: 'center', textAlign: 'center',
        }
      }
    },
    plugins: [ChartDataLabels, topBarPlugin, fieldRightLabelPlugin]
  };
  cfg6._fieldRightLabels = rightLabels;
  charts.chart6 = new Chart(ctx, cfg6);
}

// ─────────────── Q2: Chart 2 (Stanford and Peers for selected FY) ────────────
function rebuildQ2Chart2() { trackInteraction(); buildQ2Chart2(); }
function buildQ2Chart2() {
  const year = parseInt(document.getElementById('c6b-fy').value);
  buildPeerBar('chart6b', 'chart6b', year,
    (inst, yr) => (PEER_Q2[inst] || {})[String(yr)] || 0,
    fmtDollarsND);
}

let q2Inited = false;
function initQ2() { buildQ2Chart1(); buildQ2Chart2(); q2Inited = true; }

// ─────────────── Q4: Chart 1 ─────────────────────────────────────────────────
function rebuildQ4Chart1() { trackInteraction(); buildQ4Chart1(); }
function buildQ4Chart1() {
  destroyChart('chart7');
  const yf = document.getElementById('c7-year-filter').value;
  const allYears = D_NAT_Q4.map(r => r.year);
  const years = getYears(yf, allYears);
  const natRows = D_NAT_Q4.filter(r => years.includes(r.year));
  const natVals = natRows.map(r => r.value);

  const topLabels = natVals.map((v, i) => {
    const prev = i > 0 ? natVals[i-1] : null;
    const yoy  = prev ? fmtYOY(v, prev) : null;
    return { total: fmtDollars(v), changeDollar: yoy ? yoy.delta : null, changePct: yoy ? yoy.pct : null, up: yoy ? yoy.pos : true };
  });

  const ctx = document.getElementById('chart7').getContext('2d');
  charts.chart7 = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: years.map(fy),
      datasets: [
        { label: 'National Total', data: natVals, backgroundColor: '#4B8BBE' },
      ]
    },
    options: {
      responsive: true, maintainAspectRatio: false,
      animation: false,
      layout: { padding: { top: 52, right: 24 } },
      scales: {
        x: { grid: { display: false } },
        y: { ticks: { callback: v => fmtDollars(v) }, grid: { color: '#f0eeec' } }
      },
      plugins: {
        legend: { display: false },
        topBarLabels: { labels: topLabels },
        datalabels: {
          display: true,
          formatter: v => fmtDollars(v),
          color: '#fff', font: { size: 13, weight: 'bold' },
          anchor: 'center', align: 'center',
        }
      }
    },
    plugins: [ChartDataLabels, topBarPlugin]
  });
}

// ─────────────── Q4: Chart 2 (Stanford and Peers for selected FY) ────────────
function rebuildQ4Chart2() { trackInteraction(); buildQ4Chart2(); }
function buildQ4Chart2() {
  const year = parseInt(document.getElementById('c7b-fy').value);
  // MIT and UC Berkeley have no medical school data
  const q4Insts = ['Stanford', ...D2.peers_list].filter(i => i !== 'MIT' && i !== 'UC Berkeley');
  buildPeerBar('chart7b', 'chart7b', year,
    (inst, yr) => (PEER_Q4[inst] || {})[String(yr)] || 0,
    fmtDollarsND, q4Insts);
}

let q4Inited = false;
function initQ4() { buildQ4Chart1(); buildQ4Chart2(); q4Inited = true; }

// ─────────────── Q15: Chart 1 (National headcount over time) ─────────────────
function rebuildQ15Chart1() { trackInteraction(); buildQ15Chart1(); }
function buildQ15Chart1() {
  destroyChart('chart8');

  const allNat = D_NAT_Q15.filter(r => r.year >= 2022);
  const allYears = allNat.map(r => r.year).sort((a,b)=>a-b);
  const years = allYears;

  const natRows = allNat.filter(r => years.includes(r.year));
  const natVals = natRows.map(r => r.Total || 0);

  // Stanford detail (FY22-24) has Researchers/Technicians/Support Staff
  const Q15_CATS   = ['Researchers','Technicians','Support Staff'];
  const Q15_COLORS = ['#1565C0','#2E8B57','#8B6914'];
  const Q15_LABELS = ['Researchers','R&D Technicians','R&D Support Staff'];
  const detailMap  = {};
  (D_STA_Q15D || []).forEach(r => { detailMap[r.year] = r; });

  // Check if we have breakdown data for any displayed year
  const hasBreakdown = years.some(y => detailMap[y]);

  // Build stacked datasets using national totals split by Stanford proportions where available
  // For years with detail: use national total distributed by Stanford proportions
  // For years without: show total in first category
  const datasets = Q15_CATS.map((cat, ci) => ({
    label: Q15_LABELS[ci],
    data: years.map((y, yi) => {
      const detail = detailMap[y];
      const natTotal = natVals[yi];
      if (detail && detail.Total > 0) {
        const pct = (detail[cat] || 0) / detail.Total;
        return Math.round(natTotal * pct);
      }
      return ci === 0 ? natTotal : 0;
    }),
    backgroundColor: Q15_COLORS[ci], stack: 'main',
  }));

  const rightLabels = Q15_LABELS.map((lbl, ci) => ({ label: lbl, color: Q15_COLORS[ci] }));

  // Top labels: total headcount + YoY change
  const fmtHC = v => v >= 1000 ? Math.round(v).toLocaleString() : String(Math.round(v));
  const topLabels = years.map((y, i) => {
    const val = natVals[i];
    const prevV = i > 0 ? natVals[i - 1] : null;
    let changeDollar = null, changePct = null, up = true;
    if (prevV && prevV > 0) {
      const delta = val - prevV;
      const pct = (delta / Math.abs(prevV)) * 100;
      up = delta >= 0;
      const tri = up ? '▲' : '▼';
      changeDollar = tri + fmtHC(Math.abs(delta));
      changePct = tri + Math.abs(pct).toFixed(1) + '%';
    }
    return { total: fmtHC(val), changeDollar, changePct, up };
  });

  const ctx  = document.getElementById('chart8').getContext('2d');
  const cfg8 = {
    type: 'bar',
    data: { labels: years.map(fy), datasets },
    options: {
      responsive: true, maintainAspectRatio: false,
      animation: false,
      layout: { padding: { top: 52, right: 160 } },
      scales: {
        x: { stacked: true, grid: { display: false } },
        y: { stacked: true, ticks: { callback: v => v.toLocaleString() }, grid: { color: '#f0eeec' } }
      },
      plugins: {
        legend: { display: false },
        topBarLabels: { labels: topLabels },
        datalabels: {
          display: ctx2 => {
            const bar = ctx2.chart.getDatasetMeta(ctx2.datasetIndex).data[ctx2.dataIndex];
            return bar ? Math.abs(bar.base - bar.y) > 28 : false;
          },
          formatter: (val, ctx2) => {
            if (!val) return '';
            return fmtHC(val);
          },
          color: '#fff', font: { size: 13, weight: 'bold' },
          anchor: 'center', align: 'center', textAlign: 'center',
        }
      }
    },
    plugins: [ChartDataLabels, topBarPlugin, fieldRightLabelPlugin]
  };
  cfg8._fieldRightLabels = rightLabels;
  charts.chart8 = new Chart(ctx, cfg8);
}

// ─────────────── Q15: Chart 2 (Stanford vs National headcount breakdown) ─────
function rebuildQ15Chart2() { trackInteraction(); buildQ15Chart2(); }
function buildQ15Chart2() {
  destroyChart('chart8b');
  const year = parseInt(document.getElementById('c8b-fy').value);

  const Q15_CATS   = ['Researchers','Technicians','Support Staff'];
  const Q15_COLORS = ['#1565C0','#2E8B57','#8B6914'];
  const Q15_LABELS = ['Researchers','R&D Technicians','R&D Support Staff'];

  // Stanford detail
  const staDetail = (D_STA_Q15D || []).find(r => r.year === year);
  const staTotal  = staDetail ? staDetail.Total : 0;
  const staVals   = staDetail ? Q15_CATS.map(c => staDetail[c] || 0) : [0,0,0];

  // National data
  const natRow   = D_NAT_Q15.find(r => r.year === year);
  const natTotal = natRow ? natRow.Total : 0;
  // Apply Stanford proportions to national total for breakdown
  const natVals = staDetail && staDetail.Total > 0
    ? Q15_CATS.map(c => Math.round(natTotal * (staDetail[c] / staDetail.Total)))
    : [natTotal, 0, 0];

  const labels    = ['Stanford', 'National Avg'];
  const barTotals = [staTotal, natTotal];

  const datasets = Q15_CATS.map((cat, ci) => ({
    label: Q15_LABELS[ci],
    data: [staVals[ci], natVals[ci]],
    backgroundColor: Q15_COLORS[ci],
    stack: 'main',
  }));

  const ctx = document.getElementById('chart8b').getContext('2d');
  const cfg = {
    type: 'bar',
    data: { labels, datasets },
    options: {
      indexAxis: 'y',
      responsive: true, maintainAspectRatio: false,
      layout: { padding: { right: 80 } },
      scales: {
        x: { stacked: true, ticks: { callback: v => v.toLocaleString() }, grid: { color: '#f0eeec' } },
        y: { stacked: true, grid: { display: false } }
      },
      plugins: {
        legend: { display: true, position: 'bottom', labels: { font: { size: 13 } } },
        datalabels: {
          display: ctx2 => {
            const bar = ctx2.chart.getDatasetMeta(ctx2.datasetIndex).data[ctx2.dataIndex];
            if (!bar) return false;
            return Math.abs(bar.x - bar.base) > 40;
          },
          formatter: (val, ctx2) => {
            if (!val) return '';
            const total = barTotals[ctx2.dataIndex] || 1;
            const pct = Math.round(val / total * 100);
            return pct + '%';
          },
          color: '#fff', font: { size: 13, weight: 'bold' },
          anchor: 'center', align: 'center',
        }
      }
    },
    plugins: [ChartDataLabels, {
      id: 'headcountTotal',
      afterDraw(chart) {
        const { ctx: c, chartArea } = chart;
        chart.data.labels.forEach((lbl, i) => {
          const meta = chart.getDatasetMeta(chart.data.datasets.length - 1);
          const bar  = meta.data[i];
          if (!bar) return;
          const total = barTotals[i];
          c.save();
          c.font = 'bold 13px -apple-system,sans-serif';
          c.fillStyle = '#333';
          c.textAlign = 'left';
          c.textBaseline = 'middle';
          c.fillText(total.toLocaleString(), bar.x + 8, bar.y);
          c.restore();
        });
      }
    }]
  };
  charts.chart8b = new Chart(ctx, cfg);
}

// ─────────────── Q15: Chart 2 (Stanford and Peers headcount peer bar) ────────
function rebuildQ15PeerChart() { trackInteraction(); buildQ15PeerChart(); }
function buildQ15PeerChart() {
  destroyChart('chart8c');
  const year = parseInt(document.getElementById('c8c-fy').value);
  const fmtHC = v => v >= 1000 ? Math.round(v).toLocaleString() : String(Math.round(v));
  const allInsts = ['Stanford', ...D2.peers_list];
  const pts = allInsts.map(inst => ({ inst, val: ((PEER_Q15[inst] || {})[String(year)] || {}).Total || 0 }))
    .sort((a, b) => b.val - a.val);
  const colors = pts.map(p => p.inst === 'Stanford' ? '#8C1515' : '#4B8BBE');
  const ctx = document.getElementById('chart8c').getContext('2d');
  const cfg = {
    type: 'bar',
    data: {
      labels: pts.map(p => p.inst),
      datasets: [{ data: pts.map(p => p.val), backgroundColor: colors, borderRadius: 3 }]
    },
    options: {
      responsive: true, maintainAspectRatio: false,
      layout: { padding: { top: 20 } },
      scales: {
        x: {
          grid: { display: false },
          ticks: {
            font: (ctx2) => {
              if (ctx2.index == null) return { size: 13, weight: 'normal' };
              const inst = pts[ctx2.index]?.inst;
              return { size: 13, weight: inst === 'Stanford' ? 'bold' : 'normal' };
            },
            color: (ctx2) => {
              if (ctx2.index == null) return '#555';
              return pts[ctx2.index]?.inst === 'Stanford' ? '#8C1515' : '#555';
            },
            maxRotation: 45, minRotation: 25
          }
        },
        y: { ticks: { callback: v => fmtHC(v) }, grid: { color: '#f0eeec' } }
      },
      plugins: {
        legend: { display: false },
        datalabels: {
          anchor: 'end', align: 'top', clamp: true,
          formatter: v => fmtHC(v),
          color: (ctx2) => (ctx2.dataIndex != null && pts[ctx2.dataIndex]?.inst === 'Stanford') ? '#8C1515' : '#2E2D29',
          font: (ctx2) => ({ size: 13, weight: (ctx2.dataIndex != null && pts[ctx2.dataIndex]?.inst === 'Stanford') ? 'bold' : 'normal' })
        }
      }
    },
    plugins: [ChartDataLabels]
  };
  charts.chart8c = new Chart(ctx, cfg);
}

let q15Inited = false;
function initQ15() { buildQ15Chart1(); buildQ15PeerChart(); q15Inited = true; }

// ─────────────── Navigation ───────────────────────────────────────────────────
function showView(view) {
  document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
  document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
  document.getElementById('view-' + view).classList.add('active');
  document.querySelector('[data-view="' + view + '"]').classList.add('active');

  if      (view === 'intro')  { /* static content, no init needed */ }
  else if (view === 'q1')    { if (!q1Inited)  initQ1();    else { buildQ1KPIs(); buildChart1(); onC2SponsorChange(); } }
  else if (view === 'q9q11') { if (!q9Inited)  initQ9Q11(); else { buildQ9Chart1(); buildQ9Chart2(); } }
  else if (view === 'q12')   { if (!q12Inited) initQ12();   else { buildQ12Chart1(); buildQ12Chart3(); } }
  else if (view === 'q2')    { if (!q2Inited)  initQ2();    else { buildQ2Chart1(); buildQ2Chart2(); } }
  else if (view === 'q4')    { if (!q4Inited)  initQ4();    else { buildQ4Chart1(); buildQ4Chart2(); } }
  else if (view === 'q15')   { if (!q15Inited) initQ15();   else { buildQ15Chart1(); buildQ15PeerChart(); } }
  trackInteraction();
}

document.querySelectorAll('.nav-item').forEach(item => {
  item.addEventListener('click', () => showView(item.dataset.view));
});

// ─────────────── Entry Point ─────────────────────────────────────────────────
// Introduction page is static; Q1+ lazy-init on first nav click
"""

# ── ASSEMBLE ──────────────────────────────────────────────────────────────────
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NSF HERD Dashboard — Stanford ORA</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
<style>{CSS}</style>
</head>
<body>
<div id="field-tooltip" class="field-tooltip"></div>
{SIDEBAR}
<main id="main">
{INTRO_VIEW}
{Q1_VIEW}
{Q9_VIEW}
{Q12_VIEW}
{Q2_VIEW}
{Q4_VIEW}
{Q15_VIEW}
</main>
<script>
const D  = {D_js};
const D2 = {D2_js};
const PEER = {PEER_js};
const NAT_Q11 = {NAT_Q11_js};
const FED_AG = {FED_AG_js};
const SUB_RANKS = {SUB_RANKS_js};
{JS}
</script>
</body>
</html>"""

out = "/tmp/nsf_herd_dashboard_v5.html"
with open(out, "w") as f:
    f.write(html)
sz = os.path.getsize(out)
print(f"Written: {out}  ({sz // 1024} KB)")
