using Unity.Netcode;
using UnityEngine;

namespace Northbound
{
    public class Building : NetworkBehaviour
    {
        [Header("References")]
        public BuildingData buildingData;

        [Header("Runtime Info")]
        public Vector3Int gridPosition;
        public int rotation; // 0-3 (0=0°, 1=90°, 2=180°, 3=270°)

        [Header("Debug")]
        public bool showGridBounds = true;
        public Color gridBoundsColor = Color.cyan;

        public void Initialize(BuildingData data, Vector3Int gridPos, int rot)
        {
            buildingData = data;
            gridPosition = gridPos;
            rotation = rot;
        }

        /// <summary>
        /// Gets the grid-based bounds (from BuildingData width/length/height)
        /// This is used for placement validation, NOT the actual collider bounds
        /// Bounds are slightly shrunk to allow adjacent buildings to touch
        /// </summary>
        public Bounds GetGridBounds()
        {
            if (buildingData == null) return new Bounds(transform.position, Vector3.one);

            Vector3 gridSize = buildingData.GetSize(rotation);

            // Shrink slightly to allow buildings to be adjacent without Intersects() returning true
            Vector3 shrunkSize = gridSize - Vector3.one * 0.01f;
            return new Bounds(transform.position + Vector3.up * gridSize.y * 0.5f, shrunkSize);
        }

        /// <summary>
        /// Legacy method, use GetGridBounds() instead
        /// </summary>
        public Bounds GetBounds()
        {
            return GetGridBounds();
        }

        private void OnDrawGizmos()
        {
            if (!showGridBounds || buildingData == null) return;

            Bounds bounds = GetGridBounds();
            Gizmos.color = gridBoundsColor;
            Gizmos.DrawWireCube(bounds.center, bounds.size);
        }

        private void OnDrawGizmosSelected()
        {
            if (buildingData == null) return;

            Bounds bounds = GetGridBounds();
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireCube(bounds.center, bounds.size);

            // Draw grid position
            if (BuildingManager.Instance != null)
            {
                Vector3 worldPos = BuildingManager.Instance.GridToWorld(gridPosition);
                Gizmos.color = Color.magenta;
                Gizmos.DrawSphere(worldPos, 0.2f);
            }
        }
    }
}
