using UnityEngine;

public class CameraMovement : MonoBehaviour
{
    public float moveSpeed = 10f;
    public float edgeSize = 20f;  // how close to the edge before movement starts

    [Header("Movement Options")]
    public bool moveOnEdges = true;
    
    [Header("Zoom Options")]
    public float zoomSpeed = 1f;
    public float minZoom = 2.5f;     
    public float maxZoom = 8f;    
    public float zoomSmooth = 5; 
    private float targetZoom;
    private Camera cam;
    
    [Header("Camera Bounds")]
    public Vector2 minBounds; // bottom-left corner of the house area
    public Vector2 maxBounds; // top-right corner of the house area
    
    void Start()
    {
        cam = GetComponent<Camera>();
        targetZoom = cam.orthographicSize;
    }
    
    void Update()
    {
        int invert = (HUDManager.Instance != null && HUDManager.Instance.IsSanityZero) ? -1 : 1;

        Vector3 dir = Vector3.zero;

        // move with keyboard
        float h = Input.GetAxisRaw("Horizontal") * invert;
        float v = Input.GetAxisRaw("Vertical") * invert;
        dir += new Vector3(h, v, 0);

        // move with mouse at screen edges
        if (moveOnEdges)
        {
            Vector2 mouse = Input.mousePosition;

            if (mouse.x < edgeSize) dir.x -= 1 * invert;
            if (mouse.x > Screen.width - edgeSize) dir.x += 1 * invert;
            if (mouse.y < edgeSize) dir.y -= 1 * invert;
            if (mouse.y > Screen.height - edgeSize) dir.y += 1 * invert;
        }

        // normalize direction to prevent faster diagonal movement
        if (dir.sqrMagnitude > 1f)
            dir.Normalize();

        transform.position += dir * moveSpeed * Time.deltaTime;
        
        Vector3 pos = transform.position;
        pos.x = Mathf.Clamp(pos.x, minBounds.x, maxBounds.x);
        pos.y = Mathf.Clamp(pos.y, minBounds.y, maxBounds.y);
        transform.position = pos;
        
        // zoom with mouse wheel
        float scroll = Input.mouseScrollDelta.y * invert;
        if (scroll != 0f)
        {
            // adjust target zoom
            targetZoom -= scroll * zoomSpeed;
            targetZoom = Mathf.Clamp(targetZoom, minZoom, maxZoom);
        }

        // smooth zoom
        cam.orthographicSize = Mathf.Lerp(
            cam.orthographicSize,
            targetZoom,
            Time.deltaTime * zoomSmooth
        );
        
    }
}