/**
 * curveGenerator.ts
 * Converts an array of {x, y} data points into a smooth SVG cubic Bezier path string.
 * Uses a Catmull-Rom → Bezier conversion for monotone-Y curves.
 */

export interface Point {
    x: number;
    y: number;
}

/**
 * Generates a smooth SVG path string from an array of points using
 * cubic Bezier curves (Catmull-Rom spline converted to Bezier).
 *
 * @param points  Array of {x, y} pixel coordinates (already mapped from data).
 * @param tension Controls curve tightness. 0 = straight lines, 1 = very curvy. Default 0.4.
 * @returns       SVG path `d` attribute string.
 */
export function generateSmoothPath(points: Point[], tension = 0.4): string {
    if (points.length === 0) return '';
    if (points.length === 1) return `M ${points[0].x},${points[0].y}`;

    const d: string[] = [`M ${points[0].x},${points[0].y}`];

    for (let i = 0; i < points.length - 1; i++) {
        const p0 = points[Math.max(i - 1, 0)];
        const p1 = points[i];
        const p2 = points[i + 1];
        const p3 = points[Math.min(i + 2, points.length - 1)];

        // Catmull-Rom control points
        const cp1x = p1.x + ((p2.x - p0.x) / 6) * tension * 3;
        const cp1y = p1.y + ((p2.y - p0.y) / 6) * tension * 3;
        const cp2x = p2.x - ((p3.x - p1.x) / 6) * tension * 3;
        const cp2y = p2.y - ((p3.y - p1.y) / 6) * tension * 3;

        d.push(`C ${cp1x.toFixed(2)},${cp1y.toFixed(2)} ${cp2x.toFixed(2)},${cp2y.toFixed(2)} ${p2.x},${p2.y}`);
    }

    return d.join(' ');
}

/**
 * Maps a sentiment score (0–100) to a pixel X coordinate within a container.
 *
 * @param score      Sentiment score 0–100.
 * @param width      Container pixel width.
 * @param padding    Left/right padding in pixels. Default 40.
 */
export function sentimentToX(score: number, width: number, padding = 40): number {
    const usable = width - padding * 2;
    return padding + (score / 100) * usable;
}

/**
 * Maps an event index to a pixel Y coordinate within a container.
 *
 * @param index      Event index (0 = top).
 * @param total      Total number of events.
 * @param height     Container pixel height.
 * @param padding    Top/bottom padding in pixels. Default 40.
 */
export function indexToY(index: number, total: number, height: number, padding = 40): number {
    if (total <= 1) return height / 2;
    const usable = height - padding * 2;
    return padding + (index / (total - 1)) * usable;
}
