@using DeepDrftPublic.Client.Common
@using DeepDrftPublic.Client.Controls
@using DeepDrftPublic.Client.Services

@* Desktop Menu *@
<div class="d-none d-sm-flex">
    <nav class="@NavClass">
        <a class="dd-nav-brand" href="/">Deep DRFT</a>

        <ul class="dd-nav-links">
            @foreach (var navPage in Pages.MenuPages)
            {
                @if (navPage.HasChildren)
                {
                    @* Dual-role node: the parent anchor navigates to its own route on click,
                       while hover/focus reveals the child dropdown (pure CSS, no JS).
                       dd-nav-item-collapsed is added on child click to force-hide the
                       dropdown after SPA navigation (which keeps the DOM and may leave
                       :hover true). It is cleared on mouseleave so the next hover works. *@
                    <li class="dd-nav-item-parent @(_collapsedDropdowns.Contains(navPage.Route) ? "dd-nav-item-collapsed" : "")"
                        @onmouseleave="() => ResetDropdown(navPage.Route)"
                        @onfocusout="() => ResetDropdown(navPage.Route)">
                        <a href="@navPage.Route" class="dd-nav-link">@navPage.Name</a>
                        <ul class="dd-nav-dropdown">
                            @foreach (var child in navPage.Children)
                            {
                                <li>
                                    <a href="@child.Route" class="dd-nav-link dd-nav-dropdown-link"
                                       @onclick="() => CollapseDropdown(navPage.Route)">@child.Name</a>
                                </li>
                            }
                        </ul>
                    </li>
                }
                else
                {
                    <li>
                        <a href="@navPage.Route" class="dd-nav-link">@navPage.Name</a>
                    </li>
                }
            }
        </ul>

        <div class="dd-nav-actions">
            <StreamNowButton ButtonClass="dd-nav-cta" ButtonLabel="Stream Now &#9654;" />
        </div>
    </nav>
</div>

@* Mobile Menu *@
<div class="d-flex d-sm-none">
    <nav class="@NavClass">
        <a class="dd-nav-brand" href="/">Deep DRFT</a>
        
        <div class="dd-nav-actions">
            <button type="button"
                    class="dd-nav-hamburger"
                    aria-label="Toggle navigation"
                    aria-expanded="@_mobileMenuOpen.ToString().ToLowerInvariant()"
                    @onclick="ToggleMobileMenu">
                <span></span><span></span><span></span>
            </button>
        </div>

        @if (_mobileMenuOpen)
        {
            <ul class="dd-nav-links dd-nav-links-mobile">
                @foreach (var navPage in Pages.MenuPages)
                {
                    <li>
                        <a href="@navPage.Route" class="dd-nav-link" @onclick="CloseMobileMenu">@navPage.Name</a>
                    </li>
                    @* One-level fan-out: render children as an indented sub-list under the parent link. *@
                    @foreach (var child in navPage.Children)
                    {
                        <li class="dd-nav-mobile-child">
                            <a href="@child.Route" class="dd-nav-link" @onclick="CloseMobileMenu">@child.Name</a>
                        </li>
                    }
                }
                <li>
                    <StreamNowButton ButtonClass="dd-nav-cta" ButtonLabel="Stream Now &#9654;" OnStreamStarted="CloseMobileMenu" />
                </li>
            </ul>
        }
    </nav>
</div>

@code {
    [Inject] public required DarkModeCookieService DarkModeCookieService { get; set; }

    // Elevation is vestigial under the frosted-glass design but kept on the parameter
    // surface so MainLayout's <DeepDrftMenu Elevation="..."> call site stays intact.
    [Parameter] public int Elevation { get; set; }
    [Parameter] public required bool IsDarkMode { get; set; }
    [Parameter] public required EventCallback<bool> IsDarkModeChanged { get; set; }

    private bool _mobileMenuOpen;
    private readonly HashSet<string> _collapsedDropdowns = [];

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // Runs here (not OnInitializedAsync) because OnAfterRenderAsync(firstRender)
            // is guaranteed not to execute during any SSR prerender pass. During prerender
            // (now interactive across all of Routes), awaiting IsDarkModeChanged.InvokeAsync
            // triggers a parent re-render cycle that cannot complete on the prerender renderer
            // and hangs the response. Server-side DarkModeService has already seeded
            // DarkModeSettings via PersistentComponentState, so the prerender paint is
            // already correct; this call reads that persisted value and propagates it to the
            // parent so the menu's IsDarkMode parameter stays consistent with DarkModeSettings.
            IsDarkMode = DarkModeCookieService.GetDarkMode();
            await IsDarkModeChanged.InvokeAsync(IsDarkMode);
        }
    }

    private string NavClass => IsDarkMode ? "dd-nav dd-nav-dark" : "dd-nav dd-nav-light";

    private string DarkLightModeIconSvg => IsDarkMode ? DDIcons.GasLampLit : DDIcons.GasLamp;

    private async Task DarkModeToggle()
    {
        IsDarkMode = !IsDarkMode;
        await DarkModeCookieService.SetDarkModeAsync(IsDarkMode);
        await IsDarkModeChanged.InvokeAsync(IsDarkMode);
    }

    private void ToggleMobileMenu() => _mobileMenuOpen = !_mobileMenuOpen;

    private void CloseMobileMenu() => _mobileMenuOpen = false;

    private void CollapseDropdown(string route) => _collapsedDropdowns.Add(route);

    private void ResetDropdown(string route) => _collapsedDropdowns.Remove(route);
}
