import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { HelmetProvider } from "react-helmet-async";
import { I18nextProvider } from "react-i18next";
import { Provider } from "react-redux";
import { BrowserRouter as Router } from "react-router-dom";
import { PersistGate } from "redux-persist/integration/react";
import api from "./api/axios";
import App from "./App";
import i18n from "./i18n";
import "./index.css";
import { logout } from "./store/authSlice";
import { persistor, store } from "./store/store";

// Global api interceptor for 401 handle
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response && error.response.status === 401) {
      // Clear auth state if we get a 401
      store.dispatch(logout());

      // Redirect to login if 401 occurs on admin routes
      if (!window.location.pathname.includes('/admin/login') && window.location.pathname.includes('/admin')) {
        window.location.href = `/admin/login?redirect=${window.location.pathname}`;
      }
    }
    return Promise.reject(error);
  }
);

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <HelmetProvider>
      <Router>
        <I18nextProvider i18n={i18n}>
          <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
              <App />
            </PersistGate>
          </Provider>
        </I18nextProvider>
      </Router>
    </HelmetProvider>
  </StrictMode>
);
