using UnityEngine;

/// <summary>
/// SETUP GUIDE FOR FACEOFF SYSTEM
/// 
/// 1. CREATE THE PUCK:
///    - Create a GameObject named "Puck"
///    - Add the PuckController script to it
///    - Position it at your center ice faceoff spot
///    - It will automatically create its own physics and visuals
/// 
/// 2. TAG YOUR PLAYERS:
///    - Select all home team players and set their tag to "HomeTeam"
///    - Select all away team players and set their tag to "AwayTeam"
///    - (Create these tags in Tags & Layers if they don't exist)
/// 
/// 3. CREATE THE FACEOFF MANAGER:
///    - Create an empty GameObject named "FaceoffManager"
///    - Add the FaceoffManager script to it
///    - Drag the Puck GameObject into the "Puck" field
///    - The script will auto-find players by their tags
/// 
/// 4. TESTING:
///    - Press F key during play mode to trigger a faceoff
///    - Watch the console for outcome messages
/// 
/// 5. INTEGRATION WITH YOUR GAME:
///    - Call faceoffManager.InitiateFaceoff(position) from your game logic
///    - Or call faceoffManager.StartFaceoff() if puck is already positioned
/// 
/// HOW THE SYSTEM WORKS:
/// 
/// PUCK PHYSICS:
/// - The puck has a Rigidbody with realistic hockey puck properties
/// - Low friction simulates ice sliding
/// - When a player is close enough, they automatically pick it up
/// - Yellow ring indicator shows who has possession
/// 
/// FACEOFF MECHANICS:
/// - Compares center players' stats (strength, stick handling, awareness, agility)
/// - Three possible outcomes:
///   1. HOME WIN: Home center wins cleanly, passes to defender
///   2. AWAY WIN: Away center wins cleanly, passes to defender  
///   3. STRUGGLE: Puck bounces loose, both teams scramble for it
/// 
/// POSSESSION INDICATOR:
/// - Rotating yellow ring appears around player with puck
/// - Makes it instantly clear who controls the puck
/// 
/// PLAYER ACTIONS WITH PUCK:
/// - Shoot(direction, power): Fire the puck with physics
/// - Pass(targetPlayer): Pass to a teammate
/// - Check(targetPlayer): Hit opponent to knock puck loose
/// 
/// </summary>
public class FaceoffSetupGuide : MonoBehaviour
{
    [Header("Quick Setup")]
    [Tooltip("Drag your puck GameObject here")]
    public GameObject puckObject;

    [Tooltip("Drag all home team players here")]
    public GameObject[] homeTeamPlayers;

    [Tooltip("Drag all away team players here")]
    public GameObject[] awayTeamPlayers;

    [Header("Auto-Setup Options")]
    [SerializeField] private bool autoCreatePuck = true;
    [SerializeField] private Vector3 puckStartPosition = new Vector3(0, 0.5f, 0);

    [ContextMenu("Auto-Setup Faceoff System")]
    public void AutoSetup()
    {
        Debug.Log("=== Starting Auto-Setup ===");

        // Step 1: Create or find puck
        if (puckObject == null && autoCreatePuck)
        {
            puckObject = new GameObject("Puck");
            puckObject.transform.position = puckStartPosition;
            puckObject.AddComponent<PuckController>();
            Debug.Log("✓ Created Puck GameObject");
        }
        else if (puckObject != null)
        {
            if (puckObject.GetComponent<PuckController>() == null)
            {
                puckObject.AddComponent<PuckController>();
            }
            Debug.Log("✓ Puck found and configured");
        }

        // Step 2: Tag home team players
        foreach (GameObject player in homeTeamPlayers)
        {
            if (player != null)
            {
                player.tag = "HomeTeam";
            }
        }
        Debug.Log($"✓ Tagged {homeTeamPlayers.Length} home team players");

        // Step 3: Tag away team players
        foreach (GameObject player in awayTeamPlayers)
        {
            if (player != null)
            {
                player.tag = "AwayTeam";
            }
        }
        Debug.Log($"✓ Tagged {awayTeamPlayers.Length} away team players");

        // Step 4: Create or configure FaceoffManager
        FaceoffManager manager = FindObjectOfType<FaceoffManager>();
        if (manager == null)
        {
            GameObject managerObj = new GameObject("FaceoffManager");
            manager = managerObj.AddComponent<FaceoffManager>();
            Debug.Log("✓ Created FaceoffManager");
        }

        // Use reflection to set the puck reference
        var puckField = typeof(FaceoffManager).GetField("puck",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        if (puckField != null && puckObject != null)
        {
            PuckController puck = puckObject.GetComponent<PuckController>();
            puckField.SetValue(manager, puck);
            Debug.Log("✓ Linked puck to FaceoffManager");
        }

        Debug.Log("=== Auto-Setup Complete! ===");
        Debug.Log("Press F during play mode to test the faceoff");
    }

    [ContextMenu("Validate Setup")]
    public void ValidateSetup()
    {
        Debug.Log("=== Validating Setup ===");

        int issues = 0;

        // Check for puck
        PuckController puck = FindObjectOfType<PuckController>();
        if (puck == null)
        {
            Debug.LogError("✗ No PuckController found in scene!");
            issues++;
        }
        else
        {
            Debug.Log("✓ Puck found");
        }

        // Check for FaceoffManager
        FaceoffManager manager = FindObjectOfType<FaceoffManager>();
        if (manager == null)
        {
            Debug.LogError("✗ No FaceoffManager found in scene!");
            issues++;
        }
        else
        {
            Debug.Log("✓ FaceoffManager found");
        }

        // Check for tagged players
        GameObject[] homePlayers = GameObject.FindGameObjectsWithTag("HomeTeam");
        GameObject[] awayPlayers = GameObject.FindGameObjectsWithTag("AwayTeam");

        if (homePlayers.Length == 0)
        {
            Debug.LogWarning("⚠ No players tagged as 'HomeTeam'");
            issues++;
        }
        else
        {
            Debug.Log($"✓ Found {homePlayers.Length} home team players");
        }

        if (awayPlayers.Length == 0)
        {
            Debug.LogWarning("⚠ No players tagged as 'AwayTeam'");
            issues++;
        }
        else
        {
            Debug.Log($"✓ Found {awayPlayers.Length} away team players");
        }

        // Check for centers
        bool homeCenter = false;
        bool awayCenter = false;

        foreach (var player in homePlayers)
        {
            PlayerController pc = player.GetComponent<PlayerController>();
            if (pc != null && pc.stats != null && pc.stats.position == PlayerPosition.C)
            {
                homeCenter = true;
                break;
            }
        }

        foreach (var player in awayPlayers)
        {
            PlayerController pc = player.GetComponent<PlayerController>();
            if (pc != null && pc.stats != null && pc.stats.position == PlayerPosition.C)
            {
                awayCenter = true;
                break;
            }
        }

        if (!homeCenter)
        {
            Debug.LogError("✗ No home team Center found!");
            issues++;
        }
        else
        {
            Debug.Log("✓ Home team Center found");
        }

        if (!awayCenter)
        {
            Debug.LogError("✗ No away team Center found!");
            issues++;
        }
        else
        {
            Debug.Log("✓ Away team Center found");
        }

        Debug.Log("=== Validation Complete ===");
        if (issues == 0)
        {
            Debug.Log("<color=green>✓ Everything looks good! Ready for faceoff!</color>");
        }
        else
        {
            Debug.Log($"<color=red>Found {issues} issue(s) that need attention</color>");
        }
    }
}
