import "../css/app.css";
import { createInertiaApp } from "@inertiajs/react";
import { createRoot } from "react-dom/client";
import ThemeProvider from "./contexts/ThemeProvider";
import axiosInstance from '../../src/axios'; // Make sure the path is correct
import { ReactNode } from "react";

// Set CSRF token from meta tag for our custom axios instance
const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
if (token) {
  axiosInstance.defaults.headers.common['X-CSRF-TOKEN'] = token;
} else {
  console.warn('CSRF token not found in <meta name="csrf-token">');
}

// Helper function to bootstrap the Inertia app
const bootstrapApp = () => {
  createInertiaApp({
    resolve: async (name) => {
      const pages = import.meta.glob("./Pages/**/*.tsx");

      const pagePath = Object.keys(pages).find((path) => path.endsWith(`${name}.tsx`));
      if (!pagePath) throw new Error(`Page "${name}" not found.`);

      const module = await pages[pagePath]();
      const PageComponent = (module as any).default;

      // Wrap the page component with ThemeProvider
      PageComponent.layout = (page: ReactNode) => <ThemeProvider>{page}</ThemeProvider>;
      return PageComponent;
    },

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

// Try to fetch CSRF cookie first, but continue with app initialization regardless
axiosInstance.get('/sanctum/csrf-cookie')
  .then(() => {
    bootstrapApp();
  })
  .catch(error => {
    console.error('Failed to fetch CSRF cookie:', error);

    if (error.code === 'ERR_NETWORK') {
      console.warn(
        'Network error when fetching CSRF cookie. This might be due to a CORS issue. ' +
        'Check that your server allows requests from this origin.'
      );
    }

    // Continue with app initialization even if CSRF fetch fails
    bootstrapApp();
  });
