using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class ForceCurveVisualizer : MonoBehaviour
{
    private LineRenderer _lr;
    
    [Header("Visual Settings")]
    public float xScale = 0.1f;
    public float yScale = 0.05f; // Raw force is usually 0-200. 0.05 scales it to 0-10 height.
    public float lineWidth = 0.1f;
    public Color lineColor = Color.cyan;

    private void Awake()
    {
        _lr = GetComponent<LineRenderer>();
        
        // Setup LineRenderer programmatically if not set in Inspector
        _lr.positionCount = 0;
        _lr.startWidth = lineWidth;
        _lr.endWidth = lineWidth;
        _lr.useWorldSpace = false; // Important for UI/HUD
        _lr.material = new Material(Shader.Find("Sprites/Default")); // Basic white material
        _lr.startColor = lineColor;
        _lr.endColor = lineColor;
    }

    private void Start()
    {
        if (PerformanceMonitorManager.Instance != null)
        {
            PerformanceMonitorManager.Instance.OnForceCurveUpdated += UpdateGraph;
        }
    }

    private void UpdateGraph(List<float> points)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() => {
            if (points.Count < 2) 
            {
                _lr.positionCount = 0;
                return;
            }

            _lr.positionCount = points.Count;
            
            // Draw
            for (int i = 0; i < points.Count; i++)
            {
                float x = i * xScale;
                float y = points[i] * yScale;
                
                // Simple 3-point smoothing
                if (i > 0 && i < points.Count - 1)
                {
                   float prev = points[i-1] * yScale;
                   float next = points[i+1] * yScale;
                   y = (prev + y + next) / 3f; 
                }

                _lr.SetPosition(i, new Vector3(x, y, 0));
            }
        });
    }
    
    // JUICE TIP: Use this to check for "Good Form"
    // A good stroke is a smooth bell curve. 
    // A bad stroke has a "dip" in the middle (two peaks).
    // You can analyze 'points' here to trigger the "sputtering engine" sound.
}