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

public class CameraController : MonoBehaviour
{
    [SerializeField] private Transform target;
    
    [SerializeField] private float smooth = 10;

    [Header("Camera Borders")]
    [SerializeField] private float leftBorder = -1;
    [SerializeField] private float rightBorder = 1;
    [SerializeField] private float bottomBorder = -1;
    [SerializeField] private float topBorder = 1;
    
    private Camera _camera;

    private void Start()
    {
        _camera = Camera.main;
    }

    void LateUpdate()
    {
        float offsetY = _camera.orthographicSize;
        float offsetX = _camera.aspect * _camera.orthographicSize;

        float targetX = Mathf.Clamp(target.position.x, leftBorder + offsetX, rightBorder - offsetX);
        float targetY = Mathf.Clamp(target.position.y, bottomBorder + offsetY, topBorder - offsetY);
        Vector3 targetPosition = new Vector3(targetX, targetY, transform.position.z);

        transform.position = Vector3.Lerp(transform.position,targetPosition, smooth);
    }

    #region Helpers

    private void OnValidate()
    {
        leftBorder = Mathf.Clamp(leftBorder, float.MinValue, -1);
        rightBorder = Mathf.Clamp(rightBorder, 1, float.MaxValue);
        bottomBorder = Mathf.Clamp(bottomBorder, float.MinValue, -1);
        topBorder = Mathf.Clamp(topBorder, 1, float.MaxValue);
    }

    private void OnDrawGizmos()
    {
        Color color = Color.red;
        Debug.DrawLine(new Vector2(leftBorder, topBorder), new Vector2(rightBorder, topBorder), color);
        Debug.DrawLine(new Vector2(leftBorder, bottomBorder), new Vector2(rightBorder, bottomBorder), color);
        Debug.DrawLine(new Vector2(leftBorder, bottomBorder), new Vector2(leftBorder, topBorder), color);
        Debug.DrawLine(new Vector2(rightBorder, bottomBorder), new Vector2(rightBorder, topBorder), color);
    }

    #endregion
}
