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

public class Drawer : MonoBehaviour
{
    [SerializeField] private float _speed = 3f;
    [SerializeField] private float _openZ = 0.873f;
    [SerializeField] private Camera _camera;
    [SerializeField] private float _interactDistance = 3f;

    private bool _isOpen = false;
    private float _targetZ;
    private float _closedZ;
    private bool _hasTarget = false;
    public bool IsOpen => _isOpen;

    void Start()
    {
        _closedZ = transform.localPosition.z;
        _targetZ = _closedZ;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit, _interactDistance))
            {
                if (hit.collider.transform == transform ||
                    hit.collider.transform.IsChildOf(transform))
                {
                    _isOpen = !_isOpen;
                    _targetZ = _isOpen ? _openZ : _closedZ;
                    _hasTarget = true;
                }
            }
        }

        if (!_hasTarget) return;

        Vector3 pos = transform.localPosition;
        pos.z = Mathf.MoveTowards(pos.z, _targetZ, Time.deltaTime * _speed);
        transform.localPosition = pos;

        if (Mathf.Abs(pos.z - _targetZ) < 0.001f)
        {
            pos.z = _targetZ;
            transform.localPosition = pos;
            _hasTarget = false;
        }
    }
}
