<div class="js-gls-poland-delivery-options-form gls-poland-delivery-options-form"
     data-carrier-id="{$carrier_id|intval}"
     data-reference-id="{$reference_id|intval}"
     data-cart-id="{$cart_id|intval}"
     data-parcelshop-type="{$parcelshop_type|default:''|escape:'htmlall':'UTF-8'}"
>
  <input type="hidden"
         name="gls_poland[{$carrier_id|intval}][parcel_shop_id]"
         value="{$parcel_shop.id|default:''}"
         class="js-gls-poland-parcel-shop-input"
  >

  <div class="mx-1">
    <div class="js-gls-poland-parcel-shop-info-container" {if empty($parcel_shop)}style="display: none"{/if}>
      <p class="gls-shipping-machine-name">
        {l s='Selected ParcelShop' d='Modules.Glspoland.Checkout'}:
        <span class="js-gls-poland-parcel-shop-name">
          {if !empty($parcel_shop.name)}
            {$parcel_shop.name}
          {/if}
        </span>
      </p>
      <p class="gls-shipping-machine-address js-gls-poland-parcel-shop-address">
        {$addressData = []}

        {if !empty($parcel_shop.street)}
          {$addressData[] = $parcel_shop.street}
        {/if}

        {if !empty($parcel_shop.postal_code)}
          {$addressData[] = $parcel_shop.postal_code}
        {/if}

        {if !empty($parcel_shop.city)}
          {$addressData[] = $parcel_shop.city}
        {/if}

        {implode(', ', $addressData)}
      </p>
    </div>

    <div class="form-group mb-0">
      <button
        type="button"
        class="btn btn-primary gls-poland-parcel-shop-select-button js-gls-poland-parcel-shop-select-button"
        data-selected-text="{l s='Change the selected ParcelShop' d='Modules.Glspoland.Checkout'}"
        {if !empty($zip_code)}
          data-zip-code="{$zip_code}"
        {/if}
      >
        {if empty($parcel_shop)}
          {l s='Select a ParcelShop' d='Modules.Glspoland.Checkout'}
        {else}
          {l s='Change the selected ParcelShop' d='Modules.Glspoland.Checkout'}
        {/if}
      </button>
    </div>
  </div>
