using UnityEngine;
using System.Collections.Generic;
using DG.Tweening;

public class HurdleSpawner : MonoBehaviour
{
    [Header("Setup")]
    public DOTweenPath pathSource;
    public GameObject hurdlePrefab;
    public int numberOfHurdles = 10;
    public float offsetFromGround = 0f;

    [Header("Debug")]
    public List<GameObject> spawnedHurdles = new();

    [ContextMenu("Spawn Hurdles")]
    public void SpawnHurdles()
    {
        if (pathSource == null || hurdlePrefab == null)
        {
            Debug.LogError("❌ Missing references.");
            return;
        }

        // Get draw points in world space
        Vector3[] drawPoints = pathSource.GetDrawPoints();

        if (drawPoints == null || drawPoints.Length < 2)
        {
            Debug.LogError("❌ Draw points are invalid.");
            return;
        }

        // Clean previous
        foreach (var h in spawnedHurdles)
        {
            if (h != null)
                DestroyImmediate(h);
        }
        spawnedHurdles.Clear();

        // Spawn new hurdles at evenly spaced interpolated points
        for (int i = 0; i < numberOfHurdles; i++)
        {
            // Even spacing between 0.05 and 0.95 to avoid endpoints
            float t = Mathf.Lerp(0.05f, 0.95f, i / (float)(numberOfHurdles - 1));
            float floatIndex = t * (drawPoints.Length - 1);

            int iA = Mathf.FloorToInt(floatIndex);
            int iB = Mathf.Min(iA + 1, drawPoints.Length - 1);
            float lerpT = floatIndex - iA;

            Vector3 worldPos = Vector3.Lerp(drawPoints[iA], drawPoints[iB], lerpT);
            worldPos.y += offsetFromGround;

            GameObject hurdle = Instantiate(hurdlePrefab, worldPos, Quaternion.identity, transform);
            spawnedHurdles.Add(hurdle);
        }

        Debug.Log($"✅ Spawned {numberOfHurdles} hurdles at world positions in ascending order.");
    }
}