import type { ShimScriptOptions } from '../generator/generator';

const options: ShimScriptOptions = process.env.INJECT;

function unsupported() {
  console.error(
    "Handling of this message is usually done by the app shell but you're running" +
      ' this app in detached mode, which means the app shell is not available.',
  );
}

function getEnvironmentId(options: ShimScriptOptions): string {
  // For example:  https://umsaywsjuo.dev.apps.dynatracelabs.com -> umsaywsjuo
  // Remark: Soon aliases will be introduced and we need to retrieve this differently
  const match = options.environmentUrl.match(/https:\/\/(\w+)\./);
  if (match) {
    return match[1];
  }

  console.warn('Unable to extract environmentId');

  return 'dt.missing.environment.id';
}

if (new URL(window.location.href).searchParams.has('locationAppIds')) {
  // store info in storage, so it survives a route change
  sessionStorage.setItem('attachedMode', 'true');
}

if (sessionStorage.getItem('attachedMode')) {
  const s = document.createElement('script');
  s.src = '/platform/runtime/runtime-loader.js';
  // Must use document.write() here to ensure that the SDK is injected before app code runs
  document.write(s.outerHTML);
} else {
  globalThis.dtSdk = {
    getAppId: () => options.appId,
    getAppName: () => options.appName,
    getAppVersion: () => options.appVersion,
    getEnvironmentId: () => getEnvironmentId(options),
    getEnvironmentUrl: () => options.environmentUrl,
    getTheme: () =>
      window.matchMedia &&
      window.matchMedia('(prefers-color-scheme: dark)').matches
        ? 'dark'
        : 'light',
    getLanguage: () => {
      return options.language ?? new Intl.Locale(navigator.language).language;
    },
    sayHello: () => 'Hello from sdk-web-runtime!',
    createIntent: unsupported,
    sendIntent: unsupported,
    getIntent: unsupported,
    getIntentLink: unsupported,
    matchIntent: unsupported,
    getAppLink: unsupported,
    openApp: unsupported,
  };

  globalThis.dtRuntime = {
    appEnvironment: {
      getAppId: () => options.appId,
      getAppName: () => options.appName,
      getAppVersion: () => options.appVersion,
      getEnvironmentId: () => getEnvironmentId(options),
      getEnvironmentUrl: () => options.environmentUrl,
    },
    userPreferences: {
      getTheme: () =>
        window.matchMedia &&
        window.matchMedia('(prefers-color-scheme: dark)').matches
          ? 'dark'
          : 'light',
      getLanguage: () => {
        return options.language ?? new Intl.Locale(navigator.language).language;
      },
      getTimezone: () => 'UTC',
      getRegionalFormat: () => {
        return options.regionalFormat ?? navigator.language;
      },
    },
    navigation: {
      sendIntent: () => {
        const lightboxContainer = document.createElement('div');
        const lightbox = document.createElement('div');
        const lightboxContent = document.createElement('div');

        lightboxContainer.classList.add('dt-app-lightbox-container');
        lightbox.classList.add('dt-app-lightbox');
        lightboxContent.classList.add('dt-app-lightbox-content');
        lightbox.appendChild(lightboxContent);
        lightboxContainer.appendChild(lightbox);

        const closeButton = document.createElement('div');
        closeButton.classList.add('dt-app-close-button');
        closeButton.addEventListener('click', () => {
          errorShown = false;
          document.body.removeChild(lightboxContainer);
        });
        closeButton.appendChild(document.createTextNode('\u2A2F'));
        lightbox.appendChild(closeButton);

        const errorsContainer = document.createElement('div');
        errorsContainer.insertAdjacentHTML(
          'beforeend',
          '<div class="dt-app-warning-text">You cannot use intents in detached mode. Find more details on the <a href="https://dt-url.net/q52359j">Developer Portal</a></div>',
        );
        lightboxContainer
          .getElementsByClassName('dt-app-lightbox-content')[0]
          .appendChild(errorsContainer);
        document.body.appendChild(lightboxContainer);
        errorShown = true;
      },
    },
  };
}
