import focus from '@alpinejs/focus';

document.addEventListener('livewire:init', () => {
    Livewire.hook('alpine:init', ({ Alpine }) => {
        Alpine.plugin(focus);
    });

    /*
     * A cached app shell outlives the session that produced it. When the
     * session has rotated, the next Livewire request comes back 419 and the
     * page becomes a dead surface: buttons stop responding and nothing on
     * screen says why. Reloading is the only honest recovery — the server
     * decides where the member goes next.
     */
    Livewire.hook('request', ({ fail }) => {
        fail(({ status, preventDefault }) => {
            if (status === 419) {
                preventDefault();
                window.location.reload();
            }
        });
    });
});

/*
 * Register the worker with an explicit scope. The default scope would be the
 * script's own directory anyway, but stating it means a future move of the file
 * cannot silently widen what it controls to include the ERP.
 */
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/app/sw.js', { scope: '/app/' }).catch((error) => {
            // A worker that fails to register is a degraded experience, not a
            // broken one — the portal is a normal web page without it.
            console.warn('portal: service worker registration failed', error);
        });
    });
}

/*
 * The theme is the tenant's choice, not the operating system's: `auto` is the
 * only mode that defers to the device. The attribute is set before paint by an
 * inline script in the layout; this only keeps it in step when the OS changes
 * while the app is open.
 */
document.addEventListener('DOMContentLoaded', () => {
    const root = document.documentElement;

    if (root.dataset.themeMode !== 'auto' || !window.matchMedia) {
        return;
    }

    const query = window.matchMedia('(prefers-color-scheme: dark)');

    const apply = () => {
        root.setAttribute('data-theme', query.matches ? 'dark' : 'light');
    };

    apply();
    query.addEventListener('change', apply);
});
