/**
 * SeverityChart — Reusable severity-over-time SVG chart.
 *
 * Props:
 *   scans  (array)  — Array of scan objects (must have .timestamp and .percentage)
 *   title  (string) — Chart heading (default: "Severity Over Time")
 *
 * Pure presentational — no ScanStore dependency. Works for any scan subset.
 */
var SeverityChart = function (props) {
    var scans = props.scans || [];
    var title = props.title || 'Severity Over Time';

    if (scans.length === 0) {
        return (
            <div className="bg-surface rounded-xl p-5 border border-stone-100/50 shadow-soft">
                <h3 className="text-sm font-extrabold text-forest mb-4">{title}</h3>
                <div className="flex items-center justify-center" style={{ height: '160px' }}>
                    <p className="text-sm font-medium text-muted">Upload scans to see severity trends</p>
                </div>
            </div>
        );
    }

    var sorted = scans.slice().sort(function (a, b) { return a.timestamp - b.timestamp; });
    var len = sorted.length;

    var vw = 300;
    var vh = 160;
    var padLeft = 32;
    var padRight = 8;
    var padTop = 8;
    var padBottom = 20;
    var chartW = vw - padLeft - padRight;
    var chartH = vh - padTop - padBottom;

    var yForPct = function (pct) { return padTop + chartH - (pct / 100) * chartH; };
    var xForIndex = function (i) {
        if (len === 1) return padLeft + chartW / 2;
        return padLeft + (i / (len - 1)) * chartW;
    };

    var points = [];
    for (var i = 0; i < len; i++) {
        points.push({ x: xForIndex(i), y: yForPct(sorted[i].percentage) });
    }

    var lineParts = [];
    var fillParts = [];
    for (var j = 0; j < points.length; j++) {
        var prefix = j === 0 ? 'M' : 'L';
        lineParts.push(prefix + points[j].x.toFixed(1) + ' ' + points[j].y.toFixed(1));
        fillParts.push(prefix + points[j].x.toFixed(1) + ' ' + points[j].y.toFixed(1));
    }
    fillParts.push('L' + points[points.length - 1].x.toFixed(1) + ' ' + (padTop + chartH).toFixed(1));
    fillParts.push('L' + points[0].x.toFixed(1) + ' ' + (padTop + chartH).toFixed(1) + ' Z');

    var zones = [
        { label: 'Critical', min: 80, max: 100, color: 'rgba(212,131,107,0.08)' },
        { label: 'High', min: 60, max: 80, color: 'rgba(212,131,107,0.05)' },
        { label: 'Mod', min: 40, max: 60, color: 'rgba(212,163,115,0.05)' },
        { label: 'Low', min: 0, max: 40, color: 'rgba(15,189,128,0.05)' },
    ];

    var xLabels = [];
    if (len >= 1) xLabels.push({ x: points[0].x, text: FormatUtils.shortDate(sorted[0].timestamp) });
    if (len >= 3) {
        var mid = Math.floor(len / 2);
        xLabels.push({ x: points[mid].x, text: FormatUtils.shortDate(sorted[mid].timestamp) });
    }
    if (len >= 2) xLabels.push({ x: points[len - 1].x, text: FormatUtils.shortDate(sorted[len - 1].timestamp) });

    return (
        <div className="bg-background-light rounded-xl p-5 border border-stone-100/50 shadow-soft">
            <div className="flex items-center justify-between mb-4">
                <h3 className="text-sm font-extrabold text-forest">{title}</h3>
                <div className="bg-background-light px-2.5 py-1 rounded-lg">
                    <span className="text-[10px] font-black text-sage uppercase tracking-[0.1em]">{len} scan{len !== 1 ? 's' : ''}</span>
                </div>
            </div>
            <div className="relative w-full" style={{ height: '180px' }}>
                <svg className="w-full h-full" viewBox={'0 0 ' + vw + ' ' + vh} preserveAspectRatio="xMidYMid meet">
                    {zones.map(function (zone) {
                        var y1 = yForPct(zone.max);
                        var y2 = yForPct(zone.min);
                        return <rect key={zone.label} x={padLeft} y={y1} width={chartW} height={y2 - y1} fill={zone.color} />;
                    })}
                    {[40, 60, 80].map(function (pct) {
                        var y = yForPct(pct);
                        return <line key={pct} x1={padLeft} y1={y} x2={padLeft + chartW} y2={y} stroke="#e2e2e2" strokeWidth="0.5" strokeDasharray="3,3" />;
                    })}
                    <text x={padLeft - 4} y={yForPct(90)} textAnchor="end" fontSize="7" fill="#D4836B" fontWeight="600">Critical</text>
                    <text x={padLeft - 4} y={yForPct(70)} textAnchor="end" fontSize="7" fill="#d4a373" fontWeight="600">High</text>
                    <text x={padLeft - 4} y={yForPct(50)} textAnchor="end" fontSize="7" fill="#d4a373" fontWeight="600">Mod</text>
                    <text x={padLeft - 4} y={yForPct(20)} textAnchor="end" fontSize="7" fill="#0fbd80" fontWeight="600">Low</text>
                    <path d={fillParts.join(' ')} fill="rgba(15, 189, 128, 0.1)" />
                    <path d={lineParts.join(' ')} fill="none" stroke="#0fbd80" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" />
                    {points.map(function (pt, i) {
                        return <circle key={i} cx={pt.x} cy={pt.y} r="3.5" fill="#0fbd80" stroke="white" strokeWidth="1.5" />;
                    })}
                    {xLabels.map(function (lbl, i) {
                        return <text key={i} x={lbl.x} y={vh - 4} textAnchor="middle" fontSize="7" fill="#8BA888" fontWeight="500">{lbl.text}</text>;
                    })}
                </svg>
            </div>
        </div>
    );
};

window.SeverityChart = SeverityChart;