</div>
<script>
  (function () {
    if (window.glsPolandInlineParcelShopInit) {
      return;
    }

    window.glsPolandInlineParcelShopInit = true;

    var sdkUrl = 'https://mapa.gls-poland.com/js/v4.0/maps_sdk.js';
    var saveParcelShopUrl =
      window.glsPolandRoutes && window.glsPolandRoutes.selectParcelShop
        ? window.glsPolandRoutes.selectParcelShop
        : '{$urls.base_url|escape:'javascript'}module/glspoland/checkout?action=selectParcelShop';
    var csrfToken = '{$static_token|escape:'javascript'}';

    function resolveActiveForm() {
      if (window.glsPolandActiveParcelShopForm && window.glsPolandActiveParcelShopForm.isConnected) {
        return window.glsPolandActiveParcelShopForm;
      }

      if (!window.glsPolandActiveParcelShopCarrierId) {
        return null;
      }

      return document.querySelector(
        '.js-gls-poland-delivery-options-form[data-carrier-id="' + window.glsPolandActiveParcelShopCarrierId + '"]'
      );
    }

    function getCandidateForms() {
      var forms = [];
      var activeForm = resolveActiveForm();

      if (activeForm) {
        forms.push(activeForm);
      }

      document.querySelectorAll('.js-gls-poland-delivery-options-form').forEach(function (form) {
        if (forms.indexOf(form) === -1) {
          forms.push(form);
        }
      });

      return forms;
    }

    function log() {
      if (!window.console || typeof window.console.log !== 'function') {
        return;
      }

      var args = Array.prototype.slice.call(arguments);
      args.unshift('[GLS inline]');
      window.console.log.apply(window.console, args);
    }

    function ensureModal() {
      var modal = document.getElementById('gls_poland_parcel_shop_map_modal');
      if (modal) {
        if (modal.parentNode !== document.body) {
          document.body.appendChild(modal);
        }
        return modal;
      }

      var wrapper = document.createElement('div');
      wrapper.innerHTML =
        '<div id="gls_poland_parcel_shop_map_modal" class="modal fade" tabindex="-1" role="dialog" style="display:none" aria-hidden="true">' +
        '  <div class="modal-dialog gls-poland-parcel-shop-map-modal modal-lg">' +
        '    <div id="gls_poland_parcel_shop_map" class="modal-content gls-poland-parcel-shop-map-modal-content"></div>' +
        '  </div>' +
        '</div>';

      document.body.appendChild(wrapper.firstChild);
      log('modal created');
      modal = document.getElementById('gls_poland_parcel_shop_map_modal');
      if (modal && modal.parentNode !== document.body) {
        document.body.appendChild(modal);
      }

      return modal;
    }

    function resetMapContainer() {
      var currentMap = document.getElementById('gls_poland_parcel_shop_map');
      if (!currentMap || !currentMap.parentNode) {
        return null;
      }

      var replacement = currentMap.cloneNode(false);
      currentMap.parentNode.replaceChild(replacement, currentMap);

      return replacement;
    }

    function runWhenModalVisible(modal, callback) {
      if (!modal || typeof callback !== 'function') {
        return;
      }

      var called = false;
      var invoke = function () {
        if (called) {
          return;
        }

        called = true;
        window.requestAnimationFrame(function () {
          window.requestAnimationFrame(callback);
        });
      };
      var isActuallyVisible = function () {
        if (!modal || !modal.isConnected) {
          return false;
        }

        var styles = window.getComputedStyle(modal);
        if (styles.display === 'none' || styles.visibility === 'hidden') {
          return false;
        }

        return modal.offsetHeight > 0 && modal.offsetWidth > 0;
      };
      var waitForVisibility = function (attemptsLeft) {
        if (called) {
          return;
        }

        if (isActuallyVisible()) {
          invoke();
          return;
        }

        if (attemptsLeft <= 0) {
          return;
        }

        window.requestAnimationFrame(function () {
          waitForVisibility(attemptsLeft - 1);
        });
      };

      modal.addEventListener('shown.bs.modal', invoke, { once: true });
      waitForVisibility(120);
    }

    function showModal(modal, onShown) {
      runWhenModalVisible(modal, onShown);

      if (window.bootstrap && window.bootstrap.Modal) {
        window.bootstrap.Modal.getOrCreateInstance(modal).show();
        return;
      }

      if (window.jQuery && window.jQuery.fn && typeof window.jQuery.fn.modal === 'function') {
        window.jQuery(modal).modal('show');
        return;
      }

      modal.style.display = 'block';
      modal.classList.add('show');
      window.setTimeout(function () {
        if (typeof onShown === 'function') {
          onShown();
        }
      }, 0);
    }

    function guardModal(modal) {
      if (!modal || modal.dataset.glsGuarded === '1') {
        return;
      }

      modal.dataset.glsGuarded = '1';

      modal.addEventListener('submit', function (event) {
        log('prevented modal submit');
        event.preventDefault();
        event.stopPropagation();
      }, true);

      modal.addEventListener('click', function (event) {
        var target = event.target.closest('button, input[type="submit"], a[href], a[data-href]');
        if (!target) {
          return;
        }

        var isSubmitControl =
          target.matches('button:not([type])') ||
          target.matches('button[type="submit"]') ||
          target.matches('input[type="submit"]');

        var isAnchor = target.tagName === 'A';

        if (!isSubmitControl && !isAnchor) {
          return;
        }

        log('prevented modal default click', target.tagName, target.getAttribute('type') || '');
        event.preventDefault();
      }, false);
    }

    function hideModal(modal) {
      if (window.bootstrap && window.bootstrap.Modal) {
        window.bootstrap.Modal.getOrCreateInstance(modal).hide();
        return;
      }

      if (window.jQuery && window.jQuery.fn && typeof window.jQuery.fn.modal === 'function') {
        window.jQuery(modal).modal('hide');
        return;
      }

      modal.style.display = 'none';
      modal.classList.remove('show');
    }

    function ensureSdk() {
      if (window.SzybkaPaczkaMap && typeof window.SzybkaPaczkaMap.init === 'function') {
        return Promise.resolve();
      }

      return new Promise(function (resolve, reject) {
        var existing = document.querySelector('script[data-gls-inline-sdk="1"]');
        if (existing) {
          existing.addEventListener('load', resolve, { once: true });
          existing.addEventListener('error', reject, { once: true });
          return;
        }

        var script = document.createElement('script');
        script.src = sdkUrl;
        script.async = true;
        script.setAttribute('data-gls-inline-sdk', '1');
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
        log('sdk requested');
      });
    }

    function updateForm(form, parcelShop) {
      if (!form || !parcelShop) {
        return;
      }

      form.hidden = false;
      form.style.display = '';
      form.classList.remove('d-none', 'hidden');

      var formBody = form.querySelector('.mx-1');
      var formGroup = form.querySelector('.form-group');
      var input = form.querySelector('.js-gls-poland-parcel-shop-input');
      var info = form.querySelector('.js-gls-poland-parcel-shop-info-container');
      var name = form.querySelector('.js-gls-poland-parcel-shop-name');
      var address = form.querySelector('.js-gls-poland-parcel-shop-address');
      var button = form.querySelector('.js-gls-poland-parcel-shop-select-button');

      if (formBody) {
        formBody.hidden = false;
        formBody.style.display = '';
        formBody.classList.remove('d-none', 'hidden');
      }

      if (formGroup) {
        formGroup.hidden = false;
        formGroup.style.display = '';
        formGroup.classList.remove('d-none', 'hidden');
      }

      if (input) {
        input.value = parcelShop.id || '';
      }

      if (name) {
        name.textContent = parcelShop.name || '';
      }

      if (address) {
        address.textContent = [parcelShop.street, parcelShop.postal_code, parcelShop.city].filter(Boolean).join(', ');
      }

      if (info) {
        info.style.removeProperty('display');
      }

      if (button && parcelShop.postal_code) {
        button.setAttribute('data-zip-code', parcelShop.postal_code);
        button.hidden = false;
        button.disabled = false;
        button.style.display = '';
        button.classList.remove('d-none', 'hidden');
        if (button.dataset.selectedText) {
          button.textContent = button.dataset.selectedText;
        } else {
          button.textContent = '{l s='Change the selected ParcelShop' d='Modules.Glspoland.Checkout' js=1}';
        }
      }
    }

    function expandCarrierExtraContent(form) {
      if (!form) {
        return;
      }

      var wrapper = form.closest('.carrier__extra-content-wrapper, .js-carrier-extra-content');
      if (!wrapper) {
        return;
      }

      wrapper.hidden = false;
      wrapper.style.display = '';
      wrapper.classList.remove('hidden', 'd-none');
      wrapper.classList.add('carrier__extra-content-wrapper--active');

      var targetHeight = form.scrollHeight || wrapper.scrollHeight;
      if (targetHeight > 0) {
        wrapper.style.maxHeight = targetHeight + 'px';
      } else {
        wrapper.style.maxHeight = 'none';
      }
    }

    function refreshCarrierExtraContent(form) {
      if (!form) {
        return;
      }

      expandCarrierExtraContent(form);

      window.requestAnimationFrame(function () {
        expandCarrierExtraContent(form);
      });

      window.setTimeout(function () {
        expandCarrierExtraContent(form);
      }, 50);
    }

    function updateForms(parcelShop) {
      var forms = getCandidateForms();
      log('updating GLS forms', {
        forms: forms.length,
        carrierId: window.glsPolandActiveParcelShopCarrierId || null,
        activeFormConnected: !!(window.glsPolandActiveParcelShopForm && window.glsPolandActiveParcelShopForm.isConnected)
      });

      forms.forEach(function (form) {
        updateForm(form, parcelShop);
        refreshCarrierExtraContent(form);
      });
    }

    function saveParcelShopSelection(parcelShop) {
      if (!parcelShop || !parcelShop.id || !window.fetch) {
        return Promise.resolve();
      }

      return window.fetch(saveParcelShopUrl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          'X-CSRF-Token': csrfToken
        },
        body: JSON.stringify({
          parcelShopId: parcelShop.id,
          carrierReferenceId: window.glsPolandActiveParcelShopReferenceId || null,
          cartId: window.glsPolandActiveParcelShopCartId ||
            (window.glsPolandCheckoutConfig && window.glsPolandCheckoutConfig.cartId) ||
            null
        })
      }).then(function (response) {
        if (response.ok) {
          log('parcel shop saved', parcelShop.id);
          return;
        }

        return response.text().then(function (body) {
          throw new Error('HTTP ' + response.status + ' ' + body);
        });
      });
    }

    function initMap(zipCode) {
      var config = window.glsPolandCheckoutConfig || {};
      var map = resetMapContainer() || document.getElementById('gls_poland_parcel_shop_map');

      if (!map || !window.SzybkaPaczkaMap || typeof window.SzybkaPaczkaMap.init !== 'function') {
        log('map init skipped', !!map, !!window.SzybkaPaczkaMap);
        return;
      }

      var options = {
        lang: config.language || 'PL',
        country_parcelshops: config.country || 'PL',
        parcel_weight: config.weight || 0.01,
        el: 'gls_poland_parcel_shop_map'
      };

      if (zipCode) {
        options.center_point = zipCode;
      }

      var activeForm = resolveActiveForm();
      var parcelShopType = activeForm ? activeForm.getAttribute('data-parcelshop-type') : null;
      if (parcelShopType) {
        options.parcelshop_type = parcelShopType;
      }

      map.style.display = 'block';
      map.style.width = '100%';
      map.style.height = '100%';
      map.style.minHeight = '0';
      map.innerHTML = '';
      log('map init', options);
      window.SzybkaPaczkaMap.init(options);
    }

    document.addEventListener('click', function (event) {
      var button = event.target.closest('.js-gls-poland-parcel-shop-select-button');
      if (!button) {
        return;
      }

      event.preventDefault();

      var form = button.closest('.js-gls-poland-delivery-options-form');
      var modal = ensureModal();
      guardModal(modal);
      window.glsPolandActiveParcelShopCarrierId = form && form.getAttribute('data-carrier-id');
      window.glsPolandActiveParcelShopReferenceId = form && form.getAttribute('data-reference-id');
      window.glsPolandActiveParcelShopCartId = form && form.getAttribute('data-cart-id');
      window.glsPolandActiveParcelShopType = form && form.getAttribute('data-parcelshop-type');

      log('button clicked', button.getAttribute('data-zip-code'));

      ensureSdk().then(function () {
        window.glsPolandActiveParcelShopForm = form;
        showModal(modal, function () {
          initMap(button.getAttribute('data-zip-code'));
        });
        log('modal shown');
      }).catch(function (error) {
        log('sdk load failed', error);
      });
    });

    window.addEventListener('get_parcel_shop', function (event) {
      var parcelShop = event && event.target && event.target.ParcelShop && event.target.ParcelShop.selected;
      if (!parcelShop) {
        return;
      }

      log('parcel shop selected', parcelShop);
      updateForms(parcelShop);
      saveParcelShopSelection(parcelShop).then(function () {
        hideModal(ensureModal());
      }).catch(function (error) {
        log('parcel shop save failed', error);
        hideModal(ensureModal());
      });
    });

    log('inline handler ready');
  })();
</script>

