@php
    /**
     * Overlay global para Filament.
     * - Se muestra durante requests de Livewire (acciones CRUD y navegación interna de Filament).
     * - También puede mostrarse en navegación con recarga completa (beforeunload).
     */
@endphp

{{--
    Overlay global:
    - Se muestra en cualquier request de Livewire (CRUD, navegación interna de Filament, etc.)
    - También se muestra en navegación con recarga completa (beforeunload)
--}}
<div wire:teleport="body">
    <div
        id="orderflow-loading-overlay-wire"
        wire:loading.delay
        aria-live="polite"
        aria-busy="true"
        class="fixed inset-0 z-[9999] hidden h-screen w-screen place-items-center bg-white/80 backdrop-blur-sm"
    >
        <div class="w-full max-w-xs rounded-2xl bg-white px-6 py-6 shadow-lg ring-1 ring-gray-900/5">
            <div class="flex flex-col items-center gap-4">
                <img
                    src="{{ asset('images/order-flow.png') }}"
                    alt="Order Flow"
                    class="h-14 w-14 object-contain"
                    loading="eager"
                />

                <div class="flex items-center gap-3">
                    <div
                        class="h-5 w-5 animate-spin rounded-full border-2 border-gray-200 border-t-gray-700"
                        aria-hidden="true"
                    ></div>
                    <div class="text-sm font-medium text-gray-900">Cargando…</div>
                </div>
            </div>
        </div>
    </div>
</div>

<div
    id="orderflow-loading-overlay-js"
    aria-live="polite"
    aria-busy="true"
    class="fixed inset-0 z-[9999] hidden h-screen w-screen place-items-center bg-white/80 backdrop-blur-sm"
>
    <div class="w-full max-w-xs rounded-2xl bg-white px-6 py-6 shadow-lg ring-1 ring-gray-900/5">
        <div class="flex flex-col items-center gap-4">
            <img
                src="{{ asset('images/order-flow.png') }}"
                alt="Order Flow"
                class="h-14 w-14 object-contain"
                loading="eager"
            />

            <div class="flex items-center gap-3">
                <div
                    class="h-5 w-5 animate-spin rounded-full border-2 border-gray-200 border-t-gray-700"
                    aria-hidden="true"
                ></div>
                <div class="text-sm font-medium text-gray-900">Cargando…</div>
            </div>
        </div>
    </div>
</div>

<script>
    (function () {
        if (window.__orderFlowLoadingOverlayInitialized) return;
        window.__orderFlowLoadingOverlayInitialized = true;

        const overlay = document.getElementById('orderflow-loading-overlay-js');
        if (!overlay) return;

        const wireOverlay = document.getElementById('orderflow-loading-overlay-wire');

        // Asegura que el overlay no quede “atrapado” en el sidebar/layout.
        // Si algún ancestro tiene transform/filter/contain, `position: fixed` puede volverse relativo.
        if (overlay.parentElement !== document.body) {
            document.body.appendChild(overlay);
        }

        const SHOW_DELAY_MS = 150;
        let inflight = 0;
        let showTimer = null;

        function show() {
            // Si el modo JS está funcionando, evita doble overlay.
            if (wireOverlay) {
                wireOverlay.classList.add('hidden');
                wireOverlay.classList.remove('grid');
            }
            overlay.classList.remove('hidden');
            overlay.classList.add('grid');
        }

        function hide() {
            overlay.classList.add('hidden');
            overlay.classList.remove('grid');
        }

        function scheduleShow() {
            if (showTimer) return;
            showTimer = window.setTimeout(function () {
                showTimer = null;
                if (inflight > 0) show();
            }, SHOW_DELAY_MS);
        }

        function cancelScheduledShow() {
            if (!showTimer) return;
            window.clearTimeout(showTimer);
            showTimer = null;
        }

        // Muestra overlay al navegar (recarga completa).
        window.addEventListener('beforeunload', function () {
            show();
        });

        // Asegura ocultarlo cuando el navegador restaura la página.
        window.addEventListener('pageshow', function () {
            hide();
        });

        function getLivewire() {
            if (window.Livewire) return window.Livewire;
            if (window.livewire) return window.livewire;
            // Evita ReferenceError si Livewire no existe.
            if (typeof Livewire !== 'undefined') return Livewire;
            return null;
        }

        function installLivewireHooks() {
            if (window.__orderFlowLivewireHookInstalled) return;

            const lw = getLivewire();
            if (!lw || typeof lw.hook !== 'function') return;

            window.__orderFlowLivewireHookInstalled = true;

            // Requests globales (CRUD, actions, etc.)
            lw.hook('request', function ({ succeed, fail }) {
                inflight++;
                scheduleShow();

                const done = function () {
                    inflight = Math.max(0, inflight - 1);

                    if (inflight === 0) {
                        cancelScheduledShow();
                        hide();
                    }
                };

                succeed(done);
                fail(done);
            });
        }

        // Navegación SPA de Livewire (Filament usa Livewire Navigate):
        document.addEventListener('livewire:navigating', function () {
            inflight++;
            scheduleShow();
        });

        document.addEventListener('livewire:navigated', function () {
            inflight = 0;
            cancelScheduledShow();
            hide();
        });

        // Hook global de Livewire v3: instalar tanto si el evento ya ocurrió como si no.
        installLivewireHooks();
        document.addEventListener('livewire:init', installLivewireHooks);
    })();
</script>
