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,
  getTranslationsJSON,
  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 HeadData from "./utils/Helmet";
import Clarity from '@microsoft/clarity';
import { InitializationProvider } from "./initialization";
import { getSourceByPathname } from "./utils/source.utils";
import { parseQueryParams } from "./services/url";
import { actions } from "./store";
import { initWitLib } from "@wit-lab-llc/frontend-shared";

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

const environments = import.meta.env;

const init = async () => {
  // Initialize WIT shared library for fingerprint and facebook data collection
  initWitLib({
    baseUrl: environments.AURA_DAPI_HOST || '',
    debug: environments.MODE !== 'production',
  });

  // Parse UTM parameters from URL at initialization
  const utm = parseQueryParams();
  console.log('UTM parameters parsed at init:', utm);
  if (Object.keys(utm).length > 0) {
    console.log('Dispatching UTM update:', utm);
    store.dispatch(actions.utm.update(utm));
  }

  await setLanguage();
  const api = createApi();

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

  console.time('translations-loading');
  const translationsPlacement = await getTranslationsJSON(language);
  console.timeEnd('translations-loading');
  const resources = buildResources(translationsResponse, translationsPlacement);

  const legal = buildLegal(elementsResponse);
  const config = configResponse.data;
  const i18nextInstance = i18next.createInstance();
  const options = {
    resources,
    fallbackLng,
    postProcess: [`reactPostprocessor`],
    lng: getDefaultLocaleByLanguage(language),
    interpolation: {
      format: function (value: any, format: any, _lng: any) {
        if (format === 'uppercase') return value?.toUpperCase();
        // if (value instanceof Date) return moment(value).format(format);
        return value;
      }
    }
  };
  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 projectId = "pez69dq3lh"

  Clarity.init(projectId);

  const source = getSourceByPathname()

  const pixels = await api.getPixels({
    domain: window.location.hostname,
    source,
    locale: getDefaultLocaleByLanguage(language),
  });

  localStorage.setItem('fb_pixels', JSON.stringify(pixels?.data?.facebook_pixel || []));

  return (
    <React.Fragment>
      {!!pixels?.data?.facebook_pixel?.length && <HeadData pixels={pixels.data.facebook_pixel} />}
      <I18nextProvider i18n={i18nextInstance}>
        <Provider store={store}>
          <BrowserRouter>
            <ApiContext.Provider value={api}>
              <AuthProvider>
                <LegalContext.Provider value={legal}>
                  <InitializationProvider>
                    <App />
                  </InitializationProvider>
                </LegalContext.Provider>
              </AuthProvider>
            </ApiContext.Provider>
          </BrowserRouter>
        </Provider>
      </I18nextProvider>
    </React.Fragment>
  );
};

export default init;
