using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;
public class AssetBundleLoaderScene : MonoBehaviour
{
    [Header("UI Elements")]
    public TMP_Text progressText;         // Assign this in the Inspector
    public Button startSceneButton;   // Assign this in the Inspector

    [Header("Download Settings")]
    public string assetBundleUrl = "http://yourserver.com/path/to/scene_assetbundle"; // Replace with your real URL

    private AssetBundle loadedBundle;
    private string sceneNameToLoad;

    void Start()
    {
        if (progressText != null)
        {
            progressText.text = "0%";
            progressText.gameObject.SetActive(true);
        }

        if (startSceneButton != null)
        {
            startSceneButton.gameObject.SetActive(false);
            startSceneButton.onClick.AddListener(OnStartSceneClicked);
        }

        StartCoroutine(DownloadAssetBundle());
    }

    IEnumerator DownloadAssetBundle()
    {
        using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(assetBundleUrl))
        {
            uwr.SendWebRequest();

            while (!uwr.isDone)
            {
                float progress = Mathf.Clamp01(uwr.downloadProgress);
                if (progressText != null)
                    progressText.text = $"{(progress * 100f):0.0}%";

                yield return null;
            }

            if (uwr.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("Download failed: " + uwr.error);
                if (progressText != null)
                    progressText.text = "Download failed!";
                yield break;
            }

            loadedBundle = DownloadHandlerAssetBundle.GetContent(uwr);
            if (loadedBundle == null)
            {
                Debug.LogError("Failed to load AssetBundle.");
                if (progressText != null)
                    progressText.text = "Load failed!";
                yield break;
            }

            string[] scenes = loadedBundle.GetAllScenePaths();
            if (scenes.Length == 0)
            {
                Debug.LogError("No scenes found in AssetBundle.");
                if (progressText != null)
                    progressText.text = "No scenes in bundle!";
                yield break;
            }

            sceneNameToLoad = System.IO.Path.GetFileNameWithoutExtension(scenes[0]);
            Debug.Log("Scene ready to load: " + sceneNameToLoad);

            if (progressText != null)
                progressText.text = "Download complete! Click to start.";

            if (startSceneButton != null)
                startSceneButton.gameObject.SetActive(true);
        }
    }

    void OnStartSceneClicked()
    {
        if (!string.IsNullOrEmpty(sceneNameToLoad))
        {
            StartCoroutine(LoadSceneCoroutine());
        }
    }

    IEnumerator LoadSceneCoroutine()
    {
        if (progressText != null)
            progressText.text = "Loading scene...";

        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneNameToLoad, LoadSceneMode.Single);
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
    }
}