<a
    id="reportar-falla-boton"
    href="/reportar-falla?origen={{ urlencode(request()->fullUrl()) }}"
    class="btn btn-sm text-danger border-0 d-none reportar-falla-btn"
    title="Reportar un error"
>
    🐞
</a>

<style>
    .reportar-falla-btn {
        transition: background-color 0.18s ease, color 0.18s ease;
    }

    .reportar-falla-btn:hover,
    .reportar-falla-btn:focus-visible {
        background-color: #dc3545;
        color: #fff !important;
    }
</style>

<script>
    (function () {
        const boton = document.getElementById('reportar-falla-boton');
        if (!boton) {
            return;
        }

        const navbarBrand = document.querySelector('.app-navbar .navbar-brand, .navbar-brand');

        if (navbarBrand && navbarBrand.parentElement) {
            boton.classList.remove('d-none');
            boton.classList.add('ms-2', 'align-self-center');
            navbarBrand.insertAdjacentElement('afterend', boton);
        } else {
            // Fallback para pantallas sin navbar compatible.
            boton.classList.remove('d-none');
            boton.classList.add('position-fixed', 'end-0', 'bottom-0', 'm-3', 'shadow-sm');
            boton.style.zIndex = '1040';
        }

        boton.addEventListener('click', function (e) {
            e.preventDefault();
            const destino = boton.getAttribute('href');

            const capturar = window.html2canvas
                ? window.html2canvas(document.body, { useCORS: true, scale: 0.6, logging: false })
                : Promise.reject();

            boton.textContent = '⏳';
            boton.style.pointerEvents = 'none';

            capturar
                .then(function (canvas) {
                    try {
                        sessionStorage.setItem('bug_captura', canvas.toDataURL('image/jpeg', 0.75));
                    } catch (_) { /* sessionStorage lleno o bloqueado */ }
                    window.location.href = destino;
                })
                .catch(function () {
                    window.location.href = destino;
                });
        });
    })();
</script>