using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;

public class MainMenu : MonoBehaviour
{
    [Header("Header Elements")]
    public TextMeshProUGUI titleText;      // Title text UI element
    public TextMeshProUGUI subtitleText;   // Subtitle text UI element
    public VideoPlayer videoPlayer;        // Video player component
    public GameObject shapeSelect;        // Shape selection object
    public GameObject menuItems;           // Menu items object
    public GameObject controls;            // UI Control hints

    [Header("Title Customization")]
    public string title;                   // Title text
    public string subtitle;                // Subtitle text
    public Color subtitleColor;            // Subtitle color

    [Header("Logo Customization")]
    public Image primaryLogo;              // Primary logo image UI element
    public Sprite logo;                    // Logo sprite
    public Color logoColor;                // Logo color

    [Header("Background Video")]
#if UNITY_WEBGL
    public string webGLVideoURL;           // WebGL video URL
#endif
#if !UNITY_WEBGL
    public VideoClip desktopBackgroundVideo; // Desktop background video clip
#endif
    public bool playVideo;                  // Flag to play video

    [Header("Background Audio")]
    public AudioClip backgroundMusic;      // Background music audio clip
    public bool playMusic;                  // Flag to play background music
    [Range(0.0f, 1.0f)]
    public float trackVolume = 0.5f;        // Background music volume

    private float initialCutoffFrequency;   // Initial cutoff frequency for low pass filter
    private float targetCutoffFrequency = 900f; // Target cutoff frequency for low pass filter
    private float transitionTime = 2f;       // Transition time for low pass filter

    private AudioSource audioSource;        // Audio source component
    private AudioLowPassFilter lowPassFilter; // Audio low pass filter component

    public static MainMenu instance;        // Singleton instance

    private void Awake()
    {
        instance = this;

        // Add audio source and low pass filter components
        audioSource = gameObject.AddComponent<AudioSource>();
        lowPassFilter = gameObject.AddComponent<AudioLowPassFilter>();
        lowPassFilter.cutoffFrequency = 5000; // Set initial cutoff frequency
    }

    private void Start()
    {
        // Play background music
        if (playMusic && backgroundMusic != null)
        {
            audioSource.clip = backgroundMusic;
            audioSource.loop = true;
            audioSource.volume = trackVolume;
            audioSource.Play();
        }
        else
        {
            Debug.Log("Please assign an audio track to the Background Music variable.");
        }

        // Show main menu
        ShowMenu();
    }

    /// <summary>
    /// Shows the main menu with customized elements.
    /// </summary>
    public void ShowMenu()
    {
        // Set title and subtitle text
        titleText.text = title;
        subtitleText.text = subtitle;
        subtitleText.color = subtitleColor;

        // Set primary logo image and color
        primaryLogo.sprite = logo;
        primaryLogo.color = logoColor;

        // Play background video if enabled
        if (playVideo)
        {
            PlayVideo();
        }
    }

    /// <summary>
    /// Transitions the low pass filter cutoff frequency when shape select is shown.
    /// </summary>
    private IEnumerator TransitionCutoffFrequency()
    {
        float elapsedTime = 0f;

        while (elapsedTime < transitionTime)
        {
            float t = elapsedTime / transitionTime;
            float currentCutoffFrequency = Mathf.Lerp(initialCutoffFrequency, targetCutoffFrequency, t);
            lowPassFilter.cutoffFrequency = currentCutoffFrequency;

            elapsedTime += Time.deltaTime;
            yield return null;
        }

        lowPassFilter.cutoffFrequency = targetCutoffFrequency;
    }

    /// <summary>
    /// Plays the click sound effect.
    /// </summary>
    public void PlayClick()
    {
        GameObject.Find("UIAudio").GetComponent<AudioSource>().Play();
    }

    /// <summary>
    /// Plays the background video based on platform.
    /// </summary>
    private void PlayVideo()
    {
#if UNITY_WEBGL
        if (!string.IsNullOrEmpty(webGLVideoURL))
        {
            StartCoroutine(PlayWebGLVideo(webGLVideoURL));
        }
        else
        {
            videoPlayer.enabled = false;
        }
#else
        if (desktopBackgroundVideo != null)
        {
            videoPlayer.enabled = true;
            videoPlayer.clip = desktopBackgroundVideo;
            videoPlayer.Play();
        }
        else
        {
            Debug.Log("Please assign a video clip to the Desktop Background Video variable.");
        }
#endif
    }

    /// <summary>
    /// Plays the WebGL video.
    /// </summary>
    private IEnumerator PlayWebGLVideo(string url)
    {
        videoPlayer.enabled = true;
        videoPlayer.source = VideoSource.Url;
        videoPlayer.url = url;
        videoPlayer.Prepare();
        while (!videoPlayer.isPrepared)
        {
            yield return null;
        }
        videoPlayer.Play();
    }

    /// <summary>
    /// Shows the shape select screen.
    /// </summary>
    public void ShowShapeSelect()
    {
        PlayClick(); // Play click sound effect
        shapeSelect.SetActive(true); // Show shape select panel
        initialCutoffFrequency = lowPassFilter.cutoffFrequency; // Store initial cutoff frequency
        StartCoroutine(TransitionCutoffFrequency()); // Transition low pass filter cutoff frequency
    }


    /// <summary>
    /// Hide the shape select screen.
    /// </summary>
    public void HideShapeSelect()
    {
        PlayClick();
        shapeSelect.SetActive(false);
        initialCutoffFrequency = 5000;
        StartCoroutine(TransitionCutoffFrequency());
    }

    /// <summary>
    /// Shows the controls screeen.
    /// </summary>
    public void ShowControls()
    {
        PlayClick();
        controls.SetActive(true);
    }

    /// <summary>
    /// Hide the controls screen.
    /// </summary>
    public void HideControls()
    {
        PlayClick();
        controls.SetActive(false);
    }

    /// <summary>
    /// Starts the game.
    /// </summary>
    public void StartGame()
    {
        PlayClick(); // Play click sound effect
        Loader.fromMenu = true; // Set flag to indicate loading from menu
        SceneManager.LoadScene("Loading"); // Load loading scene
    }

    /// <summary>
    /// Quits the application.
    /// </summary>
    public void Quit()
    {
        PlayClick(); // Play click sound effect
        Application.Quit(); // Quit the application
    }
}
