(function() {
  if (window.__gfWrapperResponsiveBootstrapped) {
    return;
  }
  window.__gfWrapperResponsiveBootstrapped = true;

  var BREAKPOINTS = {
    xs: 480,
    sm: 768,
    md: 992
  };
  var CLASS_LIST = ['gf-xs', 'gf-sm', 'gf-md', 'gf-lg'];
  var fallbackWrappers = new Set();
  var fallbackHandlerAttached = false;

  function getClassForWidth(width) {
    if (width < BREAKPOINTS.xs) {
      return 'gf-xs';
    }
    if (width < BREAKPOINTS.sm) {
      return 'gf-sm';
    }
    if (width < BREAKPOINTS.md) {
      return 'gf-md';
    }
    return 'gf-lg';
  }

  function updatePaymentGrid(wrapper, breakpointClass) {
    var layoutMap = {
      'gf-xs': 1,
      'gf-sm': 1,
      'gf-md': 2,
      'gf-lg': 3
    };

    var columns = layoutMap[breakpointClass] || 3;
    var grids = wrapper.querySelectorAll('.griffinforms-payment-field-group[data-gf-layout="cards"]');
    if (!grids || !grids.length) {
      return;
    }

    grids.forEach(function(grid) {
      grid.style.setProperty('--griffinforms-grid-columns', columns);
    });
  }

  function applyClass(el) {
    var width = el.getBoundingClientRect().width || el.offsetWidth || 0;
    var targetClass = getClassForWidth(width);
    CLASS_LIST.forEach(function(cls) {
      el.classList.remove(cls);
    });
    el.classList.add(targetClass);
    updatePaymentGrid(el, targetClass);
  }

  function throttle(fn, wait) {
    var timeout = null;
    return function() {
      if (timeout) {
        return;
      }
      timeout = setTimeout(function() {
        timeout = null;
        fn();
      }, wait);
    };
  }

  function initWrapper(el) {
    if (el.__gfResponsiveInitialized) {
      return;
    }

    el.__gfResponsiveInitialized = true;
    applyClass(el);

    if (window.ResizeObserver) {
      var rafScheduled = false;
      var observer = new ResizeObserver(function() {
        if (rafScheduled) {
          return;
        }
        rafScheduled = true;
        window.requestAnimationFrame(function() {
          applyClass(el);
          rafScheduled = false;
        });
      });
      observer.observe(el);
      el.__gfResponsiveObserver = observer;
      return;
    }

    fallbackWrappers.add(el);
    if (!fallbackHandlerAttached) {
      fallbackHandlerAttached = true;
      var throttled = throttle(function() {
        fallbackWrappers.forEach(applyClass);
      }, 150);
      window.addEventListener('resize', throttled);
    }
  }

  function findWrappers() {
    var nodes = document.querySelectorAll('[data-gf-form-id]');
    return Array.prototype.filter.call(nodes, function(node) {
      var className = node.className || '';
      return className.indexOf('griffinforms-form') !== -1 && className.indexOf('-container') !== -1;
    });
  }

  function initAllWrappers() {
    findWrappers().forEach(initWrapper);
  }

  document.addEventListener('DOMContentLoaded', initAllWrappers);
  window.addEventListener('griffinformsFormLoaded', initAllWrappers);
})();
