import { Controller } from '@hotwired/stimulus';

export default class extends Controller<HTMLElement> {
   initialize() {
      let dataObject = JSON.parse(this.element.textContent);
      dataObject = this.replacePlaceholders(dataObject, this.element);
      this.element.textContent = JSON.stringify(dataObject);
   }

   replacePlaceholders(dataObject: object, element: Element): object {
      for (const [key, value] of Object.entries(dataObject)) {
         if ((typeof value == 'string') && value.startsWith('@')) {
            let attrName = value.substring(1);
            let el = element;
            while (el && (el = el.closest('[data-gtm-placeholders]'))) {
               let gtmData = el.getAttribute('data-gtm-placeholders');
               gtmData = JSON.parse(gtmData);
               if (gtmData.hasOwnProperty(attrName)) {
                  dataObject[key] = gtmData[attrName];
                  el = null;
               } else {
                  el = el.parentElement;
               }
            }
         }
         if ((value != null) && (typeof value == 'object')) {
            dataObject[key] = this.replacePlaceholders(value, element);
         }
      }

      return dataObject;
   }
}
