import "./utils/sentry"; // Must be first.
import * as Sentry from "@sentry/react";
import Dinero from "dinero.js";
import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import { createBrowserRouter, createRoutesFromElements, Route, RouterProvider } from "react-router-dom";
import { PersistGate } from "redux-persist/integration/react";
import { registerSW } from "virtual:pwa-register";
import AppContainer from "./App/App.container";
import LoadingSpinner from "./components/loading-spinner/loading-spinner.component";
import "./index.css";
import { persistor, store } from "./redux/store";
import reportWebVitals from "./reportWebVitals";
import "./translations/i18n";
import "./utils/CleanAxios";
// import * as amplitude from "@amplitude/analytics-browser";
import { PostHogProvider } from "posthog-js/react";
import posthog from "posthog-js";
import { StrictMode } from "react";

window.global ||= window;

registerSW({ immediate: true });

// Dinero.defaultCurrency = "CAD";
// Dinero.globalLocale = "en-CA";
Dinero.globalRoundingMode = "HALF_EVEN";

// amplitude.init(import.meta.env.VITE_APP_AMP_KEY, {
//   defaultTracking: true,
//   serverUrl: import.meta.env.VITE_APP_AMP_URL
//   //  {
//   //     attribution: {
//   //       excludeReferrers: true,
//   //       initialEmptyValue: true,
//   //       resetSessionOnNewCampaign: true,
//   //     },
//   //     fileDownloads: true,
//   //     formInteractions: true,
//   //     pageViews: {
//   //       trackHistoryChanges: 'all'
//   //     },
//   //     sessions: true
//   //   }
// });

posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_KEY, {
  autocapture: false,
  capture_exceptions: true,
  api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST
});

const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV6(createBrowserRouter);

const router = sentryCreateBrowserRouter(createRoutesFromElements(<Route path="*" element={<AppContainer />} />), {
  future: {
    v7_startTransition: true,
    v7_relativeSplatPath: true
  }
});

if (import.meta.env.DEV) {
  const styles =
    "font-weight: bold; font-size: 50px;color: red;  6px 6px 0 rgb(226,91,14) , 9px 9px 0 rgb(245,221,8) , 12px 12px 0 rgb(5,148,68) ";

  console.log("%c %s", styles, `VER: ${import.meta.env.VITE_APP_INSTANCE}`);
}

function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={<LoadingSpinner message="Restoring your settings..." />} persistor={persistor}>
        <PostHogProvider client={posthog}>
          <RouterProvider router={router} />
        </PostHogProvider>
      </PersistGate>
    </Provider>
  );
}

const rootEl = document.getElementById("root");

if (!rootEl) throw new Error('Missing root element: <div id="root" />');

const appTree =
  import.meta.env.DEV && import.meta.env?.VITE_DISABLE_STRICT_MODE !== "true" ? (
    <StrictMode>
      <App />
    </StrictMode>
  ) : (
    <App />
  );

ReactDOM.createRoot(rootEl).render(appTree);

reportWebVitals();
