using Microsoft.JSInterop;

namespace Front.Program.Services;

public class NavigationService
{
    private readonly IJSRuntime _jsRuntime;
    
    public NavigationService(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }
    
    /// <summary>
    /// 뒤로가기를 완전히 막습니다
    /// </summary>
    public async Task PreventBackNavigationAsync()
    {
        await _jsRuntime.InvokeVoidAsync("eval", @"
            history.pushState(null, null, location.href);
            window.addEventListener('popstate', function(event) {
                history.pushState(null, null, location.href);
            });
        ");
    }
    
    /// <summary>
    /// 확인 대화상자와 함께 뒤로가기를 막습니다
    /// </summary>
    public async Task PreventBackNavigationWithConfirmAsync(string message = "정말로 페이지를 떠나시겠습니까?")
    {
        await _jsRuntime.InvokeVoidAsync("eval", $@"
            history.pushState(null, null, location.href);
            window.addEventListener('popstate', function(event) {{
                if (confirm('{message}')) {{
                    history.back();
                }} else {{
                    history.pushState(null, null, location.href);
                }}
            }});
        ");
    }
    
    /// <summary>
    /// 뒤로가기 방지를 해제합니다
    /// </summary>
    public async Task AllowBackNavigationAsync()
    {
        await _jsRuntime.InvokeVoidAsync("eval", @"
            window.removeEventListener('popstate', arguments.callee);
        ");
    }
}
