@inherits LayoutComponentBase
@inject IJSRuntime JS
@inject NavigationManager NavigationManager

@Body

<script suppress-error="BL9992">
window.emptyBody = function(){
    document.body.className = '';
}
</script>

@code
{
    protected override void OnAfterRender(bool firstRender)
    {
        JS.InvokeVoidAsync("KTThemeMode.init");
        JS.InvokeVoidAsync("emptyBody");
        
        if (firstRender)
        {
            JS.InvokeVoidAsync("scrollTo", 0, 0);
            JS.InvokeVoidAsync("KTDialer.init");
            JS.InvokeVoidAsync("KTDrawer.init");
            JS.InvokeVoidAsync("KTMenu.init");
            JS.InvokeVoidAsync("KTImageInput.init");
            JS.InvokeVoidAsync("KTPasswordMeter.init");
            JS.InvokeVoidAsync("KTScroll.init");
            JS.InvokeVoidAsync("KTScrolltop.init");
            JS.InvokeVoidAsync("KTSticky.init");
            JS.InvokeVoidAsync("KTSwapper.init");
            JS.InvokeVoidAsync("KTToggle.init");
            JS.InvokeVoidAsync("KTMenu.updateByLinkAttribute", $"/{NavigationManager.ToBaseRelativePath(NavigationManager.Uri)}");
        }
        
        JS.InvokeVoidAsync("KTLayoutSearch.init");
        JS.InvokeVoidAsync("KTAppSidebar.init");
    }


    protected override void OnInitialized()
    {
        NavigationManager.LocationChanged += OnLocationChanged;
    }

    private async void OnLocationChanged(object sender, LocationChangedEventArgs args)
    {
        await InvokeJsSave("scrollTo", 0, 0);
        await InvokeJsSave("KTDrawer.createInstances");
        await InvokeJsSave("KTMenu.createInstances");
        await InvokeJsSave("KTImageInput.createInstances");
        await InvokeJsSave("KTPasswordMeter.createInstances");
        await InvokeJsSave("KTScroll.createInstances");
        await InvokeJsSave("KTScrolltop.createInstances");
        await InvokeJsSave("KTSticky.createInstances");
        await InvokeJsSave("KTSwapper.createInstances");
        await InvokeJsSave("KTToggle.createInstances");
        await InvokeJsSave("KTMenu.updateByLinkAttribute", $"/{NavigationManager.ToBaseRelativePath(args.Location)}");
        await InvokeJsSave("KTAppSidebar.init");
    }

    private async Task InvokeJsSave(string method, params object[] args)
    {
        try
        {
            await JS.InvokeVoidAsync(method, args);
        }
        catch (Exception)
        {
            // ignored
        }
    }

    public void Dispose()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;
    }
}