using UnityEngine;
using UnityEngine.Video;

/// <summary>
/// Minimal script to ensure a VideoPlayer uses a StreamingAssets video path at runtime.
/// It sets the VideoPlayer.url to the file inside StreamingAssets and auto-plays once prepared.
/// No scene management, no events – keep those externally.
/// </summary>
[RequireComponent(typeof(VideoPlayer))]
public class SplashVideoPlayer : MonoBehaviour
{
    [Tooltip("Relative video file name inside StreamingAssets (e.g. 'uncaptured_splash.mp4').")]
    public string videoFileName = "uncaptured_splash.mp4";

    [Tooltip("Fallback video file for Unity editor (WebM/VP8 for Linux compatibility).")]
    public string editorVideoFileName = "uncaptured_splash_editor.webm";

    [Tooltip("Automatically play once prepared.")]
    public bool autoPlay = true;

    private VideoPlayer _videoPlayer;

    private void Awake()
    {
        _videoPlayer = GetComponent<VideoPlayer>();
        ConfigureVideoPlayer();
        SetUrl();
        _videoPlayer.prepareCompleted += OnPrepared;
        _videoPlayer.errorReceived += OnError;
        _videoPlayer.Prepare();
    }

    private void ConfigureVideoPlayer()
    {
        _videoPlayer.playOnAwake = false; // We control when to play
        _videoPlayer.source = VideoSource.Url;
        // Choose a render mode that fits your setup; here we assume RenderTexture or Camera Near Plane set in inspector
    }

    private void SetUrl()
    {
        // Use WebM for editor (better Linux support), MP4 for builds
        string fileToUse = videoFileName;
#if UNITY_EDITOR
        if (!string.IsNullOrEmpty(editorVideoFileName))
        {
            fileToUse = editorVideoFileName;
        }
#endif

        if (string.IsNullOrEmpty(fileToUse))
        {
            Debug.LogWarning("SplashVideoPlayer: videoFileName is empty.");
            return;
        }
        string path = System.IO.Path.Combine(Application.streamingAssetsPath, fileToUse);
        if (!path.StartsWith("file://"))
            path = "file://" + path;
        _videoPlayer.url = path;
        Debug.Log($"[SplashVideoPlayer] Loading video: {path}");
    }

    private void OnPrepared(VideoPlayer vp)
    {
        if (autoPlay)
        {
            vp.Play();
        }
    }

    private void OnError(VideoPlayer vp, string message)
    {
        Debug.LogWarning($"SplashVideoPlayer: video error -> {message}");
    }
}
