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

import { createInertiaApp, router } from '@inertiajs/react';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

// Admin-pasted analytics scripts (admin/marketing → Scripts tab) are injected
// into <head> on a full marketing page load and gated server-side to public
// marketing routes only. But Inertia navigations don't reload <head>, so once
// loaded those scripts — and any analytics runtime they boot (gtag/pixel, which
// keep firing on SPA route changes) — persist into app/admin chrome on a
// client-side visit. When a navigation lands on an app-chrome page while the
// document still carries the marketing-scripts sentinel, force a full reload so
// the fresh (script-free) app document replaces it. Mirrors ChromeMode's
// marketing buckets; the reload is a no-op loop-free (the app document the
// server returns has no sentinel).
const MARKETING_COMPONENTS = new Set([
    'Welcome', 'Pricing', 'Templates', 'About', 'Contact', 'Privacy', 'Terms', 'Refund', 'CustomPage',
]);
const MARKETING_PREFIXES = ['Auth/', 'Errors/', 'Checkout/'];
function isAppChrome(component: string | undefined): boolean {
    if (!component) return true;
    if (MARKETING_COMPONENTS.has(component)) return false;
    return !MARKETING_PREFIXES.some((p) => component.startsWith(p));
}
router.on('navigate', (event) => {
    const component = event.detail.page.component;
    if (
        isAppChrome(component) &&
        document.querySelector('meta[name="marketing-scripts-active"]') !== null
    ) {
        window.location.reload();
    }
});

// Admin-editable site name resolution. Server emits a `<meta name="app-name">`
// tag in `app.blade.php` populated from `Settings::get('site.name', config(
// 'app.name'))`. We prefer the meta value so a /admin/settings rename
// flips the page title suffix on the next request without a redeploy.
// Fall back to the Vite-baked env var when the meta tag is absent (install
// wizard / error pages rendered before the settings table exists).
function readSiteName(): string {
    if (typeof document !== 'undefined') {
        const meta = document.querySelector('meta[name="app-name"]');
        const fromMeta = meta?.getAttribute('content')?.trim();
        if (fromMeta) return fromMeta;
    }
    return import.meta.env.VITE_APP_NAME || 'AppShot AI';
}

const appName = readSiteName();

createInertiaApp({
    title: (title) => (title ? `${title} — ${appName}` : appName),
    resolve: (name) =>
        resolvePageComponent(
            `./Pages/${name}.tsx`,
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            import.meta.glob('./Pages/**/*.tsx') as any,
        ),
    setup({ el, App, props }) {
        // Hand off SEO from the server. app.blade.php emits resolved meta +
        // JSON-LD (tagged `data-server-seo`) plus a crawlable body mirror
        // (.seo-ssr-body) for non-JS crawlers; remove them before mount so
        // Inertia's <Head> (PageSeo.tsx) owns meta for SPA navigation without
        // duplicate tags, and the DOM stays clean once React renders.
        document
            .querySelectorAll('head [data-server-seo], .seo-ssr-body')
            .forEach((node) => node.remove());

        createRoot(el).render(
            <StrictMode>
                <App {...props} />
            </StrictMode>,
        );
    },
    // Inertia's progress bar takes a literal color string, not a CSS class.
    // Resolve --color-accent at runtime so the bar follows the admin's theme
    // (this file mounts after CSS has parsed, so getComputedStyle is safe).
    // Falls back to the default accent when the variable isn't set (SSR /
    // early bootstrap before the theme overlay).
    progress: {
        color:
            (typeof document !== 'undefined'
                ? getComputedStyle(document.documentElement)
                      .getPropertyValue('--color-accent')
                      .trim()
                : '') || '#0052FF',
    },
});
