{% extends "base.html" %}
{% block title %}Column Interaction & Rebar Layout - ConcreteDesignPy{% endblock %}

{% block head %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/handsontable@14/dist/handsontable.full.min.css">
<script src="https://cdn.jsdelivr.net/npm/handsontable@14/dist/handsontable.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/plotly.js-dist-min/plotly.min.js"></script>
<style>
/* Column page specific styles */
.col-page-layout { display: flex; gap: 2rem; align-items: flex-start; }
.col-page-left { flex: 0 0 500px; }
.col-page-right { flex: 1; min-width: 0; }
.col-page-right .results-panel { position: sticky; top: 1rem; }

/* Report sections */
.report-full { margin-top: 1.5rem; }
.report-section {
    background: #fff; border: 1px solid var(--gray-200);
    border-radius: var(--radius); padding: 1.25rem; margin-bottom: 1rem;
}
.report-section h4 {
    font-size: .95rem; color: var(--primary-dark); margin: 0 0 .75rem;
    padding-bottom: .35rem; border-bottom: 2px solid var(--primary-light);
}
.report-grid { display: grid; grid-template-columns: 1fr 1fr; gap: .3rem 2rem; font-size: .85rem; }
.report-grid dt { color: var(--gray-500); }
.report-grid dd { font-family: "SF Mono","Fira Code",monospace; font-weight: 500; text-align: right; }
.report-eq { background: var(--gray-50); padding: .6rem 1rem; border-radius: 4px; margin: .5rem 0; font-size: .9rem; }
.report-table {
    width: 100%; border-collapse: collapse; font-size: .8rem; margin: .5rem 0;
}
.report-table th {
    background: var(--primary-dark); color: #fff; padding: .35rem .5rem;
    text-align: center; font-weight: 600; font-size: .75rem;
}
.report-table td {
    padding: .3rem .5rem; text-align: center; border-bottom: 1px solid var(--gray-200);
    font-family: "SF Mono","Fira Code",monospace; font-size: .78rem;
}
.report-table tr:nth-child(even) { background: var(--gray-50); }
.report-2col { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.dc-table th { background: #b91c1c; }
.dc-table .status-pass { background: #dcfce7; }
.dc-table .status-fail { background: #fee2e2; }
</style>
{% endblock %}

{% block content %}
<div class="calc-page">
    <a href="/" class="back-link">&larr; All Calculators</a>
    <h1>Strain-Compatibility Analysis of Reinforced Concrete Section</h1>
    <p class="ref">NSCP 2015 / ACI 318-19 &mdash; Column P-M Interaction Diagram</p>

    <div class="col-page-layout">
        <div class="col-page-left">
            <form id="calc-form" class="calc-form">
                <div class="form-section">
                    <h3>Materials</h3>
                    <div class="form-row">
                        <div class="form-group"><label>f'c (MPa)</label><input type="number" name="fc" value="30" step="0.1" required></div>
                        <div class="form-group"><label>fy (MPa)</label><input type="number" name="fy" value="415" step="0.1" required></div>
                    </div>
                </div>

                <div class="form-section">
                    <h3>Section Properties</h3>
                    <div class="form-row">
                        <div class="form-group"><label>Width, b (mm)</label><input type="number" name="b" value="450" required></div>
                        <div class="form-group"><label>Depth, h (mm)</label><input type="number" name="h" value="450" required></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>Cover (mm)</label><input type="number" name="cover" value="40" required></div>
                        <div class="form-group">
                            <label>Confinement</label>
                            <select name="confinement">
                                <option value="tied" selected>Tied</option>
                                <option value="spiral">Spiral</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3>Reinforcement
                        <span class="rebar-mode-toggle">
                            <label><input type="radio" name="rebar_mode" value="auto" checked> Auto</label>
                            <label><input type="radio" name="rebar_mode" value="manual"> Manual</label>
                        </span>
                    </h3>
                    <div id="rebar-auto">
                        <div class="form-row">
                            <div class="form-group"><label>Total bars</label><input type="number" name="n_bars" value="12" required></div>
                            <div class="form-group"><label>Bar dia. (mm)</label><input type="number" name="d_bar" value="25" required></div>
                            <div class="form-group"><label>Bars/side</label><input type="number" name="n_bars_side" value="0" placeholder="auto"></div>
                        </div>
                        <div class="form-row">
                            <div class="form-group"><label>nx (width)</label><input type="number" name="nx" value="4"></div>
                            <div class="form-group"><label>ny (depth)</label><input type="number" name="ny" value="4"></div>
                        </div>
                    </div>
                    <div id="rebar-manual" style="display:none;">
                        <p class="hint" style="text-align:left;margin-bottom:.5rem;">Y = from center (mm), Z = from bottom (mm)</p>
                        <div class="rebar-table-wrap">
                            <table class="rebar-edit-table" id="rebar-table">
                                <thead><tr><th>#</th><th>As (mm&sup2;)</th><th>Y (mm)</th><th>Z (mm)</th><th></th></tr></thead>
                                <tbody id="rebar-tbody"></tbody>
                            </table>
                        </div>
                        <div style="display:flex;gap:.5rem;margin-top:.5rem;">
                            <button type="button" class="btn-secondary" onclick="addRebarRow()">+ Add Bar</button>
                            <button type="button" class="btn-secondary" onclick="generateDefaultBars()">Generate from Section</button>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h3>Load Combinations</h3>
                    <div id="load-combo-table" style="width:100%;overflow:hidden;"></div>
                </div>

                <button type="submit" class="btn-primary" style="width:100%;">Generate Interaction Diagram</button>
            </form>
        </div>

        <div class="col-page-right">
            <div id="results" class="results-panel" style="display:none;">
                <h2>P-M Interaction Diagram</h2>
                <div id="chart-pm" style="text-align:center;"></div>
                <div id="svg-rebar" style="text-align:center;margin-top:1rem;"></div>
            </div>
        </div>
    </div>

    <!-- Full-width report below -->
    <div id="results-report" class="report-full" style="display:none;"></div>
</div>

<script>
// ── Handsontable ──
var loadComboData = [
    [1, '1.2D + 1.6L',        2500, 0, 150],
    [2, '1.2D + 1.0L + 1.0E', 1800, 0, 280],
    [3, '0.9D + 1.0E',        1200, 0, 250],
    [4, '1.2D + 1.6L + 0.5S', 2700, 0, 120],
    [5, '', null, null, null],
];
var hotContainer = document.getElementById('load-combo-table');
var hot = new Handsontable(hotContainer, {
    data: loadComboData,
    colHeaders: ['', 'Load Combination', 'P<sub>u</sub> (kN)', 'V<sub>u</sub> (kN)', 'M<sub>u</sub> (kN-m)'],
    columns: [
        { type: 'numeric', readOnly: true, width: 30 },
        { type: 'text', width: 150 },
        { type: 'numeric', numericFormat: { pattern: '0.0' }, width: 75 },
        { type: 'numeric', numericFormat: { pattern: '0.0' }, width: 75 },
        { type: 'numeric', numericFormat: { pattern: '0.0' }, width: 75 },
    ],
    rowHeaders: false, minRows: 5, minSpareRows: 1,
    contextMenu: true, stretchH: 'all', height: 'auto',
    className: 'htCenter', licenseKey: 'non-commercial-and-evaluation',
    afterCreateRow: function() { renumberLoadCombos(); },
    afterRemoveRow: function() { renumberLoadCombos(); },
});

function renumberLoadCombos() {
    if (!hot) return;
    var data = hot.getData();
    for (var i = 0; i < data.length; i++) hot.setDataAtCell(i, 0, i + 1, 'renumber');
}

function getLoadCombos() {
    var combos = [], data = hot.getData();
    for (var i = 0; i < data.length; i++) {
        var pu = data[i][2], mu = data[i][4];
        if (pu !== null && pu !== '' && mu !== null && mu !== '') {
            combos.push({
                name: data[i][1] || ('LC ' + (i + 1)),
                pu: parseFloat(pu),
                vu: data[i][3] !== null && data[i][3] !== '' ? parseFloat(data[i][3]) : 0,
                mu: parseFloat(mu),
            });
        }
    }
    return combos;
}

// ── Rebar toggle ──
document.querySelectorAll('input[name="rebar_mode"]').forEach(function(r) {
    r.addEventListener('change', function() {
        document.getElementById('rebar-auto').style.display = this.value === 'auto' ? '' : 'none';
        document.getElementById('rebar-manual').style.display = this.value === 'manual' ? '' : 'none';
        if (this.value === 'manual' && !document.getElementById('rebar-tbody').children.length) generateDefaultBars();
    });
});

var rebarCounter = 0;
function addRebarRow(area, y, z) {
    rebarCounter++;
    var tr = document.createElement('tr');
    tr.innerHTML = '<td>' + rebarCounter + '</td>'
        + '<td><input type="number" class="rb-area" value="' + (area || 490.9) + '" step="0.1"></td>'
        + '<td><input type="number" class="rb-y" value="' + (y || 0) + '" step="0.1"></td>'
        + '<td><input type="number" class="rb-z" value="' + (z || 0) + '" step="0.1"></td>'
        + '<td><button type="button" class="btn-remove" onclick="this.closest(\'tr\').remove();renumberBars();">&times;</button></td>';
    document.getElementById('rebar-tbody').appendChild(tr);
}
function renumberBars() {
    rebarCounter = 0;
    document.getElementById('rebar-tbody').querySelectorAll('tr').forEach(function(row) {
        row.cells[0].textContent = ++rebarCounter;
    });
}
function generateDefaultBars() {
    var f = document.getElementById('calc-form');
    var b = parseFloat(f.b.value)||450, h = parseFloat(f.h.value)||450;
    var cover = parseFloat(f.cover.value)||40, d_bar = parseFloat(f.d_bar.value)||25;
    var nx = parseInt(f.nx.value)||4, ny = parseInt(f.ny.value)||4;
    var tie = d_bar <= 32 ? 10 : 12, dp = cover + tie + d_bar / 2.0;
    var area = Math.PI * d_bar * d_bar / 4.0;
    document.getElementById('rebar-tbody').innerHTML = ''; rebarCounter = 0;
    var xn = -b/2+dp, xx = b/2-dp, zn = dp, zx = h-dp;
    for (var i=0;i<nx;i++) { var y = nx>1 ? xn+i*(xx-xn)/(nx-1) : 0; addRebarRow(area.toFixed(1),y.toFixed(1),zx.toFixed(1)); }
    for (var j=1;j<ny-1;j++) { var z = zx-j*(zx-zn)/(ny-1); addRebarRow(area.toFixed(1),xn.toFixed(1),z.toFixed(1)); addRebarRow(area.toFixed(1),xx.toFixed(1),z.toFixed(1)); }
    for (var i=0;i<nx;i++) { var y = nx>1 ? xn+i*(xx-xn)/(nx-1) : 0; addRebarRow(area.toFixed(1),y.toFixed(1),zn.toFixed(1)); }
}
function getManualBars() {
    var bars = [];
    document.getElementById('rebar-tbody').querySelectorAll('tr').forEach(function(row) {
        bars.push({ area: parseFloat(row.querySelector('.rb-area').value), y: parseFloat(row.querySelector('.rb-y').value), z: parseFloat(row.querySelector('.rb-z').value) });
    });
    return bars;
}

// ── Plotly Chart ──
function renderPlotlyChart(points, combos, payload) {
    // Build symmetric envelope: positive side → negative side (mirrored) → close
    var mu_nom = [], pu_nom = [], mu_fac = [], pu_fac = [];

    // Positive moment side (as-is from backend)
    for (var i = 0; i < points.length; i++) {
        mu_nom.push(points[i].mn); pu_nom.push(points[i].pn);
        mu_fac.push(points[i].mu); pu_fac.push(points[i].pu);
    }
    // Negative moment side (mirror, traverse in reverse to close the loop)
    for (var i = points.length - 1; i >= 0; i--) {
        mu_nom.push(-points[i].mn); pu_nom.push(points[i].pn);
        mu_fac.push(-points[i].mu); pu_fac.push(points[i].pu);
    }
    // Close
    if (points.length > 0) {
        mu_nom.push(mu_nom[0]); pu_nom.push(pu_nom[0]);
        mu_fac.push(mu_fac[0]); pu_fac.push(pu_fac[0]);
    }

    var traces = [
        {
            x: mu_nom, y: pu_nom, mode: 'lines', name: 'Nominal (Pn, Mn)',
            line: { color: '#93c5fd', width: 1.5, dash: 'dash' },
        },
        {
            x: mu_fac, y: pu_fac, mode: 'lines', name: 'Factored (\u03d5Pn, \u03d5Mn)',
            line: { color: '#1e40af', width: 2.5 },
            fill: 'toself', fillcolor: 'rgba(30,64,175,0.06)',
        },
    ];

    // Plot each load combination as a labeled marker
    if (combos.length > 0) {
        var colors = ['#dc2626','#f97316','#16a34a','#8b5cf6','#ec4899','#0891b2','#ca8a04','#6366f1'];
        combos.forEach(function(lc, i) {
            var clr = colors[i % colors.length];
            var sym = lc.status === 'OK' ? 'circle' : 'x';
            traces.push({
                x: [lc.mu], y: [lc.pu], mode: 'markers+text', name: lc.name,
                marker: { size: 10, color: clr, symbol: sym, line: { width: 1.5, color: '#fff' } },
                text: [lc.name], textposition: 'top right',
                textfont: { size: 10, color: clr },
            });
        });
    }

    var label = payload.b + '\u00d7' + payload.h + ' mm | ' + (payload.n_bars || (payload.manual_bars ? payload.manual_bars.length : '')) + '-\u03c6' + payload.d_bar;
    var layout = {
        title: { text: 'P-M Interaction Diagram<br><sup>' + label + ' | f\'c=' + payload.fc + ', fy=' + payload.fy + ' MPa</sup>', font: { size: 14 } },
        xaxis: { title: 'Moment, \u03d5Mn (kN-m)', zeroline: true, gridcolor: '#e5e7eb' },
        yaxis: { title: 'Axial, \u03d5Pn (kN)', zeroline: true, zerolinecolor: '#374151', zerolinewidth: 1.5, gridcolor: '#e5e7eb' },
        showlegend: true, legend: { x: 1, xanchor: 'right', y: 1, bgcolor: 'rgba(255,255,255,0.85)', bordercolor: '#d1d5db', borderwidth: 1, font: { size: 10 } },
        height: 600,
        margin: { t: 60, r: 20, b: 50, l: 65 },
        plot_bgcolor: '#fff', paper_bgcolor: '#fff',
        hovermode: 'closest',
    };

    var config = { responsive: true, displayModeBar: true, modeBarButtonsToRemove: ['lasso2d','select2d'], displaylogo: false };
    Plotly.newPlot('chart-pm', traces, layout, config);
}

// ── Submit ──
document.getElementById('calc-form').addEventListener('submit', function(e) {
    e.preventDefault();
    var f = this, isManual = f.rebar_mode.value === 'manual';
    var payload = { fc: parseFloat(f.fc.value), fy: parseFloat(f.fy.value), b: parseFloat(f.b.value), h: parseFloat(f.h.value), cover: parseFloat(f.cover.value), confinement: f.confinement.value };

    if (isManual) { payload.manual_bars = getManualBars(); payload.d_bar = 25; payload.n_bars = payload.manual_bars.length; }
    else { payload.n_bars = parseInt(f.n_bars.value); payload.d_bar = parseFloat(f.d_bar.value); payload.n_bars_side = parseInt(f.n_bars_side.value)||0; payload.nx = parseInt(f.nx.value)||0; payload.ny = parseInt(f.ny.value)||0; }

    var combos = getLoadCombos();
    if (combos.length > 0) {
        payload.load_combos = combos;
        var crit = combos.reduce(function(p,c){ return Math.abs(c.mu)>Math.abs(p.mu)?c:p; });
        payload.pu_demand = crit.pu; payload.mu_demand = Math.abs(crit.mu);
    }

    submitCalc('/api/column/interaction', payload, function(result) {
        // ── Plotly.js Interaction Diagram ──
        renderPlotlyChart(result.points, result.load_combo_checks || [], payload);
        document.getElementById('svg-rebar').innerHTML = result.svg_rebar || '';

        var r = result;
        var h = '';

        // ── Materials & Design Code ──
        h += '<div class="report-section"><h4>Materials & Design Code</h4>';
        h += '<div class="report-2col"><div>';
        h += '<dl class="report-grid">';
        h += '<dt>Concrete f\'c</dt><dd>' + payload.fc + ' MPa</dd>';
        h += '<dt>Steel fy</dt><dd>' + payload.fy + ' MPa</dd>';
        h += '<dt>Es</dt><dd>200,000 MPa</dd>';
        h += '<dt>Ultimate strain &epsilon;cu</dt><dd>0.003</dd>';
        h += '</dl></div><div>';
        h += '<dl class="report-grid">';
        h += '<dt>Design Code</dt><dd>ACI 318-19</dd>';
        h += '<dt>Confinement</dt><dd>' + r.confinement + '</dd>';
        var phi_c = r.confinement === 'spiral' ? '0.75' : '0.65';
        h += '<dt>&phi;c</dt><dd>' + phi_c + '</dd>';
        h += '<dt>&phi;b</dt><dd>0.90</dd>';
        h += '<dt>&beta;1</dt><dd>' + r.beta1 + '</dd>';
        h += '</dl></div></div></div>';

        // ── Section Properties ──
        h += '<div class="report-section"><h4>Section Properties</h4>';
        h += '<div class="report-2col"><div>';
        h += '<dl class="report-grid">';
        h += '<dt>Shape</dt><dd>Rectangular</dd>';
        h += '<dt>Width, b</dt><dd>' + payload.b + ' mm</dd>';
        h += '<dt>Height, h</dt><dd>' + payload.h + ' mm</dd>';
        h += '<dt>Cover</dt><dd>' + payload.cover + ' mm</dd>';
        h += '</dl></div><div>';
        h += '<dl class="report-grid">';
        h += '<dt>Ag</dt><dd>' + Number(r.ag).toLocaleString() + ' mm&sup2;</dd>';
        h += '<dt>Ig</dt><dd>' + Number(r.ig).toLocaleString() + ' mm&sup4;</dd>';
        h += '<dt>d<sub>eff</sub></dt><dd>' + r.d_eff + ' mm</dd>';
        h += '<dt>d\'</dt><dd>' + r.d_prime + ' mm</dd>';
        h += '</dl></div></div></div>';

        // ── Reinforcing Layout ──
        h += '<div class="report-section"><h4>Reinforcing Layout</h4>';
        h += '<div class="report-2col"><div>';
        h += '<dl class="report-grid">';
        h += '<dt>Total Bars</dt><dd>' + r.n_bars_actual + '</dd>';
        h += '<dt>Ast</dt><dd>' + r.ast_total + ' mm&sup2;</dd>';
        h += '<dt>&rho;</dt><dd>' + r.rho + '</dd>';
        h += '</dl></div><div>';
        h += '<table class="report-table"><tr><th>#</th><th>As (mm&sup2;)</th><th>ds (mm)</th></tr>';
        for (var i = 0; i < r.bar_depths.length; i++) {
            h += '<tr><td>' + (i+1) + '</td><td>' + (r.bar_areas ? r.bar_areas[i] : '—') + '</td><td>' + r.bar_depths[i] + '</td></tr>';
        }
        h += '</table></div></div></div>';

        // ── Axial Capacity ──
        h += '<div class="report-section"><h4>Axial Capacity Calculations</h4>';
        h += '<div class="report-eq">\\[ P_o = 0.85\\,f\'_c\\,(A_g - A_{st}) + f_y\\,A_{st} = ' + r.pure_compression_kn + ' \\text{ kN} \\quad \\text{(Compression)} \\]</div>';
        h += '<div class="report-eq">\\[ \\phi P_{u,max} = k_1\\,\\phi\\,[0.85\\,f\'_c\\,(b\\,h - A_s) + f_y\\,A_s] = ' + r.phi_pn_max_kn + ' \\text{ kN} \\]</div>';
        h += '<div class="report-eq">\\[ \\phi P_{u,min} = \\phi\\,(f_y\\,\\Sigma A_s) = ' + r.pure_tension_kn + ' \\text{ kN} \\quad \\text{(Tension)} \\]</div>';
        h += '</div>';

        // ── Balanced Point & Steel Forces ──
        if (r.balanced_point) {
            h += '<div class="report-section"><h4>Balanced Condition</h4>';
            h += '<div class="report-2col"><div>';
            h += '<dl class="report-grid">';
            h += '<dt>c<sub>b</sub></dt><dd>' + r.balanced_point.c + ' mm</dd>';
            h += '<dt>a<sub>b</sub></dt><dd>' + r.balanced_point.a + ' mm</dd>';
            h += '<dt>&phi;</dt><dd>' + r.balanced_point.phi + '</dd>';
            h += '<dt>Classification</dt><dd>' + r.balanced_point.classification + '</dd>';
            h += '<dt>&epsilon;<sub>t</sub></dt><dd>' + r.balanced_point.es_tension + '</dd>';
            h += '</dl>';
            h += '<dl class="report-grid" style="margin-top:.5rem;border-top:1px solid var(--gray-200);padding-top:.5rem;">';
            h += '<dt>&phi;Pn</dt><dd><b>' + r.balanced_point.pu + ' kN</b></dd>';
            h += '<dt>&phi;Mn</dt><dd><b>' + r.balanced_point.mu + ' kN-m</b></dd>';
            if (r.balanced_point.cc_kn) {
                h += '<dt>Cc = 0.85f\'c&middot;a&middot;b</dt><dd>' + r.balanced_point.cc_kn + ' kN</dd>';
                h += '<dt>&Sigma;Fs</dt><dd>' + r.balanced_point.fs_total_kn + ' kN</dd>';
            }
            h += '</dl></div>';

            if (r.balanced_steel_detail) {
                h += '<div><p style="font-size:.8rem;font-weight:600;margin-bottom:.3rem;">Steel Forces at Balanced Point</p>';
                h += '<table class="report-table">';
                h += '<tr><th>#</th><th>As (mm&sup2;)</th><th>ds (mm)</th><th>&epsilon;s</th><th>fs (MPa)</th><th>Force (kN)</th></tr>';
                r.balanced_steel_detail.forEach(function(bar) {
                    var strainColor = bar.strain >= 0 ? '#1e40af' : '#dc2626';
                    h += '<tr><td>' + bar.bar + '</td><td>' + bar.as_mm2 + '</td><td>' + bar.ds_mm + '</td>';
                    h += '<td style="color:' + strainColor + '">' + bar.strain.toFixed(6) + '</td>';
                    h += '<td>' + bar.fs_mpa.toFixed(1) + '</td><td>' + bar.force_kn.toFixed(2) + '</td></tr>';
                });
                h += '</table></div>';
            }
            h += '</div></div>';
        }

        // ── Maximum Moment ──
        if (r.max_moment_point) {
            h += '<div class="report-section"><h4>Maximum Moment Point</h4>';
            h += '<dl class="report-grid" style="max-width:400px;">';
            h += '<dt>&phi;M<sub>n,max</sub></dt><dd><b>' + r.max_moment_point.mu + ' kN-m</b></dd>';
            h += '<dt>at &phi;Pn</dt><dd>' + r.max_moment_point.pu + ' kN</dd>';
            h += '<dt>c</dt><dd>' + r.max_moment_point.c + ' mm</dd>';
            h += '<dt>&phi;</dt><dd>' + r.max_moment_point.phi + '</dd>';
            h += '</dl></div>';
        }

        // ── Demand / Capacity ──
        if (r.load_combo_checks && r.load_combo_checks.length > 0) {
            h += '<div class="report-section"><h4>Demand / Capacity Check</h4>';
            h += '<table class="report-table dc-table">';
            h += '<tr><th>Load Combination</th><th>Pu (kN)</th><th>Mu (kN-m)</th><th>&phi;Mn (kN-m)</th><th>D/C Ratio</th><th>Status</th></tr>';
            r.load_combo_checks.forEach(function(lc) {
                var cls = lc.status === 'OK' ? 'status-pass' : 'status-fail';
                h += '<tr><td style="text-align:left">' + lc.name + '</td><td>' + lc.pu.toFixed(1) + '</td><td>' + lc.mu.toFixed(1) + '</td>';
                h += '<td>' + lc.phi_mn_capacity.toFixed(1) + '</td><td>' + lc.dc_ratio.toFixed(4) + '</td>';
                h += '<td class="' + cls + '" style="font-weight:700">' + lc.status + '</td></tr>';
            });
            h += '</table></div>';
        } else if (r.demand_check) {
            var dc = r.demand_check;
            h += '<div class="report-section"><h4>Demand / Capacity Check</h4>';
            h += '<dl class="report-grid" style="max-width:400px;">';
            h += '<dt>Pu</dt><dd>' + payload.pu_demand + ' kN</dd>';
            h += '<dt>Mu</dt><dd>' + payload.mu_demand + ' kN-m</dd>';
            h += '<dt>&phi;Mn capacity</dt><dd>' + dc.phi_mn_capacity + ' kN-m</dd>';
            h += '<dt>D/C Ratio</dt><dd>' + dc.dc_ratio + '</dd>';
            var cls = dc.status === 'OK' ? 'status-pass' : 'status-fail';
            h += '<dt>Status</dt><dd class="' + cls + '">' + dc.status + '</dd>';
            h += '</dl></div>';
        }

        var reportDiv = document.getElementById('results-report');
        reportDiv.style.display = '';
        reportDiv.innerHTML = h;
        if (window.MathJax) MathJax.typeset();
    });
});
</script>
{% endblock %}
