using UnityEngine;

public class MMCameraController : MonoBehaviour
{
    [Header("Camera Settings")]
    public float moveSpeed = 10f;
    public float zoomSpeed = 5f;
    public float minZoom = 2f;
    public float maxZoom = 200f; // Increased for better map overview

    [Header("Team Marker Focus")]
    public KeyCode centerOnTeamKey = KeyCode.C;
    public KeyCode zoomToFullMapKey = KeyCode.F;
    public float focusZoomLevel = 10f;
    public float centeringSpeed = 2f;

    private Camera cam;
    private Vector3 lastMousePosition;
    private Vector3 targetPosition;
    private float targetZoom;
    private bool isMovingToTarget = false;
    private SimpleTeamPlacement teamPlacement;

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

        // Set up camera for top-down view
        cam.orthographic = true; // Ensure camera is in orthographic mode for top-down view

        // Position camera above the map center, looking down
        float mapCenterX = 0f;
        float mapCenterZ = 0f;
        float cameraHeight = 50f; // High above the map

        // Try to get map size from MapMaker2 to center properly
        var mapMaker = FindFirstObjectByType<MapMaker2>();
        if (mapMaker != null)
        {
            var mapData = mapMaker.GetMapData();
            if (mapData != null)
            {
                mapCenterX = mapData.Width / 2f;
                mapCenterZ = mapData.Height / 2f;
                cameraHeight = Mathf.Max(mapData.Width, mapData.Height) * 0.7f; // Scale height with map size
            }
        }

        transform.position = new Vector3(mapCenterX, cameraHeight, mapCenterZ);

        // Set camera to look straight down at the map (90 degrees on X-axis)
        transform.rotation = Quaternion.Euler(90f, 0f, 0f);

        // Set orthographic size to show a good portion of the map
        if (cam.orthographic)
        {
            cam.orthographicSize = Mathf.Max(20f, cameraHeight * 0.3f);
        }

        // Initialize target values
        targetPosition = transform.position;
        targetZoom = cam.orthographicSize;

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

