"<!DOCTYPE html>\n<html lang=\"en\" class=\"dark\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>BSL-to-CLO Quantitative Credit Platform</title>\n  <!-- Tailwind CSS -->\n  <script src=\"https://cdn.tailwindcss.com\"></script>\n  <!-- Chart.js -->\n  <script src=\"https://cdn.jsdelivr.net/npm/chart.js\"></script>\n  <style>\n    @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;1,6..72,400&display=swap');\n    \n    :root {\n      --font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;\n      --font-serif: 'Newsreader', Georgia, serif;\n    }\n    .font-mono-data { font-family: var(--font-mono); font-variant-numeric: tabular-nums; }\n    .font-legal { font-family: var(--font-serif); }\n    \n    .tab-btn {\n      position: relative;\n      transition: color 0.15s ease;\n    }\n    .tab-btn.tab-active {\n      color: #fafafa;\n      font-weight: 600;\n    }\n    .tab-btn.tab-active::after {\n      content: '';\n      position: absolute;\n      bottom: -1px;\n      left: 0;\n      right: 0;\n      height: 2px;\n      background-color: #fafafa;\n    }\n    \n    /* Institutional nocturnal ledger grid motif */\n    .bg-ledger-grid-dark {\n      background-color: #09090b;\n      background-image: \n        linear-gradient(to right, rgba(255, 255, 255, 0.025) 1px, transparent 1px),\n        linear-gradient(to bottom, rgba(255, 255, 255, 0.025) 1px, transparent 1px);\n      background-size: 32px 32px;\n    }\n  </style>\n</head>\n<body class=\"bg-ledger-grid-dark text-zinc-100 font-sans antialiased min-h-screen flex flex-col selection:bg-zinc-100 selection:text-zinc-950\">\n\n  <!-- Masthead -->\n  <header class=\"bg-[#0c0c0e] border-b border-zinc-800 sticky top-0 z-50\">\n    <div class=\"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-3 pb-2.5\">\n      <div class=\"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-2\">\n        <div>\n          <div class=\"flex items-center gap-2\">\n            <span class=\"text-[10px] font-mono uppercase tracking-widest text-zinc-400 bg-zinc-900 border border-zinc-800 px-1.5 py-0.5\">SEC EDGAR 17 CFR § 229.601</span>\n            <span class=\"text-[10px] font-mono text-zinc-600\">•</span>\n            <span class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">FRED SOFR</span>\n          </div>\n          <h1 class=\"text-base sm:text-lg font-semibold tracking-tight text-zinc-50 mt-1\">\n            BSL-to-CLO Quantitative Credit Platform\n          </h1>\n          <p class=\"text-xs text-zinc-400\">\n            Decoupled 3-Layer Structured Credit Engine: Collateral Audit Provenance, HiGHS LP Pool Optimizer, & 40-Quarter Waterfall\n          </p>\n        </div>\n        <div class=\"flex items-center gap-2 text-xs font-mono\">\n          <a href=\"https://github.com/sagarkolte/bsl_pipeline\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"text-zinc-400 hover:text-zinc-100 border border-zinc-800 hover:border-zinc-600 px-2.5 py-1 bg-zinc-900 transition flex items-center gap-1.5\">\n            <svg class=\"w-3.5 h-3.5\" fill=\"currentColor\" viewBox=\"0 0 24 24\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.53 1.032 1.53 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z\"/></svg>\n            <span>SOURCE REPO</span>\n          </a>\n        </div>\n      </div>\n    </div>\n\n    <!-- Tier Navigation Tabs -->\n    <div class=\"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex space-x-6 overflow-x-auto whitespace-nowrap border-t border-zinc-800 text-xs font-mono tracking-wider uppercase\">\n      <button onclick=\"switchTab('tab1')\" id=\"nav-tab1\" class=\"tab-btn py-2.5 tab-active text-zinc-100 shrink-0\">\n        01 / Tab 1: Deal Term Inspector\n      </button>\n      <button onclick=\"switchTab('tab2')\" id=\"nav-tab2\" class=\"tab-btn py-2.5 text-zinc-400 hover:text-zinc-100 shrink-0\">\n        02 / Tab 2: Seed Portfolio\n        <span id=\"nav-seed-count\" class=\"hidden ml-1 px-1.5 py-0.2 bg-emerald-950/80 border border-emerald-500/40 text-emerald-300 text-[10px]\">0</span>\n      </button>\n      <button onclick=\"switchTab('tab3')\" id=\"nav-tab3\" class=\"tab-btn py-2.5 text-zinc-400 hover:text-zinc-100 shrink-0\">\n        03 / Tab 3: Mandate Pool Optimizer\n      </button>\n      <button onclick=\"switchTab('tab4')\" id=\"nav-tab4\" class=\"tab-btn py-2.5 text-zinc-400 hover:text-zinc-100 shrink-0\">\n        04 / Tab 4: CLO Priority of Payments\n      </button>\n    </div>\n  </header>\n\n  <!-- Main Viewport Container -->\n  <main class=\"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 flex-1 w-full space-y-6\">\n\n    <!-- ========================================================================= -->\n    <!-- TAB 1: DEAL TERM INSPECTOR (LAYER 1) -->\n    <!-- ========================================================================= -->\n    <div id=\"content-tab1\" class=\"space-y-6\">\n      <!-- Layer 1 Header & Mode Switcher -->\n      <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n        <div class=\"flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4\">\n          <div>\n            <div class=\"text-[10px] font-mono uppercase tracking-widest text-zinc-400\">Layer 1: Collateral Ingestion &amp; Verbatim Audit Provenance</div>\n            <h2 class=\"text-sm sm:text-base font-semibold text-zinc-100 mt-0.5\">Exhibit 10 Facility Selection &amp; Amendment Comparison</h2>\n          </div>\n          <div class=\"inline-flex border border-zinc-700 bg-[#18181b] p-0.5 text-[11px] font-mono self-start sm:self-auto\">\n            <button id=\"t1-mode-single-btn\" onclick=\"setTab1Mode('single')\" class=\"px-3 py-1.5 bg-zinc-100 text-zinc-950 font-semibold transition\">Single Facility</button>\n            <button id=\"t1-mode-compare-btn\" onclick=\"setTab1Mode('compare')\" class=\"px-3 py-1.5 text-zinc-300 hover:text-white transition\">Compare Tranches / Amendments</button>\n          </div>\n        </div>\n        \n        <div id=\"t1-single-controls\" class=\"grid grid-cols-1 lg:grid-cols-12 gap-3 items-end\">\n          <div class=\"lg:col-span-8\">\n            <label for=\"t1-loan-search\" class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Credit Agreement Facility (Type to Filter):</label>\n            <div id=\"t1-loan-combobox\" class=\"relative\">\n              <div class=\"relative flex items-center\">\n                <input\n                  type=\"text\"\n                  id=\"t1-loan-search\"\n                  autocomplete=\"off\"\n                  spellcheck=\"false\"\n                  placeholder=\"Type borrower, rating, spread, or facility ID...\"\n                  onfocus=\"this.select(); openTab1LoanDropdown(true)\"\n                  oninput=\"handleTab1SearchInput()\"\n                  onkeydown=\"handleTab1SearchKeydown(event)\"\n                  class=\"w-full bg-[#18181b] border border-zinc-700 pl-3 pr-28 py-2 text-xs font-mono text-zinc-100 placeholder:text-zinc-500 focus:border-zinc-400 focus:outline-none\"\n                >\n                <div class=\"absolute right-1.5 flex items-center gap-1\">\n                  <span id=\"t1-loan-match-count\" class=\"text-[10px] font-mono text-zinc-500 px-1\"></span>\n                  <button type=\"button\" id=\"t1-loan-clear-btn\" onclick=\"clearTab1LoanSearch()\" class=\"hidden px-1.5 py-0.5 text-[11px] font-mono text-zinc-400 hover:text-white\" title=\"Clear search\">&times;</button>\n                  <button type=\"button\" id=\"t1-loan-dropdown-btn\" onclick=\"toggleTab1LoanDropdown()\" class=\"px-1.5 py-0.5 text-[11px] font-mono text-zinc-400 hover:text-white border-l border-zinc-700\" title=\"Browse facilities\">&#9662;</button>\n                </div>\n              </div>\n              <div id=\"t1-loan-dropdown\" class=\"hidden absolute left-0 right-0 top-full mt-1 z-40 max-h-80 overflow-y-auto bg-[#121215] border border-zinc-600 shadow-2xl divide-y divide-zinc-800/70\"></div>\n            </div>\n            <select id=\"t1-loan-select\" class=\"hidden\" onchange=\"loadSelectedLoan()\">\n              <option value=\"\">Loading facilities...</option>\n            </select>\n          </div>\n          <div class=\"lg:col-span-4 flex flex-wrap items-center justify-between lg:justify-end gap-2 text-[11px] font-mono text-zinc-400 py-1\">\n            <button type=\"button\" id=\"t1-add-seed-btn\" onclick=\"addCurrentLoanToSeed(true)\" class=\"shrink-0 px-2.5 py-1.5 border border-emerald-500/40 bg-emerald-950/40 hover:bg-emerald-900/50 text-emerald-300 text-[10px] uppercase tracking-wider font-semibold transition\">\n              + Add to Seed (Tab 2)\n            </button>\n            <a href=\"#t1-cf-section\" class=\"shrink-0 px-2.5 py-1.5 border border-zinc-700 bg-[#18181b] hover:bg-zinc-800 text-zinc-200 text-[10px] uppercase tracking-wider transition\">Jump to Cash Flows &darr;</a>\n          </div>\n        </div>\n      </section>\n\n      <div id=\"t1-single-view\" class=\"space-y-6\">\n      <!-- Invariant 6-Cell Metric Strip -->\n      <section class=\"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-px bg-zinc-800 border border-zinc-800 p-px\">\n        <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Moody's Rating</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"m-moodys\">—</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"m-warf\">—</div>\n        </div>\n        <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">S&amp;P / Fitch</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"m-sp\">—</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\"><span id=\"m-fitch\">Fitch: NR</span> · Recov: <span id=\"m-rec\">—</span></div>\n        </div>\n        <div id=\"card-spread\" class=\"bg-[#121215] p-3.5 flex flex-col justify-between transition\" onclick=\"openSecViewerForTerm('Spread Over Index')\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Spread Over Index</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"m-spread\">—</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Index: SOFR <span id=\"m-spread-cite\" class=\"text-zinc-400\"></span></div>\n        </div>\n        <div id=\"card-floor\" class=\"bg-[#121215] p-3.5 flex flex-col justify-between transition\" onclick=\"openSecViewerForTerm('Rate Floor')\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Rate Floor</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"m-floor\">—</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Basis: ACT/360 <span id=\"m-floor-cite\" class=\"text-zinc-400\"></span></div>\n        </div>\n        <div id=\"card-maturity\" class=\"bg-[#121215] p-3.5 flex flex-col justify-between transition\" onclick=\"openSecViewerForTerm('Maturity Date')\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Maturity Date</div>\n          <div class=\"flex flex-wrap items-baseline gap-x-2 mt-1\">\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100\" id=\"m-maturity\">—</div>\n            <div class=\"text-[10px] font-mono text-emerald-300/90\" id=\"m-rem-term\"></div>\n          </div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\"><span id=\"m-eff\">—</span> <span id=\"m-maturity-cite\" class=\"text-zinc-400\"></span></div>\n          <div class=\"flex flex-wrap gap-1 mt-1 hidden\" id=\"m-springing-badges\"></div>\n        </div>\n        <div id=\"card-ecf\" class=\"bg-[#121215] p-3.5 flex flex-col justify-between transition\" onclick=\"openSecViewerForTerm(findCitationIndexForTerm('Covenant Structure') >= 0 ? 'Covenant Structure' : 'ECF Sweep')\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Covenant Structure</div>\n          <div class=\"flex flex-wrap items-baseline gap-x-1.5 mt-1\">\n            <span class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100\" id=\"m-cov\">—</span>\n            <button type=\"button\" id=\"m-cov-cite\" onclick=\"event.stopPropagation(); openSecViewerForTerm('Covenant Structure')\" class=\"hidden text-[10px] font-mono text-zinc-400 hover:text-amber-200 transition\"></button>\n          </div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" onclick=\"if (findCitationIndexForTerm('ECF Sweep') >= 0) { event.stopPropagation(); openSecViewerForTerm('ECF Sweep'); }\">ECF Sweep: <span id=\"m-ecf\">—</span> <span id=\"m-ecf-cite\" class=\"text-zinc-400\"></span></div>\n        </div>\n      </section>\n\n      <!-- Side-by-Side: Mechanical Terms vs Audit Citations -->\n      <section class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n        <!-- Mechanical Terms Table -->\n        <div class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5 flex flex-col\">\n          <div class=\"flex items-center justify-between pb-3 border-b border-zinc-800 mb-3\">\n            <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">Structured Financial Terms</h3>\n            <span class=\"text-xs font-mono text-zinc-400\" id=\"t1-par-header\">Par: —</span>\n          </div>\n          <div class=\"overflow-x-auto flex-1\">\n            <table class=\"w-full text-xs text-left border-collapse\">\n              <tbody id=\"t1-terms-body\" class=\"divide-y divide-zinc-800 font-mono-data\">\n                <tr><td class=\"py-3 text-zinc-500\">Loading facility details...</td></tr>\n              </tbody>\n            </table>\n          </div>\n        </div>\n\n        <!-- Provenance Citations -->\n        <div class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5 flex flex-col\">\n          <div class=\"flex items-center justify-between pb-3 border-b border-zinc-800 mb-3\">\n            <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">SEC EDGAR Exhibit 10 Legal Provenance</h3>\n            <span class=\"text-xs font-mono text-zinc-400\" id=\"t1-cite-count\">0 quotes</span>\n          </div>\n          <div class=\"space-y-3 overflow-y-auto max-h-[380px] pr-1\" id=\"t1-citations-list\">\n            <div class=\"text-xs font-mono text-zinc-500 py-4\">No citations loaded.</div>\n          </div>\n        </div>\n      </section>\n\n      <!-- Cashflow Projection (Co-Located Docked Controls + Live Chart & Deltas) -->\n      <section id=\"t1-cf-section\" class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n        <div class=\"grid grid-cols-1 lg:grid-cols-12 gap-5 items-start\">\n          <!-- Left Docked Control Panel (Sticky on Desktop) -->\n          <aside class=\"lg:col-span-4 xl:col-span-3 lg:sticky lg:top-4 bg-[#0f0f12] border border-zinc-800 p-3.5 space-y-3 min-w-0\">\n            <div class=\"flex items-center justify-between gap-2 pb-2 border-b border-zinc-800\">\n              <span class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-200 font-semibold\">Scenario Controls</span>\n              <span id=\"t1-stress-pill\" class=\"hidden inline-flex items-center gap-1 px-1.5 py-0.5 border border-amber-500/40 bg-amber-950/50 text-amber-300 text-[10px] font-mono\"></span>\n            </div>\n\n            <!-- Term SOFR -->\n            <div class=\"space-y-1\">\n              <div class=\"flex items-center justify-between gap-2\">\n                <label for=\"t1-sofr\" class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Term SOFR (%)</label>\n                <input type=\"number\" id=\"t1-sofr\" value=\"4.5\" step=\"0.25\" min=\"0\" max=\"15\" oninput=\"handleTab1NumericInput('sofr')\" class=\"w-20 bg-[#18181b] border border-zinc-700 px-2 py-1 text-right text-xs font-mono-data text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n              </div>\n              <input type=\"range\" id=\"t1-sofr-slider\" min=\"0\" max=\"10\" step=\"0.25\" value=\"4.5\" oninput=\"handleTab1SliderInput('sofr')\" aria-label=\"Term SOFR slider\" class=\"w-full h-1.5 accent-zinc-100 bg-zinc-800 rounded cursor-pointer\">\n            </div>\n\n            <!-- CPR -->\n            <div class=\"space-y-1\">\n              <div class=\"flex items-center justify-between gap-2\">\n                <label for=\"t1-cpr\" class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">CPR Prepay (%/yr)</label>\n                <input type=\"number\" id=\"t1-cpr\" value=\"15.0\" step=\"1.0\" min=\"0\" max=\"100\" oninput=\"handleTab1NumericInput('cpr')\" class=\"w-20 bg-[#18181b] border border-zinc-700 px-2 py-1 text-right text-xs font-mono-data text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n              </div>\n              <input type=\"range\" id=\"t1-cpr-slider\" min=\"0\" max=\"60\" step=\"1.0\" value=\"15.0\" oninput=\"handleTab1SliderInput('cpr')\" aria-label=\"CPR prepayment rate slider\" class=\"w-full h-1.5 accent-zinc-100 bg-zinc-800 rounded cursor-pointer\">\n            </div>\n\n            <!-- CDR -->\n            <div class=\"space-y-1\">\n              <div class=\"flex items-center justify-between gap-2\">\n                <label for=\"t1-cdr\" class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">CDR Default (%/yr)</label>\n                <input type=\"number\" id=\"t1-cdr\" value=\"2.0\" step=\"0.5\" min=\"0\" max=\"50\" oninput=\"handleTab1NumericInput('cdr')\" class=\"w-20 bg-[#18181b] border border-zinc-700 px-2 py-1 text-right text-xs font-mono-data text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n              </div>\n              <input type=\"range\" id=\"t1-cdr-slider\" min=\"0\" max=\"25\" step=\"0.5\" value=\"2.0\" oninput=\"handleTab1SliderInput('cdr')\" aria-label=\"CDR default rate slider\" class=\"w-full h-1.5 accent-zinc-100 bg-zinc-800 rounded cursor-pointer\">\n            </div>\n\n            <!-- Valuation Horizon Toggle -->\n            <div class=\"pt-1\">\n              <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Valuation Window</div>\n              <div class=\"grid grid-cols-2 border border-zinc-700 bg-[#18181b] p-0.5 text-[10px] font-mono\">\n                <button type=\"button\" id=\"cf-mode-remaining-btn\" onclick=\"setTab1ValuationMode(false)\" class=\"px-2 py-1 bg-zinc-100 text-zinc-950 font-semibold transition\">From Today</button>\n                <button type=\"button\" id=\"cf-mode-origination-btn\" onclick=\"setTab1ValuationMode(true)\" class=\"px-2 py-1 text-zinc-300 hover:text-white transition\">From Origination</button>\n              </div>\n            </div>\n\n            <!-- Pin Baseline + Reset Actions -->\n            <div class=\"pt-1 space-y-1.5\">\n              <button type=\"button\" id=\"cf-pin-baseline-btn\" onclick=\"toggleTab1PinBaseline()\" class=\"w-full px-2.5 py-1.5 border border-zinc-700 bg-[#18181b] hover:bg-zinc-800 text-zinc-100 text-[10px] font-mono uppercase tracking-wider font-semibold transition\">\n                Pin Baseline\n              </button>\n              <div id=\"cf-pin-status\" class=\"hidden text-[10px] font-mono text-sky-300 leading-tight px-0.5\"></div>\n              <button type=\"button\" id=\"t1-reset-base-btn\" onclick=\"resetTab1ToBaseCase()\" class=\"w-full px-2.5 py-1 border border-zinc-700 bg-[#18181b] hover:bg-zinc-800 text-zinc-300 text-[10px] font-mono transition\">\n                Reset to Base Case (4.5% / 15% / 2%)\n              </button>\n            </div>\n\n            <div class=\"pt-2 border-t border-zinc-800/80 text-[10px] font-mono text-zinc-500 leading-snug\" title=\"SOFR, CPR, and CDR are uniform annualized scenario stress assumptions applied by you — not credit-specific model predictions. Contractual spread, floor, maturity, call schedule, and recovery rate come from the loan.\">\n              User Stress Assumptions (Annualized Constant Rates — uniform scenario inputs, not credit-derived)\n            </div>\n          </aside>\n\n          <!-- Right Outputs Column (KPI Strip + Chart) -->\n          <div class=\"lg:col-span-8 xl:col-span-9 min-w-0 flex flex-col\">\n            <div class=\"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-2 pb-3 border-b border-zinc-800 mb-3\">\n              <div>\n                <div class=\"flex flex-wrap items-center gap-2\">\n                  <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">Deterministic Loan Cash-Flow Projection</h3>\n                  <span id=\"cf-floor-badge\" class=\"hidden text-[10px] font-mono px-2 py-0.5 border\"></span>\n                </div>\n                <p class=\"text-xs text-zinc-400 mt-0.5\">Quarterly interest, scheduled amortization, prepayments (CPR), and default recovery dynamics.</p>\n              </div>\n              <button type=\"button\" onclick=\"recalculateCashflows()\" class=\"shrink-0 bg-zinc-100 hover:bg-white text-zinc-950 font-mono text-xs uppercase tracking-wider px-3.5 py-1.5 font-semibold transition\">\n                Recalculate\n              </button>\n            </div>\n\n            <div class=\"grid grid-cols-2 xl:grid-cols-4 gap-px bg-zinc-800 border border-zinc-800 p-px mb-3\">\n              <div class=\"bg-[#121215] p-3 min-w-0\">\n                <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Weighted Average Life</div>\n                <div class=\"flex flex-wrap items-baseline gap-x-2 gap-y-0.5 mt-1\">\n                  <span class=\"text-sm sm:text-base font-mono-data font-semibold text-zinc-100\" id=\"cf-wal\">— yrs</span>\n                  <span class=\"hidden text-[11px] font-mono-data font-semibold\" id=\"cf-wal-delta\"></span>\n                </div>\n                <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"cf-wal-meta\">—</div>\n              </div>\n              <div class=\"bg-[#121215] p-3 min-w-0\">\n                <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Total Interest Due</div>\n                <div class=\"flex flex-wrap items-baseline gap-x-2 gap-y-0.5 mt-1\">\n                  <span class=\"text-sm sm:text-base font-mono-data font-semibold text-zinc-100\" id=\"cf-int\">—</span>\n                  <span class=\"hidden text-[11px] font-mono-data font-semibold\" id=\"cf-int-delta\"></span>\n                </div>\n                <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"cf-int-meta\">—</div>\n              </div>\n              <div class=\"bg-[#121215] p-3 min-w-0\">\n                <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Total Principal Repaid</div>\n                <div class=\"flex flex-wrap items-baseline gap-x-2 gap-y-0.5 mt-1\">\n                  <span class=\"text-sm sm:text-base font-mono-data font-semibold text-zinc-100\" id=\"cf-prin\">—</span>\n                  <span class=\"hidden text-[11px] font-mono-data font-semibold\" id=\"cf-prin-delta\"></span>\n                </div>\n                <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"cf-prin-meta\">—</div>\n              </div>\n              <div class=\"bg-[#121215] p-3 min-w-0\">\n                <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Total Recoveries</div>\n                <div class=\"flex flex-wrap items-baseline gap-x-2 gap-y-0.5 mt-1\">\n                  <span class=\"text-sm sm:text-base font-mono-data font-semibold text-zinc-100\" id=\"cf-rec\">—</span>\n                  <span class=\"hidden text-[11px] font-mono-data font-semibold\" id=\"cf-rec-delta\"></span>\n                </div>\n                <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"cf-rec-meta\">Default recovery inflow</div>\n              </div>\n            </div>\n\n            <div class=\"h-64 sm:h-72 w-full min-w-0 relative\">\n              <canvas id=\"t1-chart\"></canvas>\n            </div>\n          </div>\n        </div>\n      </section>\n      </div>\n\n      <!-- Compare Tranches & Amendments View (Layer A) -->\n      <div id=\"t1-compare-view\" class=\"space-y-6 hidden\">\n        <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5 space-y-4\">\n          <div>\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-2\">Quick Select Multi-Tranche / Amended Borrowers</div>\n            <div id=\"cmp-group-pills\" class=\"flex flex-wrap gap-2 text-[11px] font-mono\">\n              <span class=\"text-zinc-500\">Loading multi-tranche issuers...</span>\n            </div>\n          </div>\n\n          <div class=\"grid grid-cols-1 md:grid-cols-11 gap-3 items-end\">\n            <div class=\"md:col-span-5\">\n              <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Baseline (Earlier Tranche / Filing):</label>\n              <select id=\"cmp-left-select\" onchange=\"runCompare()\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\"></select>\n            </div>\n            <div class=\"md:col-span-1 flex justify-center\">\n              <button onclick=\"swapCompareSides()\" class=\"w-full md:w-auto px-3 py-2 border border-zinc-700 bg-[#18181b] text-xs font-mono text-zinc-200 hover:bg-zinc-800\" title=\"Swap Left &amp; Right\">&harr;</button>\n            </div>\n            <div class=\"md:col-span-5\">\n              <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Comparison (Newer / Amended Tranche):</label>\n              <select id=\"cmp-right-select\" onchange=\"runCompare()\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\"></select>\n            </div>\n          </div>\n\n          <div id=\"cmp-events-bar\" class=\"hidden pt-2 border-t border-zinc-800/80\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1.5\">Same-Facility Historical Term Snapshots (Postgres Event Ledger)</div>\n            <div id=\"cmp-event-pills\" class=\"flex flex-wrap gap-2 text-[11px] font-mono\"></div>\n          </div>\n        </section>\n\n        <!-- Economic Delta KPI Strip & Collapsible Overlaid Cash-Flow Diff -->\n        <section id=\"cmp-econ-panel\" class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5 space-y-3\">\n          <div class=\"flex flex-col lg:flex-row lg:items-center justify-between gap-3 pb-3 border-b border-zinc-800\">\n            <div>\n              <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">Economic Delta (Facility B vs. Facility A)</h3>\n              <div class=\"text-[11px] font-mono text-zinc-400 mt-0.5\" id=\"cmp-econ-sublabel\">Projected cash-flow differences under matched SOFR, CPR &amp; CDR assumptions</div>\n            </div>\n            <div class=\"flex flex-wrap items-end gap-2\">\n              <div>\n                <label for=\"cmp-sofr\" class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">SOFR (%)</label>\n                <input type=\"number\" id=\"cmp-sofr\" value=\"4.5\" step=\"0.25\" min=\"0\" max=\"15\" oninput=\"handleCompareScenarioInput()\" class=\"w-20 bg-[#18181b] border border-zinc-700 px-2 py-1 text-right text-xs font-mono-data text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n              </div>\n              <div>\n                <label for=\"cmp-cpr\" class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">CPR (%/yr)</label>\n                <input type=\"number\" id=\"cmp-cpr\" value=\"15.0\" step=\"1.0\" min=\"0\" max=\"100\" oninput=\"handleCompareScenarioInput()\" class=\"w-20 bg-[#18181b] border border-zinc-700 px-2 py-1 text-right text-xs font-mono-data text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n              </div>\n              <div>\n                <label for=\"cmp-cdr\" class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">CDR (%/yr)</label>\n                <input type=\"number\" id=\"cmp-cdr\" value=\"2.0\" step=\"0.5\" min=\"0\" max=\"50\" oninput=\"handleCompareScenarioInput()\" class=\"w-20 bg-[#18181b] border border-zinc-700 px-2 py-1 text-right text-xs font-mono-data text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n              </div>\n              <div class=\"inline-flex border border-zinc-700 bg-[#18181b] p-0.5 text-[10px] font-mono\">\n                <button type=\"button\" id=\"cmp-mode-remaining-btn\" onclick=\"setCompareValuationMode(false)\" class=\"px-2 py-1 bg-zinc-100 text-zinc-950 font-semibold transition\">From Today</button>\n                <button type=\"button\" id=\"cmp-mode-origination-btn\" onclick=\"setCompareValuationMode(true)\" class=\"px-2 py-1 text-zinc-300 hover:text-white transition\">From Origination</button>\n              </div>\n              <button type=\"button\" id=\"cmp-reset-base-btn\" onclick=\"resetCompareToBaseCase()\" class=\"px-2.5 py-1 border border-zinc-700 bg-[#18181b] hover:bg-zinc-800 text-zinc-300 text-[10px] font-mono transition\" title=\"Reset shared assumptions to Base Case (4.5% / 15% / 2%)\">\n                Reset Base\n              </button>\n            </div>\n          </div>\n\n          <!-- 3-Metric Delta KPI Strip -->\n          <div class=\"grid grid-cols-1 sm:grid-cols-3 gap-px bg-zinc-800 border border-zinc-800 p-px\">\n            <div class=\"bg-[#121215] p-3 min-w-0\">\n              <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">&Delta; Weighted Avg Life (WAL)</div>\n              <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"cmp-delta-wal\">—</div>\n              <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5 truncate\" id=\"cmp-delta-wal-meta\">Facility B vs Facility A</div>\n            </div>\n            <div class=\"bg-[#121215] p-3 min-w-0\">\n              <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">&Delta; Total Interest</div>\n              <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"cmp-delta-int\">—</div>\n              <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5 truncate\" id=\"cmp-delta-int-meta\">Interest differential (B − A)</div>\n            </div>\n            <div class=\"bg-[#121215] p-3 min-w-0\">\n              <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">&Delta; Total Cash Collected</div>\n              <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"cmp-delta-cash\">—</div>\n              <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5 truncate\" id=\"cmp-delta-cash-meta\">Principal + Interest + Call Premiums</div>\n            </div>\n          </div>\n\n          <!-- Collapsible Compare Cash Flows Trigger + Mode Switch -->\n          <div class=\"pt-1 flex flex-wrap items-center justify-between gap-2\">\n            <div class=\"flex flex-wrap items-center gap-2\">\n              <button type=\"button\" id=\"cmp-cf-toggle-btn\" onclick=\"toggleCompareCashflowChart()\" class=\"px-3 py-1.5 border border-zinc-700 bg-[#18181b] hover:bg-zinc-800 hover:border-zinc-500 text-xs font-mono text-zinc-200 font-semibold transition\">\n                Compare Cash Flows &#9662;\n              </button>\n              <span class=\"text-[11px] font-mono text-zinc-500 hidden sm:inline\">Expand shared-axis cumulative curves or quarterly cash-flow delta</span>\n            </div>\n            <div id=\"cmp-cf-mode-group\" class=\"hidden inline-flex border border-zinc-700 bg-[#18181b] p-0.5 text-[10px] font-mono\">\n              <button type=\"button\" id=\"cmp-cf-mode-cum\" onclick=\"setCompareChartMode('cumulative')\" class=\"px-2.5 py-1 bg-zinc-100 text-zinc-950 font-semibold transition\">Cumulative Overlay</button>\n              <button type=\"button\" id=\"cmp-cf-mode-delta\" onclick=\"setCompareChartMode('delta')\" class=\"px-2.5 py-1 text-zinc-300 hover:text-white transition\">Quarterly Delta (B &minus; A)</button>\n            </div>\n          </div>\n\n          <!-- Collapsible Shared-Axis Chart Panel (Collapsed by Default) -->\n          <div id=\"cmp-cf-chart-wrap\" class=\"hidden pt-2 border-t border-zinc-800/80 space-y-2\">\n            <div class=\"h-64 sm:h-72 w-full min-w-0 relative\">\n              <canvas id=\"cmp-cf-chart\"></canvas>\n            </div>\n            <div id=\"cmp-cf-chart-caption\" class=\"text-[10px] font-mono text-zinc-500\">\n              Overlaid cumulative cash flows (Principal + Interest + Call Premiums + Recoveries) across mismatched maturities.\n            </div>\n          </div>\n        </section>\n\n        <!-- Comparison Delta Summary & Filter -->\n        <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n          <div class=\"flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-3 border-b border-zinc-800 mb-4\">\n            <div>\n              <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">Side-by-Side Structured Term Diff</h3>\n              <div class=\"flex flex-wrap gap-2 mt-2\" id=\"cmp-summary-badges\"></div>\n            </div>\n            <div class=\"inline-flex border border-zinc-700 bg-[#18181b] p-0.5 text-[11px] font-mono self-start\">\n              <button id=\"cmp-filter-changed\" onclick=\"setCompareFilter('changed')\" class=\"px-2.5 py-1 bg-zinc-200 text-zinc-950 font-semibold\">Changed Only</button>\n              <button id=\"cmp-filter-all\" onclick=\"setCompareFilter('all')\" class=\"px-2.5 py-1 text-zinc-300 hover:text-white\">All Fields</button>\n            </div>\n          </div>\n\n          <div class=\"overflow-x-auto\">\n            <table class=\"w-full text-xs text-left border-collapse\">\n              <thead>\n                <tr class=\"border-b border-zinc-800 text-zinc-400 font-mono text-[10px] uppercase tracking-wider bg-zinc-900/80\">\n                  <th class=\"p-2.5 w-1/5\">Term / Dimension</th>\n                  <th class=\"p-2.5 w-[32%]\" id=\"cmp-th-left\">Baseline</th>\n                  <th class=\"p-2.5 w-[32%]\" id=\"cmp-th-right\">Comparison</th>\n                  <th class=\"p-2.5 text-right w-[16%]\">Delta</th>\n                </tr>\n              </thead>\n              <tbody id=\"cmp-diff-tbody\" class=\"divide-y divide-zinc-800/70 font-mono-data\">\n                <tr><td colspan=\"4\" class=\"p-4 text-zinc-500 font-mono\">Select two tranches or facilities above to compare.</td></tr>\n              </tbody>\n            </table>\n          </div>\n        </section>\n      </div>\n    </div>\n\n    <!-- ========================================================================= -->\n    <!-- TAB 2: SEED PORTFOLIO & CLO RAMP-UP (LAYER 2A) -->\n    <!-- ========================================================================= -->\n    <div id=\"content-tab2\" class=\"space-y-6 hidden\">\n      <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n        <div class=\"flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4\">\n          <div>\n            <div class=\"text-[10px] font-mono uppercase tracking-widest text-zinc-400\">Layer 2A: Warehouse Anchor Loans &amp; CLO Ramp-Up Construction</div>\n            <h2 class=\"text-sm sm:text-base font-semibold text-zinc-100 mt-0.5\">Seed Portfolio Builder</h2>\n          </div>\n          <div class=\"flex flex-wrap items-center gap-2 text-[11px] font-mono\">\n            <button type=\"button\" id=\"seed-add-current-btn\" onclick=\"addCurrentLoanToSeed(false)\" class=\"px-3 py-1.5 border border-emerald-500/40 bg-emerald-950/40 hover:bg-emerald-900/50 text-emerald-300 font-semibold transition\">\n              + Add Current Tab 1 Loan\n            </button>\n            <button type=\"button\" onclick=\"loadSampleSeedStarter()\" class=\"px-3 py-1.5 border border-zinc-700 bg-[#18181b] hover:bg-zinc-800 text-zinc-200 transition\">\n              Load 4-Loan Starter\n            </button>\n            <button type=\"button\" onclick=\"clearSeedPortfolio()\" class=\"px-3 py-1.5 border border-zinc-700 bg-[#18181b] hover:border-rose-500/50 hover:text-rose-300 text-zinc-400 transition\">\n              Clear All\n            </button>\n          </div>\n        </div>\n\n        <p class=\"text-xs font-mono text-zinc-400 mb-4 leading-relaxed\">\n          Select the core facilities you want to anchor in the CLO warehouse. Choose <span class=\"text-emerald-300 font-semibold\">Exact Lock</span> to hold the exact dollar par specified, or <span class=\"text-sky-300 font-semibold\">Min Floor</span> to guarantee at least that dollar commitment while letting Tab 3&apos;s LP optimizer add capacity up to obligor/mandate caps.\n        </p>\n\n        <!-- Search & Add Bar -->\n        <div class=\"grid grid-cols-1 lg:grid-cols-12 gap-3 items-end\">\n          <div class=\"lg:col-span-6\">\n            <label for=\"seed-loan-search\" class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Add Facility to Seed Pool (Type to Filter):</label>\n            <div id=\"seed-loan-combobox\" class=\"relative\">\n              <div class=\"relative flex items-center\">\n                <input\n                  type=\"text\"\n                  id=\"seed-loan-search\"\n                  autocomplete=\"off\"\n                  spellcheck=\"false\"\n                  placeholder=\"Type borrower, Moody's/S&P rating, industry, or spread...\"\n                  onfocus=\"openSeedLoanDropdown(true)\"\n                  oninput=\"handleSeedSearchInput()\"\n                  onkeydown=\"handleSeedSearchKeydown(event)\"\n                  class=\"w-full bg-[#18181b] border border-zinc-700 pl-3 pr-24 py-2 text-xs font-mono text-zinc-100 placeholder:text-zinc-500 focus:border-zinc-400 focus:outline-none\"\n                >\n                <div class=\"absolute right-1.5 flex items-center gap-1\">\n                  <span id=\"seed-loan-match-count\" class=\"text-[10px] font-mono text-zinc-500 px-1\"></span>\n                  <button type=\"button\" id=\"seed-loan-clear-btn\" onclick=\"clearSeedLoanSearch()\" class=\"hidden px-1.5 py-0.5 text-[11px] font-mono text-zinc-400 hover:text-white\" title=\"Clear search\">&times;</button>\n                  <button type=\"button\" id=\"seed-loan-dropdown-btn\" onclick=\"toggleSeedLoanDropdown()\" class=\"px-1.5 py-0.5 text-[11px] font-mono text-zinc-400 hover:text-white border-l border-zinc-700\" title=\"Browse facilities\">&#9662;</button>\n                </div>\n              </div>\n              <div id=\"seed-loan-dropdown\" class=\"hidden absolute left-0 right-0 top-full mt-1 z-40 max-h-80 overflow-y-auto bg-[#121215] border border-zinc-600 shadow-2xl divide-y divide-zinc-800/70\"></div>\n            </div>\n          </div>\n          <div class=\"lg:col-span-2\">\n            <label for=\"seed-default-par\" class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Default Par ($):</label>\n            <input type=\"number\" id=\"seed-default-par\" value=\"20000000\" step=\"1000000\" min=\"1000000\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div class=\"lg:col-span-2\">\n            <label for=\"seed-default-mode\" class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Default Lock Mode:</label>\n            <select id=\"seed-default-mode\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n              <option value=\"exact\">Exact Lock</option>\n              <option value=\"min\">Min Floor (&ge;)</option>\n            </select>\n          </div>\n          <div class=\"lg:col-span-2\">\n            <label for=\"seed-target-par-sync\" class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Target CLO Par ($):</label>\n            <input type=\"number\" id=\"seed-target-par-sync\" value=\"400000000\" step=\"10000000\" min=\"10000000\" oninput=\"syncSeedTargetPar(this.value)\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n        </div>\n      </section>\n\n      <!-- Live 6-Cell Seed Quality Strip -->\n      <section class=\"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-px bg-zinc-800 border border-zinc-800 p-px\">\n        <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Seeded Par / Target</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"seed-stat-par\">$0M (0.0%)</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"seed-stat-rem\">Remaining Ramp: $400.0M</div>\n        </div>\n        <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Seed WAS</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"seed-stat-was\">— bps</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"seed-stat-was-sub\">Mandate Min: 250 bps</div>\n        </div>\n        <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Seed WARF</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"seed-stat-warf\">—</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"seed-stat-warf-sub\">Mandate Max: 2800</div>\n        </div>\n        <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Seed Diversity</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"seed-stat-div\">0.0</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Moody&apos;s Industry Equiv.</div>\n        </div>\n        <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Seed WARR</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"seed-stat-warr\">—%</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"seed-stat-warr-sub\">Mandate Min: 44.0%</div>\n        </div>\n        <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n          <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Seed CCC / Cov-Lite</div>\n          <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"seed-stat-buckets\">0.0% / 0.0%</div>\n          <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\" id=\"seed-stat-buckets-sub\">% of Target Pool Par</div>\n        </div>\n      </section>\n\n      <!-- Live Seed Concentration / Par Diagnostics -->\n      <div id=\"seed-warnings-box\" class=\"hidden bg-amber-950/30 border border-amber-500/40 p-3.5 text-xs font-mono text-amber-200 space-y-1\"></div>\n\n      <!-- Seeded Portfolio Table -->\n      <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n        <div class=\"flex flex-col sm:flex-row sm:items-center justify-between gap-2 pb-3 border-b border-zinc-800 mb-3\">\n          <div>\n            <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">Anchored Seed Loans</h3>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Saved locally in your browser; enforced automatically when ramping in Tab 3 or modeling the waterfall in Tab 4.</div>\n          </div>\n          <span class=\"text-xs font-mono text-zinc-400\" id=\"seed-row-count\">0 facilities anchored</span>\n        </div>\n\n        <div class=\"overflow-x-auto\">\n          <table class=\"w-full text-xs text-left border-collapse\">\n            <thead>\n              <tr class=\"border-b border-zinc-800 text-zinc-400 font-mono text-[10px] uppercase tracking-wider bg-zinc-900/80\">\n                <th class=\"p-2.5\">Facility / Borrower</th>\n                <th class=\"p-2.5\">Rating / WARF</th>\n                <th class=\"p-2.5\">Spread / Recov</th>\n                <th class=\"p-2.5 text-right\">Available Par</th>\n                <th class=\"p-2.5 text-right\">Seed Par ($)</th>\n                <th class=\"p-2.5 text-right\">Pool Wt (%)</th>\n                <th class=\"p-2.5\">Lock Mode</th>\n                <th class=\"p-2.5 text-right\">Actions</th>\n              </tr>\n            </thead>\n            <tbody id=\"seed-tbody\" class=\"divide-y divide-zinc-800/60 font-mono-data\">\n              <tr>\n                <td colspan=\"8\" class=\"p-6 text-center text-xs font-mono text-zinc-500\">\n                  No seed loans selected yet. Search above, click &ldquo;+ Add Current Tab 1 Loan&rdquo;, or load the 4-Loan Starter to begin constructing your CLO ramp-up.\n                </td>\n              </tr>\n            </tbody>\n          </table>\n        </div>\n\n        <div class=\"mt-4 pt-4 border-t border-zinc-800 flex flex-col sm:flex-row sm:items-center justify-between gap-3\">\n          <div class=\"text-xs font-mono text-zinc-400\" id=\"seed-footer-summary\">\n            0 loans anchored · LP solver will optimize 100% of Target Pool Par from scratch.\n          </div>\n          <div class=\"flex flex-wrap items-center gap-2\">\n            <button type=\"button\" onclick=\"rampSeedToTab3()\" id=\"btn-ramp-tab3\" class=\"bg-zinc-100 hover:bg-white text-zinc-950 font-mono text-xs uppercase tracking-wider px-4 py-2.5 font-semibold transition\">\n              Ramp Up Remaining Pool in Tab 3 &rarr;\n            </button>\n            <button type=\"button\" onclick=\"rampSeedToTab4()\" class=\"border border-zinc-600 bg-[#18181b] hover:bg-zinc-800 text-zinc-100 font-mono text-xs uppercase tracking-wider px-4 py-2.5 font-semibold transition\">\n              Run CLO Waterfall in Tab 4 &rarr;\n            </button>\n          </div>\n        </div>\n      </section>\n    </div>\n\n    <!-- ========================================================================= -->\n    <!-- TAB 3: MANDATE POOL BUILDER & OPTIMIZER (LAYER 2) -->\n    <!-- ========================================================================= -->\n    <div id=\"content-tab3\" class=\"space-y-6 hidden\">\n      <!-- Mandate Parameters -->\n      <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n        <div class=\"mb-4\">\n          <div class=\"text-[10px] font-mono uppercase tracking-widest text-zinc-400\">Layer 2: Mandate Portfolio Engine & HiGHS LP Optimizer</div>\n          <h2 class=\"text-sm sm:text-base font-semibold text-zinc-100 mt-0.5\">Collateral Quality Matrix & Concentration Limits</h2>\n        </div>\n\n        <div class=\"grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4\">\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Target Pool Par ($):</label>\n            <input type=\"number\" id=\"opt-par\" value=\"400000000\" step=\"10000000\" oninput=\"onOptParChanged(this.value)\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Minimum WAS (bps):</label>\n            <input type=\"number\" id=\"opt-was\" value=\"250\" step=\"10\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Maximum WARF:</label>\n            <input type=\"number\" id=\"opt-warf\" value=\"2800\" step=\"50\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Minimum WARR (%):</label>\n            <input type=\"number\" id=\"opt-warr\" value=\"44.0\" step=\"0.5\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Max Single Obligor (%):</label>\n            <input type=\"number\" id=\"opt-obligor\" value=\"8.0\" step=\"0.5\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Max Single Industry (%):</label>\n            <input type=\"number\" id=\"opt-industry\" value=\"25.0\" step=\"1.0\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Max CCC Bucket (%):</label>\n            <input type=\"number\" id=\"opt-ccc\" value=\"7.5\" step=\"0.5\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Max Cov-Lite (%):</label>\n            <input type=\"number\" id=\"opt-cov\" value=\"75.0\" step=\"5.0\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n        </div>\n\n        <div class=\"mb-4 text-[11px] font-mono text-zinc-400 bg-zinc-900/70 border border-zinc-800 px-3 py-2\">\n          <span class=\"text-zinc-200 font-semibold uppercase tracking-wider\">Pricing Basis Assumption:</span>\n          Portfolio constraints (WAS, WARF, WARR, obligor/industry caps) and LP allocations are solved at <span class=\"text-zinc-200\">100% of par</span> (<code class=\"text-zinc-300\">Target Pool Par</code>), ignoring secondary market price / OID discounts (canonical loan records retain a modeled default <code class=\"text-zinc-300\">purchase_price_pct</code> of 99.5% when unquoted).\n        </div>\n\n        <div id=\"opt-seed-banner\" class=\"hidden mb-4 bg-emerald-950/25 border border-emerald-500/40 px-3.5 py-2.5 flex flex-col sm:flex-row sm:items-center justify-between gap-2 text-xs font-mono\">\n          <div class=\"flex items-center gap-2 text-emerald-200\">\n            <input type=\"checkbox\" id=\"opt-use-seed-cb\" checked class=\"accent-emerald-400\">\n            <label for=\"opt-use-seed-cb\" class=\"cursor-pointer\">\n              <span class=\"font-semibold uppercase tracking-wider text-emerald-300\">Seed Anchors Active:</span>\n              <span id=\"opt-seed-summary\">0 loans ($0M)</span>\n            </label>\n          </div>\n          <button type=\"button\" onclick=\"switchTab('tab2')\" class=\"self-start sm:self-auto px-2.5 py-1 border border-emerald-500/40 text-emerald-300 hover:bg-emerald-900/40 text-[10px] uppercase tracking-wider transition\">\n            Edit Seed Portfolio (Tab 2)\n          </button>\n        </div>\n\n        <button onclick=\"runOptimizer()\" id=\"btn-run-opt\" class=\"bg-zinc-100 hover:bg-white text-zinc-950 font-mono text-xs uppercase tracking-wider px-5 py-2.5 font-semibold transition\">\n          <span>Solve Optimal Pool (SciPy HiGHS LP)</span>\n        </button>\n      </section>\n\n      <!-- Compliance Results Section -->\n      <div id=\"opt-results-section\" class=\"space-y-6 hidden\">\n        <!-- Invariant 6-Cell Metric Strip -->\n        <section class=\"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-px bg-zinc-800 border border-zinc-800 p-px\">\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Optimal WAS</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"res-was\">— bps</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Min: <span id=\"res-was-target\">—</span></div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Portfolio WARF</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"res-warf\">—</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Max: <span id=\"res-warf-limit\">—</span></div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Moody's Diversity</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"res-diversity\">—</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Target: &ge; 10.0</div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Recovery (WARR)</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"res-warr\">—%</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Min: <span id=\"res-warr-min\">—</span></div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">CCC Bucket</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"res-ccc\">—%</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Cap: <span id=\"res-ccc-max\">—</span></div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Cov-Lite Bucket</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"res-cov\">—%</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Cap: <span id=\"res-cov-max\">—</span></div>\n          </div>\n        </section>\n\n        <!-- Allocated Loans Table -->\n        <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n          <div class=\"flex items-center justify-between pb-3 border-b border-zinc-800 mb-3\">\n            <div>\n              <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">Optimal Collateral Allocations</h3>\n              <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Weighted and constrained on a 100% par basis (secondary market prices / OID not modeled).</div>\n            </div>\n            <span class=\"text-xs font-mono text-zinc-400\" id=\"res-alloc-count\">—</span>\n          </div>\n          <div class=\"overflow-x-auto\">\n            <table class=\"w-full text-xs text-left border-collapse\">\n              <thead>\n                <tr class=\"border-b border-zinc-800 text-zinc-400 font-mono text-[10px] uppercase tracking-wider bg-zinc-900/80\">\n                  <th class=\"p-2.5\">Borrower</th>\n                  <th class=\"p-2.5\">Source</th>\n                  <th class=\"p-2.5\">Industry</th>\n                  <th class=\"p-2.5\">Rating / WARF</th>\n                  <th class=\"p-2.5\">Spread</th>\n                  <th class=\"p-2.5 text-right\">Allocated Par ($)</th>\n                  <th class=\"p-2.5 text-right\">Weight (%)</th>\n                </tr>\n              </thead>\n              <tbody id=\"opt-allocations-tbody\" class=\"divide-y divide-zinc-800/60 font-mono-data\">\n              </tbody>\n            </table>\n          </div>\n        </section>\n      </div>\n    </div>\n\n    <!-- ========================================================================= -->\n    <!-- TAB 4: CLO WATERFALL & PM ARBITRAGE (LAYER 3) -->\n    <!-- ========================================================================= -->\n    <div id=\"content-tab4\" class=\"space-y-6 hidden\">\n      <!-- Waterfall Parameters -->\n      <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n        <div class=\"mb-4\">\n          <div class=\"text-[10px] font-mono uppercase tracking-widest text-zinc-400\">Layer 3: CLO Priority of Payments Waterfall & PM Arbitrage</div>\n          <h2 class=\"text-sm sm:text-base font-semibold text-zinc-100 mt-0.5\">Indenture Structure (§ 11.1) & Forward Macro Assumptions</h2>\n        </div>\n\n        <div class=\"grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4\">\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">CLO Indenture Preset:</label>\n            <select id=\"t3-preset-select\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\" onchange=\"loadSelectedPreset()\">\n              <option value=\"tier1_us_bsl_2026.json\">Tier 1 US BSL 2026 ($400M)</option>\n              <option value=\"high_arb_wide_spread.json\">High Arbitrage Wide Spread ($400M)</option>\n              <option value=\"defensive_low_leverage.json\">Defensive Low Leverage ($400M)</option>\n            </select>\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Forward SOFR Curve (%):</label>\n            <input type=\"number\" id=\"t3-sofr\" value=\"4.5\" step=\"0.25\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Annual CPR (%):</label>\n            <input type=\"number\" id=\"t3-cpr\" value=\"15.0\" step=\"1.0\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Annual CDR (%):</label>\n            <input type=\"number\" id=\"t3-cdr\" value=\"1.5\" step=\"0.5\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Recovery Rate (%):</label>\n            <input type=\"number\" id=\"t3-rec\" value=\"65.0\" step=\"5.0\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n          <div>\n            <label class=\"block text-[10px] font-mono uppercase tracking-wider text-zinc-400 mb-1\">Reinvestment Spread (bps):</label>\n            <input type=\"number\" id=\"t3-reinv\" value=\"365.0\" step=\"25.0\" class=\"w-full bg-[#18181b] border border-zinc-700 px-3 py-2 text-xs font-mono text-zinc-100 focus:border-zinc-400 focus:outline-none\">\n          </div>\n        </div>\n\n        <div id=\"wf-seed-banner\" class=\"hidden mb-4 bg-emerald-950/25 border border-emerald-500/40 px-3.5 py-2.5 flex flex-col sm:flex-row sm:items-center justify-between gap-2 text-xs font-mono\">\n          <div class=\"flex items-center gap-2 text-emerald-200\">\n            <input type=\"checkbox\" id=\"wf-use-seed-cb\" checked class=\"accent-emerald-400\">\n            <label for=\"wf-use-seed-cb\" class=\"cursor-pointer\">\n              <span class=\"font-semibold uppercase tracking-wider text-emerald-300\">Include Seed Portfolio Constraints (Tab 2) &amp; Mandate Guardrails (Tab 3):</span>\n              <span id=\"wf-seed-summary\">0 loans ($0M)</span>\n            </label>\n          </div>\n          <button type=\"button\" onclick=\"switchTab('tab2')\" class=\"self-start sm:self-auto px-2.5 py-1 border border-emerald-500/40 text-emerald-300 hover:bg-emerald-900/40 text-[10px] uppercase tracking-wider transition\">\n            Edit Seed Portfolio (Tab 2)\n          </button>\n        </div>\n\n        <button onclick=\"runWaterfall()\" id=\"btn-run-wf\" class=\"bg-zinc-100 hover:bg-white text-zinc-950 font-mono text-xs uppercase tracking-wider px-5 py-2.5 font-semibold transition\">\n          <span>Execute 40-Quarter Waterfall Simulation</span>\n        </button>\n      </section>\n\n      <!-- Waterfall Results Section -->\n      <div id=\"wf-results-section\" class=\"space-y-6 hidden\">\n        <!-- Invariant 5-Cell PM Key Economics Strip -->\n        <section class=\"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-px bg-zinc-800 border border-zinc-800 p-px\">\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Net Arbitrage Spread</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"pm-arb\">— bps</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Asset WAS - Debt WAC</div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Equity IRR</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"pm-irr\">—%</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">40-Quarter Horizon</div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Equity MOIC</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"pm-moic\">—x</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Invested Capital Multiple</div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Yr 1 Cash-on-Cash</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"pm-coc\">—%</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Annualized Distribution</div>\n          </div>\n          <div class=\"bg-[#121215] p-3.5 flex flex-col justify-between\">\n            <div class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-400\">Manager Fee PV</div>\n            <div class=\"text-base sm:text-lg font-mono-data font-semibold text-zinc-100 mt-1\" id=\"pm-fees\">—</div>\n            <div class=\"text-[10px] font-mono text-zinc-500 mt-0.5\">Senior + Subordinated</div>\n          </div>\n        </section>\n\n        <div id=\"wf-collateral-adjustments\" class=\"hidden flex flex-wrap items-center gap-2 text-[11px] font-mono px-3 py-2 border border-zinc-800 bg-[#121215] text-zinc-300\"></div>\n\n        <!-- OC Test Coverage Chart -->\n        <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n          <div class=\"pb-3 border-b border-zinc-800 mb-4\">\n            <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">Overcollateralization (OC) Coverage Ratio History</h3>\n            <p class=\"text-xs text-zinc-400 mt-0.5\">Quarterly OC test ratios across tranches AAA through BB including CCC excess-haircut diversions.</p>\n          </div>\n          <div class=\"h-64 w-full\">\n            <canvas id=\"t3-oc-chart\"></canvas>\n          </div>\n        </section>\n\n        <!-- Tranche Capital Structure Table -->\n        <section class=\"bg-[#121215] border border-zinc-800 p-4 sm:p-5\">\n          <div class=\"pb-3 border-b border-zinc-800 mb-3\">\n            <h3 class=\"text-xs font-mono uppercase tracking-wider text-zinc-200 font-semibold\">CLO Tranche Performance & Weighted Average Life Summary</h3>\n          </div>\n          <div class=\"overflow-x-auto\">\n            <table class=\"w-full text-xs text-left border-collapse\">\n              <thead>\n                <tr class=\"border-b border-zinc-800 text-zinc-400 font-mono text-[10px] uppercase tracking-wider bg-zinc-900/80\">\n                  <th class=\"p-2.5\">Tranche</th>\n                  <th class=\"p-2.5\">Rating Agency</th>\n                  <th class=\"p-2.5 text-right\">Initial Par ($)</th>\n                  <th class=\"p-2.5 text-right\">Spread (bps)</th>\n                  <th class=\"p-2.5 text-right\">WAL (Years)</th>\n                  <th class=\"p-2.5 text-right\">Yield / IRR (%)</th>\n                </tr>\n              </thead>\n              <tbody id=\"wf-tranche-tbody\" class=\"divide-y divide-zinc-800/60 font-mono-data\">\n              </tbody>\n            </table>\n          </div>\n        </section>\n      </div>\n    </div>\n\n  </main>\n\n  <!-- Institutional Colophon -->\n  <footer class=\"bg-[#0c0c0e] border-t border-zinc-800 py-3.5 text-center text-[11px] font-mono text-zinc-500 mt-auto\">\n    <div class=\"max-w-7xl mx-auto px-4 flex flex-col sm:flex-row justify-between items-center gap-2\">\n      <div>\n        BSL-to-CLO Quantitative Credit Platform • SEC EDGAR Clean-Room Architecture\n      </div>\n      <div>\n        Deterministic Cash Flows • SciPy HiGHS LP • Priority of Payments Engine\n      </div>\n    </div>\n  </footer>\n\n  <!-- Side-by-Side Click-to-Highlight SEC Exhibit 10 Viewer Modal -->\n  <div id=\"sec-viewer-modal\" class=\"fixed inset-0 z-50 hidden bg-black/80 backdrop-blur-sm flex items-center justify-center p-1.5 sm:p-6\">\n    <div class=\"bg-[#0f0f12] border border-zinc-700 w-full max-w-6xl h-[94dvh] sm:h-[88vh] flex flex-col shadow-2xl\">\n      <!-- Modal Top Header -->\n      <div class=\"flex flex-wrap items-center justify-between gap-2 px-3 py-2 sm:px-4 sm:py-3 border-b border-zinc-800 bg-[#121215]\">\n        <div class=\"min-w-0 flex-1\">\n          <div class=\"text-[10px] font-mono uppercase tracking-widest text-zinc-400\" id=\"sv-subtitle\">SEC EDGAR Exhibit 10 Clause Inspector</div>\n          <h3 class=\"text-xs sm:text-sm font-semibold text-zinc-100 truncate\" id=\"sv-title\">—</h3>\n        </div>\n        <div class=\"flex items-center gap-1.5 sm:gap-2 flex-wrap\">\n          <button onclick=\"navigateSecViewerPage(secViewerState.prevPage)\" id=\"sv-prev-btn\" class=\"px-2 sm:px-2.5 py-1 border border-zinc-700 text-[11px] sm:text-xs font-mono text-zinc-200 hover:bg-zinc-800 disabled:opacity-40 disabled:cursor-not-allowed\">&larr; Prev</button>\n          <span class=\"text-[11px] sm:text-xs font-mono text-zinc-300\" id=\"sv-page-indicator\">Page —</span>\n          <button onclick=\"navigateSecViewerPage(secViewerState.nextPage)\" id=\"sv-next-btn\" class=\"px-2 sm:px-2.5 py-1 border border-zinc-700 text-[11px] sm:text-xs font-mono text-zinc-200 hover:bg-zinc-800 disabled:opacity-40 disabled:cursor-not-allowed\">Next &rarr;</button>\n          <a id=\"sv-raw-link\" href=\"#\" target=\"_blank\" class=\"px-2 sm:px-2.5 py-1 border border-zinc-700 text-[11px] sm:text-xs font-mono text-zinc-200 hover:bg-zinc-800 underline\">Raw &nearr;</a>\n          <button onclick=\"closeSecViewer()\" class=\"px-2 sm:px-2.5 py-1 bg-zinc-200 text-zinc-950 font-mono text-[11px] sm:text-xs font-semibold hover:bg-white\">Close</button>\n        </div>\n      </div>\n\n      <!-- Modal Split Body -->\n      <div class=\"flex-1 min-h-0 flex flex-col lg:grid lg:grid-cols-12\">\n        <!-- Mobile Collapsible Clause Bar -->\n        <div class=\"lg:hidden flex items-center justify-between gap-2 px-3 py-1.5 border-b border-zinc-800 bg-[#121215]\">\n          <span class=\"text-[10px] font-mono uppercase tracking-wider text-zinc-300\">\n            Cited Clauses (<span id=\"sv-mobile-cite-count\">0</span>)\n          </span>\n          <button type=\"button\" id=\"sv-mobile-cites-toggle\" onclick=\"toggleSecMobileDrawer()\" class=\"px-2 py-0.5 border border-zinc-700 bg-zinc-900 text-[10px] font-mono text-zinc-200 hover:border-zinc-500\">\n            Show Clauses &#9662;\n          </button>\n        </div>\n\n        <!-- Left Sidebar: Loan Clause Provenance Navigator -->\n        <div id=\"sv-cite-drawer\" class=\"hidden lg:block lg:col-span-4 border-b lg:border-b-0 lg:border-r border-zinc-800 bg-[#121215] overflow-y-auto p-3 space-y-2 max-h-48 lg:max-h-none shrink-0\">\n          <div class=\"hidden lg:block text-[10px] font-mono uppercase tracking-wider text-zinc-400 px-1 pb-1 border-b border-zinc-800\">\n            Jump to Cited Clause (<span id=\"sv-cite-count\">0</span>)\n          </div>\n          <div id=\"sv-cite-nav\" class=\"space-y-2\"></div>\n        </div>\n\n        <!-- Right Viewer: Highlighted Filing Page Text -->\n        <div class=\"lg:col-span-8 flex-1 flex flex-col min-h-0 min-w-0 bg-[#09090b]\">\n          <div class=\"px-3 sm:px-4 py-1.5 sm:py-2 border-b border-zinc-800/80 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-[10px] sm:text-[11px] font-mono text-zinc-400 bg-zinc-900/50\">\n            <span id=\"sv-active-clause\" class=\"text-zinc-200 truncate max-w-full\">Clause Highlight</span>\n            <div class=\"flex items-center gap-2 ml-auto shrink-0\">\n              <span id=\"sv-match-status\">—</span>\n              <button type=\"button\" id=\"sv-jump-mark-btn\" onclick=\"scrollSecHighlightIntoView()\" class=\"hidden px-2 py-0.5 border border-amber-400/70 bg-amber-400/20 text-amber-100 font-semibold hover:bg-amber-400/30 transition\">\n                Highlight &darr;\n              </button>\n            </div>\n          </div>\n          <div id=\"sv-doc-scroll\" class=\"flex-1 overflow-y-auto overscroll-contain p-3 sm:p-5 text-[11px] sm:text-[13px] leading-relaxed font-mono-data text-zinc-300 whitespace-pre-wrap break-words\">\n            Loading filing page...\n          </div>\n        </div>\n      </div>\n    </div>\n  </div>\n\n  <script>\n    let allLoans = [];\n    let currentLoan = null;\n    let secViewerState = { prevPage: null, nextPage: null, activeCiteIdx: -1, currentQuote: null, loan: null };\n    let compareState = {\n      options: null,\n      lastDiff: null,\n      filter: 'changed',\n      chartExpanded: false,\n      chartMode: 'cumulative',\n      startFromOrigination: false,\n      projA: null,\n      projB: null,\n      cfReqSeq: 0,\n      recalcTimer: null,\n      chart: null,\n    };\n\n    const TERM_FIELD_MAP = {\n      'Borrower Name': ['borrower.legal_name', 'borrower_name'],\n      'Facility Type': ['facility.facility_type', 'tranches[0].facility_type', 'tranches.0.facility_type'],\n      'Seniority / Security': ['facility.lien_priority', 'tranches[0].lien_priority', 'tranches.0.lien_priority', 'facility.administrative_agent', 'administrative_agent'],\n      'Spread Over Index': ['interest.spread_bps', 'interest.source_clause', 'spread_bps'],\n      'Rate Floor': ['interest.floor_bps', 'rate_floor_pct'],\n      'Maturity Date': ['tranches[0].maturity_date', 'tranches.0.maturity_date', 'dates.maturity_date', 'maturity_date'],\n      'Springing Maturity': [\n        'dates.springing_maturity.tlb_detail',\n        'dates.springing_maturity.rcf_detail',\n        'dates.springing_maturity.tlb',\n        'dates.springing_maturity.rcf',\n        'dates.springing_maturity',\n        'springing_maturity.tlb_detail',\n        'springing_maturity.rcf_detail',\n        'springing_maturity.source_clause',\n        'springing_maturity.reference_debt',\n        'springing_maturity.scope',\n        'springing_maturity',\n        'has_springing_maturity',\n        'dates.maturity_date',\n        'maturity_date',\n      ],\n      'Covenant Structure': ['covenants.covenant_lite', 'covenants.financial_maintenance_covenants', 'covenants.notes'],\n      'ECF Sweep': [\n        'mandatory_prepayments.ecf_sweep.tiers',\n        'mandatory_prepayments.ecf_sweep.tiers[0].sweep_rate',\n        'mandatory_prepayments.ecf_sweep.de_minimis_amount',\n        'mandatory_prepayments.ecf_sweep.source_clause',\n        'mandatory_prepayments.ecf_sweep.enabled',\n        'ecf_sweep_pct',\n      ],\n      'Original Par': ['facility.original_principal', 'tranches[0].original_principal', 'tranches.0.original_principal', 'original_par'],\n      'Current Par': ['facility.original_principal', 'tranches[0].original_principal', 'tranches.0.original_principal', 'original_par'],\n      'Original Issue Discount (OID)': ['facility.oid_bps', 'facility.issue_price_pct'],\n      'Day Count Convention': ['interest.day_count_convention', 'day_count'],\n      'Scheduled Amortization': ['amortization.quarterly_rate', 'amortization.annual_rate', 'amortization.quarterly_dollar_amount', 'amortization.type', 'amortization.source_clause', 'amortization.verbatim_excerpt', 'scheduled_amort'],\n      'Call Protection': ['call_protection.source_clause', 'call_protection.type', 'call_protection.premium_pct', 'call_protection.duration_months', 'call_protection.expiration_date', 'call_schedule', 'call_protection.thereafter_price_pct']\n    };\n\n    function escapeHtml(str) {\n      return String(str ?? '')\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;')\n        .replace(/'/g, '&#39;');\n    }\n\n    function hasRealSecFiling(loan) {\n      return Boolean(loan && /\\/\\d{18}\\//.test(loan.source_filing_url || ''));\n    }\n\n    function findCitationIndexForTerm(termKey) {\n      if (!hasRealSecFiling(currentLoan)) return -1;\n      if (termKey === 'ECF Sweep' && currentLoan && currentLoan.ecf_sweep_summary && !currentLoan.ecf_sweep_summary.has_ecf_sweep) {\n        return -1;\n      }\n      if (termKey === 'Springing Maturity' && currentLoan && currentLoan.springing_maturity_summary && !currentLoan.springing_maturity_summary.has_trigger) {\n        return -1;\n      }\n      const citations = (currentLoan && currentLoan.citations) || [];\n      const candidates = TERM_FIELD_MAP[termKey];\n      if (!candidates || citations.length === 0) return -1;\n      for (const alias of candidates) {\n        const exactIdx = citations.findIndex(c => c.field_name !== 'credit_rating' && c.field_name === alias);\n        if (exactIdx >= 0) return exactIdx;\n      }\n      for (const alias of candidates) {\n        const leaf = alias.split('.').pop();\n        const fuzzyIdx = citations.findIndex(c => c.field_name !== 'credit_rating' && c.field_name && c.field_name.endsWith(leaf));\n        if (fuzzyIdx >= 0) return fuzzyIdx;\n      }\n      return -1;\n    }\n\n    function openSecViewerForTerm(termKey) {\n      const idx = findCitationIndexForTerm(termKey);\n      if (idx >= 0) {\n        openSecViewerByCiteIdx(idx, termKey);\n      }\n    }\n\n    function setSecMobileDrawerOpen(open) {\n      const drawer = document.getElementById('sv-cite-drawer');\n      const toggle = document.getElementById('sv-mobile-cites-toggle');\n      if (drawer) {\n        drawer.classList.toggle('hidden', !open);\n      }\n      if (toggle) {\n        toggle.innerHTML = open ? 'Hide Clauses &#9652;' : 'Show Clauses &#9662;';\n      }\n    }\n\n    function toggleSecMobileDrawer() {\n      const drawer = document.getElementById('sv-cite-drawer');\n      if (!drawer) return;\n      setSecMobileDrawerOpen(drawer.classList.contains('hidden'));\n    }\n\n    function scrollSecHighlightIntoView() {\n      const scrollBox = document.getElementById('sv-doc-scroll');\n      const mark = document.getElementById('sec-active-mark');\n      if (!scrollBox || !mark) return;\n      const boxRect = scrollBox.getBoundingClientRect();\n      const markRect = mark.getBoundingClientRect();\n      const offsetWithinBox = markRect.top - boxRect.top + scrollBox.scrollTop;\n      const targetTop = Math.max(0, offsetWithinBox - scrollBox.clientHeight / 2 + markRect.height / 2);\n      scrollBox.scrollTo({ top: targetTop, behavior: 'smooth' });\n    }\n\n    function renderSecViewerSidebar(citations) {\n      const filingCites = citations\n        .map((c, idx) => ({ c, idx }))\n        .filter(({ c }) => c.field_name !== 'credit_rating');\n      document.getElementById('sv-cite-count').textContent = filingCites.length;\n      const mobCountEl = document.getElementById('sv-mobile-cite-count');\n      if (mobCountEl) mobCountEl.textContent = filingCites.length;\n      const nav = document.getElementById('sv-cite-nav');\n      if (filingCites.length === 0) {\n        nav.innerHTML = '<div class=\"text-xs font-mono text-zinc-500 p-2\">No Exhibit 10 citations available for this loan.</div>';\n        return;\n      }\n      nav.innerHTML = filingCites.map(({ c, idx }) => {\n        const isActive = idx === secViewerState.activeCiteIdx;\n        return `\n          <button onclick=\"openSecViewerByCiteIdx(${idx})\" class=\"w-full text-left p-2.5 border transition ${isActive ? 'border-amber-400/70 bg-amber-400/10' : 'border-zinc-800 bg-zinc-900/70 hover:border-zinc-600'}\">\n            <div class=\"flex justify-between items-center text-[10px] font-mono mb-0.5\">\n              <span class=\"text-zinc-200 font-semibold truncate\">${escapeHtml(c.field_name || 'clause')}</span>\n              ${c.page_number ? `<span class=\"text-zinc-400 shrink-0 ml-1\">p. ${c.page_number}</span>` : ''}\n            </div>\n            <div class=\"text-[10px] font-mono text-zinc-400 truncate\">&sect; ${escapeHtml(c.section_ref || 'Filing Section')}</div>\n            <div class=\"text-[11px] text-zinc-300 line-clamp-2 mt-1 italic\">\"${escapeHtml(c.verbatim_snippet || '')}\"</div>\n          </button>\n        `;\n      }).join('');\n    }\n\n    async function fetchAndRenderSecPage({ page = null, quote = null, label = null, loanObj = null, strictPage = false }) {\n      const targetLoan = loanObj || secViewerState.loan || currentLoan;\n      if (!targetLoan) return;\n      secViewerState.loan = targetLoan;\n      const scrollBox = document.getElementById('sv-doc-scroll');\n      const jumpBtn = document.getElementById('sv-jump-mark-btn');\n      if (jumpBtn) jumpBtn.classList.add('hidden');\n      document.getElementById('sv-title').textContent = `${targetLoan.borrower_name} — ${targetLoan.facility_id}`;\n      document.getElementById('sv-raw-link').href = targetLoan.source_filing_url || '#';\n      document.getElementById('sv-active-clause').textContent = label || 'Filing Page View';\n      document.getElementById('sv-match-status').textContent = 'Loading from SEC EDGAR / cache...';\n      scrollBox.innerHTML = '<div class=\"text-xs font-mono text-zinc-400 py-8 text-center\">Fetching SEC Exhibit 10 page...</div>';\n\n      const params = new URLSearchParams();\n      if (page != null) params.set('page', String(page));\n      if (quote) params.set('quote', quote);\n      if (strictPage) params.set('strict_page', '1');\n\n      try {\n        const res = await fetch(`/api/facilities/${encodeURIComponent(targetLoan.facility_id)}/document?${params.toString()}`);\n        const data = await res.json();\n        if (!res.ok) {\n          throw new Error(data.detail || 'Could not load SEC filing document');\n        }\n\n        secViewerState.prevPage = data.prev_page;\n        secViewerState.nextPage = data.next_page;\n        document.getElementById('sv-page-indicator').textContent = `Page ${data.page_number} (${data.page_index} / ${data.total_pages})`;\n        document.getElementById('sv-prev-btn').disabled = data.prev_page == null;\n        document.getElementById('sv-next-btn').disabled = data.next_page == null;\n        document.getElementById('sv-raw-link').href = data.sec_filing_url || '#';\n        document.getElementById('sv-match-status').textContent = data.quote_matched\n          ? `Clause highlighted${data.cached ? ' (cached)' : ''}`\n          : (strictPage || !quote\n            ? `Page ${data.page_number}${data.cached ? ' (cached)' : ''}`\n            : 'Showing target page (exact inline match unavailable)');\n\n        const txt = data.page_text || '';\n        const hs = data.highlight_start;\n        const he = data.highlight_end;\n        if (hs != null && he != null && he > hs) {\n          scrollBox.innerHTML =\n            escapeHtml(txt.slice(0, hs)) +\n            `<mark id=\"sec-active-mark\" class=\"bg-amber-400/45 text-amber-50 ring-2 ring-amber-400 font-semibold px-1 py-0.5 rounded-sm\">${escapeHtml(txt.slice(hs, he))}</mark>` +\n            escapeHtml(txt.slice(he));\n          if (jumpBtn) jumpBtn.classList.remove('hidden');\n          requestAnimationFrame(() => requestAnimationFrame(scrollSecHighlightIntoView));\n        } else {\n          scrollBox.textContent = txt;\n          scrollBox.scrollTop = 0;\n        }\n      } catch (err) {\n        document.getElementById('sv-page-indicator').textContent = 'Unavailable';\n        document.getElementById('sv-prev-btn').disabled = true;\n        document.getElementById('sv-next-btn').disabled = true;\n        document.getElementById('sv-match-status').textContent = 'Document fetch failed';\n        scrollBox.innerHTML = `\n          <div class=\"border border-zinc-800 bg-zinc-900/70 p-4 text-xs font-mono text-zinc-300 space-y-2\">\n            <div class=\"text-amber-300 font-semibold\">Unable to load live SEC EDGAR exhibit text</div>\n            <div class=\"text-zinc-400\">${escapeHtml(err.message || err)}</div>\n            ${quote ? `<div class=\"pt-2 border-t border-zinc-800 text-zinc-200 italic\">\"${escapeHtml(quote)}\"</div>` : ''}\n          </div>\n        `;\n      }\n    }\n\n    function openSecViewerByCiteIdx(citeIdx, termLabel = null, loanOverride = null) {\n      const targetLoan = loanOverride || secViewerState.loan || currentLoan;\n      if (!targetLoan) return;\n      const citations = targetLoan.citations || [];\n      const cit = citations[citeIdx];\n      if (!cit) return;\n      secViewerState.loan = targetLoan;\n      secViewerState.activeCiteIdx = citeIdx;\n      secViewerState.currentQuote = cit.verbatim_snippet || null;\n      document.getElementById('sec-viewer-modal').classList.remove('hidden');\n      document.body.classList.add('overflow-hidden');\n      setSecMobileDrawerOpen(false);\n      renderSecViewerSidebar(citations);\n      const label = termLabel ? `${termLabel} · § ${cit.section_ref || cit.field_name}` : `${cit.field_name} · § ${cit.section_ref || 'Clause'}`;\n      fetchAndRenderSecPage({\n        page: cit.page_number || null,\n        quote: cit.verbatim_snippet || null,\n        label,\n        loanObj: targetLoan\n      });\n    }\n\n    function openSecViewerForComparison(rowIdx, side) {\n      const diff = compareState.lastDiff;\n      if (!diff || !diff.rows || !diff.rows[rowIdx]) return;\n      const row = diff.rows[rowIdx];\n      const meta = side === 'left' ? diff.left_meta : diff.right_meta;\n      const cit = side === 'left' ? row.left_citation : row.right_citation;\n      if (!meta || !cit) return;\n      const targetLoan = allLoans.find(l => l.facility_id === meta.facility_id);\n      if (!targetLoan) return;\n      const citeIdx = (targetLoan.citations || []).findIndex(\n        c => c.field_name === cit.field_name && c.verbatim_snippet === cit.verbatim_snippet\n      );\n      if (citeIdx >= 0) {\n        openSecViewerByCiteIdx(citeIdx, `${side === 'left' ? 'Baseline' : 'Comparison'} · ${row.label}`, targetLoan);\n      } else {\n        secViewerState.loan = targetLoan;\n        secViewerState.activeCiteIdx = -1;\n        secViewerState.currentQuote = cit.verbatim_snippet || null;\n        document.getElementById('sec-viewer-modal').classList.remove('hidden');\n        document.body.classList.add('overflow-hidden');\n        setSecMobileDrawerOpen(false);\n        renderSecViewerSidebar(targetLoan.citations || []);\n        fetchAndRenderSecPage({\n          page: cit.page_number || null,\n          quote: cit.verbatim_snippet || null,\n          label: `${row.label} · § ${cit.section_ref || cit.field_name}`,\n          loanObj: targetLoan\n        });\n      }\n    }\n\n    function navigateSecViewerPage(targetPage) {\n      if (targetPage == null) return;\n      fetchAndRenderSecPage({\n        page: targetPage,\n        quote: secViewerState.currentQuote,\n        label: document.getElementById('sv-active-clause').textContent,\n        strictPage: true\n      });\n    }\n\n    function closeSecViewer() {\n      document.getElementById('sec-viewer-modal').classList.add('hidden');\n      document.body.classList.remove('overflow-hidden');\n    }\n\n    document.addEventListener('keydown', e => {\n      if (e.key === 'Escape') closeSecViewer();\n    });\n\n    let t1Chart = null;\n    let t3Chart = null;\n\n    function switchTab(tabId) {\n      ['tab1', 'tab2', 'tab3', 'tab4'].forEach(t => {\n        const contentEl = document.getElementById(`content-${t}`);\n        const navEl = document.getElementById(`nav-${t}`);\n        if (contentEl) contentEl.classList.add('hidden');\n        if (navEl) {\n          navEl.classList.remove('tab-active');\n          navEl.classList.add('text-zinc-400');\n          navEl.classList.remove('text-zinc-100');\n        }\n      });\n      const activeContent = document.getElementById(`content-${tabId}`);\n      const activeNav = document.getElementById(`nav-${tabId}`);\n      if (activeContent) activeContent.classList.remove('hidden');\n      if (activeNav) {\n        activeNav.classList.add('tab-active');\n        activeNav.classList.remove('text-zinc-400');\n        activeNav.classList.add('text-zinc-100');\n      }\n      if (tabId === 'tab2') {\n        renderSeedTable();\n        refreshSeedPreview();\n      } else if (tabId === 'tab3' || tabId === 'tab4') {\n        updateSeedBannersAcrossTabs();\n      }\n    }\n\n    async function setTab1Mode(mode) {\n      const isCompare = mode === 'compare';\n      document.getElementById('t1-single-controls').classList.toggle('hidden', isCompare);\n      document.getElementById('t1-single-view').classList.toggle('hidden', isCompare);\n      document.getElementById('t1-compare-view').classList.toggle('hidden', !isCompare);\n\n      const sBtn = document.getElementById('t1-mode-single-btn');\n      const cBtn = document.getElementById('t1-mode-compare-btn');\n      if (isCompare) {\n        cBtn.className = 'px-3 py-1.5 bg-zinc-100 text-zinc-950 font-semibold transition';\n        sBtn.className = 'px-3 py-1.5 text-zinc-300 hover:text-white transition';\n        syncCompareInputsFromSingle();\n        if (!compareState.options) {\n          await loadCompareOptions();\n        } else {\n          await runCompareCashflows();\n        }\n      } else {\n        sBtn.className = 'px-3 py-1.5 bg-zinc-100 text-zinc-950 font-semibold transition';\n        cBtn.className = 'px-3 py-1.5 text-zinc-300 hover:text-white transition';\n        recalculateCashflows();\n      }\n    }\n\n    function syncCompareInputsFromSingle() {\n      const pairs = [\n        ['t1-sofr', 'cmp-sofr', TAB1_BASE_CASE.sofr, 'sofr'],\n        ['t1-cpr', 'cmp-cpr', TAB1_BASE_CASE.cpr, 'cpr'],\n        ['t1-cdr', 'cmp-cdr', TAB1_BASE_CASE.cdr, 'cdr'],\n      ];\n      for (const [srcId, dstId, fb, key] of pairs) {\n        const src = document.getElementById(srcId);\n        const dst = document.getElementById(dstId);\n        if (src && dst) {\n          const val = parseNumericInput(srcId, fb);\n          dst.value = formatScenarioValue(key, val);\n        }\n      }\n      compareState.startFromOrigination = tab1StartFromOrigination;\n      updateCompareValuationModeButtons();\n    }\n\n    function syncSingleInputsFromCompare() {\n      const pairs = [\n        ['cmp-sofr', 't1-sofr', 't1-sofr-slider', TAB1_BASE_CASE.sofr, 'sofr', 0, 10],\n        ['cmp-cpr', 't1-cpr', 't1-cpr-slider', TAB1_BASE_CASE.cpr, 'cpr', 0, 60],\n        ['cmp-cdr', 't1-cdr', 't1-cdr-slider', TAB1_BASE_CASE.cdr, 'cdr', 0, 25],\n      ];\n      for (const [srcId, dstId, sliderId, fb, key, minV, maxV] of pairs) {\n        const dst = document.getElementById(dstId);\n        const slider = document.getElementById(sliderId);\n        const val = parseNumericInput(srcId, fb);\n        if (dst) dst.value = formatScenarioValue(key, val);\n        if (slider) slider.value = String(Math.min(maxV, Math.max(minV, val)));\n      }\n      if (typeof updateTab1StressStatus === 'function') updateTab1StressStatus();\n    }\n\n    function updateCompareValuationModeButtons() {\n      const remBtn = document.getElementById('cmp-mode-remaining-btn');\n      const origBtn = document.getElementById('cmp-mode-origination-btn');\n      if (remBtn && origBtn) {\n        remBtn.className = !compareState.startFromOrigination\n          ? 'px-2 py-1 bg-zinc-100 text-zinc-950 font-semibold transition'\n          : 'px-2 py-1 text-zinc-300 hover:text-white transition';\n        origBtn.className = compareState.startFromOrigination\n          ? 'px-2 py-1 bg-zinc-100 text-zinc-950 font-semibold transition'\n          : 'px-2 py-1 text-zinc-300 hover:text-white transition';\n      }\n    }\n\n    function setCompareValuationMode(fromOrigination) {\n      compareState.startFromOrigination = Boolean(fromOrigination);\n      updateCompareValuationModeButtons();\n      runCompareCashflows();\n    }\n\n    function resetCompareToBaseCase() {\n      if (compareState.recalcTimer) {\n        clearTimeout(compareState.recalcTimer);\n        compareState.recalcTimer = null;\n      }\n      document.getElementById('cmp-sofr').value = TAB1_BASE_CASE.sofr.toFixed(1);\n      document.getElementById('cmp-cpr').value = TAB1_BASE_CASE.cpr.toFixed(1);\n      document.getElementById('cmp-cdr').value = TAB1_BASE_CASE.cdr.toFixed(1);\n      syncSingleInputsFromCompare();\n      runCompareCashflows();\n    }\n\n    function handleCompareScenarioInput() {\n      syncSingleInputsFromCompare();\n      if (compareState.recalcTimer) clearTimeout(compareState.recalcTimer);\n      compareState.recalcTimer = setTimeout(() => {\n        compareState.recalcTimer = null;\n        runCompareCashflows();\n      }, 140);\n    }\n\n    function toggleCompareCashflowChart() {\n      compareState.chartExpanded = !compareState.chartExpanded;\n      const wrap = document.getElementById('cmp-cf-chart-wrap');\n      const modeGrp = document.getElementById('cmp-cf-mode-group');\n      const btn = document.getElementById('cmp-cf-toggle-btn');\n      if (wrap) wrap.classList.toggle('hidden', !compareState.chartExpanded);\n      if (modeGrp) modeGrp.classList.toggle('hidden', !compareState.chartExpanded);\n      if (btn) {\n        btn.innerHTML = compareState.chartExpanded\n          ? 'Hide Cash Flows &#9652;'\n          : 'Compare Cash Flows &#9662;';\n      }\n      if (compareState.chartExpanded) {\n        renderCompareCashflowChart();\n      }\n    }\n\n    function setCompareChartMode(mode) {\n      compareState.chartMode = mode === 'delta' ? 'delta' : 'cumulative';\n      const cumBtn = document.getElementById('cmp-cf-mode-cum');\n      const deltaBtn = document.getElementById('cmp-cf-mode-delta');\n      if (cumBtn && deltaBtn) {\n        cumBtn.className = compareState.chartMode === 'cumulative'\n          ? 'px-2.5 py-1 bg-zinc-100 text-zinc-950 font-semibold transition'\n          : 'px-2.5 py-1 text-zinc-300 hover:text-white transition';\n        deltaBtn.className = compareState.chartMode === 'delta'\n          ? 'px-2.5 py-1 bg-zinc-100 text-zinc-950 font-semibold transition'\n          : 'px-2.5 py-1 text-zinc-300 hover:text-white transition';\n      }\n      if (compareState.chartExpanded) {\n        renderCompareCashflowChart();\n      }\n    }\n\n    function getCompareCashTotal(proj) {\n      if (!proj) return 0;\n      if (proj.total_cash_flow != null) return Number(proj.total_cash_flow);\n      return Number(proj.total_interest || 0)\n        + Number(proj.total_principal_repaid || 0)\n        + Number(proj.total_recoveries || 0)\n        + Number(proj.total_prepayment_penalty || 0);\n    }\n\n    async function runCompareCashflows() {\n      const leftId = (compareState.lastDiff && compareState.lastDiff.left_meta && compareState.lastDiff.left_meta.facility_id)\n        || document.getElementById('cmp-left-select')?.value;\n      const rightId = (compareState.lastDiff && compareState.lastDiff.right_meta && compareState.lastDiff.right_meta.facility_id)\n        || document.getElementById('cmp-right-select')?.value;\n      if (!leftId || !rightId) return;\n\n      const reqSeq = ++compareState.cfReqSeq;\n      const sofrPct = parseNumericInput('cmp-sofr', TAB1_BASE_CASE.sofr);\n      const cprPct = parseNumericInput('cmp-cpr', TAB1_BASE_CASE.cpr);\n      const cdrPct = parseNumericInput('cmp-cdr', TAB1_BASE_CASE.cdr);\n      const startOrig = Boolean(compareState.startFromOrigination);\n\n      const postProj = async (facilityId) => {\n        const res = await fetch('/api/project_loan_cashflows', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify({\n            facility_id: facilityId,\n            sofr_pct: sofrPct,\n            cpr_pct: cprPct,\n            cdr_pct: cdrPct,\n            start_from_origination: startOrig,\n          }),\n        });\n        const body = await res.json();\n        if (!res.ok) throw new Error(body.detail || `Projection failed for ${facilityId}`);\n        return body;\n      };\n\n      try {\n        const [projA, projB] = await Promise.all([postProj(leftId), postProj(rightId)]);\n        if (reqSeq !== compareState.cfReqSeq) return;\n        compareState.projA = projA;\n        compareState.projB = projB;\n        renderCompareEconomicKpis();\n        if (compareState.chartExpanded) {\n          renderCompareCashflowChart();\n        }\n      } catch (err) {\n        if (reqSeq !== compareState.cfReqSeq) return;\n        console.error('Compare cashflow error:', err);\n      }\n    }\n\n    function renderCompareEconomicKpis() {\n      const projA = compareState.projA;\n      const projB = compareState.projB;\n      if (!projA || !projB) return;\n\n      const dWal = Number(projB.weighted_average_life_years || 0) - Number(projA.weighted_average_life_years || 0);\n      const dInt = Number(projB.total_interest || 0) - Number(projA.total_interest || 0);\n      const cashA = getCompareCashTotal(projA);\n      const cashB = getCompareCashTotal(projB);\n      const dCash = cashB - cashA;\n\n      const walEl = document.getElementById('cmp-delta-wal');\n      const walMetaEl = document.getElementById('cmp-delta-wal-meta');\n      if (walEl) {\n        walEl.textContent = formatSignedWalDelta(dWal);\n        walEl.className = `text-base sm:text-lg font-mono-data font-semibold mt-1 ${Math.abs(dWal) < 0.005 ? 'text-zinc-400' : 'text-amber-300'}`;\n      }\n      if (walMetaEl) {\n        walMetaEl.textContent = `B: ${Number(projB.weighted_average_life_years || 0).toFixed(2)} yrs vs A: ${Number(projA.weighted_average_life_years || 0).toFixed(2)} yrs`;\n      }\n\n      const intEl = document.getElementById('cmp-delta-int');\n      const intMetaEl = document.getElementById('cmp-delta-int-meta');\n      if (intEl) {\n        intEl.textContent = formatSignedCompactUsd(dInt);\n        intEl.className = `text-base sm:text-lg font-mono-data font-semibold mt-1 ${Math.abs(dInt) < 1 ? 'text-zinc-400' : (dInt > 0 ? 'text-emerald-300' : 'text-rose-300')}`;\n      }\n      if (intMetaEl) {\n        intMetaEl.textContent = `B: ${formatCompactUsd(projB.total_interest || 0)} vs A: ${formatCompactUsd(projA.total_interest || 0)}`;\n      }\n\n      const cashEl = document.getElementById('cmp-delta-cash');\n      const cashMetaEl = document.getElementById('cmp-delta-cash-meta');\n      if (cashEl) {\n        cashEl.textContent = formatSignedCompactUsd(dCash);\n        cashEl.className = `text-base sm:text-lg font-mono-data font-semibold mt-1 ${Math.abs(dCash) < 1 ? 'text-zinc-400' : (dCash > 0 ? 'text-emerald-300' : 'text-rose-300')}`;\n      }\n      if (cashMetaEl) {\n        cashMetaEl.textContent = `B: ${formatCompactUsd(cashB)} vs A: ${formatCompactUsd(cashA)}`;\n      }\n\n      const subEl = document.getElementById('cmp-econ-sublabel');\n      if (subEl) {\n        const modeTxt = compareState.startFromOrigination ? 'From Origination' : 'From Today';\n        const leftLbl = (compareState.lastDiff && compareState.lastDiff.left_meta && compareState.lastDiff.left_meta.facility_id) || projA.facility_id;\n        const rightLbl = (compareState.lastDiff && compareState.lastDiff.right_meta && compareState.lastDiff.right_meta.facility_id) || projB.facility_id;\n        subEl.textContent = `${rightLbl} vs ${leftLbl} · ${modeTxt}`;\n      }\n    }\n\n    function renderCompareCashflowChart() {\n      const projA = compareState.projA;\n      const projB = compareState.projB;\n      if (!projA || !projB) return;\n\n      const periodsA = projA.periods || [];\n      const periodsB = projB.periods || [];\n      const maxLen = Math.max(periodsA.length, periodsB.length);\n      const labels = Array.from({ length: maxLen }, (_, idx) => `Q${idx + 1}`);\n\n      const cashA = labels.map((_, idx) => Number((periodsA[idx] && periodsA[idx].total_cash_flow) || 0));\n      const cashB = labels.map((_, idx) => Number((periodsB[idx] && periodsB[idx].total_cash_flow) || 0));\n\n      const captionEl = document.getElementById('cmp-cf-chart-caption');\n      const canvas = document.getElementById('cmp-cf-chart');\n      if (!canvas) return;\n      if (compareState.chart) {\n        compareState.chart.destroy();\n        compareState.chart = null;\n      }\n\n      const ctx = canvas.getContext('2d');\n      if (compareState.chartMode === 'delta') {\n        const deltaSeries = labels.map((_, idx) => cashB[idx] - cashA[idx]);\n        const barColors = deltaSeries.map(v => (v >= 0 ? 'rgba(52, 211, 153, 0.8)' : 'rgba(251, 113, 133, 0.8)'));\n        if (captionEl) {\n          captionEl.textContent = 'Quarterly Delta (Facility B − Facility A): green bars show higher quarterly cash inflow on Facility B; rose bars show higher inflow on Facility A.';\n        }\n        compareState.chart = new Chart(ctx, {\n          type: 'bar',\n          data: {\n            labels,\n            datasets: [\n              {\n                label: 'Quarterly Cash Delta (B − A)',\n                data: deltaSeries,\n                backgroundColor: barColors,\n                borderWidth: 0,\n              },\n            ],\n          },\n          options: {\n            responsive: true,\n            maintainAspectRatio: false,\n            interaction: { mode: 'index', intersect: false },\n            plugins: {\n              legend: {\n                position: 'top',\n                align: 'end',\n                labels: { boxWidth: 10, font: { family: 'ui-monospace, monospace', size: 10 }, color: '#a1a1aa' },\n              },\n              tooltip: {\n                callbacks: {\n                  label: (item) => `Delta (B − A): ${formatSignedCompactUsd(item.parsed.y)}`,\n                },\n              },\n            },\n            scales: {\n              x: {\n                grid: { display: false },\n                ticks: { font: { family: 'ui-monospace, monospace', size: 10 }, color: '#71717a', maxTicksLimit: 14 },\n              },\n              y: {\n                grid: { color: (c) => (c.tick && c.tick.value === 0 ? '#52525b' : '#27272a') },\n                ticks: {\n                  font: { family: 'ui-monospace, monospace', size: 10 },\n                  color: '#71717a',\n                  callback: v => formatSignedCompactUsd(v),\n                },\n              },\n            },\n          },\n        });\n      } else {\n        let runA = 0;\n        let runB = 0;\n        const cumA = cashA.map(v => { runA += v; return runA; });\n        const cumB = cashB.map(v => { runB += v; return runB; });\n        if (captionEl) {\n          captionEl.textContent = `Cumulative Cash Flow (Principal + Interest + Call Premiums + Recoveries) across mismatched maturities (A: ${periodsA.length}Q vs B: ${periodsB.length}Q).`;\n        }\n        compareState.chart = new Chart(ctx, {\n          type: 'line',\n          data: {\n            labels,\n            datasets: [\n              {\n                label: `Facility A (${periodsA.length}Q)`,\n                data: cumA,\n                borderColor: '#a1a1aa',\n                backgroundColor: 'rgba(161, 161, 170, 0.12)',\n                borderDash: [4, 4],\n                borderWidth: 2,\n                pointRadius: 1.5,\n                tension: 0.15,\n              },\n              {\n                label: `Facility B (${periodsB.length}Q)`,\n                data: cumB,\n                borderColor: '#38bdf8',\n                backgroundColor: 'rgba(56, 189, 248, 0.12)',\n                borderWidth: 2.5,\n                pointRadius: 1.5,\n                tension: 0.15,\n              },\n            ],\n          },\n          options: {\n            responsive: true,\n            maintainAspectRatio: false,\n            interaction: { mode: 'index', intersect: false },\n            plugins: {\n              legend: {\n                position: 'top',\n                align: 'end',\n                labels: { boxWidth: 12, font: { family: 'ui-monospace, monospace', size: 10 }, color: '#a1a1aa' },\n              },\n              tooltip: {\n                callbacks: {\n                  label: (item) => `${item.dataset.label}: ${formatCompactUsd(item.parsed.y)}`,\n                },\n              },\n            },\n            scales: {\n              x: {\n                grid: { display: false },\n                ticks: { font: { family: 'ui-monospace, monospace', size: 10 }, color: '#71717a', maxTicksLimit: 14 },\n              },\n              y: {\n                grid: { color: '#27272a' },\n                ticks: {\n                  font: { family: 'ui-monospace, monospace', size: 10 },\n                  color: '#71717a',\n                  callback: v => formatCompactUsd(v),\n                },\n              },\n            },\n          },\n        });\n      }\n    }\n\n    async function loadCompareOptions() {\n      try {\n        const res = await fetch('/api/compare/options');\n        const opts = await res.json();\n        compareState.options = opts;\n\n        const pills = document.getElementById('cmp-group-pills');\n        const groups = opts.groups || [];\n        if (groups.length === 0) {\n          pills.innerHTML = '<span class=\"text-zinc-500\">No multi-tranche borrowers found; pick any two facilities below.</span>';\n        } else {\n          pills.innerHTML = groups.map((g, gi) => `\n            <button onclick=\"selectCompareGroup(${gi})\" class=\"px-2.5 py-1 border border-zinc-700 bg-[#18181b] text-zinc-200 hover:border-zinc-400 hover:text-white transition\">\n              ${escapeHtml(g.borrower_name)} <span class=\"text-zinc-400\">(${g.count})</span>\n            </button>\n          `).join('');\n        }\n\n        const leftSel = document.getElementById('cmp-left-select');\n        const rightSel = document.getElementById('cmp-right-select');\n        const facOpts = (opts.all_facilities || []).map(f =>\n          `<option value=\"${escapeHtml(f.facility_id)}\">${escapeHtml(f.borrower_name)} · ${escapeHtml(f.facility_id)} (${f.effective_date}, +${f.spread_bps} bps)</option>`\n        ).join('');\n        leftSel.innerHTML = facOpts;\n        rightSel.innerHTML = facOpts;\n\n        const histories = opts.event_histories || [];\n        const evBar = document.getElementById('cmp-events-bar');\n        const evPills = document.getElementById('cmp-event-pills');\n        if (histories.length > 0) {\n          evBar.classList.remove('hidden');\n          evPills.innerHTML = histories.map((h, hi) => `\n            <button onclick=\"runEventHistoryCompare(${hi})\" class=\"px-2.5 py-1 border border-zinc-700 bg-zinc-900 text-zinc-200 hover:border-amber-400/70 transition\">\n              ${escapeHtml(h.borrower_name)} · ${escapeHtml(h.facility_id)} (${h.events.length} snapshots)\n            </button>\n          `).join('');\n        }\n\n        if (groups.length > 0) {\n          await selectCompareGroup(0);\n        } else if ((opts.all_facilities || []).length >= 2) {\n          leftSel.value = opts.all_facilities[0].facility_id;\n          rightSel.value = opts.all_facilities[1].facility_id;\n          await runCompare();\n        }\n      } catch (err) {\n        console.error('Compare options error:', err);\n      }\n    }\n\n    async function selectCompareGroup(groupIdx) {\n      const groups = (compareState.options && compareState.options.groups) || [];\n      const g = groups[groupIdx];\n      if (!g || g.facilities.length < 2) return;\n      document.getElementById('cmp-left-select').value = g.facilities[0].facility_id;\n      document.getElementById('cmp-right-select').value = g.facilities[g.facilities.length - 1].facility_id;\n      await runCompare();\n    }\n\n    async function runEventHistoryCompare(histIdx) {\n      const histories = (compareState.options && compareState.options.event_histories) || [];\n      const h = histories[histIdx];\n      if (!h || h.events.length < 2) return;\n      const firstEv = h.events[0].event_id;\n      const lastEv = h.events[h.events.length - 1].event_id;\n      const res = await fetch(`/api/compare?left_event_id=${firstEv}&right_event_id=${lastEv}`);\n      compareState.lastDiff = await res.json();\n      renderCompareResults();\n      await runCompareCashflows();\n    }\n\n    async function swapCompareSides() {\n      const l = document.getElementById('cmp-left-select');\n      const r = document.getElementById('cmp-right-select');\n      const tmp = l.value;\n      l.value = r.value;\n      r.value = tmp;\n      await runCompare();\n    }\n\n    async function runCompare() {\n      const leftId = document.getElementById('cmp-left-select').value;\n      const rightId = document.getElementById('cmp-right-select').value;\n      if (!leftId || !rightId) return;\n      const tbody = document.getElementById('cmp-diff-tbody');\n      tbody.innerHTML = '<tr><td colspan=\"4\" class=\"p-4 text-zinc-400 font-mono\">Computing term diff...</td></tr>';\n      try {\n        const res = await fetch(`/api/compare?left_facility_id=${encodeURIComponent(leftId)}&right_facility_id=${encodeURIComponent(rightId)}`);\n        const data = await res.json();\n        if (!res.ok) throw new Error(data.detail || 'Comparison failed');\n        compareState.lastDiff = data;\n        renderCompareResults();\n        await runCompareCashflows();\n      } catch (err) {\n        tbody.innerHTML = `<tr><td colspan=\"4\" class=\"p-4 text-red-400 font-mono\">${escapeHtml(err.message || err)}</td></tr>`;\n      }\n    }\n\n    function setCompareFilter(mode) {\n      compareState.filter = mode;\n      const chBtn = document.getElementById('cmp-filter-changed');\n      const allBtn = document.getElementById('cmp-filter-all');\n      if (mode === 'changed') {\n        chBtn.className = 'px-2.5 py-1 bg-zinc-200 text-zinc-950 font-semibold';\n        allBtn.className = 'px-2.5 py-1 text-zinc-300 hover:text-white';\n      } else {\n        allBtn.className = 'px-2.5 py-1 bg-zinc-200 text-zinc-950 font-semibold';\n        chBtn.className = 'px-2.5 py-1 text-zinc-300 hover:text-white';\n      }\n      renderCompareResults();\n    }\n\n    function renderCompareResults() {\n      const diff = compareState.lastDiff;\n      if (!diff) return;\n      document.getElementById('cmp-th-left').textContent = diff.left_meta ? diff.left_meta.label : 'Baseline';\n      document.getElementById('cmp-th-right').textContent = diff.right_meta ? diff.right_meta.label : 'Comparison';\n\n      const badges = document.getElementById('cmp-summary-badges');\n      const pills = [`<span class=\"px-2 py-0.5 border border-zinc-700 bg-zinc-900 text-[10px] font-mono text-zinc-200\">${diff.changed_count} / ${diff.total_fields} Terms Changed</span>`];\n      (diff.highlights || []).forEach(h => {\n        const cls = h.direction === 'tighter'\n          ? 'border-emerald-500/40 bg-emerald-500/10 text-emerald-300'\n          : (h.direction === 'wider' || h.direction === 'extended'\n            ? 'border-amber-500/40 bg-amber-500/10 text-amber-200'\n            : 'border-zinc-700 bg-zinc-900 text-zinc-300');\n        pills.push(`<span class=\"px-2 py-0.5 border text-[10px] font-mono ${cls}\">${escapeHtml(h.label)}: ${escapeHtml(h.delta)}</span>`);\n      });\n      badges.innerHTML = pills.join('');\n\n      const rows = (diff.rows || []).filter(r => compareState.filter === 'all' || r.changed);\n      const tbody = document.getElementById('cmp-diff-tbody');\n      if (rows.length === 0) {\n        tbody.innerHTML = '<tr><td colspan=\"4\" class=\"p-4 text-zinc-400 font-mono\">No structured term differences detected between these two selections. Switch to \"All Fields\" to inspect identical values.</td></tr>';\n        return;\n      }\n\n      tbody.innerHTML = (diff.rows || []).map((r, rowIdx) => {\n        if (compareState.filter !== 'all' && !r.changed) return '';\n        const lBtn = r.left_citation\n          ? `<button onclick=\"openSecViewerForComparison(${rowIdx}, 'left')\" class=\"ml-2 px-1.5 py-0.5 text-[10px] font-mono border border-zinc-700 text-zinc-300 hover:border-amber-400/70 hover:text-amber-200 shrink-0\">${r.left_citation.page_number ? `p. ${r.left_citation.page_number}` : 'Clause'} &nearr;</button>`\n          : '';\n        const rBtn = r.right_citation\n          ? `<button onclick=\"openSecViewerForComparison(${rowIdx}, 'right')\" class=\"ml-2 px-1.5 py-0.5 text-[10px] font-mono border border-zinc-700 text-zinc-300 hover:border-amber-400/70 hover:text-amber-200 shrink-0\">${r.right_citation.page_number ? `p. ${r.right_citation.page_number}` : 'Clause'} &nearr;</button>`\n          : '';\n        const deltaCls = !r.changed\n          ? 'text-zinc-500'\n          : (r.direction === 'tighter'\n            ? 'text-emerald-300 font-semibold'\n            : (r.direction === 'wider' || r.direction === 'extended' ? 'text-amber-200 font-semibold' : 'text-zinc-100 font-semibold'));\n        return `\n          <tr class=\"${r.changed ? 'bg-zinc-900/40 hover:bg-zinc-800/50' : 'hover:bg-zinc-900/30'}\">\n            <td class=\"p-2.5\">\n              <div class=\"font-semibold text-zinc-200\">${escapeHtml(r.label)}</div>\n              <div class=\"text-[10px] font-mono text-zinc-500\">${escapeHtml(r.category)}</div>\n            </td>\n            <td class=\"p-2.5 text-zinc-300\"><div class=\"flex items-center justify-between gap-2\"><span>${escapeHtml(r.left_display)}</span>${lBtn}</div></td>\n            <td class=\"p-2.5 text-zinc-100\"><div class=\"flex items-center justify-between gap-2\"><span>${escapeHtml(r.right_display)}</span>${rBtn}</div></td>\n            <td class=\"p-2.5 text-right font-mono ${deltaCls}\">${escapeHtml(r.delta_display)}</td>\n          </tr>\n        `;\n      }).join('');\n    }\n\n    const tab1PickerState = { open: false, filtered: [], activeIdx: 0, showAll: true };\n\n    function formatTab1LoanLabel(loan) {\n      if (!loan) return '';\n      const tag = hasRealSecFiling(loan) ? 'SEC Exhibit 10' : 'Seed Sample';\n      return `${loan.borrower_name} [${tag} · ${loan.facility_id}]`;\n    }\n\n    function getLoanSearchHaystack(loan) {\n      const tag = hasRealSecFiling(loan) ? 'sec exhibit 10 live' : 'seed sample';\n      const spr = loan.spread_bps != null ? `${loan.spread_bps} +${loan.spread_bps}bps` : '';\n      return `${loan.borrower_name || ''} ${loan.facility_id || ''} ${loan.facility_type || ''} ${loan.moodys_rating || ''} ${loan.sp_rating || ''} ${loan.industry_moodys || ''} ${spr} ${tag}`.toLowerCase();\n    }\n\n    function filterTab1Loans(query) {\n      const tokens = String(query || '').trim().toLowerCase().split(/\\s+/).filter(Boolean);\n      if (tokens.length === 0) return [...allLoans];\n      return allLoans.filter(l => {\n        const hay = getLoanSearchHaystack(l);\n        return tokens.every(tok => hay.includes(tok));\n      });\n    }\n\n    function syncTab1SearchDisplay() {\n      const input = document.getElementById('t1-loan-search');\n      const countEl = document.getElementById('t1-loan-match-count');\n      const clearBtn = document.getElementById('t1-loan-clear-btn');\n      if (input && currentLoan && document.activeElement !== input) {\n        input.value = formatTab1LoanLabel(currentLoan);\n      }\n      if (countEl && allLoans.length > 0) {\n        const nShow = tab1PickerState.open ? tab1PickerState.filtered.length : allLoans.length;\n        countEl.textContent = `${nShow}/${allLoans.length}`;\n      }\n      if (clearBtn && input) {\n        clearBtn.classList.toggle('hidden', !tab1PickerState.open || !input.value);\n      }\n    }\n\n    function renderTab1LoanDropdown() {\n      const listEl = document.getElementById('t1-loan-dropdown');\n      const countEl = document.getElementById('t1-loan-match-count');\n      if (!listEl) return;\n      const items = tab1PickerState.filtered;\n      if (countEl) countEl.textContent = `${items.length}/${allLoans.length}`;\n      if (items.length === 0) {\n        listEl.innerHTML = '<div class=\"px-3 py-4 text-xs font-mono text-zinc-500\">No facilities match that filter.</div>';\n        return;\n      }\n      const activeFid = currentLoan ? currentLoan.facility_id : document.getElementById('t1-loan-select').value;\n      listEl.innerHTML = items.map((l, idx) => {\n        const isCurrent = l.facility_id === activeFid;\n        const isHighlighted = idx === tab1PickerState.activeIdx;\n        const isSec = hasRealSecFiling(l);\n        const badgeCls = isSec\n          ? 'border-emerald-500/40 bg-emerald-950/40 text-emerald-300'\n          : 'border-zinc-700 bg-zinc-900 text-zinc-400';\n        const spr = l.spread_bps != null ? `+${Number(l.spread_bps).toFixed(0)} bps` : '—';\n        const parStr = l.original_par != null ? formatCompactUsd(l.original_par) : '—';\n        return `\n          <button\n            type=\"button\"\n            data-fid=\"${escapeHtml(l.facility_id)}\"\n            onmousedown=\"event.preventDefault(); selectTab1LoanById('${escapeHtml(l.facility_id)}')\"\n            class=\"w-full text-left px-3 py-2 flex items-start justify-between gap-3 transition ${isHighlighted ? 'bg-zinc-800' : (isCurrent ? 'bg-zinc-900/80' : 'hover:bg-zinc-800/60')}\"\n          >\n            <div class=\"min-w-0\">\n              <div class=\"flex flex-wrap items-center gap-1.5\">\n                <span class=\"text-xs font-semibold text-zinc-100 truncate\">${escapeHtml(l.borrower_name)}</span>\n                <span class=\"px-1 py-0.2 text-[9px] font-mono border border-zinc-700 bg-zinc-900 text-zinc-300\">${escapeHtml(l.facility_type || 'TLB')}</span>\n                <span class=\"px-1 py-0.2 text-[9px] font-mono border ${badgeCls}\">${isSec ? 'SEC Exhibit 10' : 'Seed Sample'}</span>\n              </div>\n              <div class=\"text-[10px] font-mono text-zinc-500 truncate mt-0.5\">${escapeHtml(l.facility_id)}</div>\n            </div>\n            <div class=\"shrink-0 text-right font-mono text-[10px]\">\n              <div class=\"text-zinc-200 font-semibold\">${spr} · ${parStr}</div>\n              <div class=\"text-zinc-400\">${escapeHtml(l.moodys_rating || '—')} / ${escapeHtml(l.sp_rating || '—')}</div>\n            </div>\n          </button>\n        `;\n      }).join('');\n    }\n\n    function openTab1LoanDropdown(showAll = false) {\n      const dd = document.getElementById('t1-loan-dropdown');\n      const input = document.getElementById('t1-loan-search');\n      if (!dd || !input) return;\n      tab1PickerState.open = true;\n      tab1PickerState.showAll = Boolean(showAll);\n      tab1PickerState.filtered = showAll ? [...allLoans] : filterTab1Loans(input.value);\n      const curIdx = currentLoan ? tab1PickerState.filtered.findIndex(l => l.facility_id === currentLoan.facility_id) : 0;\n      tab1PickerState.activeIdx = curIdx >= 0 ? curIdx : 0;\n      dd.classList.remove('hidden');\n      renderTab1LoanDropdown();\n      const clearBtn = document.getElementById('t1-loan-clear-btn');\n      if (clearBtn) clearBtn.classList.toggle('hidden', !input.value);\n    }\n\n    function closeTab1LoanDropdown(restoreLabel = true) {\n      const dd = document.getElementById('t1-loan-dropdown');\n      const input = document.getElementById('t1-loan-search');\n      tab1PickerState.open = false;\n      if (dd) dd.classList.add('hidden');\n      if (restoreLabel && input && currentLoan) {\n        input.value = formatTab1LoanLabel(currentLoan);\n      }\n      const clearBtn = document.getElementById('t1-loan-clear-btn');\n      if (clearBtn) clearBtn.classList.add('hidden');\n      const countEl = document.getElementById('t1-loan-match-count');\n      if (countEl && allLoans.length > 0) countEl.textContent = `${allLoans.length}/${allLoans.length}`;\n    }\n\n    function toggleTab1LoanDropdown() {\n      if (tab1PickerState.open) {\n        closeTab1LoanDropdown(true);\n      } else {\n        const input = document.getElementById('t1-loan-search');\n        if (input) input.focus();\n        openTab1LoanDropdown(true);\n      }\n    }\n\n    function clearTab1LoanSearch() {\n      const input = document.getElementById('t1-loan-search');\n      if (input) {\n        input.value = '';\n        input.focus();\n      }\n      openTab1LoanDropdown(true);\n    }\n\n    function handleTab1SearchInput() {\n      const input = document.getElementById('t1-loan-search');\n      if (!input) return;\n      tab1PickerState.open = true;\n      tab1PickerState.showAll = false;\n      tab1PickerState.filtered = filterTab1Loans(input.value);\n      tab1PickerState.activeIdx = 0;\n      const dd = document.getElementById('t1-loan-dropdown');\n      if (dd) dd.classList.remove('hidden');\n      const clearBtn = document.getElementById('t1-loan-clear-btn');\n      if (clearBtn) clearBtn.classList.toggle('hidden', !input.value);\n      renderTab1LoanDropdown();\n    }\n\n    function handleTab1SearchKeydown(e) {\n      if (!tab1PickerState.open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {\n        openTab1LoanDropdown(true);\n        e.preventDefault();\n        return;\n      }\n      if (!tab1PickerState.open) return;\n      const len = tab1PickerState.filtered.length;\n      if (e.key === 'ArrowDown') {\n        e.preventDefault();\n        if (len > 0) {\n          tab1PickerState.activeIdx = (tab1PickerState.activeIdx + 1) % len;\n          renderTab1LoanDropdown();\n          const btns = document.querySelectorAll('#t1-loan-dropdown button');\n          if (btns[tab1PickerState.activeIdx]) btns[tab1PickerState.activeIdx].scrollIntoView({ block: 'nearest' });\n        }\n      } else if (e.key === 'ArrowUp') {\n        e.preventDefault();\n        if (len > 0) {\n          tab1PickerState.activeIdx = (tab1PickerState.activeIdx - 1 + len) % len;\n          renderTab1LoanDropdown();\n          const btns = document.querySelectorAll('#t1-loan-dropdown button');\n          if (btns[tab1PickerState.activeIdx]) btns[tab1PickerState.activeIdx].scrollIntoView({ block: 'nearest' });\n        }\n      } else if (e.key === 'Enter') {\n        e.preventDefault();\n        const chosen = tab1PickerState.filtered[tab1PickerState.activeIdx];\n        if (chosen) selectTab1LoanById(chosen.facility_id);\n      } else if (e.key === 'Escape') {\n        e.preventDefault();\n        closeTab1LoanDropdown(true);\n        const input = document.getElementById('t1-loan-search');\n        if (input) input.blur();\n      }\n    }\n\n    function selectTab1LoanById(fid) {\n      const sel = document.getElementById('t1-loan-select');\n      if (sel) sel.value = fid;\n      closeTab1LoanDropdown(false);\n      loadSelectedLoan();\n      const input = document.getElementById('t1-loan-search');\n      if (input) {\n        if (currentLoan) input.value = formatTab1LoanLabel(currentLoan);\n        input.blur();\n      }\n    }\n\n    document.addEventListener('click', (e) => {\n      const box = document.getElementById('t1-loan-combobox');\n      if (tab1PickerState.open && box && !box.contains(e.target)) {\n        closeTab1LoanDropdown(true);\n      }\n      const seedBox = document.getElementById('seed-loan-combobox');\n      if (seedState.dropdownOpen && seedBox && !seedBox.contains(e.target)) {\n        closeSeedLoanDropdown();\n      }\n    });\n\n    async function init() {\n      try {\n        const res = await fetch('/api/loans');\n        const fetchedLoans = await res.json();\n        allLoans = [...fetchedLoans].sort((a, b) => {\n          const aLive = hasRealSecFiling(a) ? 0 : 1;\n          const bLive = hasRealSecFiling(b) ? 0 : 1;\n          if (aLive !== bLive) return aLive - bLive;\n          return (a.borrower_name || '').localeCompare(b.borrower_name || '');\n        });\n        const select = document.getElementById('t1-loan-select');\n        select.innerHTML = '';\n        allLoans.forEach(l => {\n          const opt = document.createElement('option');\n          opt.value = l.facility_id;\n          opt.textContent = formatTab1LoanLabel(l);\n          select.appendChild(opt);\n        });\n        loadSeedPortfolioFromStorage();\n        if (allLoans.length > 0) {\n          await loadSelectedLoan();\n          syncTab1SearchDisplay();\n        }\n        renderSeedTable();\n        refreshSeedPreview();\n      } catch (err) {\n        console.error('Failed to load loans:', err);\n      }\n    }\n\n    function loadSelectedPreset() {\n      const sel = document.getElementById('t3-preset-select').value;\n      console.log('Selected preset:', sel);\n    }\n\n    async function loadSelectedLoan() {\n      const fid = document.getElementById('t1-loan-select').value;\n      if (!fid) return;\n      if (tab1LastFacilityId && tab1LastFacilityId !== fid) {\n        clearTab1PinnedBaseline();\n      }\n      tab1LastFacilityId = fid;\n      currentLoan = allLoans.find(l => l.facility_id === fid);\n      if (!currentLoan) return;\n      secViewerState.loan = currentLoan;\n      syncTab1SearchDisplay();\n      updateTab1SeedButtonState();\n\n      // Update Key Metrics safely\n      document.getElementById('m-moodys').textContent = currentLoan.moodys_rating || '—';\n      const mStatus = currentLoan.moodys_watch_status || currentLoan.moodys_outlook;\n      document.getElementById('m-warf').textContent = mStatus ? `WARF ${currentLoan.moodys_warf || '—'} · ${mStatus}` : `WARF ${currentLoan.moodys_warf || '—'}`;\n      document.getElementById('m-sp').textContent = currentLoan.fitch_rating ? `${currentLoan.sp_rating || '—'} / ${currentLoan.fitch_rating}` : (currentLoan.sp_rating || '—');\n      const spStatus = currentLoan.sp_watch_status || currentLoan.sp_outlook;\n      document.getElementById('m-fitch').textContent = spStatus ? `S&P ${spStatus}` : `Fitch: ${currentLoan.fitch_rating || 'NR'}`;\n      const recStr = currentLoan.sp_recovery_rating ? `${currentLoan.sp_recovery_rate_pct}% (${currentLoan.sp_recovery_rating})` : (currentLoan.sp_recovery_rate_pct != null ? `${currentLoan.sp_recovery_rate_pct}%` : '—');\n      document.getElementById('m-rec').textContent = recStr;\n      const setCardCiteCue = (cardId, spanId, termKey) => {\n        const hasCite = findCitationIndexForTerm(termKey) >= 0;\n        const card = document.getElementById(cardId);\n        const span = document.getElementById(spanId);\n        if (span) span.textContent = hasCite ? '· Clause ↗' : '';\n        if (card) {\n          card.classList.toggle('cursor-pointer', hasCite);\n          card.classList.toggle('hover:bg-zinc-900/70', hasCite);\n          card.title = hasCite ? `Click to inspect ${termKey} clause in SEC Exhibit 10` : '';\n        }\n      };\n\n      document.getElementById('m-spread').textContent = currentLoan.spread_bps != null ? `+${currentLoan.spread_bps.toFixed(0)} bps` : '—';\n      setCardCiteCue('card-spread', 'm-spread-cite', 'Spread Over Index');\n      document.getElementById('m-floor').textContent = currentLoan.rate_floor_pct != null ? `${currentLoan.rate_floor_pct.toFixed(2)}%` : '—';\n      setCardCiteCue('card-floor', 'm-floor-cite', 'Rate Floor');\n      document.getElementById('m-maturity').textContent = currentLoan.maturity_date || '—';\n      const remTermYrs = currentLoan.remaining_term_years != null\n        ? Number(currentLoan.remaining_term_years)\n        : (currentLoan.maturity_date ? Math.max(0, (new Date(`${currentLoan.maturity_date}T00:00:00Z`) - new Date()) / (365.25 * 86400000)) : null);\n      const remTermEl = document.getElementById('m-rem-term');\n      if (remTermEl) {\n        remTermEl.textContent = remTermYrs != null ? `Remaining Term: ${remTermYrs.toFixed(1)} yrs` : '';\n      }\n      document.getElementById('m-eff').textContent = currentLoan.effective_date ? `Closed: ${currentLoan.effective_date}` : '—';\n      setCardCiteCue('card-maturity', 'm-maturity-cite', 'Maturity Date');\n      const findSpringingCiteIdx = (loan, scope) => {\n        if (!hasRealSecFiling(loan)) return -1;\n        const cits = loan.citations || [];\n        const scopeTag = scope === 'RCF' ? 'rcf' : 'tlb';\n        const scopedCandidates = [\n          `dates.springing_maturity.${scopeTag}`,\n          `dates.springing_maturity.${scopeTag}_detail`,\n          `springing_maturity.${scopeTag}_detail`,\n          `springing_maturity.${scopeTag}`,\n        ];\n        for (const fname of scopedCandidates) {\n          const idx = cits.findIndex(c => c.field_name === fname);\n          if (idx >= 0) return idx;\n        }\n        const allSm = cits.map((c, idx) => ({ c, idx })).filter(({ c }) => (\n          c.field_name === 'dates.springing_maturity' || c.field_name === 'springing_maturity'\n        ));\n        if (allSm.length > 1) {\n          const needle = scope === 'RCF' ? /revolv|rcf/i : /term loan|tlb|notes/i;\n          const match = allSm.find(({ c }) => needle.test(`${c.section_ref || ''} ${c.verbatim_snippet || ''}`));\n          if (match) return match.idx;\n        }\n        return findCitationIndexForTerm('Springing Maturity');\n      };\n      const renderSpringingBadgesHtml = (loan) => {\n        const smSum = loan.springing_maturity_summary;\n        if (!smSum || !smSum.has_trigger || !Array.isArray(smSum.badges) || smSum.badges.length === 0) {\n          return '';\n        }\n        return smSum.badges.map(b => {\n          const smCiteIdx = findSpringingCiteIdx(loan, b.scope);\n          const smCit = smCiteIdx >= 0 ? (loan.citations || [])[smCiteIdx] : null;\n          const cls = b.scope === 'TLB'\n            ? 'border-rose-500/40 bg-rose-950/50 text-rose-200 hover:border-rose-400'\n            : 'border-amber-500/40 bg-amber-950/50 text-amber-200 hover:border-amber-400';\n          if (smCit) {\n            const pageCue = smCit.page_number ? ` · Clause p. ${smCit.page_number} ↗` : ' · Clause ↗';\n            return `<button type=\"button\" onclick=\"event.stopPropagation(); openSecViewerByCiteIdx(${smCiteIdx}, 'Springing Maturity')\" class=\"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono border ${cls} transition text-left\" title=\"Click to highlight springing maturity proviso in SEC Exhibit 10\">${escapeHtml(b.label)}${pageCue}</button>`;\n          }\n          return `<span class=\"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono border ${cls}\">${escapeHtml(b.label)}</span>`;\n        }).join('');\n      };\n      const mSpringBox = document.getElementById('m-springing-badges');\n      if (mSpringBox) {\n        const badgesHtml = renderSpringingBadgesHtml(currentLoan);\n        mSpringBox.innerHTML = badgesHtml;\n        mSpringBox.classList.toggle('hidden', !badgesHtml);\n      }\n      document.getElementById('m-cov').textContent = currentLoan.is_cov_lite ? 'Cov-Lite' : 'Maintenance';\n      const covCiteIdx = findCitationIndexForTerm('Covenant Structure');\n      const mCovCite = document.getElementById('m-cov-cite');\n      if (mCovCite) {\n        const covCit = covCiteIdx >= 0 ? (currentLoan.citations || [])[covCiteIdx] : null;\n        mCovCite.textContent = covCit ? (covCit.page_number ? `· Clause p. ${covCit.page_number} ↗` : '· Clause ↗') : '';\n        mCovCite.classList.toggle('hidden', !covCit);\n      }\n      const ecfSum = currentLoan.ecf_sweep_summary;\n      document.getElementById('m-ecf').textContent = ecfSum\n        ? ecfSum.kpi_text\n        : (currentLoan.ecf_sweep_pct != null ? `${currentLoan.ecf_sweep_pct}%` : 'None');\n      const ecfHasCite = findCitationIndexForTerm('ECF Sweep') >= 0;\n      const cardEcf = document.getElementById('card-ecf');\n      const spanEcf = document.getElementById('m-ecf-cite');\n      if (spanEcf) spanEcf.textContent = ecfHasCite ? '· Clause ↗' : '';\n      if (cardEcf) {\n        const anyCite = ecfHasCite || covCiteIdx >= 0;\n        cardEcf.classList.toggle('cursor-pointer', anyCite);\n        cardEcf.classList.toggle('hover:bg-zinc-900/70', anyCite);\n        cardEcf.title = covCiteIdx >= 0\n          ? 'Click to inspect Covenant Structure clause in SEC Exhibit 10'\n          : (ecfHasCite ? 'Click to inspect ECF Sweep clause in SEC Exhibit 10' : '');\n      }\n      document.getElementById('t1-par-header').textContent = currentLoan.original_par ? `Par: $${Number(currentLoan.original_par).toLocaleString()}` : '—';\n\n      // Update Terms Table\n      const fmtAgencyMeta = (outlook, watch) => [outlook, watch].filter(Boolean).join(' · ') || '—';\n      const renderEcfSweepCell = (loan) => {\n        const es = loan.ecf_sweep_summary || {\n          has_ecf_sweep: loan.ecf_sweep_pct != null,\n          headline_pct: loan.ecf_sweep_pct,\n          step_downs_label: null,\n          de_minimis_label: null,\n          display_text: loan.ecf_sweep_pct != null ? `${loan.ecf_sweep_pct}%` : 'None / Not Specified',\n        };\n        if (!es.has_ecf_sweep) {\n          return '<span class=\"text-zinc-400\">None / Not Specified</span>';\n        }\n        const headlineHtml = `<span class=\"font-semibold text-zinc-100\">${escapeHtml(String(es.headline_pct))}%</span>`;\n        const stepHtml = es.step_downs_label\n          ? `<span class=\"text-zinc-300 text-[11px]\">(Step-downs: ${escapeHtml(es.step_downs_label)})</span>`\n          : '';\n        const dmHtml = es.de_minimis_label\n          ? `<span class=\"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono border border-zinc-700 bg-zinc-900 text-zinc-300\">${escapeHtml(es.de_minimis_label)}</span>`\n          : '';\n        return `<div class=\"flex flex-wrap items-center gap-1.5\">${headlineHtml}${stepHtml}${dmHtml}</div>`;\n      };\n      const renderCallProtectionCell = (loan) => {\n        const cp = loan.call_protection_summary || {\n          category: 'Freely Callable (Par)',\n          schedule_category: 'Freely Callable (Par)',\n          status: 'Par',\n          is_active: false,\n          is_make_whole: false,\n          schedule_detail: 'No call protection',\n          status_pill: 'Callable at Par',\n        };\n        if (cp.is_active) {\n          const pillCls = cp.is_make_whole\n            ? 'border-amber-500/40 bg-amber-950/50 text-amber-300'\n            : 'border-emerald-500/40 bg-emerald-950/50 text-emerald-300';\n          return `<div class=\"flex flex-wrap items-center gap-1.5\"><span class=\"font-semibold text-zinc-100\">${escapeHtml(cp.category)}</span><span class=\"text-zinc-400 text-[11px]\">· ${escapeHtml(cp.schedule_detail)}</span><span class=\"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono border ${pillCls}\">${escapeHtml(cp.status_pill)}</span></div>`;\n        }\n        if (cp.status === 'Expired') {\n          return `<div class=\"flex flex-wrap items-center gap-1.5\"><span class=\"font-semibold text-zinc-200\">Freely Callable (Par)</span><span class=\"text-zinc-500 text-[11px]\">· was ${escapeHtml(cp.schedule_detail)}</span><span class=\"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono border border-zinc-700 bg-zinc-900 text-zinc-400\">${escapeHtml(cp.status_pill)}</span></div>`;\n        }\n        return `<div class=\"flex flex-wrap items-center gap-1.5\"><span class=\"font-semibold text-zinc-200\">Freely Callable (Par)</span><span class=\"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono border border-zinc-800 bg-zinc-900/60 text-zinc-500\">${escapeHtml(cp.status_pill)}</span></div>`;\n      };\n      const terms = [\n        ['Facility ID', currentLoan.facility_id],\n        ['Borrower Name', currentLoan.borrower_name],\n        ['Country of Domicile', currentLoan.country_of_domicile || '—'],\n        ['Facility Type', currentLoan.facility_type],\n        ['Seniority / Security', currentLoan.seniority || '—'],\n        ['Moody\\'s Rating / CFR', `${currentLoan.moodys_rating || '—'}${currentLoan.moodys_cfr ? ` (CFR: ${currentLoan.moodys_cfr})` : ''}`],\n        ['Moody\\'s Outlook / Watch', fmtAgencyMeta(currentLoan.moodys_outlook, currentLoan.moodys_watch_status)],\n        ['Moody\\'s LGD / Recovery', `${currentLoan.moodys_lgd_assessment ? `${currentLoan.moodys_lgd_assessment} · ` : ''}${currentLoan.moodys_recovery_rate_pct != null ? `${currentLoan.moodys_recovery_rate_pct}%` : '—'}`],\n        ['S&P Rating / ICR', `${currentLoan.sp_rating || '—'}${currentLoan.sp_icr ? ` (ICR: ${currentLoan.sp_icr})` : ''}`],\n        ['S&P Outlook / CreditWatch', fmtAgencyMeta(currentLoan.sp_outlook, currentLoan.sp_watch_status)],\n        ['S&P Recovery', `${currentLoan.sp_recovery_rating ? `RR '${currentLoan.sp_recovery_rating}' · ` : ''}${currentLoan.sp_recovery_rate_pct != null ? `${currentLoan.sp_recovery_rate_pct}%` : '—'}`],\n        ['Fitch Rating / IDR', currentLoan.fitch_rating ? `${currentLoan.fitch_rating}${currentLoan.fitch_idr && currentLoan.fitch_idr !== currentLoan.fitch_rating ? ` (IDR: ${currentLoan.fitch_idr})` : ''}` : 'NR / Not Published'],\n        ['Fitch Outlook / Recovery', fmtAgencyMeta(currentLoan.fitch_outlook, currentLoan.fitch_recovery_rating ? `RR ${currentLoan.fitch_recovery_rating}` : null)],\n        ['Moody\\'s Industry', currentLoan.industry_moodys || '—'],\n        ['S&P Industry', currentLoan.industry_sp || '—'],\n        ['Fitch Industry', currentLoan.industry_fitch || '—'],\n        ['Original Par', `$${Number(currentLoan.original_par || 0).toLocaleString()}`],\n        ['Current Par', `$${Number(currentLoan.current_par || 0).toLocaleString()}`],\n        ...(currentLoan.oid_bps != null ? [['Original Issue Discount (OID)', `${Number(currentLoan.oid_bps)} bps`]] : []),\n        ['Maturity Date', (() => {\n          const matStr = escapeHtml(currentLoan.maturity_date || '—');\n          const remStr = remTermYrs != null ? ` <span class=\"text-emerald-300/90 text-[11px]\">(Remaining: ${remTermYrs.toFixed(1)} yrs)</span>` : '';\n          const sBadges = renderSpringingBadgesHtml(currentLoan);\n          return sBadges\n            ? `<div class=\"flex flex-wrap items-center gap-1.5\"><span>${matStr}${remStr}</span>${sBadges}</div>`\n            : `<span>${matStr}${remStr}</span>`;\n        })()],\n        ['Day Count Convention', currentLoan.day_count || 'Actual/360'],\n        ['Scheduled Amortization', currentLoan.scheduled_amort_pct_annual != null\n          ? (Number(currentLoan.scheduled_amort_pct_annual) === 0 ? '0% / yr (Bullet)' : `${currentLoan.scheduled_amort_pct_annual}% / yr`)\n          : '—'],\n        ['ECF Sweep', renderEcfSweepCell(currentLoan)],\n        ['Call Protection', renderCallProtectionCell(currentLoan)],\n        ['Filing Source URL', hasRealSecFiling(currentLoan)\n          ? `<a href=\"${currentLoan.source_filing_url}\" target=\"_blank\" class=\"text-zinc-100 underline hover:text-zinc-400\">SEC EDGAR Exhibit 10 Link &rarr;</a>`\n          : `<span class=\"text-zinc-400\">Legacy Seed Sample (no live EDGAR filing URL)</span>`]\n      ];\n      const tbody = document.getElementById('t1-terms-body');\n      tbody.innerHTML = terms.map(([k, v]) => {\n        const citeIdx = findCitationIndexForTerm(k);\n        const cit = citeIdx >= 0 ? currentLoan.citations[citeIdx] : null;\n        const badge = cit\n          ? `<button onclick=\"openSecViewerByCiteIdx(${citeIdx}, '${escapeHtml(k)}')\" class=\"ml-2 inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono border border-zinc-700 text-zinc-300 hover:border-amber-400/70 hover:text-amber-200 transition\" title=\"Inspect &amp; highlight verbatim clause in SEC Exhibit 10\">${cit.page_number ? `Clause p. ${cit.page_number}` : 'Clause'} &nearr;</button>`\n          : '';\n        return `\n          <tr class=\"hover:bg-zinc-800/40\">\n            <td class=\"py-2 px-3 font-semibold text-zinc-400 w-1/3\">${k}</td>\n            <td class=\"py-2 px-3 text-zinc-200 font-mono-data\"><div class=\"flex items-center justify-between gap-2\"><span>${v}</span>${badge}</div></td>\n          </tr>\n        `;\n      }).join('');\n\n      // Update Citations List\n      const citeBox = document.getElementById('t1-citations-list');\n      const citations = currentLoan.citations || [];\n      document.getElementById('t1-cite-count').textContent = `${citations.length} verified quotes`;\n      if (citations.length === 0) {\n        citeBox.innerHTML = '<div class=\"text-xs font-mono text-zinc-500 py-4\">No citations recorded for this facility.</div>';\n      } else {\n        citeBox.innerHTML = citations.map((c, idx) => {\n          const canOpenInDoc = c.field_name !== 'credit_rating' && hasRealSecFiling(currentLoan);\n          const openBtn = canOpenInDoc\n            ? `<button onclick=\"openSecViewerByCiteIdx(${idx})\" class=\"text-[10px] font-mono px-2 py-0.5 border border-zinc-700 text-zinc-200 hover:border-amber-400/70 hover:text-amber-200 transition\">${c.page_number ? `Highlight p. ${c.page_number}` : 'Highlight in Filing'} &rarr;</button>`\n            : '';\n          return `\n            <div class=\"border-l-2 border-zinc-400 bg-zinc-900/70 p-3\">\n              <div class=\"flex justify-between items-center gap-2 text-xs mb-1 font-mono\">\n                <span class=\"font-semibold text-zinc-200\">&sect; ${escapeHtml(c.section_ref)}</span>\n                <div class=\"flex items-center gap-2 shrink-0\">\n                  ${c.page_number ? `<span class=\"text-zinc-400 text-[10px]\">p. ${c.page_number}</span>` : ''}\n                  ${openBtn}\n                </div>\n              </div>\n              <div class=\"text-[11px] font-mono text-zinc-400 mb-1\">Field: <span class=\"text-zinc-200 font-semibold\">${escapeHtml(c.field_name)}</span></div>\n              <blockquote class=\"text-xs italic text-zinc-300 pl-1 py-0.5 font-legal leading-relaxed\">\"${escapeHtml(c.verbatim_snippet)}\"</blockquote>\n            </div>\n          `;\n        }).join('');\n      }\n\n      updateTab1StressStatus();\n      recalculateCashflows();\n    }\n\n    const TAB1_BASE_CASE = { sofr: 4.5, cpr: 15.0, cdr: 2.0 };\n    const TAB1_CONTROL_SPECS = {\n      sofr: { inputId: 't1-sofr', sliderId: 't1-sofr-slider', min: 0, max: 10, fallback: TAB1_BASE_CASE.sofr },\n      cpr: { inputId: 't1-cpr', sliderId: 't1-cpr-slider', min: 0, max: 60, fallback: TAB1_BASE_CASE.cpr },\n      cdr: { inputId: 't1-cdr', sliderId: 't1-cdr-slider', min: 0, max: 25, fallback: TAB1_BASE_CASE.cdr },\n    };\n    let tab1StartFromOrigination = false;\n    let tab1PinnedBaseline = null;\n    let tab1LastProjection = null;\n    let tab1LastFacilityId = null;\n    let tab1RecalcTimer = null;\n    let tab1CashflowReqSeq = 0;\n\n    function parseNumericInput(id, fallback) {\n      const val = parseFloat(document.getElementById(id).value);\n      return Number.isFinite(val) ? val : fallback;\n    }\n\n    function formatScenarioValue(key, val) {\n      if (key === 'sofr') {\n        return Number.isInteger(Math.round(val * 100) / 10) ? val.toFixed(1) : val.toFixed(2);\n      }\n      return val.toFixed(1);\n    }\n\n    function scheduleTab1Recalculate(delayMs = 120) {\n      if (tab1RecalcTimer) clearTimeout(tab1RecalcTimer);\n      tab1RecalcTimer = setTimeout(() => {\n        tab1RecalcTimer = null;\n        recalculateCashflows();\n      }, delayMs);\n    }\n\n    function handleTab1SliderInput(key) {\n      const spec = TAB1_CONTROL_SPECS[key];\n      if (!spec) return;\n      const val = parseNumericInput(spec.sliderId, spec.fallback);\n      document.getElementById(spec.inputId).value = formatScenarioValue(key, val);\n      updateTab1StressStatus();\n      scheduleTab1Recalculate(120);\n    }\n\n    function handleTab1NumericInput(key) {\n      const spec = TAB1_CONTROL_SPECS[key];\n      if (!spec) return;\n      const raw = parseFloat(document.getElementById(spec.inputId).value);\n      const sliderEl = document.getElementById(spec.sliderId);\n      if (sliderEl && Number.isFinite(raw)) {\n        sliderEl.value = String(Math.min(spec.max, Math.max(spec.min, raw)));\n      }\n      updateTab1StressStatus();\n      scheduleTab1Recalculate(180);\n    }\n\n    function updateTab1StressStatus() {\n      const sofr = parseNumericInput('t1-sofr', TAB1_BASE_CASE.sofr);\n      const cpr = parseNumericInput('t1-cpr', TAB1_BASE_CASE.cpr);\n      const cdr = parseNumericInput('t1-cdr', TAB1_BASE_CASE.cdr);\n      const diffs = [];\n      if (Math.abs(sofr - TAB1_BASE_CASE.sofr) > 1e-6) diffs.push(`SOFR ${Number(sofr.toFixed(2))}%`);\n      if (Math.abs(cpr - TAB1_BASE_CASE.cpr) > 1e-6) diffs.push(`${Number(cpr.toFixed(1))}% CPR`);\n      if (Math.abs(cdr - TAB1_BASE_CASE.cdr) > 1e-6) diffs.push(`${Number(cdr.toFixed(1))}% CDR`);\n\n      const pill = document.getElementById('t1-stress-pill');\n      const resetBtn = document.getElementById('t1-reset-base-btn');\n      if (pill) {\n        if (diffs.length > 0) {\n          pill.innerHTML = `<span>Stress Active</span><button type=\"button\" onclick=\"resetTab1ToBaseCase()\" class=\"underline text-amber-200 hover:text-white font-semibold\">&middot; Reset</button>`;\n          pill.title = `Custom Stress Active: ${diffs.join(' / ')}`;\n          pill.classList.remove('hidden');\n        } else {\n          pill.innerHTML = '';\n          pill.title = '';\n          pill.classList.add('hidden');\n        }\n      }\n      if (resetBtn) {\n        resetBtn.classList.toggle('border-amber-500/50', diffs.length > 0);\n        resetBtn.classList.toggle('text-amber-200', diffs.length > 0);\n      }\n    }\n\n    function resetTab1ToBaseCase() {\n      if (tab1RecalcTimer) {\n        clearTimeout(tab1RecalcTimer);\n        tab1RecalcTimer = null;\n      }\n      document.getElementById('t1-sofr').value = TAB1_BASE_CASE.sofr.toFixed(1);\n      document.getElementById('t1-cpr').value = TAB1_BASE_CASE.cpr.toFixed(1);\n      document.getElementById('t1-cdr').value = TAB1_BASE_CASE.cdr.toFixed(1);\n      const sofrSlider = document.getElementById('t1-sofr-slider');\n      const cprSlider = document.getElementById('t1-cpr-slider');\n      const cdrSlider = document.getElementById('t1-cdr-slider');\n      if (sofrSlider) sofrSlider.value = TAB1_BASE_CASE.sofr.toFixed(1);\n      if (cprSlider) cprSlider.value = TAB1_BASE_CASE.cpr.toFixed(1);\n      if (cdrSlider) cdrSlider.value = TAB1_BASE_CASE.cdr.toFixed(1);\n      updateTab1StressStatus();\n      recalculateCashflows();\n    }\n\n    function setTab1ValuationMode(fromOrigination) {\n      tab1StartFromOrigination = Boolean(fromOrigination);\n      const remBtn = document.getElementById('cf-mode-remaining-btn');\n      const origBtn = document.getElementById('cf-mode-origination-btn');\n      if (remBtn && origBtn) {\n        remBtn.className = !tab1StartFromOrigination\n          ? 'px-2 py-1 bg-zinc-100 text-zinc-950 font-semibold transition'\n          : 'px-2 py-1 text-zinc-300 hover:text-white transition';\n        origBtn.className = tab1StartFromOrigination\n          ? 'px-2 py-1 bg-zinc-100 text-zinc-950 font-semibold transition'\n          : 'px-2 py-1 text-zinc-300 hover:text-white transition';\n      }\n      recalculateCashflows();\n    }\n\n    function formatCompactUsd(amount) {\n      const abs = Math.abs(amount || 0);\n      if (abs >= 1e9) return `$${(amount / 1e9).toFixed(2)}B`;\n      if (abs >= 1e6) return `$${(amount / 1e6).toFixed(2)}M`;\n      if (abs >= 1e3) return `$${(amount / 1e3).toFixed(1)}K`;\n      return `$${Math.round(amount || 0).toLocaleString()}`;\n    }\n\n    function formatSignedCompactUsd(delta) {\n      if (!Number.isFinite(delta) || Math.abs(delta) < 1) return '$0';\n      const sign = delta > 0 ? '+' : '-';\n      const abs = Math.abs(delta);\n      if (abs >= 1e9) return `${sign}$${(abs / 1e9).toFixed(2)}B`;\n      if (abs >= 1e6) return `${sign}$${(abs / 1e6).toFixed(1)}M`;\n      if (abs >= 1e3) return `${sign}$${(abs / 1e3).toFixed(1)}K`;\n      return `${sign}$${Math.round(abs).toLocaleString()}`;\n    }\n\n    function formatSignedWalDelta(delta) {\n      if (!Number.isFinite(delta) || Math.abs(delta) < 0.005) return '0.00 yrs';\n      return `${delta > 0 ? '+' : '-'}${Math.abs(delta).toFixed(2)} yrs`;\n    }\n\n    function updateTab1PinButtonUi() {\n      const btn = document.getElementById('cf-pin-baseline-btn');\n      const statusEl = document.getElementById('cf-pin-status');\n      if (!btn || !statusEl) return;\n      if (tab1PinnedBaseline) {\n        btn.textContent = 'Unpin Baseline';\n        btn.className = 'w-full px-2.5 py-1.5 border border-sky-500/60 bg-sky-950/50 hover:bg-sky-900/50 text-sky-200 text-[10px] font-mono uppercase tracking-wider font-semibold transition';\n        const modeTag = tab1PinnedBaseline.valuationMode === 'origination' ? 'Orig' : 'Today';\n        statusEl.textContent = `Pinned: SOFR ${Number(tab1PinnedBaseline.sofrPct).toFixed(2).replace(/\\.00$/, '.0')}% · ${Number(tab1PinnedBaseline.cprPct).toFixed(0)}% CPR · ${Number(tab1PinnedBaseline.cdrPct).toFixed(1)}% CDR (${modeTag})`;\n        statusEl.classList.remove('hidden');\n      } else {\n        btn.textContent = 'Pin Baseline';\n        btn.className = 'w-full px-2.5 py-1.5 border border-zinc-700 bg-[#18181b] hover:bg-zinc-800 text-zinc-100 text-[10px] font-mono uppercase tracking-wider font-semibold transition';\n        statusEl.textContent = '';\n        statusEl.classList.add('hidden');\n      }\n    }\n\n    function clearTab1PinnedBaseline() {\n      tab1PinnedBaseline = null;\n      updateTab1PinButtonUi();\n      ['cf-wal-delta', 'cf-int-delta', 'cf-prin-delta', 'cf-rec-delta'].forEach(id => {\n        const el = document.getElementById(id);\n        if (el) {\n          el.textContent = '';\n          el.classList.add('hidden');\n        }\n      });\n    }\n\n    function setDeltaBadge(id, text, tone) {\n      const el = document.getElementById(id);\n      if (!el) return;\n      el.classList.remove('hidden', 'text-emerald-400', 'text-rose-400', 'text-amber-300', 'text-zinc-500');\n      el.classList.add(tone);\n      el.textContent = text;\n    }\n\n    function renderTab1BaselineDeltas(proj) {\n      if (!tab1PinnedBaseline || !proj || !currentLoan || tab1PinnedBaseline.facilityId !== currentLoan.facility_id) {\n        return;\n      }\n      const dWal = Number(proj.weighted_average_life_years ?? 0) - Number(tab1PinnedBaseline.wal ?? 0);\n      const dInt = Number(proj.total_interest ?? 0) - Number(tab1PinnedBaseline.totalInterest ?? 0);\n      const dPrin = Number(proj.total_principal_repaid ?? 0) - Number(tab1PinnedBaseline.totalPrincipalRepaid ?? 0);\n      const dRec = Number(proj.total_recoveries ?? 0) - Number(tab1PinnedBaseline.totalRecoveries ?? 0);\n\n      setDeltaBadge(\n        'cf-wal-delta',\n        `Δ ${formatSignedWalDelta(dWal)}`,\n        Math.abs(dWal) < 0.005 ? 'text-zinc-500' : 'text-amber-300'\n      );\n      setDeltaBadge(\n        'cf-int-delta',\n        `Δ ${formatSignedCompactUsd(dInt)}`,\n        Math.abs(dInt) < 1 ? 'text-zinc-500' : (dInt > 0 ? 'text-emerald-400' : 'text-rose-400')\n      );\n      setDeltaBadge(\n        'cf-prin-delta',\n        `Δ ${formatSignedCompactUsd(dPrin)}`,\n        Math.abs(dPrin) < 1 ? 'text-zinc-500' : (dPrin > 0 ? 'text-emerald-400' : 'text-rose-400')\n      );\n      setDeltaBadge(\n        'cf-rec-delta',\n        `Δ ${formatSignedCompactUsd(dRec)}`,\n        Math.abs(dRec) < 1 ? 'text-zinc-500' : 'text-amber-300'\n      );\n    }\n\n    function toggleTab1PinBaseline() {\n      if (tab1PinnedBaseline) {\n        clearTab1PinnedBaseline();\n        return;\n      }\n      if (!currentLoan || !tab1LastProjection) return;\n      tab1PinnedBaseline = {\n        facilityId: currentLoan.facility_id,\n        wal: Number(tab1LastProjection.weighted_average_life_years ?? 0),\n        totalInterest: Number(tab1LastProjection.total_interest ?? 0),\n        totalPrincipalRepaid: Number(tab1LastProjection.total_principal_repaid ?? 0),\n        totalRecoveries: Number(tab1LastProjection.total_recoveries ?? 0),\n        sofrPct: Number(tab1LastProjection._inputs?.sofr_pct ?? TAB1_BASE_CASE.sofr),\n        cprPct: Number(tab1LastProjection._inputs?.cpr_pct ?? TAB1_BASE_CASE.cpr),\n        cdrPct: Number(tab1LastProjection._inputs?.cdr_pct ?? TAB1_BASE_CASE.cdr),\n        valuationMode: tab1LastProjection.valuation_mode || 'remaining',\n      };\n      updateTab1PinButtonUi();\n      renderTab1BaselineDeltas(tab1LastProjection);\n    }\n\n    async function recalculateCashflows() {\n      if (!currentLoan) return;\n      updateTab1StressStatus();\n      const reqSeq = ++tab1CashflowReqSeq;\n      const facilityAtRequest = currentLoan.facility_id;\n      const payload = {\n        facility_id: facilityAtRequest,\n        sofr_pct: parseNumericInput('t1-sofr', TAB1_BASE_CASE.sofr),\n        cpr_pct: parseNumericInput('t1-cpr', TAB1_BASE_CASE.cpr),\n        cdr_pct: parseNumericInput('t1-cdr', TAB1_BASE_CASE.cdr),\n        start_from_origination: tab1StartFromOrigination,\n      };\n\n      try {\n        const res = await fetch('/api/project_loan_cashflows', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify(payload)\n        });\n        const proj = await res.json();\n        if (!res.ok) {\n          throw new Error(proj.detail || 'Cashflow projection failed');\n        }\n        if (reqSeq !== tab1CashflowReqSeq || !currentLoan || currentLoan.facility_id !== facilityAtRequest) {\n          return;\n        }\n        proj._inputs = payload;\n        tab1LastProjection = proj;\n\n        document.getElementById('cf-wal').textContent = proj.weighted_average_life_years != null ? `${proj.weighted_average_life_years.toFixed(2)} yrs` : '—';\n        const walMetaEl = document.getElementById('cf-wal-meta');\n        if (walMetaEl) {\n          walMetaEl.textContent = proj.valuation_mode === 'origination'\n            ? `From closing (${proj.valuation_date || currentLoan.effective_date || '—'})`\n            : `Remaining from ${proj.valuation_date || 'today'} (${Number(proj.remaining_term_years ?? 0).toFixed(1)}y to mat)`;\n        }\n        document.getElementById('cf-int').textContent = `$${Math.round(proj.total_interest || 0).toLocaleString()}`;\n        document.getElementById('cf-prin').textContent = `$${Math.round(proj.total_principal_repaid || 0).toLocaleString()}`;\n        document.getElementById('cf-rec').textContent = `$${Math.round(proj.total_recoveries || 0).toLocaleString()}`;\n        renderTab1BaselineDeltas(proj);\n\n        // Floor Benefit Badge & Interest Meta\n        const badgeEl = document.getElementById('cf-floor-badge');\n        const intMetaEl = document.getElementById('cf-int-meta');\n        const floorPct = Number(proj.rate_floor_pct ?? currentLoan.rate_floor_pct ?? 0);\n        const floorBenefitBps = Number(proj.floor_benefit_bps || 0);\n        const floorBenefitUsd = Number(proj.total_floor_benefit || 0);\n        const q1Period = (proj.periods && proj.periods[0]) || null;\n        const q1AllIn = q1Period && q1Period.all_in_rate_pct != null ? Number(q1Period.all_in_rate_pct) : null;\n\n        if (badgeEl) {\n          badgeEl.classList.remove(\n            'hidden',\n            'border-emerald-500/40', 'bg-emerald-950/50', 'text-emerald-300',\n            'border-zinc-700', 'bg-zinc-900', 'text-zinc-400',\n            'border-zinc-800', 'bg-zinc-900/60', 'text-zinc-500'\n          );\n          if (proj.floor_active && floorBenefitUsd > 0) {\n            const bpsStr = Number.isInteger(floorBenefitBps) ? `${floorBenefitBps}` : floorBenefitBps.toFixed(1);\n            badgeEl.classList.add('border-emerald-500/40', 'bg-emerald-950/50', 'text-emerald-300');\n            badgeEl.textContent = `FLOOR ACTIVE · +${bpsStr} bps (+${formatCompactUsd(floorBenefitUsd)})`;\n            badgeEl.title = `Contractual ${floorPct.toFixed(2)}% floor overrides ${payload.sofr_pct.toFixed(2)}% SOFR, protecting +$${Math.round(floorBenefitUsd).toLocaleString()} in interest.`;\n          } else if (floorPct > 0) {\n            badgeEl.classList.add('border-zinc-700', 'bg-zinc-900', 'text-zinc-400');\n            badgeEl.textContent = `FLOOR ${floorPct.toFixed(2)}% · INACTIVE`;\n            badgeEl.title = `SOFR (${payload.sofr_pct.toFixed(2)}%) is at or above the ${floorPct.toFixed(2)}% contractual floor.`;\n          } else {\n            badgeEl.classList.add('border-zinc-800', 'bg-zinc-900/60', 'text-zinc-500');\n            badgeEl.textContent = 'NO FLOOR (0.00%)';\n            badgeEl.title = 'Facility has a 0.00% contractual SOFR floor.';\n          }\n        }\n        if (intMetaEl) {\n          intMetaEl.classList.remove('text-emerald-400', 'text-zinc-500');\n          if (proj.floor_active && floorBenefitUsd > 0) {\n            intMetaEl.classList.add('text-emerald-400');\n            intMetaEl.textContent = `Includes +$${Math.round(floorBenefitUsd).toLocaleString()} floor benefit (${floorPct.toFixed(2)}% floor)`;\n          } else {\n            intMetaEl.classList.add('text-zinc-500');\n            const allInStr = q1AllIn != null ? `All-in Q1: ${q1AllIn.toFixed(2)}%` : 'Projected interest';\n            intMetaEl.textContent = floorPct > 0\n              ? `${allInStr} · ${floorPct.toFixed(2)}% floor inactive`\n              : `${allInStr} · 0.00% floor`;\n          }\n        }\n\n        const prinMetaEl = document.getElementById('cf-prin-meta');\n        const prepayPenaltyUsd = Number(proj.total_prepayment_penalty || 0);\n        if (prinMetaEl) {\n          prinMetaEl.classList.remove('text-amber-300', 'text-zinc-500');\n          if (prepayPenaltyUsd > 0) {\n            prinMetaEl.classList.add('text-amber-300');\n            prinMetaEl.textContent = proj.is_make_whole_facility\n              ? `+$${Math.round(prepayPenaltyUsd).toLocaleString()} call penalties modeled (Make-Whole / Hard Call active; voluntary CPR refi unlikely)`\n              : `Includes +$${Math.round(prepayPenaltyUsd).toLocaleString()} call premium on early CPR prepayments`;\n          } else if (proj.is_make_whole_facility && proj.call_protection_active) {\n            prinMetaEl.classList.add('text-amber-300');\n            prinMetaEl.textContent = 'Make-Whole / Hard Call active (early refi penalized)';\n          } else {\n            prinMetaEl.classList.add('text-zinc-500');\n            prinMetaEl.textContent = 'Callable at par / no CPR call penalty';\n          }\n        }\n\n        // Render Monochromatic Dark Chart.js\n        const periods = (proj.periods || []).slice(0, 28);\n        const labels = periods.map(p => `Q${p.period}`);\n        const intData = periods.map(p => p.interest_due || 0);\n        const amortData = periods.map(p => p.scheduled_amortization || 0);\n        const cprData = periods.map(p => p.prepayment_cpr || 0);\n        const recData = periods.map(p => p.recoveries || 0);\n\n        if (t1Chart) {\n          t1Chart.data.labels = labels;\n          t1Chart.data.datasets[0].data = intData;\n          t1Chart.data.datasets[1].data = amortData;\n          t1Chart.data.datasets[2].data = cprData;\n          t1Chart.data.datasets[3].data = recData;\n          t1Chart.update('none');\n        } else {\n          const ctx = document.getElementById('t1-chart').getContext('2d');\n          t1Chart = new Chart(ctx, {\n            type: 'bar',\n            data: {\n              labels,\n              datasets: [\n                { label: 'Interest', data: intData, backgroundColor: '#f4f4f5' },\n                { label: 'Amortization', data: amortData, backgroundColor: '#a1a1aa' },\n                { label: 'CPR Prepay', data: cprData, backgroundColor: '#52525b' },\n                { label: 'Recoveries', data: recData, backgroundColor: '#3f3f46' },\n              ]\n            },\n            options: {\n              responsive: true,\n              maintainAspectRatio: false,\n              plugins: {\n                legend: {\n                  position: 'top',\n                  align: 'end',\n                  labels: {\n                    boxWidth: 10,\n                    font: { family: 'ui-monospace, monospace', size: 10 },\n                    color: '#a1a1aa'\n                  }\n                }\n              },\n              scales: {\n                x: {\n                  stacked: true,\n                  grid: { display: false },\n                  ticks: { font: { family: 'ui-monospace, monospace', size: 10 }, color: '#71717a' }\n                },\n                y: {\n                  stacked: true,\n                  grid: { color: '#27272a' },\n                  ticks: {\n                    font: { family: 'ui-monospace, monospace', size: 10 },\n                    color: '#71717a',\n                    callback: v => `$${(v/1e6).toFixed(1)}M`\n                  }\n                }\n              }\n            }\n          });\n        }\n      } catch (err) {\n        console.error('Cashflow error:', err);\n      }\n    }\n\n    const SEED_STORAGE_KEY = 'bsl_seed_portfolio_v1';\n    const seedState = {\n      items: [],\n      preview: null,\n      dropdownOpen: false,\n      filtered: [],\n      activeIdx: 0,\n      showAll: true,\n      reqSeq: 0,\n    };\n\n    function getSeedMandateInputs() {\n      return {\n        target_pool_par: parseNumericInput('opt-par', 400000000),\n        min_was_bps: parseNumericInput('opt-was', 250),\n        max_warf: Math.round(parseNumericInput('opt-warf', 2800)),\n        min_warr_pct: parseNumericInput('opt-warr', 44.0),\n        max_single_obligor_pct: parseNumericInput('opt-obligor', 8.0),\n        max_single_industry_pct: parseNumericInput('opt-industry', 25.0),\n        max_ccc_bucket_pct: parseNumericInput('opt-ccc', 7.5),\n        max_cov_lite_pct: parseNumericInput('opt-cov', 75.0),\n      };\n    }\n\n    function getActiveSeedAllocationsPayload() {\n      return seedState.items.map(it => ({\n        facility_id: it.facility_id,\n        allocated_par: Number(it.allocated_par || 0),\n        lock_mode: it.lock_mode === 'min' ? 'min' : 'exact',\n      }));\n    }\n\n    function saveSeedPortfolioToStorage() {\n      try {\n        localStorage.setItem(SEED_STORAGE_KEY, JSON.stringify(seedState.items));\n      } catch (e) {}\n    }\n\n    function loadSeedPortfolioFromStorage() {\n      try {\n        const raw = localStorage.getItem(SEED_STORAGE_KEY);\n        if (!raw) {\n          seedState.items = [];\n          return;\n        }\n        const parsed = JSON.parse(raw);\n        if (!Array.isArray(parsed)) {\n          seedState.items = [];\n          return;\n        }\n        const byId = new Map(allLoans.map(l => [l.facility_id, l]));\n        const seen = new Set();\n        seedState.items = [];\n        parsed.forEach(entry => {\n          const fid = entry && entry.facility_id;\n          if (!fid || seen.has(fid) || !byId.has(fid)) return;\n          seen.add(fid);\n          seedState.items.push({\n            facility_id: fid,\n            allocated_par: Math.max(0, Number(entry.allocated_par || 20000000)),\n            lock_mode: entry.lock_mode === 'min' ? 'min' : 'exact',\n          });\n        });\n      } catch (e) {\n        seedState.items = [];\n      }\n    }\n\n    function syncSeedTargetPar(val) {\n      const optPar = document.getElementById('opt-par');\n      if (optPar && val !== undefined && val !== '') optPar.value = val;\n      renderSeedTable();\n      refreshSeedPreview();\n    }\n\n    function onOptParChanged(val) {\n      const syncEl = document.getElementById('seed-target-par-sync');\n      if (syncEl && val !== undefined && val !== '') syncEl.value = val;\n      updateSeedBannersAcrossTabs();\n      refreshSeedPreview();\n    }\n\n    function computeDefaultSeedPar(loan) {\n      const rawDefault = parseNumericInput('seed-default-par', 20000000);\n      const mandate = getSeedMandateInputs();\n      const obligorCap = mandate.target_pool_par * (mandate.max_single_obligor_pct / 100.0);\n      const avail = Number(loan.current_par || rawDefault);\n      return Math.max(1000000, Math.round(Math.min(rawDefault, obligorCap, avail)));\n    }\n\n    function updateTab1SeedButtonState() {\n      const btn = document.getElementById('t1-add-seed-btn');\n      if (!btn || !currentLoan) return;\n      const inSeed = seedState.items.some(it => it.facility_id === currentLoan.facility_id);\n      if (inSeed) {\n        btn.textContent = '✓ In Seed Pool (Tab 2)';\n        btn.className = 'shrink-0 px-2.5 py-1.5 border border-emerald-400 bg-emerald-950/60 text-emerald-200 text-[10px] uppercase tracking-wider font-semibold transition';\n      } else {\n        btn.textContent = '+ Add to Seed (Tab 2)';\n        btn.className = 'shrink-0 px-2.5 py-1.5 border border-emerald-500/40 bg-emerald-950/40 hover:bg-emerald-900/50 text-emerald-300 text-[10px] uppercase tracking-wider font-semibold transition';\n      }\n    }\n\n    function addFacilityToSeed(fid, parOverride = null, modeOverride = null) {\n      const loan = allLoans.find(l => l.facility_id === fid);\n      if (!loan) return false;\n      const existing = seedState.items.find(it => it.facility_id === fid);\n      if (existing) {\n        return false;\n      }\n      const par = parOverride != null ? Number(parOverride) : computeDefaultSeedPar(loan);\n      const modeEl = document.getElementById('seed-default-mode');\n      const mode = modeOverride || (modeEl ? modeEl.value : 'exact');\n      seedState.items.push({\n        facility_id: fid,\n        allocated_par: par,\n        lock_mode: mode === 'min' ? 'min' : 'exact',\n      });\n      saveSeedPortfolioToStorage();\n      updateTab1SeedButtonState();\n      renderSeedTable();\n      refreshSeedPreview();\n      return true;\n    }\n\n    function addCurrentLoanToSeed(stayOnTab1 = false) {\n      if (!currentLoan) return;\n      const added = addFacilityToSeed(currentLoan.facility_id);\n      if (!added && stayOnTab1) {\n        switchTab('tab2');\n      } else if (!stayOnTab1) {\n        renderSeedTable();\n        refreshSeedPreview();\n      }\n    }\n\n    function loadSampleSeedStarter() {\n      const candidates = [];\n      const seenIndustries = new Set();\n      const seenBorrowers = new Set();\n      for (const loan of allLoans) {\n        if ((loan.current_par || 0) < 20000000) continue;\n        if (loan.moodys_rating && loan.moodys_rating.startsWith('Caa')) continue;\n        if (seenBorrowers.has(loan.borrower_name) || seenIndustries.has(loan.industry_moodys)) continue;\n        seenBorrowers.add(loan.borrower_name);\n        seenIndustries.add(loan.industry_moodys);\n        candidates.push(loan);\n        if (candidates.length >= 4) break;\n      }\n      if (candidates.length === 0) return;\n      const mandate = getSeedMandateInputs();\n      const maxSingle = Math.floor(mandate.target_pool_par * (mandate.max_single_obligor_pct / 100.0));\n      const starterPar = Math.min(25000000, maxSingle);\n      seedState.items = candidates.map((loan, idx) => ({\n        facility_id: loan.facility_id,\n        allocated_par: Math.min(starterPar, Math.round(loan.current_par || starterPar)),\n        lock_mode: idx < 2 ? 'exact' : 'min',\n      }));\n      saveSeedPortfolioToStorage();\n      updateTab1SeedButtonState();\n      renderSeedTable();\n      refreshSeedPreview();\n    }\n\n    function updateSeedItemPar(idx, rawVal) {\n      const item = seedState.items[idx];\n      if (!item) return;\n      const parsed = Number(rawVal);\n      if (!Number.isFinite(parsed) || parsed < 0) return;\n      item.allocated_par = parsed;\n      saveSeedPortfolioToStorage();\n      renderSeedTable();\n      refreshSeedPreview();\n    }\n\n    function setSeedItemMode(idx, mode) {\n      const item = seedState.items[idx];\n      if (!item) return;\n      item.lock_mode = mode === 'min' ? 'min' : 'exact';\n      saveSeedPortfolioToStorage();\n      renderSeedTable();\n      refreshSeedPreview();\n    }\n\n    function removeSeedItem(idx) {\n      seedState.items.splice(idx, 1);\n      saveSeedPortfolioToStorage();\n      updateTab1SeedButtonState();\n      renderSeedTable();\n      refreshSeedPreview();\n    }\n\n    function clearSeedPortfolio() {\n      seedState.items = [];\n      saveSeedPortfolioToStorage();\n      updateTab1SeedButtonState();\n      renderSeedTable();\n      refreshSeedPreview();\n    }\n\n    function inspectSeedLoanInTab1(fid) {\n      switchTab('tab1');\n      selectTab1LoanById(fid);\n    }\n\n    function renderSeedTable() {\n      const tbody = document.getElementById('seed-tbody');\n      const countEl = document.getElementById('seed-row-count');\n      const badgeEl = document.getElementById('nav-seed-count');\n      if (!tbody) return;\n\n      const mandate = getSeedMandateInputs();\n      const targetPar = Math.max(1, mandate.target_pool_par);\n      const syncInput = document.getElementById('seed-target-par-sync');\n      if (syncInput && document.activeElement !== syncInput) {\n        syncInput.value = mandate.target_pool_par;\n      }\n\n      const n = seedState.items.length;\n      if (countEl) countEl.textContent = `${n} facilit${n === 1 ? 'y' : 'ies'} anchored`;\n      if (badgeEl) {\n        badgeEl.textContent = `${n}`;\n        badgeEl.classList.toggle('hidden', n === 0);\n      }\n\n      if (n === 0) {\n        tbody.innerHTML = `\n          <tr>\n            <td colspan=\"8\" class=\"p-6 text-center text-xs font-mono text-zinc-500\">\n              No seed loans selected yet. Search above, click &ldquo;+ Add Current Tab 1 Loan&rdquo;, or load the 4-Loan Starter to begin constructing your CLO ramp-up.\n            </td>\n          </tr>`;\n        updateSeedBannersAcrossTabs();\n        return;\n      }\n\n      const byId = new Map(allLoans.map(l => [l.facility_id, l]));\n      tbody.innerHTML = seedState.items.map((item, idx) => {\n        const loan = byId.get(item.facility_id) || { facility_id: item.facility_id, borrower_name: item.facility_id };\n        const wtPct = (Number(item.allocated_par || 0) / targetPar) * 100.0;\n        const isExact = item.lock_mode !== 'min';\n        const isCcc = (loan.moodys_rating || '').startsWith('Caa') || (loan.sp_rating || '').startsWith('CCC');\n        const covTag = loan.is_cov_lite ? 'Cov-Lite' : 'Covenanted';\n        const tags = [loan.industry_moodys || '—', covTag];\n        if (isCcc) tags.push('CCC');\n        const wtWarn = wtPct > mandate.max_single_obligor_pct + 1e-4 ? 'text-rose-400 font-semibold' : 'text-zinc-300';\n        const availPar = Number(loan.current_par || 0);\n        const parWarn = item.allocated_par > availPar + 1 ? 'border-rose-500 text-rose-300' : 'border-zinc-700 text-zinc-100';\n\n        return `\n          <tr class=\"hover:bg-zinc-900/40\">\n            <td class=\"p-2.5\">\n              <div class=\"font-semibold text-zinc-100\">${escapeHtml(loan.borrower_name || item.facility_id)}</div>\n              <div class=\"text-[10px] font-mono text-zinc-500\">${escapeHtml(tags.join(' · '))}</div>\n            </td>\n            <td class=\"p-2.5 text-zinc-300\">${escapeHtml(loan.moodys_rating || '—')} (${loan.moodys_warf ?? '—'})</td>\n            <td class=\"p-2.5 text-zinc-300\">+${Number(loan.spread_bps || 0).toFixed(0)} bps · ${Number(loan.moodys_recovery_rate_pct || 0).toFixed(0)}%</td>\n            <td class=\"p-2.5 text-right text-zinc-400\">$${Math.round(availPar).toLocaleString()}</td>\n            <td class=\"p-2.5 text-right\">\n              <input\n                type=\"number\"\n                value=\"${Math.round(item.allocated_par)}\"\n                step=\"1000000\"\n                min=\"0\"\n                onchange=\"updateSeedItemPar(${idx}, this.value)\"\n                class=\"w-36 text-right bg-[#18181b] border ${parWarn} px-2 py-1 text-xs font-mono focus:border-zinc-400 focus:outline-none\"\n              >\n            </td>\n            <td class=\"p-2.5 text-right ${wtWarn}\">${wtPct.toFixed(1)}%</td>\n            <td class=\"p-2.5\">\n              <div class=\"inline-flex border border-zinc-700 bg-[#18181b] text-[10px] font-mono\">\n                <button type=\"button\" onclick=\"setSeedItemMode(${idx}, 'exact')\" class=\"px-2 py-1 ${isExact ? 'bg-emerald-950/70 text-emerald-300 font-semibold' : 'text-zinc-400 hover:text-zinc-200'}\">Exact</button>\n                <button type=\"button\" onclick=\"setSeedItemMode(${idx}, 'min')\" class=\"px-2 py-1 border-l border-zinc-700 ${!isExact ? 'bg-sky-950/70 text-sky-300 font-semibold' : 'text-zinc-400 hover:text-zinc-200'}\">Min &ge;</button>\n              </div>\n            </td>\n            <td class=\"p-2.5 text-right whitespace-nowrap\">\n              <button type=\"button\" onclick=\"inspectSeedLoanInTab1('${escapeHtml(item.facility_id)}')\" class=\"px-2 py-1 text-[10px] font-mono border border-zinc-700 text-zinc-300 hover:text-white hover:border-zinc-500 mr-1\">Inspect</button>\n              <button type=\"button\" onclick=\"removeSeedItem(${idx})\" class=\"px-2 py-1 text-[10px] font-mono border border-zinc-700 text-zinc-400 hover:text-rose-300 hover:border-rose-500/50\">&times;</button>\n            </td>\n          </tr>\n        `;\n      }).join('');\n\n      updateSeedBannersAcrossTabs();\n    }\n\n    function updateSeedBannersAcrossTabs() {\n      const n = seedState.items.length;\n      let exactPar = 0;\n      let minPar = 0;\n      seedState.items.forEach(it => {\n        const p = Number(it.allocated_par || 0);\n        if (it.lock_mode === 'min') minPar += p;\n        else exactPar += p;\n      });\n      const totalM = ((exactPar + minPar) / 1e6).toFixed(1);\n      const summary = `${n} loan${n === 1 ? '' : 's'} ($${(exactPar / 1e6).toFixed(1)}M Exact Lock · $${(minPar / 1e6).toFixed(1)}M Min Floor · $${totalM}M total)`;\n\n      const optBanner = document.getElementById('opt-seed-banner');\n      const optSum = document.getElementById('opt-seed-summary');\n      if (optBanner && optSum) {\n        optSum.textContent = summary;\n        optBanner.classList.toggle('hidden', n === 0);\n      }\n\n      const wfBanner = document.getElementById('wf-seed-banner');\n      const wfSum = document.getElementById('wf-seed-summary');\n      if (wfBanner && wfSum) {\n        wfSum.textContent = summary;\n        wfBanner.classList.toggle('hidden', n === 0);\n      }\n    }\n\n    async function refreshSeedPreview() {\n      const mandate = getSeedMandateInputs();\n      const targetPar = Math.max(1, mandate.target_pool_par);\n      const payload = {\n        ...mandate,\n        seed_allocations: getActiveSeedAllocationsPayload(),\n      };\n      const seq = ++seedState.reqSeq;\n\n      const setText = (id, txt) => {\n        const el = document.getElementById(id);\n        if (el) el.textContent = txt;\n      };\n      setText('seed-stat-was-sub', `Mandate Min: ${mandate.min_was_bps} bps`);\n      setText('seed-stat-warf-sub', `Mandate Max: ${mandate.max_warf}`);\n      setText('seed-stat-warr-sub', `Mandate Min: ${mandate.min_warr_pct.toFixed(1)}%`);\n\n      try {\n        const res = await fetch('/api/seed_preview', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify(payload),\n        });\n        const data = await res.json();\n        if (!res.ok || seq !== seedState.reqSeq) return;\n        seedState.preview = data;\n\n        const seededPar = Number(data.seeded_par || 0);\n        const remPar = Number(data.remaining_ramp_par || 0);\n        const pctTarget = Number(data.seeded_pct_of_target || 0);\n        setText('seed-stat-par', `$${(seededPar / 1e6).toFixed(1)}M (${pctTarget.toFixed(1)}%)`);\n        setText('seed-stat-rem', `Remaining Ramp: $${(remPar / 1e6).toFixed(1)}M`);\n        setText('seed-stat-was', seededPar > 0 ? `${Number(data.weighted_avg_spread_bps || 0).toFixed(1)} bps` : '— bps');\n        setText('seed-stat-warf', seededPar > 0 ? `${Math.round(Number(data.weighted_avg_warf || 0))}` : '—');\n        setText('seed-stat-div', `${Number(data.diversity_score || 0).toFixed(1)}`);\n        setText('seed-stat-warr', seededPar > 0 ? `${Number(data.weighted_avg_recovery_pct || 0).toFixed(1)}%` : '—%');\n        setText('seed-stat-buckets', `${Number(data.ccc_bucket_pct_of_target || 0).toFixed(1)}% / ${Number(data.cov_lite_pct_of_target || 0).toFixed(1)}%`);\n        setText('seed-stat-buckets-sub', `Caps: ${mandate.max_ccc_bucket_pct.toFixed(1)}% CCC · ${mandate.max_cov_lite_pct.toFixed(1)}% Cov-Lite`);\n\n        const warnBox = document.getElementById('seed-warnings-box');\n        const warnings = data.warnings || [];\n        if (warnBox) {\n          if (warnings.length > 0) {\n            warnBox.innerHTML = `<div class=\"font-semibold uppercase tracking-wider text-amber-300 mb-1\">Seed Concentration / Capacity Warnings</div>` +\n              warnings.map(w => `<div>• ${escapeHtml(w)}</div>`).join('');\n            warnBox.classList.remove('hidden');\n          } else {\n            warnBox.innerHTML = '';\n            warnBox.classList.add('hidden');\n          }\n        }\n\n        const n = seedState.items.length;\n        setText(\n          'seed-footer-summary',\n          n === 0\n            ? `0 loans anchored · LP solver will optimize 100% of $${(targetPar / 1e6).toFixed(0)}M Target Pool Par from scratch.`\n            : `${n} loan${n === 1 ? '' : 's'} anchored ($${(seededPar / 1e6).toFixed(1)}M / ${pctTarget.toFixed(1)}%) · Remaining LP ramp: $${(remPar / 1e6).toFixed(1)}M`\n        );\n      } catch (e) {\n        console.error('Seed preview error:', e);\n      }\n      updateSeedBannersAcrossTabs();\n    }\n\n    function renderSeedLoanDropdown() {\n      const dd = document.getElementById('seed-loan-dropdown');\n      const countEl = document.getElementById('seed-loan-match-count');\n      if (!dd) return;\n      const items = seedState.filtered || [];\n      if (countEl) countEl.textContent = `${items.length}/${allLoans.length}`;\n      if (items.length === 0) {\n        dd.innerHTML = '<div class=\"p-3 text-xs font-mono text-zinc-500\">No matching facilities found.</div>';\n        return;\n      }\n      const seededSet = new Set(seedState.items.map(it => it.facility_id));\n      const limit = seedState.showAll ? items.length : Math.min(items.length, 60);\n      const visible = items.slice(0, limit);\n      dd.innerHTML = visible.map((l, idx) => {\n        const isActive = idx === seedState.activeIdx;\n        const already = seededSet.has(l.facility_id);\n        const tag = hasRealSecFiling(l) ? 'SEC EX-10' : 'SEED SAMPLE';\n        const spr = l.spread_bps != null ? `+${Math.round(l.spread_bps)} bps` : '—';\n        const parM = l.current_par ? `$${(Number(l.current_par) / 1e6).toFixed(0)}M` : '—';\n        return `\n          <button\n            type=\"button\"\n            onmousedown=\"event.preventDefault(); selectSeedDropdownLoan('${escapeHtml(l.facility_id)}')\"\n            class=\"w-full text-left px-3 py-2 flex items-center justify-between gap-2 text-xs font-mono transition ${isActive ? 'bg-zinc-800 text-white' : 'text-zinc-300 hover:bg-zinc-900'}\"\n          >\n            <div class=\"min-w-0 truncate\">\n              <span class=\"font-semibold text-zinc-100\">${escapeHtml(l.borrower_name || l.facility_id)}</span>\n              <span class=\"text-zinc-500 text-[10px] ml-1\">${escapeHtml(l.industry_moodys || '')}</span>\n            </div>\n            <div class=\"shrink-0 flex items-center gap-2 text-[10px]\">\n              <span class=\"text-zinc-400\">${escapeHtml(l.moodys_rating || '—')} · ${spr} · ${parM}</span>\n              <span class=\"px-1.5 py-0.5 border ${already ? 'border-emerald-400 text-emerald-300 bg-emerald-950/50' : (tag === 'SEC EX-10' ? 'border-zinc-700 text-zinc-300' : 'border-zinc-700 text-zinc-500')}\">${already ? 'ADDED' : '+ ADD'}</span>\n            </div>\n          </button>`;\n      }).join('') + (items.length > limit\n        ? `<div class=\"p-2 text-center text-[10px] font-mono text-zinc-500 bg-zinc-950\">Showing ${limit} of ${items.length}. Keep typing to narrow results...</div>`\n        : '');\n    }\n\n    function openSeedLoanDropdown(showAll = true) {\n      const dd = document.getElementById('seed-loan-dropdown');\n      const input = document.getElementById('seed-loan-search');\n      if (!dd || allLoans.length === 0) return;\n      seedState.dropdownOpen = true;\n      seedState.showAll = showAll && !(input && input.value.trim());\n      seedState.filtered = input && input.value.trim() ? filterTab1Loans(input.value) : [...allLoans];\n      seedState.activeIdx = 0;\n      dd.classList.remove('hidden');\n      const clearBtn = document.getElementById('seed-loan-clear-btn');\n      if (clearBtn) clearBtn.classList.toggle('hidden', !(input && input.value));\n      renderSeedLoanDropdown();\n    }\n\n    function closeSeedLoanDropdown() {\n      const dd = document.getElementById('seed-loan-dropdown');\n      seedState.dropdownOpen = false;\n      if (dd) dd.classList.add('hidden');\n      const countEl = document.getElementById('seed-loan-match-count');\n      if (countEl && allLoans.length > 0) countEl.textContent = `${allLoans.length}/${allLoans.length}`;\n    }\n\n    function toggleSeedLoanDropdown() {\n      if (seedState.dropdownOpen) {\n        closeSeedLoanDropdown();\n      } else {\n        const input = document.getElementById('seed-loan-search');\n        if (input) input.focus();\n        openSeedLoanDropdown(true);\n      }\n    }\n\n    function clearSeedLoanSearch() {\n      const input = document.getElementById('seed-loan-search');\n      if (input) {\n        input.value = '';\n        input.focus();\n      }\n      openSeedLoanDropdown(true);\n    }\n\n    function handleSeedSearchInput() {\n      const input = document.getElementById('seed-loan-search');\n      if (!input) return;\n      seedState.dropdownOpen = true;\n      seedState.showAll = false;\n      seedState.filtered = filterTab1Loans(input.value);\n      seedState.activeIdx = 0;\n      const dd = document.getElementById('seed-loan-dropdown');\n      if (dd) dd.classList.remove('hidden');\n      const clearBtn = document.getElementById('seed-loan-clear-btn');\n      if (clearBtn) clearBtn.classList.toggle('hidden', !input.value);\n      renderSeedLoanDropdown();\n    }\n\n    function handleSeedSearchKeydown(e) {\n      if (!seedState.dropdownOpen && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {\n        openSeedLoanDropdown(true);\n        e.preventDefault();\n        return;\n      }\n      if (!seedState.dropdownOpen) return;\n      const len = seedState.filtered.length;\n      if (e.key === 'ArrowDown') {\n        e.preventDefault();\n        if (len > 0) {\n          seedState.activeIdx = (seedState.activeIdx + 1) % len;\n          renderSeedLoanDropdown();\n        }\n      } else if (e.key === 'ArrowUp') {\n        e.preventDefault();\n        if (len > 0) {\n          seedState.activeIdx = (seedState.activeIdx - 1 + len) % len;\n          renderSeedLoanDropdown();\n        }\n      } else if (e.key === 'Enter') {\n        e.preventDefault();\n        const chosen = seedState.filtered[seedState.activeIdx];\n        if (chosen) selectSeedDropdownLoan(chosen.facility_id);\n      } else if (e.key === 'Escape') {\n        e.preventDefault();\n        closeSeedLoanDropdown();\n      }\n    }\n\n    function selectSeedDropdownLoan(fid) {\n      addFacilityToSeed(fid);\n      const input = document.getElementById('seed-loan-search');\n      if (input) input.value = '';\n      closeSeedLoanDropdown();\n    }\n\n    async function rampSeedToTab3() {\n      const cb = document.getElementById('opt-use-seed-cb');\n      if (cb) cb.checked = true;\n      switchTab('tab3');\n      await runOptimizer();\n    }\n\n    async function rampSeedToTab4() {\n      const cb = document.getElementById('wf-use-seed-cb');\n      if (cb) cb.checked = true;\n      switchTab('tab4');\n      await runWaterfall();\n    }\n\n    async function runOptimizer() {\n      const btn = document.getElementById('btn-run-opt');\n      btn.innerHTML = '<span>Solving HiGHS Linear Program...</span>';\n      btn.disabled = true;\n\n      const useSeeds = seedState.items.length > 0 && document.getElementById('opt-use-seed-cb')?.checked;\n      const payload = {\n        ...getSeedMandateInputs(),\n        seed_allocations: useSeeds ? getActiveSeedAllocationsPayload() : [],\n      };\n\n      try {\n        const res = await fetch('/api/optimize_pool', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify(payload)\n        });\n        const pool = await res.json();\n        if (!res.ok) {\n          throw new Error(pool.detail || pool.message || 'Optimization failed');\n        }\n        document.getElementById('opt-results-section').classList.remove('hidden');\n\n        document.getElementById('res-was').textContent = pool.weighted_avg_spread_bps != null ? `${pool.weighted_avg_spread_bps.toFixed(1)} bps` : '—';\n        document.getElementById('res-was-target').textContent = `${payload.min_was_bps} bps`;\n        document.getElementById('res-warf').textContent = pool.weighted_avg_warf != null ? Math.round(pool.weighted_avg_warf) : '—';\n        document.getElementById('res-warf-limit').textContent = payload.max_warf;\n        document.getElementById('res-diversity').textContent = pool.diversity_score != null ? pool.diversity_score : '—';\n        document.getElementById('res-warr').textContent = pool.weighted_avg_recovery_pct != null ? `${pool.weighted_avg_recovery_pct.toFixed(1)}%` : '—';\n        document.getElementById('res-warr-min').textContent = `${payload.min_warr_pct}%`;\n        document.getElementById('res-ccc').textContent = pool.ccc_bucket_pct != null ? `${pool.ccc_bucket_pct.toFixed(1)}%` : '—';\n        document.getElementById('res-ccc-max').textContent = `${payload.max_ccc_bucket_pct}%`;\n        document.getElementById('res-cov').textContent = pool.cov_lite_pct != null ? `${pool.cov_lite_pct.toFixed(1)}%` : '—';\n        document.getElementById('res-cov-max').textContent = `${payload.max_cov_lite_pct}%`;\n\n        const allocs = pool.allocations || [];\n        const seededCount = allocs.filter(a => a.is_seeded).length;\n        document.getElementById('res-alloc-count').textContent = seededCount > 0\n          ? `${allocs.length} facilities (${seededCount} seeded · ${allocs.length - seededCount} ramped)`\n          : `${allocs.length} facilities allocated`;\n        const tbody = document.getElementById('opt-allocations-tbody');\n        tbody.innerHTML = allocs.map(a => {\n          const borrower = a.borrower_name || (a.facility && a.facility.borrower_name) || a.facility_id || 'Unknown';\n          const industry = a.industry_moodys || (a.facility && a.facility.industry_moodys) || '—';\n          const rating = a.moodys_rating || (a.facility && a.facility.moodys_rating) || '—';\n          const warfVal = (a.warf !== undefined && a.warf !== null) ? a.warf : (a.facility && (a.facility.moodys_warf ?? a.facility.warf)) ?? '—';\n          const spread = (a.spread_bps !== undefined && a.spread_bps !== null) ? a.spread_bps : (a.facility && a.facility.spread_bps) ?? 0;\n          const par = Number(a.allocated_par || 0).toLocaleString();\n          const weight = ((a.weight_pct !== undefined ? a.weight_pct : a.allocation_pct) || 0).toFixed(1);\n          const sourceBadge = a.is_seeded\n            ? (a.seed_lock_mode === 'min'\n              ? '<span class=\"px-1.5 py-0.5 text-[10px] font-mono border border-sky-500/40 bg-sky-950/40 text-sky-300\">SEED (Min)</span>'\n              : '<span class=\"px-1.5 py-0.5 text-[10px] font-mono border border-emerald-500/40 bg-emerald-950/40 text-emerald-300\">SEED (Exact)</span>')\n            : '<span class=\"px-1.5 py-0.5 text-[10px] font-mono border border-zinc-700 bg-zinc-900 text-zinc-400\">RAMP (LP)</span>';\n          return `\n            <tr class=\"${a.is_seeded ? 'bg-emerald-950/10 hover:bg-emerald-950/20' : 'hover:bg-zinc-800/40'}\">\n              <td class=\"p-2.5 font-medium text-zinc-100\">${escapeHtml(borrower)}</td>\n              <td class=\"p-2.5\">${sourceBadge}</td>\n              <td class=\"p-2.5 text-zinc-300\">${escapeHtml(industry)}</td>\n              <td class=\"p-2.5 text-zinc-300\">${escapeHtml(rating)} (${warfVal})</td>\n              <td class=\"p-2.5 text-zinc-100 font-semibold\">+${Number(spread).toFixed(0)} bps</td>\n              <td class=\"p-2.5 text-right font-mono-data text-zinc-100 font-semibold\">$${par}</td>\n              <td class=\"p-2.5 text-right font-mono-data text-zinc-400\">${weight}%</td>\n            </tr>\n          `;\n        }).join('');\n\n      } catch (err) {\n        alert('Optimizer error: ' + (err.message || err));\n      } finally {\n        btn.innerHTML = '<span>Solve Optimal Pool (SciPy HiGHS LP)</span>';\n        btn.disabled = false;\n      }\n    }\n\n    async function runWaterfall() {\n      const btn = document.getElementById('btn-run-wf');\n      btn.innerHTML = '<span>Simulating Priority of Payments...</span>';\n      btn.disabled = true;\n\n      const useSeeds = seedState.items.length > 0 && document.getElementById('wf-use-seed-cb')?.checked;\n      const seedPayload = useSeeds ? getActiveSeedAllocationsPayload() : [];\n      const payload = {\n        term_sheet_name: document.getElementById('t3-preset-select').value,\n        sofr_pct: parseFloat(document.getElementById('t3-sofr').value),\n        cpr_pct: parseFloat(document.getElementById('t3-cpr').value),\n        cdr_pct: parseFloat(document.getElementById('t3-cdr').value),\n        recovery_pct: parseFloat(document.getElementById('t3-rec').value),\n        reinvestment_spread_bps: parseFloat(document.getElementById('t3-reinv').value),\n        seed_allocations: seedPayload,\n        custom_mandate: useSeeds ? { ...getSeedMandateInputs(), seed_allocations: seedPayload } : null,\n      };\n\n      try {\n        const res = await fetch('/api/run_waterfall', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify(payload)\n        });\n        const wf = await res.json();\n        if (!res.ok) {\n          throw new Error(wf.detail || wf.message || 'Waterfall simulation failed');\n        }\n        document.getElementById('wf-results-section').classList.remove('hidden');\n\n        document.getElementById('pm-arb').textContent = wf.net_arbitrage_spread_bps != null ? `+${wf.net_arbitrage_spread_bps.toFixed(1)} bps` : '—';\n        document.getElementById('pm-irr').textContent = wf.equity_irr_pct != null ? `${wf.equity_irr_pct.toFixed(2)}%` : '—';\n        document.getElementById('pm-moic').textContent = wf.equity_moic != null ? `${wf.equity_moic.toFixed(2)}x` : '—';\n        document.getElementById('pm-coc').textContent = wf.equity_cash_on_cash_yr1_pct != null ? `${wf.equity_cash_on_cash_yr1_pct.toFixed(2)}%` : '—';\n        document.getElementById('pm-fees').textContent = wf.manager_total_fee_pv != null ? `$${Math.round(wf.manager_total_fee_pv).toLocaleString()}` : '—';\n\n        const adjEl = document.getElementById('wf-collateral-adjustments');\n        if (adjEl) {\n          const floorUsd = Number(wf.effective_pool_floor_benefit_usd || 0);\n          const cpTot = Number(wf.total_call_penalties_collected || 0);\n          const cpInt = Number(wf.call_penalties_to_interest || 0);\n          const cpPrin = Number(wf.call_penalties_to_principal || 0);\n          const seededCnt = Number(wf.seeded_facility_count || 0);\n          const seededPar = Number(wf.seeded_par || 0);\n          const pills = [];\n          if (seededCnt > 0) {\n            pills.push(`<span class=\"px-2 py-0.5 border border-emerald-500/40 bg-emerald-950/40 text-emerald-300\">Seed Portfolio Enforced: ${seededCnt} loans ($${(seededPar / 1e6).toFixed(1)}M)</span>`);\n          }\n          if (floorUsd > 0) {\n            pills.push(`<span class=\"px-2 py-0.5 border border-emerald-500/40 bg-emerald-950/40 text-emerald-300\">Pool SOFR Floor Benefit: +$${Math.round(floorUsd).toLocaleString()}</span>`);\n          }\n          if (cpTot > 0) {\n            const routeParts = [];\n            if (cpInt > 0) routeParts.push(`$${Math.round(cpInt).toLocaleString()} → Interest Waterfall`);\n            if (cpPrin > 0) routeParts.push(`$${Math.round(cpPrin).toLocaleString()} → Trapped in Principal (OC Fail)`);\n            pills.push(`<span class=\"px-2 py-0.5 border border-amber-500/40 bg-amber-950/40 text-amber-300\">Call Penalties Collected: +$${Math.round(cpTot).toLocaleString()} (${routeParts.join(' · ')})</span>`);\n          }\n          if (pills.length > 0) {\n            adjEl.innerHTML = `<span class=\"text-zinc-400 uppercase tracking-wider text-[10px] mr-1\">Collateral Waterfall Adjustments:</span>` + pills.join('');\n            adjEl.classList.remove('hidden');\n          } else {\n            adjEl.innerHTML = '';\n            adjEl.classList.add('hidden');\n          }\n        }\n\n        // Tranche Table: Accurate Indenture Liability Stack\n        const tb = document.getElementById('wf-tranche-tbody');\n        const walMap = wf.tranche_wal_years || {};\n        const yldMap = wf.tranche_yields_pct || {};\n        \n        // Build metadata lookup from API response if present\n        const trancheMetaMap = {};\n        if (Array.isArray(wf.tranches)) {\n          wf.tranches.forEach(t => {\n            trancheMetaMap[t.tranche_name] = t;\n          });\n        }\n\n        // Verified preset fallback parameters\n        const fallbackPresets = {\n          'tier1_us_bsl_2026.json': {\n            'Class A-1': { rating_moodys: 'Aaa', initial_par: 248000000, coupon_spread_bps: 135, is_equity: false },\n            'Class A-2': { rating_moodys: 'Aaa', initial_par: 16000000, coupon_spread_bps: 175, is_equity: false },\n            'Class B': { rating_moodys: 'Aa2', initial_par: 48000000, coupon_spread_bps: 200, is_equity: false },\n            'Class C': { rating_moodys: 'A2', initial_par: 24000000, coupon_spread_bps: 275, is_equity: false },\n            'Class D': { rating_moodys: 'Baa3', initial_par: 20000000, coupon_spread_bps: 375, is_equity: false },\n            'Class E': { rating_moodys: 'Ba3', initial_par: 12000000, coupon_spread_bps: 650, is_equity: false },\n            'Subordinated Notes': { rating_moodys: 'NR', initial_par: 32000000, coupon_spread_bps: 0, is_equity: true }\n          },\n          'high_arb_wide_spread.json': {\n            'Class A-1': { rating_moodys: 'Aaa', initial_par: 250000000, coupon_spread_bps: 150, is_equity: false },\n            'Class A-2': { rating_moodys: 'Aaa', initial_par: 14000000, coupon_spread_bps: 190, is_equity: false },\n            'Class B': { rating_moodys: 'Aa2', initial_par: 48000000, coupon_spread_bps: 230, is_equity: false },\n            'Class C': { rating_moodys: 'A2', initial_par: 24000000, coupon_spread_bps: 320, is_equity: false },\n            'Class D': { rating_moodys: 'Baa3', initial_par: 20000000, coupon_spread_bps: 440, is_equity: false },\n            'Class E': { rating_moodys: 'Ba3', initial_par: 14000000, coupon_spread_bps: 750, is_equity: false },\n            'Subordinated Notes': { rating_moodys: 'NR', initial_par: 30000000, coupon_spread_bps: 0, is_equity: true }\n          },\n          'defensive_low_leverage.json': {\n            'Class A-1': { rating_moodys: 'Aaa', initial_par: 232000000, coupon_spread_bps: 120, is_equity: false },\n            'Class A-2': { rating_moodys: 'Aaa', initial_par: 16000000, coupon_spread_bps: 150, is_equity: false },\n            'Class B': { rating_moodys: 'Aa2', initial_par: 48000000, coupon_spread_bps: 175, is_equity: false },\n            'Class C': { rating_moodys: 'A2', initial_par: 28000000, coupon_spread_bps: 240, is_equity: false },\n            'Class D': { rating_moodys: 'Baa3', initial_par: 20000000, coupon_spread_bps: 320, is_equity: false },\n            'Class E': { rating_moodys: 'Ba3', initial_par: 16000000, coupon_spread_bps: 575, is_equity: false },\n            'Subordinated Notes': { rating_moodys: 'NR', initial_par: 40000000, coupon_spread_bps: 0, is_equity: true }\n          }\n        };\n\n        const selectedPresetKey = document.getElementById('t3-preset-select').value;\n        const currentPresetFallback = fallbackPresets[selectedPresetKey] || fallbackPresets['tier1_us_bsl_2026.json'];\n\n        tb.innerHTML = Object.entries(walMap).map(([tname, wal]) => {\n          const meta = trancheMetaMap[tname] || currentPresetFallback[tname] || {};\n          const isEq = meta.is_equity || tname.toLowerCase().includes('subordinated') || tname.toLowerCase().includes('equity');\n          const rating = meta.rating_moodys || (isEq ? 'NR' : '—');\n          const par = Number(meta.initial_par || 0).toLocaleString();\n          const spreadText = isEq ? 'Residual' : (meta.coupon_spread_bps != null ? `+${Number(meta.coupon_spread_bps).toFixed(0)} bps` : '—');\n          const yld = yldMap[tname] || 0.0;\n\n          return `\n            <tr class=\"hover:bg-zinc-800/40\">\n              <td class=\"p-2.5 font-semibold text-zinc-100\">${tname}</td>\n              <td class=\"p-2.5 text-zinc-300 font-mono-data\">${rating}</td>\n              <td class=\"p-2.5 text-right text-zinc-100 font-mono-data\">$${par}</td>\n              <td class=\"p-2.5 text-right text-zinc-300 font-mono-data\">${spreadText}</td>\n              <td class=\"p-2.5 text-right font-mono-data font-semibold text-zinc-100\">${Number(wal).toFixed(2)} yrs</td>\n              <td class=\"p-2.5 text-right font-mono-data font-semibold text-zinc-100\">${Number(yld).toFixed(2)}%</td>\n            </tr>\n          `;\n        }).join('');\n\n        // Monochromatic Dark OC Test Chart\n        const ocHistory = wf.oc_test_history || {};\n        const ocKeys = Object.keys(ocHistory);\n        const labels = Array.from({length: 40}, (_, i) => `Q${i+1}`);\n        const shades = ['#f4f4f5', '#d4d4d8', '#a1a1aa', '#71717a', '#52525b'];\n        const datasets = ocKeys.map((k, idx) => ({\n          label: k,\n          data: ocHistory[k] || [],\n          borderColor: shades[idx % shades.length],\n          backgroundColor: 'transparent',\n          borderWidth: idx === 0 ? 2 : 1.25,\n          tension: 0.1,\n          pointRadius: 0\n        }));\n\n        if (t3Chart) t3Chart.destroy();\n        const ctx = document.getElementById('t3-oc-chart').getContext('2d');\n        t3Chart = new Chart(ctx, {\n          type: 'line',\n          data: { labels, datasets },\n          options: {\n            responsive: true,\n            maintainAspectRatio: false,\n            plugins: {\n              legend: {\n                position: 'top',\n                align: 'end',\n                labels: {\n                  boxWidth: 10,\n                  font: { family: 'ui-monospace, monospace', size: 10 },\n                  color: '#a1a1aa'\n                }\n              }\n            },\n            scales: {\n              x: {\n                grid: { display: false },\n                ticks: { font: { family: 'ui-monospace, monospace', size: 10 }, color: '#71717a' }\n              },\n              y: {\n                grid: { color: '#27272a' },\n                ticks: {\n                  font: { family: 'ui-monospace, monospace', size: 10 },\n                  color: '#71717a',\n                  callback: v => `${Number(v).toFixed(1)}%`\n                }\n              }\n            }\n          }\n        });\n\n      } catch (err) {\n        alert('Waterfall simulation error: ' + (err.message || err));\n      } finally {\n        btn.innerHTML = '<span>Execute 40-Quarter Waterfall Simulation</span>';\n        btn.disabled = false;\n      }\n    }\n\n    document.addEventListener('DOMContentLoaded', init);\n  </script>\n</body>\n</html>\n"