@if($page_loader_enabled ?? false)
@php
    $loaderImg = trim((string) ($page_loader_image ?? ''));
    if ($loaderImg === '' && ($logo ?? null)) {
        $loaderImg = $logo;
    }
    $loaderUrl = $loaderImg === '' ? '' : (str_starts_with($loaderImg, 'http') || str_starts_with($loaderImg, '/') ? $loaderImg : asset('storage/'.$loaderImg));
@endphp
<div id="page-loader-overlay" class="fixed inset-0 z-[9997] flex items-center justify-center bg-white/90 backdrop-blur-sm transition-opacity duration-300" aria-hidden="true">
    <div class="flex flex-col items-center gap-4">
        @if($loaderUrl !== '')
            <img src="{{ $loaderUrl }}" alt="" class="w-32 h-32 object-contain page-loader-spin" width="128" height="128">
        @else
            <div class="w-32 h-32 rounded-full border-4 border-slate-200 border-t-primary-500 page-loader-spin"></div>
        @endif
    </div>
</div>
<style>
.page-loader-spin { animation: page-loader-spin 1.2s linear infinite; }
@keyframes page-loader-spin {
    to { transform: rotate(360deg); }
}
#page-loader-overlay.page-loader-hidden { opacity: 0; pointer-events: none; }
</style>
<script>
(function() {
    var overlay = document.getElementById('page-loader-overlay');
    if (!overlay) return;
    function hide() {
        overlay.classList.add('page-loader-hidden');
        setTimeout(function() { overlay.style.display = 'none'; }, 300);
    }
    function show() {
        overlay.style.display = 'flex';
        overlay.classList.remove('page-loader-hidden');
    }
    if (document.readyState === 'complete') {
        hide();
    } else {
        window.addEventListener('load', hide);
    }
    setTimeout(hide, 15000);
    document.addEventListener('click', function(e) {
        var a = e.target.closest('a[href]');
        if (!a || a.target === '_blank' || a.href.startsWith('javascript:') || a.href.startsWith('mailto:') || a.href.startsWith('tel:')) return;
        try {
            var url = new URL(a.href);
            if (url.origin !== window.location.origin) return;
            if (url.pathname === window.location.pathname && url.search === window.location.search) return;
        } catch (err) { return; }
        show();
    });
    document.addEventListener('submit', function(e) {
        var form = e.target;
        if (form.method.toLowerCase() === 'get') return;
        var action = form.action || '';
        try {
            var url = new URL(action, window.location.href);
            if (url.origin !== window.location.origin) return;
        } catch (err) { return; }
        show();
    });
})();
</script>
@endif
