using System.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

public class VectorFencePrefab : NetworkBehaviour
{
    [Header("Fence Settings")]
    public VectorFenceAbility Ability;
    private NavMeshObstacle navMeshObstacle;

    private void Awake()
    {
        navMeshObstacle = GetComponent<NavMeshObstacle>();
        if (navMeshObstacle == null)
        {
            Debug.LogError("[VectorFencePrefab] NavMeshObstacle is missing on the prefab!");
        }

        transform.localScale = new Vector3(Ability.wallLength, 0, Ability.wallWidth); // Start with zero height
    }

    public override void OnNetworkSpawn()
    {
        if (IsServer)
        {
            StartCoroutine(ScaleUp());
            StartCoroutine(DestroyAfterLifetime());
        }
    }

    private IEnumerator ScaleUp()
    {
        if (navMeshObstacle != null)
        {
            navMeshObstacle.enabled = true;
            navMeshObstacle.carving = true;
            navMeshObstacle.carveOnlyStationary = false;
            navMeshObstacle.carvingMoveThreshold = 0.01f;
            navMeshObstacle.center = Vector3.zero; // Adjust center if needed
            navMeshObstacle.shape = NavMeshObstacleShape.Box;
        }
        float elapsedTime = 0f;
        Vector3 originalScale = transform.localScale;
        Vector3 targetScale = new Vector3(Ability.wallLength, Ability.wallHeight, Ability.wallWidth); // Target full height scale

        while (elapsedTime < Ability.scaleUpDuration)
        {
            transform.localScale = Vector3.Lerp(originalScale, targetScale, elapsedTime / Ability.scaleUpDuration);
            elapsedTime += Time.deltaTime;
            yield return null;
        }

        transform.localScale = targetScale;

       
    }

    private IEnumerator DestroyAfterLifetime()
    {
        yield return new WaitForSeconds(Ability.abilityDuration);

        if (IsServer)
        {
            if (NetworkObject != null)
            {
                NetworkObject.Despawn(true);
            }
            else
            {
                Destroy(gameObject);
            }

            Debug.Log("[VectorFencePrefab] Fence destroyed.");
        }
    }
}