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

public class GroundCheck : MonoBehaviour
{
    public float groundDistance = 1.5f;
    
    [Tooltip("Layers to check for ground. Must include environment/ground layers. If left at 0, auto-detects at startup.")]
    public LayerMask groundLayer;
    
    public Transform groundCheckTransform;

    public bool isGrounded;

    // Initialize a safe default for groundCheckTransform and auto-detect ground layer
    private void Awake()
    {
        // AUTO-FIX: If groundLayer is 0 (Nothing), set it to detect everything EXCEPT 
        // characters. This prevents detecting character body colliders as "ground".
        if (groundLayer.value == 0)
        {
            // Include Default layer and all non-character layers
            // Exclude layers commonly used for characters: "Player", "Enemy", "Character"
            // Start with everything, then exclude known character layers
            groundLayer = ~0; // Everything
            
            int playerLayer = LayerMask.NameToLayer("Player");
            int enemyLayer = LayerMask.NameToLayer("Enemy");
            int characterLayer = LayerMask.NameToLayer("Character");
            int ignoreRaycastLayer = LayerMask.NameToLayer("Ignore Raycast");
            
            if (playerLayer >= 0) groundLayer &= ~(1 << playerLayer);
            if (enemyLayer >= 0) groundLayer &= ~(1 << enemyLayer);
            if (characterLayer >= 0) groundLayer &= ~(1 << characterLayer);
            if (ignoreRaycastLayer >= 0) groundLayer &= ~(1 << ignoreRaycastLayer);
            
            Debug.Log($"[GroundCheck] Auto-configured groundLayer mask to {groundLayer.value} on '{gameObject.name}'");
        }
        
        if (groundCheckTransform == null)
        {
            // Prefer a child named "GroundCheck" if present
            var child = transform.Find("GroundCheck");
            if (child != null)
            {
                groundCheckTransform = child;
            }
            else
            {
                // Fallback to a scene object named "floor_limit" if it exists, else use this transform
                var floor = GameObject.Find("floor_limit");
                groundCheckTransform = floor != null ? floor.transform : transform;
            }
        }
    }

    private void Update()
    {
        if (groundCheckTransform == null)
        {
            // Still initializing or missing reference; do not attempt a check
            isGrounded = false;
            return;
        }

        // Use the chosen transform's position as the check origin
        isGrounded = Physics.CheckSphere(groundCheckTransform.position, groundDistance, groundLayer, QueryTriggerInteraction.Ignore);
    }

    public bool IsGrounded()
    {
        return isGrounded;
    }
}
