using UnityEngine;
using UnityEngine.UI;

namespace AvatarSDKMove
{
    /// <summary>Responsive framing shared by the two sample scenes. Does not change project settings.</summary>
    [ExecuteAlways]
    public sealed class SamplePresentation : MonoBehaviour
    {
        public Camera previewCamera;
        public RectTransform sidebar;
        public Canvas canvas;
        public AccountPanel account;
        public Text generationStatus;
        public RectTransform historyScroll;

        private void LateUpdate()
        {
            if (canvas == null || previewCamera == null || sidebar == null)
                return;

            // Also resolve the account in already-open scenes that have not reloaded
            // the newly serialized reference after a script update.
            if (account == null)
                account = canvas.GetComponentInChildren<AccountPanel>(true);

            bool showSidebar = account == null || account.IsSignedIn;
            if (sidebar.gameObject.activeSelf != showSidebar)
                sidebar.gameObject.SetActive(showSidebar);

            float width = ((RectTransform)canvas.transform).rect.width;
            float panelWidth = Mathf.Min(520f, width * 0.48f);
            float split = showSidebar ? panelWidth / Mathf.Max(1f, width) : 0;
            sidebar.anchorMax = new Vector2(0, 1);
            sidebar.sizeDelta = new Vector2(panelWidth, 0);
            previewCamera.rect = new Rect(0, 0, 1, 1);
            // Keep the full character in frame when the Game view becomes narrow.
            float aspect = Mathf.Max(0.2f, previewCamera.aspect * (1 - split));
            previewCamera.fieldOfView = Mathf.Max(32f, 2f * Mathf.Atan(0.85f / aspect / 4.9f) * Mathf.Rad2Deg);
            previewCamera.ResetProjectionMatrix();
            Matrix4x4 projection = previewCamera.projectionMatrix;
            projection.m02 = -split;
            previewCamera.projectionMatrix = projection;

            // Reserve only the space needed by the existing status message.
            if (generationStatus != null && historyScroll != null)
            {
                float height = string.IsNullOrEmpty(generationStatus.text) ? 0 : generationStatus.preferredHeight;
                var statusRect = generationStatus.rectTransform;
                statusRect.sizeDelta = new Vector2(statusRect.sizeDelta.x, height);
                historyScroll.offsetMax = new Vector2(historyScroll.offsetMax.x,
                    statusRect.anchoredPosition.y - height - 12);
            }

        }

        private void OnDisable()
        {
            if (previewCamera != null)
                previewCamera.ResetProjectionMatrix();
        }
    }
}
