using UnityEngine;

public class FurnitureObject : MonoBehaviour
{
    [Header("Тип объекта")]
    public bool isWallObject = false; // ГАЛОЧКА: Это настенный предмет?

    [Header("Настройки")]
    public LayerMask obstacleLayers; 
    
    private int _obstaclesCount = 0; 
    public bool IsPlacementValid => _obstaclesCount == 0; 

    private GameObject _highlightBox;
    private Material _highlightMaterial;

    void Awake()
    {
        CreateHighlightBox();
    }

    private void CreateHighlightBox()
    {
        BoxCollider col = GetComponent<BoxCollider>();
        if (col == null) return;

        _highlightBox = GameObject.CreatePrimitive(PrimitiveType.Cube);
        Destroy(_highlightBox.GetComponent<Collider>()); 

        _highlightBox.transform.SetParent(transform);
        _highlightBox.transform.localPosition = col.center;
        _highlightBox.transform.localRotation = Quaternion.identity;
        _highlightBox.transform.localScale = col.size;

        _highlightMaterial = new Material(Shader.Find("Sprites/Default"));
        _highlightBox.GetComponent<Renderer>().material = _highlightMaterial;
        _highlightBox.SetActive(false);
    }

    public void SetEditMode(bool active)
    {
        if (_highlightBox != null)
        {
            _highlightBox.SetActive(active);
            if (active) UpdateColor();
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (((1 << other.gameObject.layer) & obstacleLayers) != 0)
        {
            _obstaclesCount++;
            UpdateColor();
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (((1 << other.gameObject.layer) & obstacleLayers) != 0)
        {
            _obstaclesCount--;
            UpdateColor();
        }
    }

    private void UpdateColor()
    {
        if (_highlightMaterial != null)
        {
            Color targetColor = IsPlacementValid ? new Color(0, 1, 0, 0.4f) : new Color(1, 0, 0, 0.4f);
            _highlightMaterial.color = targetColor;
        }
    }
}