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

public class GoalController : MonoBehaviour
{
    [Header("Win Settings")]
    [Tooltip("Name of the scene to load on win (leave empty to reload current scene)")]
    public string winSceneName = "";
    
    [Tooltip("Delay before loading win scene")]
    public float winDelay = 1f;
    
    [Tooltip("Show debug messages")]
    public bool showDebug = true;

    [Header("Visual Feedback")]
    [Tooltip("Sprite to show when goal is reached")]
    public GameObject winEffectPrefab;

    private HashSet<PlayerController> playersInZone = new HashSet<PlayerController>();
    private bool hasWon = false;
    private int totalPlayers = 2;  // Snail and Ghost

    private void OnTriggerEnter2D(Collider2D collision)
    {
        PlayerController player = collision.GetComponent<PlayerController>();
        if (player == null) return;

        playersInZone.Add(player);
        
        if (showDebug)
            Debug.Log($"Player '{player.name}' entered goal zone. {playersInZone.Count}/{totalPlayers} players in zone.");

        CheckWinCondition();
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        PlayerController player = collision.GetComponent<PlayerController>();
        if (player == null) return;

        playersInZone.Remove(player);
        
        if (showDebug)
            Debug.Log($"Player '{player.name}' left goal zone. {playersInZone.Count}/{totalPlayers} players in zone.");
    }

    private void CheckWinCondition()
    {
        if (hasWon) return;

        if (playersInZone.Count >= totalPlayers)
        {
            hasWon = true;
            OnWin();
        }
    }

    private void OnWin()
    {
        // Spawn win effect if assigned
        if (winEffectPrefab != null)
        {
            Instantiate(winEffectPrefab, transform.position, Quaternion.identity);
        }

        // Load win scene after delay
        Invoke(nameof(LoadWinScene), winDelay);
    }

    private void LoadWinScene()
    {
        if (!string.IsNullOrEmpty(winSceneName))
        {
            SceneManager.LoadScene(winSceneName);
        }
    }

    void OnDrawGizmos()
    {
        Collider2D col = GetComponent<Collider2D>();
        if (col != null)
        {
            Gizmos.color = new Color(0f, 1f, 0f, 0.3f);  // Semi-transparent green
            
            if (col is BoxCollider2D boxCol)
            {
                Vector3 center = transform.position + (Vector3)boxCol.offset;
                Vector3 size = boxCol.size;
                Gizmos.DrawCube(center, size);
                
                Gizmos.color = Color.green;
                Gizmos.DrawWireCube(center, size);
            }
            else
            {
                Gizmos.DrawWireSphere(transform.position, 1f);
            }
        }
    }
}
