import './bootstrap';
import { registerSW } from 'virtual:pwa-register';
import { initInstallBanner } from './pwa/install-banner.js';
import { initPullToRefresh } from './pwa/pull-to-refresh.js';
import { initWebPushSettings } from './pwa/web-push.js';

registerSW({ immediate: true });

function initPwaUi() {
    initInstallBanner();
    initPullToRefresh();
    initWebPushSettings();
}

initPwaUi();
document.addEventListener('livewire:navigated', initPwaUi);

const TOAST_DURATION_MS = 2800;

function ensureToastHost() {
    let host = document.getElementById('app-toast-host');
    if (!host) {
        host = document.createElement('div');
        host.id = 'app-toast-host';
        host.setAttribute('aria-live', 'polite');
        host.className =
            'pointer-events-none fixed bottom-[max(1.25rem,env(safe-area-inset-bottom))] left-1/2 z-[300] flex w-[min(100%-2rem,24rem)] -translate-x-1/2 flex-col items-stretch gap-2 sm:bottom-8';
        document.body.appendChild(host);
    }

    return host;
}

window.addEventListener('app-toast', (e) => {
    const message = e.detail?.message ?? '';
    if (!message) {
        return;
    }
    const variant = e.detail?.variant === 'destructive' ? 'destructive' : 'success';

    const host = ensureToastHost();
    const el = document.createElement('div');
    el.className =
        variant === 'destructive'
            ? 'app-toast-enter rounded-2xl border border-destructive/35 bg-destructive/12 px-4 py-3 text-center text-sm font-medium text-destructive shadow-lg ring-1 ring-black/[0.04] backdrop-blur-sm dark:ring-white/[0.06]'
            : 'app-toast-enter rounded-2xl border border-success/35 bg-success/12 px-4 py-3 text-center text-sm font-medium text-success shadow-lg ring-1 ring-black/[0.04] backdrop-blur-sm dark:ring-white/[0.06]';
    el.textContent = message;
    host.appendChild(el);

    requestAnimationFrame(() => {
        el.classList.add('app-toast-visible');
    });

    window.setTimeout(() => {
        el.classList.remove('app-toast-visible');
        window.setTimeout(() => el.remove(), 220);
    }, TOAST_DURATION_MS);
});
