using System.Collections;
using UnityEngine;

namespace Quest_Environment.Q2
{
    public class DirtSpot : MonoBehaviour, IInteractable
    {
        [Header("Settings")]
        public ItemData requiredBroomItem;
        [SerializeField] private float cleanDuration = 1.5f;

        private bool isCleaning = false;
        private Renderer _renderer;

        private void Start()
        {
            _renderer = GetComponent<Renderer>();
            if (_renderer == null)
            {
                _renderer = GetComponentInChildren<Renderer>();
            }
        }

        public void Interact()
        {
            if (isCleaning) return;

            bool hasBroom = InventorySystem.Instance.HasItem(requiredBroomItem);

            if (hasBroom)
            {
                if (QuestManager.Instance != null && QuestManager.Instance.currentQuest is Q2_SweepDirtQuest)
                {
                    StartCoroutine(CleanRoutine());
                }
                else
                {
                    Debug.Log("It's dirty here, but I have no reason to clean it right now.");
                }
            }
            else
            {
                Debug.Log("A broom is needed to clean this!");
            }
        }

        private IEnumerator CleanRoutine()
        {
            isCleaning = true;

            // --- TRIGGER ANIMATION ---
            PlayerHandsController.Instance?.PlaySweepAnimation();
            // -------------------------

            InteractionHandler.Instance.NotifyInteraction(gameObject);

            if (_renderer != null)
            {
                Material mat = _renderer.material;
                Color startColor = mat.color;
                float timer = 0f;

                while (timer < cleanDuration)
                {
                    timer += Time.deltaTime;
                    float alpha = Mathf.Lerp(startColor.a, 0f, timer / cleanDuration);
                    mat.color = new Color(startColor.r, startColor.g, startColor.b, alpha);
                    yield return null;
                }
            }
            else
            {
                yield return new WaitForSeconds(cleanDuration);
            }

            Debug.Log("Dirt cleaned!");
            Destroy(gameObject);
        }

        public string GetDescription()
        {
            if (isCleaning) return "";
            return "Sweep";
        }
    }
}