using System; using AppleHills.Core.Settings; using Core; using Input; using Interactions; using UnityEngine; // Added for IInteractionSettings namespace LevelS { /// /// Handles level switching when interacted with. Applies switch data and triggers scene transitions. /// public class LevelSwitch : MonoBehaviour { /// /// Data for this level switch (target scene, icon, etc). /// public LevelSwitchData switchData; private SpriteRenderer _iconRenderer; private Interactable _interactable; // Settings reference private IInteractionSettings _interactionSettings; private bool _isActive = true; /// /// Unity Awake callback. Sets up icon, interactable, and event handlers. /// void Awake() { _isActive = true; if (_iconRenderer == null) _iconRenderer = GetComponent(); _interactable = GetComponent(); if (_interactable != null) { _interactable.characterArrived.AddListener(OnCharacterArrived); } // Initialize settings reference _interactionSettings = GameManager.GetSettingsObject(); ApplySwitchData(); } /// /// Unity OnDestroy callback. Cleans up event handlers. /// void OnDestroy() { if (_interactable != null) { _interactable.characterArrived.RemoveListener(OnCharacterArrived); } } #if UNITY_EDITOR /// /// Unity OnValidate callback. Ensures icon and data are up to date in editor. /// void OnValidate() { if (_iconRenderer == null) _iconRenderer = GetComponent(); ApplySwitchData(); } #endif /// /// Applies the switch data to the level switch (icon, name, etc). /// public void ApplySwitchData() { if (switchData != null) { if (_iconRenderer != null) _iconRenderer.sprite = switchData.mapSprite; gameObject.name = switchData.targetLevelSceneName; // Optionally update other fields, e.g. description } } /// /// Handles the start of an interaction (shows confirmation menu and switches the level if confirmed). /// private void OnCharacterArrived() { if (switchData == null || string.IsNullOrEmpty(switchData.targetLevelSceneName) || !_isActive) return; var menuPrefab = _interactionSettings?.LevelSwitchMenuPrefab; if (menuPrefab == null) { Debug.LogError("LevelSwitchMenu prefab not assigned in InteractionSettings!"); return; } // Spawn the menu overlay (assume Canvas parent is handled in prefab setup) var menuGo = Instantiate(menuPrefab); var menu = menuGo.GetComponent(); if (menu == null) { Debug.LogError("LevelSwitchMenu component missing on prefab!"); Destroy(menuGo); return; } // Setup menu with data and callbacks menu.Setup(switchData, OnMenuConfirm, OnMenuCancel); _isActive = false; // Prevent re-triggering until menu is closed // Switch input mode to UI only InputManager.Instance.SetInputMode(InputMode.UI); } private async void OnMenuConfirm() { var progress = new Progress(p => Debug.Log($"Loading progress: {p * 100:F0}%")); await SceneManagerService.Instance.SwitchSceneAsync(switchData.targetLevelSceneName, progress); } private void OnMenuCancel() { _isActive = true; // Allow interaction again if cancelled } } }