using UnityEngine;
using IStalk.Data;

namespace IStalk.EditorTools.MapGen
{
    public class RoomBounds : MonoBehaviour
    {
        public Vector3Int gridSize = new(1, 1, 1);

        private float CellWidth => GlobalRules_SO.Instance != null ? GlobalRules_SO.Instance.cellWidth : 4f;
        private float CellHeight => GlobalRules_SO.Instance != null ? GlobalRules_SO.Instance.cellHeight : 3f;

        public Vector3 WorldSize => new(gridSize.x * CellWidth, gridSize.y * CellHeight, gridSize.z * CellWidth);

        private void OnDrawGizmos()
        {
            Gizmos.color = new Color(0f, 1f, 1f, 0.3f);
            Vector3 size = WorldSize;
            Vector3 center = transform.position + size / 2f;
            Gizmos.DrawWireCube(center, size);

            Gizmos.color = new Color(0f, 1f, 1f, 0.05f);
            Gizmos.DrawCube(center, size);

            DrawGrid();
        }

        private void DrawGrid()
        {
            Gizmos.color = new Color(1f, 1f, 1f, 0.1f);
            Vector3 origin = transform.position;

            for (int x = 0; x <= gridSize.x; x++)
            {
                Vector3 start = origin + Vector3.right * (x * CellWidth);
                Vector3 end = start + Vector3.forward * (gridSize.z * CellWidth);
                Gizmos.DrawLine(start, end);
            }

            for (int z = 0; z <= gridSize.z; z++)
            {
                Vector3 start = origin + Vector3.forward * (z * CellWidth);
                Vector3 end = start + Vector3.right * (gridSize.x * CellWidth);
                Gizmos.DrawLine(start, end);
            }
        }

        public bool ContainsPoint(Vector3 point)
        {
            Vector3 local = point - transform.position;
            Vector3 size = WorldSize;
            return local.x >= 0 && local.x <= size.x &&
                   local.y >= 0 && local.y <= size.y &&
                   local.z >= 0 && local.z <= size.z;
        }
    }
}
