import {loadScript, validateData} from '#3p/3p';
import {parseJson} from '#core/types/object/json';

const requiredParams = ['spot'];
const optionsParams = [
  'uploadLink',
  'nativeSettings',
  'wrapperStyles',
  'iFrameStyles',
  'queriesParams',
  'onLoadResponseHook',
  'onSpotRenderedHook',
  'onLoadErrorHook',
];
const adContainerId = 'trafficstars_id';

/**
 * @param {!Window} global
 * @param {!Object} data
 */
export function trafficstars(global, data) {
  // ensure we have valid widgetIds value
  validateData(data, requiredParams, optionsParams);

  const adContainer = global.document.getElementById('c');
  const adNativeContainer = getAdContainer(global);
  const initScript = getInitAdScript(global, data);

  adContainer.appendChild(adNativeContainer);

  // load the TrafficStars master spot JS file
  loadScript(global, 'https://cdn.tsyndicate.com/sdk/v1/master.spot.js', () => {
    global.document.body.appendChild(initScript);
  });
}

/**
 * @param {!Object} data
 * @return {JsonObject}
 */
function getInitData(data) {
  const initKeys = requiredParams.concat(optionsParams);
  const initParams = {};

  initKeys.forEach((key) => {
    if (key in data) {
      initParams[key] = data[key];
    }
  });

  initParams['containerId'] = adContainerId;

  return parseJson(initParams);
}

/**
 * @param {!Window} global
 * @return {?Node}
 */
function getAdContainer(global) {
  const container = global.document.createElement('div');

  container['id'] = adContainerId;

  return container;
}

/**
 * @param {!Window} global
 * @param {!Object} data
 * @return {?Node}
 */
function getInitAdScript(global, data) {
  const scriptElement = global.document.createElement('script');
  const initData = getInitData(data);
  const initScript = global.document.createTextNode(
    `TsMasterSpot(${JSON.stringify(initData)});`
  );

  scriptElement.appendChild(initScript);

  return scriptElement;
}

@@ -133,23 +133,20 @@
 ;%0Aconst 
-opti
+js
 on
-s
 Params =
@@ -151,27 +151,8 @@
  = %5B
-%0A  'uploadLink',%0A  
 'nat
@@ -164,18 +164,16 @@
 ttings',
-%0A 
  'wrappe
@@ -181,18 +181,16 @@
 Styles',
-%0A 
  'iFrame
@@ -196,16 +196,50 @@
 eStyles'
+%5D;%0Aconst params = %5B%0A  'uploadLink'
 ,%0A  'que
@@ -323,16 +323,66 @@
 ok',%0A%5D;%0A
+const optionalParams = params.concat(jsonParams);%0A
 const ad
@@ -601,25 +601,26 @@
 rams, option
-s
+al
 Params);%0A%0A  
@@ -1148,17 +1148,18 @@
 t(option
-s
+al
 Params);
@@ -1238,16 +1238,119 @@
 data) %7B%0A
+      if (jsonParams.includes(key)) %7B%0A        initParams%5Bkey%5D = parseJson(data%5Bkey%5D);%0A      %7D else %7B%0A  
       in
@@ -1376,16 +1376,24 @@
 a%5Bkey%5D;%0A
+      %7D%0A
     %7D%0A  
@@ -1452,26 +1452,16 @@
  return 
-parseJson(
 initPara
@@ -1462,17 +1462,16 @@
 itParams
-)
 ;%0A%7D%0A%0A/**

Fix trafficstars integration (#35965)