/**
 * sparkline.js — Canvas 2D sparkline with fill area, dot at last point.
 * Ported from index.html:2239-2263 drawSparkline().
 */

/**
 * Draw a sparkline onto a <canvas> element.
 * @param {string|HTMLCanvasElement} idOrEl - Canvas id or element
 * @param {number[]} data  - Data array (at least 2 points)
 * @param {string}   color - CSS color string (OKLCh or hex)
 */
export function drawSparkline(idOrEl, data, color) {
    const canvas = typeof idOrEl === 'string'
        ? document.getElementById(idOrEl)
        : idOrEl;
    if (!canvas?.getContext) return;

    const W = canvas.width, H = canvas.height;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, W, H);
    if (!data || data.length < 2) return;

    const min = Math.min(...data);
    const max = Math.max(...data);
    const range = max - min || 1;

    const xs = i => (i / (data.length - 1)) * W;
    const ys = v => H - 2 - ((v - min) / range) * (H - 4);

    // Line
    ctx.beginPath();
    ctx.moveTo(xs(0), ys(data[0]));
    for (let i = 1; i < data.length; i++) ctx.lineTo(xs(i), ys(data[i]));
    ctx.strokeStyle = color;
    ctx.lineWidth = 1.5;
    ctx.lineJoin = 'round';
    ctx.stroke();

    // Fill under line
    ctx.lineTo(xs(data.length - 1), H);
    ctx.lineTo(xs(0), H);
    ctx.closePath();
    // Build a fill color at 12% opacity from the stroke color
    const fillColor = color.startsWith('oklch(')
        ? color.replace(')', ' / 0.12)').replace('oklch(', 'oklch(')
        : color + '1f'; // hex fallback ~12%
    ctx.fillStyle = fillColor;
    ctx.fill();

    // Dot at last point
    const lx = xs(data.length - 1);
    const ly = ys(data[data.length - 1]);
    ctx.beginPath();
    ctx.arc(lx, ly, 2, 0, Math.PI * 2);
    ctx.fillStyle = color;
    ctx.fill();
}
