using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CleaningBot : MonoBehaviour
{
    [SerializeField] private List<Transform> chargingPoints;
    [SerializeField] private Animator animator;
    [SerializeField] private float speed = 5f;
    [SerializeField] private Image fillImage;
    [SerializeField] private Transform spriteTransform;
    
    private BoxCollider2D _hitbox;
    private Rigidbody2D _rb;
    private Health _health;
    private bool _facingRight = true;
    private float _arriveThreshold = 0.05f;
    private int _nextIdx = 1;
    
    private void Awake()
    {
        _hitbox = GetComponent<BoxCollider2D>();
        _rb = GetComponent<Rigidbody2D>();
        _health = GetComponent<Health>();
    }
    
    void Start()
    {
        _health.OnHealthChanged += HandleHealthChanged;
        _hitbox.enabled = true;
    }
    private void Update()
    {
        HandleFacing(chargingPoints[_nextIdx].position.x);
    }
    
    private void FixedUpdate()
    {
        Move();
    }
    private void OnDestroy()
    {
        _health.OnHealthChanged -= HandleHealthChanged;
    }

    private void Move()
    {

        Vector2 pos = _rb.position;
        Vector2 target = chargingPoints[_nextIdx].position;

        float dist = Vector2.Distance(pos, target);

        if (dist <= _arriveThreshold)
        {
            _rb.MovePosition(target);   // snap cleanly
            _nextIdx = (_nextIdx + 1) % chargingPoints.Count;
            return;
        }

        Vector2 direction = (target - pos).normalized;
        _rb.MovePosition(pos + direction * (speed * Time.fixedDeltaTime));
    }
    
    private void HandleHealthChanged(int currentHealth)
    {
        float t = (_health.GetMaxHealth() <= 0) ? 0f : (float)currentHealth / _health.GetMaxHealth();
        fillImage.fillAmount = t;
    }
    
    private void HandleFacing(float targetX)
    {
        float dirX = targetX - transform.position.x;
        if (dirX > 0 && !_facingRight) Flip();
        else if (dirX < 0 && _facingRight) Flip();
    }

    private void Flip()
    {
        _facingRight = !_facingRight;
        Vector3 scale = spriteTransform.localScale;
        scale.x *= -1;
        spriteTransform.localScale = scale;
    }
}
