using UnityEngine;
using UnityEngine.UI;

public class ExitConfirmationDialog : MonoBehaviour
{
    public GameObject dialog; // Reference to the dialog panel
    public Button confirmButton;
    public Button cancelButton;

    void Start()
    {
        // 初始化时不强制设置 dialog 状态，保持与 Inspector 设置一致
        // 如果 dialog 未分配，则默认隐藏
        if (dialog != null)
        {
            // 只在 dialog 已分配的情况下进行初始化
        }
        else
        {
            dialog = gameObject; // 默认使用自身 GameObject
        }

        // Set up button listeners
        confirmButton.onClick.AddListener(OnConfirmExit);
        cancelButton.onClick.AddListener(OnCancelExit);

        // 确保初始隐藏
        HideDialog();
    }
    // Method to show the dialog
    public void ShowDialog()
    {
        try
        {
            UnityMainThreadDispatcher.Instance.Enqueue(() => {
                if (dialog != null)
                {
                    NativeLogger.I("[Unity Dialog]", $"SetActive 1 {dialog.activeSelf}");
                    dialog.SetActive(true);
                    NativeLogger.I("[Unity Dialog]", $"SetActive 2 {dialog.activeSelf}");
                }
                else
                {
                    NativeLogger.I("[Unity Dialog]", "Dialog is null");
                }
            });
        }
        catch (System.Exception ex)
        {
            NativeLogger.I("[Unity Dialog]", $"SetActive true {ex.Message}");
        }
    }

    // Method to hide the dialog
    public void HideDialog()
    {
        try
        {
            UnityMainThreadDispatcher.Instance.Enqueue(() => {
                if (dialog != null)
                {
                    dialog.SetActive(false);
                }
            });
        }
        catch (System.Exception ex)
        {
            NativeLogger.I("[Unity Dialog]", $"SetActive false {ex.Message}");
        }
    }

    // Method to handle confirm exit
    public void OnConfirmExit()
    {
        Debug.Log("Exiting the application...");
        // Exit the application
        Application.Quit();
    }

    // Method to handle cancel exit
    public void OnCancelExit()
    {
        Debug.Log("Exit canceled.");
        // Hide the dialog
        dialog.SetActive(false);
    }
}
