using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using CustomAssetBundleSystem;

/// <summary>
/// Example integration: Replace Addressables with custom AssetBundle system
/// Drop-in replacement for your existing SceneLoader
/// </summary>
public class CustomAssetBundleSceneLoader : MonoBehaviour
{
    [Header("UI References (Optional)")]
    public Slider progressSlider;
    public Text statusText;

    [Header("Settings")]
    public bool initializeOnStart = true;

    private bool isInitialized = false;

    void Start()
    {
        if (initializeOnStart)
        {
            StartCoroutine(InitializeAndLoadGameScene());
        }
    }

    /// <summary>
    /// Initialize the AssetBundle system and load Game scene
    /// Call this instead of Addressables.InitializeAsync()
    /// </summary>
    public IEnumerator InitializeAndLoadGameScene()
    {
        UpdateStatus("Initializing AssetBundle system...");

        // Initialize the catalog
        yield return RemoteAssetBundleManager.Instance.InitializeAsync();

        if (!RemoteAssetBundleManager.Instance.IsInitialized)
        {
            UpdateStatus("✗ Failed to initialize AssetBundle system");
            Debug.LogError("[CustomAssetBundleLoader] Initialization failed!");
            yield break;
        }

        isInitialized = true;
        UpdateStatus("✓ AssetBundle system initialized");

        // Optional: Show catalog info
        var catalog = RemoteAssetBundleManager.Instance.GetCatalog();
        Debug.Log($"[CustomAssetBundleLoader] Catalog version: {catalog.version}");
        Debug.Log($"[CustomAssetBundleLoader] Available bundles: {catalog.bundles.Count}");

        // Load the Game scene
        yield return LoadGameScene();
    }

    /// <summary>
    /// Load the Game scene from remote AssetBundle
    /// </summary>
    public IEnumerator LoadGameScene()
    {
        if (!isInitialized)
        {
            Debug.LogError("[CustomAssetBundleLoader] Not initialized! Call InitializeAndLoadGameScene() first.");
            yield break;
        }

        UpdateStatus("Loading Game scene...");

        bool sceneLoaded = false;

        // Subscribe to download progress
        RemoteAssetBundleManager.Instance.OnBundleDownloadProgress += (bundleName, progress) =>
        {
            UpdateProgress(progress);
            UpdateStatus($"Downloading {bundleName}: {progress * 100:F1}%");
        };

        // Load the scene
        yield return RemoteAssetBundleManager.Instance.LoadSceneAsync("Game", (success) =>
        {
            sceneLoaded = success;
        });

        if (sceneLoaded)
        {
            UpdateStatus("✓ Game scene loaded!");
            Debug.Log("[CustomAssetBundleLoader] ✓ Game scene loaded successfully!");
        }
        else
        {
            UpdateStatus("✗ Failed to load Game scene");
            Debug.LogError("[CustomAssetBundleLoader] ✗ Failed to load Game scene!");
        }
    }

    /// <summary>
    /// Load any scene by name
    /// </summary>
    public void LoadScene(string sceneName)
    {
        StartCoroutine(LoadSceneCoroutine(sceneName));
    }

    private IEnumerator LoadSceneCoroutine(string sceneName)
    {
        if (!isInitialized)
        {
            Debug.LogError("[CustomAssetBundleLoader] Not initialized!");
            yield break;
        }

        UpdateStatus($"Loading {sceneName}...");

        bool success = false;
        yield return RemoteAssetBundleManager.Instance.LoadSceneAsync(sceneName, (loaded) =>
        {
            success = loaded;
        });

        if (success)
        {
            UpdateStatus($"✓ {sceneName} loaded!");
        }
        else
        {
            UpdateStatus($"✗ Failed to load {sceneName}");
        }
    }

    #region UI Helpers

    private void UpdateProgress(float progress)
    {
        if (progressSlider != null)
        {
            progressSlider.value = progress;
        }
    }

    private void UpdateStatus(string message)
    {
        if (statusText != null)
        {
            statusText.text = message;
        }
        Debug.Log($"[CustomAssetBundleLoader] {message}");
    }

    #endregion

    #region Public API - Replace your existing SceneLoader calls

    /// <summary>
    /// Check if the system is ready (replaces Addressables initialization check)
    /// </summary>
    public bool IsReady()
    {
        return RemoteAssetBundleManager.Instance.IsInitialized;
    }

    /// <summary>
    /// Get memory usage info
    /// </summary>
    public string GetMemoryInfo()
    {
        return RemoteAssetBundleManager.Instance.GetMemoryStats();
    }

    /// <summary>
    /// Unload all bundles to free memory
    /// </summary>
    public void UnloadAllBundles()
    {
        RemoteAssetBundleManager.Instance.UnloadAllBundles(true);
    }

    #endregion
}
