<script src="{{ asset('pmar/js/jquery-3.7.1.min.js') }}"></script>
<script src="{{ asset('pmar/js/sidebar.js') }}"></script>
{{-- TinyMCE (via npm - copiado pelo Vite durante o build) --}}
<script src="{{ asset('pmar/build/tinymce/tinymce.min.js') }}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
<script src="https://cdn.sheetjs.com/xlsx-0.19.3/package/dist/xlsx.full.min.js"></script>
{{-- Bootstrap JS já é carregado uma única vez no <head> (head.blade.php).
     Carregá-lo novamente aqui registrava o data-api duas vezes, fazendo dropdowns
     abrirem e fecharem no mesmo clique e duplicando backdrops de modais. --}}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

@if (Route::currentRouteName() == 'admin.ocorrencias-pca.index')
    <script src="{{ asset('pmar/js/dashboard.js') }}"></script>
@endif
@if (in_array(Route::currentRouteName(), [
        'admin.empresas.create',
        'admin.empresas.edit',
        'admin.turismoNautico.embarcacoes.create',
        'admin.turismoNautico.embarcacoes.edit',
        'admin.cadastroDeAmbulantes.ambulantes.dadosDoComercioIndex',
        'admin.cadastroDeAmbulantes.ambulantes.dadosDoComercioStore',
        'admin.dividaAtiva.create',
        'admin.dividaAtiva.edit',
        'admin.turisAngra.fluxoDeOnibus.onibusTurismo.create',
    ]))
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
@endif

<script src="{{ asset('pmar/js/preparaMenu.js') }}"></script>
<script src="{{ asset('pmar/js/mascaras.js') }}"></script>
<script src="{{ asset('pmar/js/validacoes.js') }}"></script>
<script src="{{ asset('pmar/js/utilitarios.js') }}"></script>
<script src="{{ asset('pmar/js/janelas.js') }}"></script>
<script src="{{ asset('pmar/js/toggle.js') }}"></script>
<script src="{{ asset('pmar/js/classes/BoletimFunctions.js') }}"></script>
<script src="{{ asset('pmar/js/functions.js') }}"></script>
<script src="{{ asset('pmar/js/app.js') }}"></script>
<script src="{{ asset('pmar/js/menu.js') }}"></script>
<script src="{{ asset('pmar/js/functionsArteSacra.js') }}"></script>
@if (Route::currentRouteName() == 'admin.fibromialgia.index')
    <script src="{{ asset('pmar/js/fibromialgia/fibromialgia-laudo.js') }}"></script>
@endif

@if (in_array(Route::currentRouteName(), [
        'admin.visiteAngra.pontos.create',
        'admin.visiteAngra.pontos.edit',
        'admin.visiteAngra.atrativos.create',
        'admin.visiteAngra.atrativos.edit',
        'admin.guias.create',
        'admin.guias.edit',
        'admin.contas.enderecos.create',
        'admin.contas.enderecos.edit',
        'admin.perfilEnderecos.create',
        'admin.perfilEnderecos.edit',
        'admin.meioAmbiente.castracaoAnimal.tutores.create',
        'admin.meioAmbiente.castracaoAnimal.tutores.edit',
        'admin.acaoSocial.centrosDeReferencia.create',
        'admin.acaoSocial.centrosDeReferencia.edit',
        'admin.turisAngra.fluxoDeOnibus.onibusTurismo.endereco',
    ]))
    <script src="{{ asset('pmar/js/visite_angra/ponto-turistico.js') }}"></script>
@endif

@if (in_array(Route::currentRouteName(), [
        'admin.visiteAngra.pontos.create',
        'admin.visiteAngra.pontos.edit',
        'admin.visiteAngra.atrativos.create',
        'admin.visiteAngra.atrativos.edit',
        'admin.guias.create',
        'admin.guias.edit',
        'admin.empresas.create',
        'admin.empresas.edit',
        'admin.empresasDeTurismo.endereco',
        'admin.empresasDeTurismo.create',
        'admin.contas.enderecos.create',
        'admin.contas.enderecos.edit',
        'admin.perfilEnderecos.create',
        'admin.perfilEnderecos.edit',
        'admin.saude.fibromialgia.endereco',
        'admin.cultura.credenciamentoMusicos.endereco',
        'admin.meioAmbiente.castracaoAnimal.tutores.create',
        'admin.meioAmbiente.castracaoAnimal.tutores.edit',
        'admin.acaoSocial.centrosDeReferencia.create',
        'admin.acaoSocial.centrosDeReferencia.edit',
        'admin.turisAngra.fluxoDeOnibus.onibusTurismo.endereco',
    ]))
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <script src="{{ asset('pmar/js/visite_angra/map-leaflet.js') }}"></script>
@endif
@if (in_array(Route::currentRouteName(), [
        'admin.escolas.create',
        'admin.escolas.edit',
        'admin.projetosProgramas.create',
        'admin.projetosProgramas.identificacao',
    ]))
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <script src="{{ asset('pmar/js/admin/escolas/escola-mapa.js') }}"></script>
@endif