        Debug.Log($"🎥 Camera initialized: Position={transform.position}, Rotation={transform.rotation.eulerAngles}, OrthographicSize={cam.orthographicSize}, Mode={(cam.orthographic ? "Orthographic" : "Perspective")}");
    }

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

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

        // Handle smooth movement to target
        if (isMovingToTarget)
        {
            transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * centeringSpeed);
            cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, targetZoom, Time.deltaTime * centeringSpeed);

            // Check if we're close enough to stop moving
            if (Vector3.Distance(transform.position, targetPosition) < 0.1f &&
                Mathf.Abs(cam.orthographicSize - targetZoom) < 0.1f)
            {
                isMovingToTarget = false;
            }
        }
        else
        {
            // Normal camera controls
            HandleMovement();
            HandleZoom();
            HandleMouseDrag();
        }

        // Help find ForestRiver tiles
        if (Input.GetKeyDown(KeyCode.H))
        {
            Debug.Log("💡 Camera Controls:\n" +
                     $"- {centerOnTeamKey}: Center on team marker (preserves zoom)\n" +
                     $"- {zoomToFullMapKey}: Zoom to full map\n" +
                     "- WASD/Arrows: Move camera\n" +
                     $"- Mouse wheel: Zoom (range: {minZoom}-{maxZoom})\n" +
                     "- Middle mouse: Drag\n" +
                     "- R: Place team randomly (if needed)\n" +
                     "- F: Look for blue-green ForestRiver tiles");
        }
    }

    /// <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 (keep Y position for camera height)
                // For top-down view: X and Z are the map coordinates, Y is camera height
                targetPosition = new Vector3(teamPos.x, transform.position.y, teamPos.z);
                // Keep current zoom level instead of changing to focusZoomLevel
                targetZoom = cam.orthographicSize;
                isMovingToTarget = true;

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

                // Try to find team marker by name as backup
                GameObject foundMarker = GameObject.Find("TeamMarker");
                if (foundMarker != null)
                {
                    Vector3 teamPos = foundMarker.transform.position;
                    targetPosition = new Vector3(teamPos.x, transform.position.y, teamPos.z);
                    targetZoom = cam.orthographicSize;
                    isMovingToTarget = true;
                    Debug.Log($"🎯 Found team marker by name, centering at: {teamPos}");
                }
                else
                {
                    Debug.LogError("❌ Could not find team marker by name either!");
                }
            }
        }
        else
        {
            Debug.LogWarning("⚠️ Team placement not found or team not placed! Try pressing R to place team first.");
        }
    }

    /// <summary>
    /// Zoom out to show the entire map
    /// </summary>
    public void ZoomToFullMap()
    {
        MapData mapData = null;
        float tileSize = 1f;

        // Try to find MapMaker2 first
        MapMaker2 mapMaker = FindFirstObjectByType<MapMaker2>();
        if (mapMaker != null)
        {
            mapData = mapMaker.GetMapData();

            // Get the MapVisualizer to account for tile scaling
            MapVisualizer mapVisualizer = FindFirstObjectByType<MapVisualizer>();
            tileSize = mapVisualizer != null ? mapVisualizer.tileSize : 1f;
        }

        if (mapData != null)
        {
            // Calculate map center accounting for tile size
            targetPosition = new Vector3(
                (mapData.Width * tileSize) / 2f,
                transform.position.y,
                (mapData.Height * tileSize) / 2f
            );

            // Calculate required zoom to fit entire map
            float mapHeight = mapData.Height * tileSize;
            float mapWidth = mapData.Width * tileSize;
            float mapSize = Mathf.Max(mapWidth, mapHeight);
            targetZoom = (mapSize / 2f) + 5f; // Add padding for better view
            targetZoom = Mathf.Clamp(targetZoom, minZoom, maxZoom);

            isMovingToTarget = true;

            Debug.Log($"🗺️ Zooming to full map: Size {mapData.Width}x{mapData.Height}, TileSize: {tileSize}, WorldSize: {mapWidth:F1}x{mapHeight:F1}, Zoom: {targetZoom}");
        }
        else
        {
            Debug.LogWarning("⚠️ No MapMaker2 component found!");
        }
    }

    private void HandleMovement()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        if (horizontal != 0 || vertical != 0)
        {
            // For top-down view: horizontal = X movement, vertical = Z movement
            Vector3 movement = new Vector3(horizontal, 0, vertical) * moveSpeed * Time.deltaTime;
            transform.Translate(movement, Space.World); // Use world space for consistent movement

            // Stop automatic movement to target if user is manually controlling
            isMovingToTarget = false;
            targetPosition = transform.position;
        }
    }

    private void HandleZoom()
    {
        float scroll = Input.GetAxis("Mouse ScrollWheel");
        if (scroll != 0)
        {
            float oldSize = cam.orthographicSize;
            float newSize = cam.orthographicSize - scroll * zoomSpeed;
            newSize = Mathf.Clamp(newSize, minZoom, maxZoom);
            cam.orthographicSize = newSize;

            // Debug log to check zoom limits
            if (newSize >= maxZoom - 0.1f || newSize <= minZoom + 0.1f)
            {
                Debug.Log($"🔍 Zoom limit reached: {newSize:F1} (min: {minZoom}, max: {maxZoom})");
            }

            // Update target zoom if we're not moving to a target
            if (!isMovingToTarget)
            {
                targetZoom = newSize;
            }
        }
    }

    private void HandleMouseDrag()
    {
        if (Input.GetMouseButtonDown(2)) // Middle mouse button
        {
            lastMousePosition = Input.mousePosition;
        }

        if (Input.GetMouseButton(2))
        {
            Vector3 delta = Input.mousePosition - lastMousePosition;
            Vector3 worldDelta = cam.ScreenToWorldPoint(delta) - cam.ScreenToWorldPoint(Vector3.zero);
            transform.position -= worldDelta;
            lastMousePosition = Input.mousePosition;

            // Stop automatic movement to target if user is manually controlling
            isMovingToTarget = false;
            targetPosition = transform.position;
        }
    }
}