/**
 * ACF AUX Integration Script
 *
 * Enhance Advanced Custom Fields (ACF) admin interface with AUX component mode functionality.
 * Handle AUX component mode detection via URL parameters, automatically prepend 'AUX ' prefix
 * to new field group titles when in AUX component mode, maintain AUX state in ACF menu navigation,
 * and provide field highlighting/scrolling when URL hash matches field names.
 *
 * Enqueued by: inc/AuxCF/AuxCF.php (AuxCF::prepareHooks() method via admin_init action hook)
 *
 * @since 1.0.0
 */
if (typeof AUX_STATE_KEY !== 'undefined') {
  const urlParams = new Proxy(new URLSearchParams(window.location.search), {
    get: (searchParams, prop) => searchParams.get(prop),
  });
  const isAux = urlParams[AUX_STATE_KEY];

  if (null !== isAux) {
    // Prepend 'AUX ' to new field group title when in AUX component mode
    if ('1' === isAux && 'edit' !== urlParams.action && 'acf-field-group' === urlParams.post_type) {
      let titleField = document.getElementById('title');
      titleField.value = AUX_COMPONENT_PREFIX + ' ';
    }

    // Add AUX component mode query string to ACF menu when in an AUX/NOT AUX component mode
    let submenuFieldGroups = document.getElementsByClassName('acf-header-tab-acf-field-group');
    submenuFieldGroups.forEach((element) => {
      let href = element.getAttribute('href');

      if ('edit.php?post_type=acf-field-group' === href) {
        href += '&' + AUX_STATE_KEY + '=' + isAux;
        element.setAttribute('href', href);
      }
    });
  }
}

// Add 'active-field' class to field when URL hash matches field name and scroll to field
if (document.location.hash.indexOf('#acf-') === 0) {
  let fieldName = document.location.hash.substring(5);

  let $field = document.querySelector('[data-name="' + fieldName + '"]');
  if ($field) {
    $field.classList.add('active-field');
    $field.scrollIntoView();
  }
}
