import { Renderable } from '../../core/renderable.js';

const PRODUCTION_ENV = 'prod';

class AnalyticsConfig extends Renderable {
  constructor (data) {
    super(data, 'analyticsConfig');
    this._analytics = data.analytics;
    this._analytics.domain = '$(1)';
    this._analytics.site.environment = '$(2)';
  }

  async render () {
    return `
    <script>
      const PRODUCTION_ENV = '${PRODUCTION_ENV}';
      const xhr = new XMLHttpRequest();
      xhr.open('GET', '/env.json', false);
      xhr.send(null);

      if (xhr.status === 200) {
        const env = JSON.parse(xhr.responseText);
        const analytics = ${JSON.stringify(this._analytics).replace('"$(1)"', 'env.domain').replace('"$(2)"', 'env.env')};
        const dsfr = { analytics };
        if (env.env === PRODUCTION_ENV) {
          dsfr.production = true;
        }
        window.dsfr = dsfr;
      } else {
        console.error('Failed to load JSON:', xhr.status, xhr.statusText);
      }
    </script>`;
  }
}

export { AnalyticsConfig };
