( function( $ ) {
  'use strict';

  function escapeHtml( text ) {
    return $( '<div>' ).text( text ).html();
  }

  function sanitizeFooterPreviewHtml( html ) {
    var template = document.createElement( 'template' );
    var allowedTags = {
      a: [ 'href', 'title', 'target', 'rel' ],
      strong: [],
      em: [],
      b: [],
      i: [],
      br: [],
      span: [ 'class' ]
    };

    template.innerHTML = String( html || '' );

    function sanitizeNode( node ) {
      var children = Array.prototype.slice.call( node.childNodes );

      children.forEach( function( child ) {
        if ( child.nodeType === Node.ELEMENT_NODE ) {
          var tagName = child.tagName.toLowerCase();

          if ( ! Object.prototype.hasOwnProperty.call( allowedTags, tagName ) ) {
            while ( child.firstChild ) {
              node.insertBefore( child.firstChild, child );
            }
            node.removeChild( child );
            return;
          }

          var allowedAttrs = allowedTags[ tagName ];
          Array.prototype.slice.call( child.attributes ).forEach( function( attr ) {
            var attrName = attr.name.toLowerCase();
            var attrValue = attr.value;

            if ( allowedAttrs.indexOf( attrName ) === -1 ) {
              child.removeAttribute( attr.name );
              return;
            }

            if ( attrName === 'href' ) {
              var safeHref = $.trim( attrValue );
              if ( safeHref && ! /^(https?:|mailto:|tel:|\/|#)/i.test( safeHref ) ) {
                child.removeAttribute( 'href' );
              }
            }

            if ( attrName === 'target' && attrValue === '_blank' ) {
              var rel = child.getAttribute( 'rel' ) || '';
              if ( rel.indexOf( 'noopener' ) === -1 || rel.indexOf( 'noreferrer' ) === -1 ) {
                child.setAttribute( 'rel', 'noopener noreferrer' );
              }
            }
          } );

          sanitizeNode( child );
        } else if ( child.nodeType === Node.COMMENT_NODE ) {
          node.removeChild( child );
        }
      } );
    }

    sanitizeNode( template.content );
    return template.innerHTML;
  }

  function initGeneralTab() {
    var $restrictAccess = $( '#restrict_access' );
    var $userSelectionWrapper = $( '#user-selection-wrapper' );

    if ( ! $restrictAccess.length || ! $userSelectionWrapper.length ) {
      return;
    }

    function toggleUserSelection() {
      if ( $restrictAccess.is( ':checked' ) ) {
        $userSelectionWrapper.addClass( 'is-visible' ).slideDown();
      } else {
        $userSelectionWrapper.removeClass( 'is-visible' ).slideUp();
      }
    }

    function setAccessSelectorVisibility( $wrapper, isVisible ) {
      var $selector = $wrapper.find( '.pdt-access-level-selector' );

      $selector.toggleClass( 'is-visible', isVisible );
      if ( isVisible ) {
        $selector.stop( true, true ).slideDown( 150 );
      } else {
        $selector.stop( true, true ).slideUp( 150 );
      }
    }

    function syncUserCardState( $checkbox ) {
      var $wrapper = $checkbox.closest( '.pdt-user-card-wrapper' );
      var isChecked = $checkbox.is( ':checked' );

      $wrapper.toggleClass( 'selected', isChecked );
      setAccessSelectorVisibility( $wrapper, isChecked );
    }

    function updateSuperAdminState() {
      var $superAdmin = $( 'input[data-super-admin="1"]' );
      if ( ! $superAdmin.length ) {
        return;
      }

      var $otherAdmins = $( '.pdt-user-checkbox' ).not( $superAdmin );
      var otherChecked = $otherAdmins.filter( ':checked' ).length;

      if ( otherChecked === 0 ) {
        $superAdmin.prop( 'checked', true ).prop( 'disabled', true );
        $superAdmin.closest( '.pdt-user-card-wrapper' ).addClass( 'selected locked' );
        syncUserCardState( $superAdmin );
      } else {
        $superAdmin.prop( 'disabled', false );
        $superAdmin.closest( '.pdt-user-card-wrapper' ).removeClass( 'locked' );
      }
    }

    $restrictAccess.on( 'change', toggleUserSelection );

    $( '.pdt-user-checkbox' ).on( 'change', function() {
      syncUserCardState( $( this ) );
      updateSuperAdminState();
    } );

    $( '.pdt-user-checkbox' ).each( function() {
      syncUserCardState( $( this ) );
    } );

    updateSuperAdminState();
    toggleUserSelection();
  }

  function initSecurityTab() {
    var $toggle = $( '#two_factor_enabled' );
    var $options = $( '#2fa-options-wrapper' );
    var $superAdminToggle = $( '#two_factor_include_super_admin' );
    var $superAdminWarning = $( '#pdt-super-admin-2fa-warning' );
    var $methodRadios = $( 'input[name="two_factor_method"]' );
    var $emailSettings = $( '#pdt-method-email-settings' );
    var $authenticatorSettings = $( '#pdt-method-authenticator-settings' );

    if ( ! $toggle.length || ! $options.length ) {
      return;
    }

    function toggleSuperAdminWarning() {
      if ( ! $superAdminToggle.length || ! $superAdminWarning.length ) {
        return;
      }

      $superAdminWarning.toggleClass( 'is-visible', $superAdminToggle.is( ':checked' ) );
    }

    function syncSuperAdminToggleWith2FA() {
      if ( ! $superAdminToggle.length ) {
        return;
      }

      if ( $toggle.is( ':checked' ) ) {
        $superAdminToggle.prop( 'disabled', false );
      } else {
        $superAdminToggle.prop( 'checked', false ).prop( 'disabled', true );
      }

      toggleSuperAdminWarning();
    }

    function updateMethodSelection() {
      var selectedMethod = $methodRadios.filter( ':checked' ).val() || 'email';

      $( '.pdt-method-option' ).removeClass( 'is-selected' );
      $( '.pdt-method-option input[value="' + selectedMethod + '"]' ).closest( '.pdt-method-option' ).addClass( 'is-selected' );

      if ( $emailSettings.length ) {
        if ( selectedMethod === 'email' ) {
          $emailSettings.slideDown( 200 );
        } else {
          $emailSettings.slideUp( 200 );
        }
      }

      if ( $authenticatorSettings.length ) {
        if ( selectedMethod === 'authenticator' ) {
          $authenticatorSettings.slideDown( 200 );
        } else {
          $authenticatorSettings.slideUp( 200 );
        }
      }
    }

    $toggle.on( 'change', function() {
      if ( $toggle.is( ':checked' ) ) {
        $options.addClass( 'is-visible' ).slideDown();
      } else {
        $options.removeClass( 'is-visible' ).slideUp();
      }

      syncSuperAdminToggleWith2FA();
    } );

    if ( $superAdminToggle.length ) {
      $superAdminToggle.on( 'change', toggleSuperAdminWarning );
      syncSuperAdminToggleWith2FA();
    }

    if ( $methodRadios.length ) {
      $methodRadios.on( 'change', updateMethodSelection );
      updateMethodSelection();
    }
  }

  function initContentVisibilityTab() {
    var $toggle = $( '#content_visibility_enabled' );
    var $options = $( '#pdt-content-visibility-options' );
    var $behavior = $( '#content_visibility_default_denied_behavior' );
    var $redirectRow = $( '.pdt-content-visibility-default-redirect-row' );
    var $messageRow = $( '.pdt-content-visibility-default-message-row' );

    if ( ! $toggle.length || ! $options.length ) {
      return;
    }

    function updateBehaviorFields() {
      if ( ! $behavior.length ) {
        return;
      }

      var showRedirect = $behavior.val() === 'custom_redirect';
      var showMessage = $behavior.val() === 'message';

      if ( $redirectRow.length ) {
        $redirectRow.toggle( showRedirect );
      }

      if ( $messageRow.length ) {
        $messageRow.toggle( showMessage );
      }
    }

    function toggleOptions() {
      if ( $toggle.is( ':checked' ) ) {
        $options.addClass( 'is-visible' ).stop( true, true ).slideDown( 180 );
      } else {
        $options.removeClass( 'is-visible' ).stop( true, true ).slideUp( 180 );
      }

      updateBehaviorFields();
    }

    $toggle.on( 'change', toggleOptions );

    if ( $behavior.length ) {
      $behavior.on( 'change', updateBehaviorFields );
    }

    toggleOptions();
  }

  function initRecoveryKeysModal() {
    function closeRecoveryModal( element ) {
      var modal = null;

      if ( element && element.closest ) {
        modal = element.closest( '.pdt-recovery-keys-modal' );
      }

      if ( ! modal ) {
        modal = document.querySelector( '.pdt-recovery-keys-modal' );
      }

      if ( modal ) {
        modal.style.display = 'none';
      }
    }

    $( document ).on( 'click', '.pdt-copy-recovery-keys', function() {
      var text = $( this ).attr( 'data-recovery-keys' ) || '';
      var successText = $( this ).attr( 'data-copy-success' ) || '';

      if ( navigator.clipboard && navigator.clipboard.writeText ) {
        navigator.clipboard.writeText( text ).then( function() {
          if ( successText ) {
            window.alert( successText );
          }
        } );
      }
    } );

    $( document ).on( 'click', '.pdt-close-recovery-modal, .pdt-recovery-modal-close', function() {
      closeRecoveryModal( this );
    } );

    $( document ).on( 'click', '.pdt-recovery-keys-modal', function( event ) {
      if ( event.target === this ) {
        $( this ).hide();
      }
    } );

    $( document ).on( 'keydown', function( event ) {
      if ( event.key === 'Escape' ) {
        $( '.pdt-recovery-keys-modal:visible' ).hide();
      }
    } );

    document.addEventListener( 'click', function( event ) {
      var closeTrigger = event.target.closest( '.pdt-close-recovery-modal, .pdt-recovery-modal-close' );
      if ( closeTrigger ) {
        event.preventDefault();
        closeRecoveryModal( closeTrigger );
        return;
      }

      if ( event.target.classList && event.target.classList.contains( 'pdt-recovery-keys-modal' ) ) {
        closeRecoveryModal( event.target );
      }
    }, true );
  }

  function initActivityLogTab() {
    var $range = $( '#export_range' );
    if ( ! $range.length ) {
      return;
    }

    $range.on( 'change', function() {
      var selectedRange = $range.val();
      var csvBase = $range.attr( 'data-csv-base' ) || '';
      var jsonBase = $range.attr( 'data-json-base' ) || '';

      if ( csvBase ) {
        $( '#export-csv-btn' ).attr( 'href', csvBase + '&range=' + selectedRange );
      }
      if ( jsonBase ) {
        $( '#export-json-btn' ).attr( 'href', jsonBase + '&range=' + selectedRange );
      }
    } );
  }

  function initMiscTab() {
    var $footerInput = $( '#admin_footer_text' );
    var $footerVersion = $( 'input[name="admin_footer_version"]' );
    var $preview = $( '#pdt-footer-preview' );
    var $footerLeft = $( '#footer-left' );
    var $footerRight = $( '#footer-upgrade' );

    if ( ! $footerInput.length || ! $footerVersion.length || ! $preview.length ) {
      return;
    }

    function syncLiveAdminFooter( footerHtml, showVersion ) {
      if ( $footerLeft.length ) {
        $footerLeft.html( footerHtml );
      }

      if ( $footerRight.length ) {
        if ( showVersion && window.pdtSettingsPageI18n ) {
          $footerRight.text( window.pdtSettingsPageI18n.versionLabel ).show();
        } else {
          $footerRight.text( '' ).hide();
        }
      }
    }

    function updateFooterPreview() {
      var footerText = $footerInput.val();
      var showVersion = $footerVersion.is( ':checked' );
      var versionText = showVersion && window.pdtSettingsPageI18n ? ' &mdash; ' + escapeHtml( window.pdtSettingsPageI18n.versionLabel ) : '';
      var hiddenLabel = window.pdtSettingsPageI18n ? window.pdtSettingsPageI18n.footerHiddenLabel : '';
      var footerHtml;

      if ( ! footerText ) {
        footerHtml = '';
        footerText = '<em>' + escapeHtml( hiddenLabel ) + '</em>';
      } else {
        footerText = sanitizeFooterPreviewHtml( footerText );
        footerHtml = footerText;
      }

      $preview.html( footerText + versionText );
      syncLiveAdminFooter( footerHtml, showVersion );
    }

    $footerInput.on( 'input', updateFooterPreview );
    $footerVersion.on( 'change', updateFooterPreview );
    updateFooterPreview();
  }

  $( document ).ready( function() {
    initGeneralTab();
    initSecurityTab();
    initContentVisibilityTab();
    initRecoveryKeysModal();
    initActivityLogTab();
    initMiscTab();
  } );
}( jQuery ) );
