import '../css/app.css';
import './bootstrap';

import { createInertiaApp, router } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { createApp, h } from 'vue';
import { ZiggyVue } from '../../vendor/tightenco/ziggy';

// PWA Service Worker registration with auto-update
import { registerSW } from 'virtual:pwa-register';

const updateSW = registerSW({
    onNeedRefresh() {
        // Show update notification to user
        const toast = document.getElementById('pwa-toast');
        if (toast) {
            toast.classList.remove('hidden');
        }
    },
    onOfflineReady() {
    },
    onRegistered(r) {
        // Check for updates every hour
        if (r) {
            setInterval(() => {
                r.update();
            }, 60 * 60 * 1000);
        }
    },
    onRegisterError(error) {
    }
});

const appName = import.meta.env.VITE_APP_NAME || 'CoachPro';

// Handle expired session (419) - auto refresh the page to get a new CSRF token
router.on('invalid', (event) => {
    if (event.detail.response.status === 419) {
        event.preventDefault();
        window.location.reload();
    }
});

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) =>
        resolvePageComponent(
            `./Pages/${name}.vue`,
            import.meta.glob('./Pages/**/*.vue'),
        ),
    setup({ el, App, props, plugin }) {
        return createApp({ render: () => h(App, props) })
            .use(plugin)
            .use(ZiggyVue)
            .mount(el);
    },
    progress: {
        color: '#4f46e5',
        showSpinner: true,
    },
});
