@inherits LayoutComponentBase
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject FilterCair.Client.Services.AppState State

@inject IJSRuntime JS

<div class="d-flex flex-column min-vh-100">

    <!-- 🔹 NAVBAR -->
    <nav class="navbar navbar-expand-lg shadow-sm main-nav">
        <div class="container-fluid">
            <a class="navbar-brand fw-semibold text-white d-flex align-items-center gap-2" href="/">
                <i class="bi bi-wind me-1"></i>
                FilterCair
                <span class="status-dot" id="onlineStatusDot">●</span>
            </a>

            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <NavLink class="nav-link text-white" href="/" Match="NavLinkMatch.All">
                            <i class="bi bi-house-door me-1"></i> Start
                        </NavLink>
                    </li>

                    <li class="nav-item">
                        <NavLink class="nav-link text-white" href="/tasks">
                            <i class="bi bi-list-check me-1"></i> Tasklist
                        </NavLink>
                    </li>

                    <li class="nav-item">
                        <NavLink class="nav-link text-white" href="/customers">
                            <i class="bi bi-buildings me-1"></i> Kunden
                        </NavLink>
                    </li>
                </ul>

                

                <!-- 🔐 Login/Logout Bereich -->
                <AuthorizeView>
                    <Authorized Context="auth">
                        <div class="d-flex align-items-center gap-2">
                            <span class="text-white small">
                                @auth.User.Identity?.Name
                            </span>
                            <NavLink href="authentication/logout" class="btn btn-outline-light btn-sm">
                                <i class="bi bi-box-arrow-right me-1"></i> Abmelden
                            </NavLink>
                        </div>
                    </Authorized>
                    <NotAuthorized>
                        <NavLink href="authentication/login" class="btn btn-light btn-sm">
                            <i class="bi bi-person-lock me-1"></i> Anmelden
                        </NavLink>
                    </NotAuthorized>
                </AuthorizeView>
            </div>
        </div>
    </nav>

    <!-- 🔹 Seiteninhalt -->
    <main class="flex-fill bg-light">
        <div class="container py-4">
            @Body
        </div>
    </main>

    <!-- 🔹 FOOTER -->
    <footer class="footer text-center small text-secondary py-2 mt-auto border-top">
        @if (!string.IsNullOrEmpty(State.SelectedCustomer))
        {
            <div class="text-muted small mb-1">
                <i class="bi bi-geo-alt me-1 text-primary"></i>
                Aktiver Kunde: <strong>@State.SelectedCustomer</strong>
            </div>
        }
        @DateTime.Now.Year FilterCair - FPM Service GmbH
    </footer>
</div>


@code{
    protected override async Task OnInitializedAsync()
    {
        await State.LoadFromSessionAsync();
        State.OnChange += StateHasChanged;
    }

    public void Dispose()
    {
        State.OnChange -= StateHasChanged;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JS.InvokeVoidAsync("eval", @"
                // Warte auf filterDb
                const waitForFilterDb = () => new Promise(resolve => {
                    const check = () => window.filterDbReady ? resolve() : setTimeout(check, 50);
                    check();
                });

                // === ONLINE STATUS DOT ===
                async function updateStatus() {
                    try {
                        await waitForFilterDb();
                        const dot = document.getElementById('onlineStatusDot');
                        if (!dot) return;

                        if (navigator.onLine) {
                            dot.classList.remove('offline');
                            dot.classList.add('online');
                            dot.title = 'Online – alles sync!';
                        } else {
                            dot.classList.remove('online');
                            dot.classList.add('offline');
                            dot.title = 'Offline – Änderungen werden gespeichert';
                        }
                    } catch (err) {
                        console.error('updateStatus Fehler:', err);
                    }
                }

                // === AUTO SYNC ===
                let isSyncing = false;
                async function startSync() {
                    if (isSyncing || !navigator.onLine) return;
                    isSyncing = true;
                    try {
                        await waitForFilterDb();
                        await window.filterDb.syncOutbox();
                        console.log('Sync erfolgreich');
                        updateStatus(); // Sync → Status aktualisieren
                    } catch (err) {
                        console.error('Sync Fehler:', err);
                    }
                    isSyncing = false;
                }

                // === INITIALISIERUNG ===
                updateStatus(); 
                setInterval(updateStatus, 2000);
                window.addEventListener('online', () => { updateStatus(); startSync(); });
                window.addEventListener('offline', updateStatus);
                setInterval(() => { if (navigator.onLine) startSync(); }, 30000);
                if (navigator.onLine) startSync();
            ");
        }
    }
}