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

import { createInertiaApp } from '@inertiajs/react';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { createRoot } from 'react-dom/client';
import { ThemeProvider } from '@/Components/ThemeProvider';
import ErrorBoundary from '@/Components/ErrorBoundary'; 

if (typeof window !== 'undefined') {
    const originalRemoveChild = Node.prototype.removeChild;
    Node.prototype.removeChild = function (child) {
        if (child.parentNode !== this) {
            console.warn('[React Resilience] Prevented crash: The node to be removed is not a child of this node.');
            return child;
        }
        return originalRemoveChild.apply(this, arguments);
    };

    const originalInsertBefore = Node.prototype.insertBefore;
    Node.prototype.insertBefore = function (newNode, referenceNode) {
        if (referenceNode && referenceNode.parentNode !== this) {
            console.warn('[React Resilience] Prevented crash: The reference node is not a child of this node.');
            if (referenceNode instanceof Node) {
                return this.appendChild(newNode);
            }
            return newNode;
        }
        return originalInsertBefore.apply(this, arguments);
    };
}

const appName = 'Admin Panel';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    
    resolve: (name) =>
        resolvePageComponent(
            `./Admin/Pages/${name}.jsx`,
            import.meta.glob('./Admin/Pages/**/*.jsx'),
        ).then((module) => {
            const page = module.default;
            const defaultLayout = page.layout || ((page) => page);

            page.layout = (children) => (
                <ErrorBoundary>
                    <ThemeProvider apiRoute="admin">
                        {defaultLayout(children)}
                    </ThemeProvider>
                </ErrorBoundary>
            );

            return module;
        }),

    setup({ el, App, props }) {
        const root = createRoot(el);
        root.render(
            <ErrorBoundary>
                <App {...props} />
            </ErrorBoundary>
        );
    },
    progress: {
        color: '#DC2626',
    },
});