@if (in_array(Route::currentRouteName(), [
        'admin.indicadoresTi.index',
        'admin.indicadoresTi.relatorio.index',
        'admin.indicadoresTi.gerenciar.clientes',
        'admin.indicadoresTi.gerenciar',
    ]))
    <script src="{{ asset('pmar/js/indicadoresTi.js') }}?v={{ filemtime(public_path('pmar/js/indicadoresTi.js')) }}" defer></script>
@endif

@if (in_array(Route::currentRouteName(), ['admin.contas.create', 'admin.contas.edit']))
    <script src="{{ asset('pmar/js/admin/contas/unidades-selector.js') }}" defer></script>
    <script src="{{ asset('pmar/js/admin/contas/empresas-selector.js') }}" defer></script>
@endif

@if (in_array(Route::currentRouteName(), ['admin.contas.create', 'admin.contas.edit', 'admin.contas.index']))
    <script src="{{ asset('pmar/js/admin/contas/permissions-search.js') }}" defer></script>
@endif

@if (Route::currentRouteName() === 'admin.contas.index')
    <script src="{{ asset('pmar/js/admin/contas/permissions-filter-modal.js') }}" defer></script>
@endif

@stack('after-scripts')

<script>
    // Correção definitiva para modais - usar z-index muito alto
    (function() {
        function fixModalZIndex() {
            const backdrops = document.querySelectorAll('.modal-backdrop');
            const modals = document.querySelectorAll('.modal');

            // Corrigir todos os backdrops
            backdrops.forEach(function(backdrop) {
                backdrop.style.setProperty('z-index', '9998', 'important');
                backdrop.style.setProperty('pointer-events', 'auto', 'important');
                backdrop.style.setProperty('position', 'fixed', 'important');
            });

            // Corrigir todos os modais e mover para body se necessário
            modals.forEach(function(modal) {
                // Mover modal para body se estiver dentro de wrapper/main-content
                const wrapper = modal.closest('.wrapper');
                const mainContent = modal.closest('.main-content');
                if (wrapper || mainContent) {
                    document.body.appendChild(modal);
                }

                modal.style.setProperty('z-index', '9999', 'important');
                modal.style.setProperty('position', 'fixed', 'important');

                const modalDialog = modal.querySelector('.modal-dialog');
                if (modalDialog) {
                    modalDialog.style.setProperty('z-index', '9999', 'important');
                    modalDialog.style.setProperty('pointer-events', 'auto', 'important');
                    modalDialog.style.setProperty('position', 'relative', 'important');
                }

                const modalContent = modal.querySelector('.modal-content');
                if (modalContent) {
                    modalContent.style.setProperty('z-index', '9999', 'important');
                    modalContent.style.setProperty('pointer-events', 'auto', 'important');
                    modalContent.style.setProperty('position', 'relative', 'important');
                }
            });
        }

        // Executar imediatamente
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', fixModalZIndex);
        } else {
            fixModalZIndex();
        }

        // Executar quando modais são abertos
        document.addEventListener('show.bs.modal', function(event) {
            // Remover backdrops duplicados
            const backdrops = document.querySelectorAll('.modal-backdrop');
            if (backdrops.length > 1) {
                for (let i = 1; i < backdrops.length; i++) {
                    backdrops[i].remove();
                }
            }
            setTimeout(fixModalZIndex, 10);
        });

        document.addEventListener('shown.bs.modal', function(event) {
            setTimeout(fixModalZIndex, 10);
        });

        // Observar mudanças no DOM para modais
        const observer = new MutationObserver(function(mutations) {
            let shouldFix = false;
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes.length) {
                    mutation.addedNodes.forEach(function(node) {
                        if (node.nodeType === 1) {
                            if (node.classList && (node.classList.contains(
                                    'modal-backdrop') || node.classList.contains(
                                    'modal'))) {
                                shouldFix = true;
                            }
                        }
                    });
                }
            });
            if (shouldFix) {
                setTimeout(fixModalZIndex, 10);
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    })();
</script>
