namespace splat;

using Godot;

/// <summary>
/// Simple flat ground for Phase 1: a large static plane with a <see cref="GroundType"/>
/// describing its physical behaviour. Heightmap-based terrain and erosion arrive
/// in later phases (see Environment/TerrainDeformer).
/// </summary>
public partial class Terrain : StaticBody3D
{
    [Export] public GroundType Ground { get; set; } = default!;

    [Export] public float Size { get; set; } = 200f;

    public override void _Ready()
    {
        CollisionLayer = 16u; // Terrain physics layer (layer 5)
        Ground ??= GroundType.Default();

        if (GetNodeOrNull<CollisionShape3D>("CollisionShape3D") == null)
        {
            var shape = new CollisionShape3D { Name = "CollisionShape3D" };
            // A thin box gives the ground real thickness for stable collisions.
            shape.Shape = new BoxShape3D { Size = new Vector3(Size, 1f, Size) };
            shape.Position = new Vector3(0f, -0.5f, 0f);
            AddChild(shape);
        }

        if (GetNodeOrNull<MeshInstance3D>("MeshInstance3D") == null)
        {
            var mesh = new MeshInstance3D { Name = "MeshInstance3D" };
            var plane = new PlaneMesh { Size = new Vector2(Size, Size) };
            mesh.Mesh = plane;
            var mat = new StandardMaterial3D
            {
                VertexColorUseAsAlbedo = false,
                AlbedoColor = Ground.Type switch
                {
                    GroundType.Kind.Rock => new Color(0.5f, 0.5f, 0.52f),
                    GroundType.Kind.Clay => new Color(0.55f, 0.42f, 0.32f),
                    GroundType.Kind.PeatBog => new Color(0.32f, 0.24f, 0.18f),
                    _ => new Color(0.32f, 0.5f, 0.28f) // Soil/grass
                }
            };
            mesh.MaterialOverride = mat;
            AddChild(mesh);
        }
    }
}
