import React from "react";
import i18next from "i18next";
import ReactPostprocessor from "i18next-react-postprocessor";
import { BrowserRouter } from "react-router-dom";
import { I18nextProvider, initReactI18next } from "react-i18next";
import { Provider } from "react-redux";
import { store } from "./store";
import { AuthProvider } from "./auth";
import { ApiContext, createApi } from "./api";
import { LegalContext, buildLegal } from "./legal";
import {
  buildResources,
  fallbackLng,
  getDefaultLocaleByLanguage,
  getTranslationJSON,
  ELocalesPlacement,
  language,
  setLanguage,
} from "./locales";
import App from "./components/App";
import metricService from "./services/metric/metricService";
import "core-js/actual";
import { pdfjs } from "react-pdf";
import MetaPixel from "./utils/FBMetaPixel";

pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.js`;

const environments = import.meta.env;

const init = async () => {
  await setLanguage();
  const api = createApi();
  const currentPlacement = localStorage.getItem(
    "locales-placement"
  ) as ELocalesPlacement;

  const [
    translationsResponse,
    elementsResponse,
    configResponse,
    translationJSON,
  ] = await Promise.all([
    api.getTranslations(null),
    api.getElements({ locale: language }),
    api.getAppConfig({ bundleId: "auraweb" }),
    getTranslationJSON(currentPlacement, language),
  ]);
  const resources = buildResources(translationsResponse, translationJSON);

  const legal = buildLegal(elementsResponse);
  const config = configResponse.data;
  const i18nextInstance = i18next.createInstance();
  const options = {
    resources,
    fallbackLng,
    postProcess: [`reactPostprocessor`],
    lng: getDefaultLocaleByLanguage(language),
  };
  await i18nextInstance
    .use(initReactI18next)
    .use(new ReactPostprocessor())
    .init(options);

  const isProduction = environments.MODE === "production";

  // SCRIPTS TO HEAD
  const smartLook = () => {
    if (!config.smartlook_manage) return;
    const script = document.createElement("script");
    script.setAttribute("src", "/metrics/smartlook.js");
    document.head.appendChild(script);
  };

  metricService.initMetric();
  // metricService.initMetricAB();

  if (isProduction) {
    smartLook();
  }

  // const googleManager = () => {
  //   const script = document.createElement("script");
  //   script.setAttribute("src", "/metrics/google-manager.js");
  //   document.head.appendChild(script);
  // };
  // googleManager();

  return (
    <React.Fragment>
      <MetaPixel />
      <I18nextProvider i18n={i18nextInstance}>
        <Provider store={store}>
          <BrowserRouter>
            <ApiContext.Provider value={api}>
              <AuthProvider>
                <LegalContext.Provider value={legal}>
                  <App />
                </LegalContext.Provider>
              </AuthProvider>
            </ApiContext.Provider>
          </BrowserRouter>
        </Provider>
      </I18nextProvider>
    </React.Fragment>
  );
};

export default init;
