@inherits LayoutComponentBase
@inject NavigationManager NavigationManager

<DxLayoutBreakpoint MaxWidth="1200"
                    @bind-IsActive="@IsMobileLayout" />

<div class="page">
    <DxGridLayout CssClass="page-layout">
        <Rows>
            @if(IsMobileLayout) {
                <DxGridLayoutRow Areas="header" Height="auto"></DxGridLayoutRow>
                <DxGridLayoutRow Areas="sidebar" Height="auto"></DxGridLayoutRow>
                <DxGridLayoutRow Areas="content" />
            }
            else {
                <DxGridLayoutRow Areas="header header" Height="auto" />
                <DxGridLayoutRow Areas="@(IsSidebarExpanded ? "sidebar content" : "content content")" />
            }
        </Rows>
        <Columns>
            @if(!IsMobileLayout) {
                <DxGridLayoutColumn Width="auto" />
                <DxGridLayoutColumn />
            }
        </Columns>
        <Items>
            <DxGridLayoutItem Area="header" CssClass="layout-item">
                <Template>
                    <Header @bind-ToggleOn="@IsSidebarExpanded" />
                </Template>
            </DxGridLayoutItem>
            <DxGridLayoutItem Area="sidebar" CssClass="layout-item">
                <Template>
                    <NavMenu StateCssClass="@NavMenuCssClass" />
                </Template>
            </DxGridLayoutItem>
            <DxGridLayoutItem Area="content" CssClass="content px-4 layout-item">
                <Template>
                    @Body
                </Template>
            </DxGridLayoutItem>
        </Items>
    </DxGridLayout>
    </div>

@code{
    string? NavMenuCssClass { get; set; }
    bool _isMobileLayout;
    bool IsMobileLayout {
        get => _isMobileLayout;
        set {
            _isMobileLayout = value;
            IsSidebarExpanded = !_isMobileLayout;
        }
    }

    bool _isSidebarExpanded = true;
    bool IsSidebarExpanded {
        get => _isSidebarExpanded;
        set {
            if(_isSidebarExpanded != value) {
                NavMenuCssClass = value ? "expand" : "collapse";
                _isSidebarExpanded = value;
            }
        }
    }

    protected override void OnInitialized() {
        NavigationManager.LocationChanged += OnLocationChanged;
    }
    async void OnLocationChanged(object? sender, LocationChangedEventArgs args) {
        if(IsMobileLayout) {
            IsSidebarExpanded = false;
            await InvokeAsync(StateHasChanged);
        }
    }

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