using UnityEngine;
using UnityEngine.EventSystems;

public class MapCameraController : MonoBehaviour
{
    [Header("Camera Movement")]
    public float moveSpeed = 10f;
    public float zoomSpeed = 5f;
    public float minZoom = 5f;
    public float maxZoom = 100f; // Increased for better map overview
    public float initialZoom = 35f; // Starting zoom level to see more of the map

    [Header("Team Marker Focus")]
    public KeyCode centerOnTeamKey = KeyCode.C;
    public float focusZoomLevel = 15f; // Zoom level when focusing on team marker
    public float centeringSpeed = 2f; // Speed of camera movement when centering

    private Camera cam;
    private Vector3 targetPosition;
    private float targetSize;
    private SimpleTeamPlacement teamPlacement;

    void Start()
    {
        cam = GetComponent<Camera>();
        if (cam == null)
            cam = Camera.main;

        // Set camera to look straight down
        transform.rotation = Quaternion.Euler(90f, 0f, 0f);

        // Position camera above the center of the map (assuming 100x100 map)
        transform.position = new Vector3(50f, 30f, 50f);

        targetPosition = transform.position;
        targetSize = initialZoom;
        cam.orthographicSize = initialZoom;

        // Ensure camera is orthographic for top-down view
        cam.orthographic = true;

        // Find team placement component
        teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
    }

    void Update()
    {
        // Handle team marker centering
        if (Input.GetKeyDown(centerOnTeamKey))
        {
            CenterOnTeamMarker();
        }

        // Handle zoom to full map
        if (Input.GetKeyDown(KeyCode.F))
        {
            ZoomToFullMap();
        }

        // Show help
        if (Input.GetKeyDown(KeyCode.H))
        {
            Debug.Log("💡 Camera Controls:\n" +
                     $"- {centerOnTeamKey}: Center on team marker\n" +
                     "- F: Zoom to full map\n" +
                     "- WASD/Arrows: Move camera\n" +
                     "- Mouse wheel: Zoom");
        }

        // Only handle camera input if mouse is within the map area
        if (IsMouseInMapArea())
        {
            HandleMovement();
            HandleZoom();
        }

        // Always smooth camera movement (even if input is disabled)
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * centeringSpeed);
        cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, targetSize, Time.deltaTime * centeringSpeed);
    }

    /// <summary>
    /// Center the camera on the team marker position
    /// </summary>
    public void CenterOnTeamMarker()
    {
        if (teamPlacement == null)
        {
            teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
        }

        if (teamPlacement != null && teamPlacement.IsTeamPlaced())
        {
            GameObject teamMarker = teamPlacement.GetTeamMarker();
            if (teamMarker != null)
            {
                Vector3 teamPos = teamMarker.transform.position;

                // Set target position to center on team marker
                targetPosition = new Vector3(teamPos.x, transform.position.y, teamPos.z);

                // Optionally adjust zoom level for better focus
                targetSize = focusZoomLevel;

                Debug.Log($"🎯 Centering camera on team marker at position: {teamPos}");
            }
            else
            {
                Debug.LogWarning("⚠️ Team marker object not found!");
            }
        }
        else
        {
            Debug.LogWarning("⚠️ Team placement not found or team not placed!");
        }
    }

    /// <summary>
    /// Zoom out to show the entire map
    /// </summary>
    public void ZoomToFullMap()
    {
        // Find the MapMaker2 component to get map dimensions
        MapMaker2 mapMaker = FindFirstObjectByType<MapMaker2>();
        if (mapMaker != null)
        {
            var mapData = mapMaker.GetMapData();
            if (mapData != null)
            {
                // Calculate map center
                Vector3 mapCenter = new Vector3(
                    mapData.Width / 2f,
                    transform.position.y,
                    mapData.Height / 2f
                );

                // Calculate required zoom to fit entire map
                float mapSize = Mathf.Max(mapData.Width, mapData.Height);
                float requiredZoom = mapSize * 0.6f; // Add some padding

                targetPosition = mapCenter;
                targetSize = Mathf.Clamp(requiredZoom, minZoom, maxZoom);

                Debug.Log($"🗺️ Zooming to full map: Size {mapData.Width}x{mapData.Height}, Zoom: {targetSize}");
            }
        }
    }

    void HandleMovement()
    {
        Vector3 moveDirection = Vector3.zero;

        // WASD or Arrow Keys movement
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
            moveDirection.z += 1f;
        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
            moveDirection.z -= 1f;
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
            moveDirection.x -= 1f;
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
            moveDirection.x += 1f;

        // Apply movement
        targetPosition += moveDirection.normalized * moveSpeed * Time.deltaTime;

        // Keep camera within reasonable bounds (adjust based on your map size)
        targetPosition.x = Mathf.Clamp(targetPosition.x, -20f, 120f);
        targetPosition.z = Mathf.Clamp(targetPosition.z, -20f, 120f);
    }

    void HandleZoom()
    {
        float scroll = Input.GetAxis("Mouse ScrollWheel");
        if (scroll != 0f)
        {
            targetSize -= scroll * zoomSpeed;
            targetSize = Mathf.Clamp(targetSize, minZoom, maxZoom);
        }
    }

    /// <summary>
    /// Check if the mouse is currently within the map area (not in UI panels)
    /// </summary>
    /// <returns>True if mouse is in the map area, false if in UI areas</returns>
    private bool IsMouseInMapArea()
    {
        Vector2 mousePosition = Input.mousePosition;

        // Define the map area bounds (adjust these values based on your UI layout)
        // These values represent the approximate red square area from your image
        float leftUIWidth = 150f;      // Map Legend panel width
        float rightUIWidth = 300f;     // Your Team panel width
        float topUIHeight = 0f;        // No top UI currently
        float bottomUIHeight = 0f;     // No bottom UI currently

        // Calculate the actual map area
        float mapLeft = leftUIWidth;
        float mapRight = Screen.width - rightUIWidth;
        float mapTop = Screen.height - topUIHeight;
        float mapBottom = bottomUIHeight;

        // Check if mouse is within the map area
        bool inMapArea = mousePosition.x >= mapLeft &&
                        mousePosition.x <= mapRight &&
                        mousePosition.y >= mapBottom &&
                        mousePosition.y <= mapTop;

        return inMapArea;
    }
}
