import { createInertiaApp } from '@inertiajs/react';
import * as Sentry from '@sentry/react';
import { createRoot } from 'react-dom/client';

const dsn = (document.querySelector('meta[name="sentry-dsn"]') as HTMLMetaElement | null)?.content;

if (dsn) {
    Sentry.init({
        dsn,
        environment: (document.querySelector('meta[name="app-env"]') as HTMLMetaElement | null)?.content ?? 'production',
        tracesSampleRate: 0.1,
        // Never send PII — matched server-side scrubbing
        beforeSend(event) {
            if (event.request?.data) {
                const piiFields = ['password', 'email', 'name', 'phone', 'ic_number', 'nric', 'token'];
                const data = event.request.data as Record<string, unknown>;
                piiFields.forEach((f) => {
                    if (f in data) data[f] = '[REDACTED]';
                });
            }
            return event;
        },
    });
}

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js').catch(() => {
            // SW registration failed (non-HTTPS or unsupported); app works online-only.
        });
    });
}

type SharedProps = {
    locale?: string;
    translations?: Record<string, string>;
    [key: string]: unknown;
};

// Mutable store — updated synchronously from AppShell before each render.
let _translations: Record<string, string> = {};

// Called by AppShell at render time so __ is always in sync with current page props.
(window as Record<string, unknown>).__setTranslations = (t: Record<string, string>) => {
    _translations = t;
};

// Global translation helper. Fallback: second arg, then the key itself.
(window as Record<string, unknown>).__ = (key: string, fallback?: string): string =>
    _translations[key] ?? fallback ?? key;

createInertiaApp({
    progress: {
        color: 'var(--color-primary)',
        showSpinner: false,
        delay: 150,
    },
    resolve: (name) => {
        const pages = import.meta.glob('./pages/**/*.tsx', { eager: true });
        return pages[`./pages/${name}.tsx`] as object;
    },
    setup({ el, App, props }) {
        // Seed translations from initial page load
        const initial = props.initialPage.props as SharedProps;
        _translations = initial.translations ?? {};

        // Keep in sync on every Inertia navigation (locale may change mid-session)
        document.addEventListener('inertia:success', (e) => {
            const page = (e as CustomEvent<{ page: { props: SharedProps } }>).detail.page;
            if (page.props.translations) {
                _translations = page.props.translations;
            }
        });

        const SentryApp = dsn ? Sentry.withErrorBoundary(App, {
            fallback: <div>An unexpected error occurred. Our team has been notified.</div>,
        }) : App;

        createRoot(el).render(<SentryApp {...props} />);
    },
});
