import { Controller } from '@hotwired/stimulus';
import { Component, getComponent } from '@symfony/ux-live-component';

export default class extends Controller<HTMLElement> {
   private component: Component;
   private smartFormCache = {};

   static targets = [ "firm", "street", "city", "zip", "countryField" ];

   declare firmTarget: HTMLInputElement;
   declare streetTarget: HTMLInputElement;
   declare cityTarget: HTMLInputElement;
   declare zipTarget: HTMLInputElement;
   declare countryFieldTarget: HTMLInputElement;

   async connect() {
      const header = document.querySelector(COMPONENTS['Header'].selector);
      const headerHeight = header.offsetHeight;

      const elementPosition = this.element.getBoundingClientRect().top;
      window.scrollTo({
         top: elementPosition - headerHeight + window.scrollY,
         behavior: 'smooth'
      });

      if (typeof wpj.smartform !== 'undefined') {
         const countryField = this.countryFieldTarget;
         // @ts-ignore
         wpj.smartform.rebindAllForms(function() {
            const data = {
               inputName: countryField.name,
               instance: 'delivery',
               country: countryField.value
            };

            document.body.dispatchEvent(
               new CustomEvent(
                  'countryChanged',
                  { 'detail': data }
               )
            );
         });

         this.component = await getComponent(this.element);

         this.component.on('render:started', () => {
            this.smartFormCache = {
               firm: this.firmTarget.value,
               street: this.streetTarget.value,
               city: this.cityTarget.value,
               zip: this.zipTarget.value
            };
         });

         this.component.on('render:finished', () => {
            for (const key in this.smartFormCache) {
               const el = this.targets.find(key) as HTMLInputElement;
               if (el && el.value != this.smartFormCache[key]) {
                  el.value = this.smartFormCache[key];
                  el.dispatchEvent(new Event('change', { bubbles: true }));
               }
            }
         });
      }
   }
}
