( function() {
  'use strict';

  function markReady() {
    var root = document.documentElement;

    root.classList.remove( 'pdt-login-runtime-pending' );
    root.classList.add( 'pdt-login-runtime-ready' );
  }

  function applyTheme() {
    if ( ! window.pdtLoginPageConfig ) {
      return;
    }

    var config = window.pdtLoginPageConfig;
    var root = document.documentElement;
    var body = document.body;

    root.style.setProperty( '--pdt-login-primary', config.primaryColor );
    root.style.setProperty( '--pdt-login-primary-hover', config.primaryHoverColor );
    root.style.setProperty( '--pdt-login-card-bg', config.cardBackground );

    if ( config.bgType === 'color' ) {
      body.style.background = config.bgColor;
    } else if ( config.bgType === 'gradient' ) {
      body.style.background = 'linear-gradient(135deg, ' + config.bgGradientStart + ' 0%, ' + config.bgGradientEnd + ' 100%)';
    } else if ( config.bgType === 'image' && config.bgImageUrl ) {
      body.style.background = "url('" + config.bgImageUrl + "') center center / cover no-repeat fixed";
    }

    if ( config.customLogoUrl ) {
      var logo = document.querySelector( '#login h1 a' );
      if ( logo ) {
        logo.style.backgroundImage = "url('" + config.customLogoUrl + "')";
        logo.style.width = '100%';
        logo.style.maxWidth = '320px';
        logo.style.backgroundSize = 'contain';
      }
    }
  }

  function buildSplitLayout() {
    if ( ! window.pdtLoginPageConfig ) {
      return;
    }

    var config = window.pdtLoginPageConfig;
    var supportedForms = document.querySelector( '#login form#loginform, #login form#registerform, #login form#lostpasswordform, #login form#resetpassform, #login form[name="resetpassform"]' );

    if ( ! config.enableSplitLayout || ! supportedForms ) {
      return;
    }

    var loginDiv = document.getElementById( 'login' );
    if ( ! loginDiv || loginDiv.querySelector( '.pdt-login-wrapper' ) ) {
      return;
    }

    var wrapper = document.createElement( 'div' );
    wrapper.className = 'pdt-login-wrapper';

    var leftPanel = document.createElement( 'div' );
    leftPanel.className = 'pdt-login-left-panel';
    leftPanel.style.background = 'linear-gradient(135deg, ' + config.primaryColor + ' 0%, ' + config.leftGradientEnd + ' 100%)';

    var leftHtml = '' +
      '<div class="pdt-login-decor pdt-login-decor-1"></div>' +
      '<div class="pdt-login-decor pdt-login-decor-2"></div>' +
      '<div class="pdt-login-decor pdt-login-decor-3"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div>' +
      '<div class="pdt-login-decor pdt-login-decor-4"></div>' +
      '<div class="pdt-login-wave"></div>' +
      '<div class="pdt-login-welcome">' + ( config.logoHtml || '' ) + '<h2></h2><p></p></div>';

    leftPanel.innerHTML = leftHtml;
    leftPanel.querySelector( 'h2' ).textContent = config.siteTitle || '';
    var taglineNode = leftPanel.querySelector( 'p' );
    if ( config.tagline ) {
      taglineNode.textContent = config.tagline;
    } else {
      taglineNode.remove();
    }

    var rightPanel = document.createElement( 'div' );
    rightPanel.className = 'pdt-login-right-panel';
    while ( loginDiv.firstChild ) {
      rightPanel.appendChild( loginDiv.firstChild );
    }

    var title = document.createElement( 'h2' );
    title.className = 'pdt-login-form-title';
    title.textContent = getFormTitle( supportedForms, config );
    rightPanel.insertBefore( title, rightPanel.firstChild );

    wrapper.appendChild( leftPanel );
    wrapper.appendChild( rightPanel );
    loginDiv.appendChild( wrapper );
    document.body.classList.add( 'pdt-split-login' );

    var userLogin = document.getElementById( 'user_login' );
    var userPass = document.getElementById( 'user_pass' );
    var userEmail = document.getElementById( 'user_email' );
    if ( userLogin && config.strings && config.strings.usernameOrEmail ) {
      userLogin.placeholder = config.strings.usernameOrEmail;
    }
    if ( userPass && config.strings && config.strings.password ) {
      userPass.placeholder = config.strings.password;
    }
    if ( userEmail && config.strings && config.strings.emailAddress ) {
      userEmail.placeholder = config.strings.emailAddress;
    }
  }

  /**
   * Mobile: replace bulky language bar with a globe FAB + bottom sheet.
   * Desktop: leave WordPress markup in place (fixed bottom-right via CSS).
   */
  function initLanguageDrawer() {
    var cfg = window.pdtLoginPageConfig || {};
    if ( cfg.hideLanguageSwitcher ) {
      return;
    }

    var switcher = document.querySelector( '.language-switcher' );
    if ( ! switcher ) {
      return;
    }

    var mq = window.matchMedia( '(max-width: 520px)' );
    var str = ( window.pdtLoginPageConfig && window.pdtLoginPageConfig.strings ) ? window.pdtLoginPageConfig.strings : {};
    var titleText = str.languageTitle || 'Language';
    var fabLabel = str.languageFab || 'Language';
    var closeLabel = str.close || 'Close';

    var originalParent = null;
    var originalNext = null;

    var shell = document.createElement( 'div' );
    shell.className = 'pdt-lang-mobile-shell';
    shell.setAttribute( 'aria-hidden', 'true' );

    var fab = document.createElement( 'button' );
    fab.type = 'button';
    fab.className = 'pdt-lang-fab';
    fab.setAttribute( 'aria-label', fabLabel );
    fab.setAttribute( 'aria-expanded', 'false' );
    fab.innerHTML = '<span class="pdt-lang-fab__icon" aria-hidden="true">' +
      '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
      '<circle cx="12" cy="12" r="10"></circle>' +
      '<path d="M2 12h20"></path>' +
      '<path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path>' +
      '</svg></span>';

    var drawer = document.createElement( 'div' );
    drawer.className = 'pdt-lang-drawer';
    drawer.setAttribute( 'aria-hidden', 'true' );
    drawer.id = 'pdt-lang-drawer';

    var backdrop = document.createElement( 'button' );
    backdrop.type = 'button';
    backdrop.className = 'pdt-lang-drawer__backdrop';
    backdrop.setAttribute( 'aria-label', closeLabel );

    var sheet = document.createElement( 'div' );
    sheet.className = 'pdt-lang-drawer__sheet';
    sheet.setAttribute( 'role', 'dialog' );
    sheet.setAttribute( 'aria-modal', 'true' );
    sheet.setAttribute( 'aria-labelledby', 'pdt-lang-drawer-title' );

    sheet.innerHTML = '<div class="pdt-lang-drawer__handle" aria-hidden="true"></div>' +
      '<div class="pdt-lang-drawer__head">' +
      '<h2 id="pdt-lang-drawer-title" class="pdt-lang-drawer__title">' + escapeHtml( titleText ) + '</h2>' +
      '<button type="button" class="pdt-lang-drawer__close" aria-label="' + escapeAttr( closeLabel ) + '">' +
      '<span aria-hidden="true">&times;</span></button></div>' +
      '<div class="pdt-lang-drawer__body"></div>';

    var bodyMount = sheet.querySelector( '.pdt-lang-drawer__body' );
    var closeBtn = sheet.querySelector( '.pdt-lang-drawer__close' );

    drawer.appendChild( backdrop );
    drawer.appendChild( sheet );
    shell.appendChild( fab );
    shell.appendChild( drawer );
    document.body.appendChild( shell );

    function escapeHtml( s ) {
      var d = document.createElement( 'div' );
      d.textContent = s;
      return d.innerHTML;
    }

    function escapeAttr( s ) {
      return String( s ).replace( /&/g, '&amp;' ).replace( /"/g, '&quot;' ).replace( /</g, '&lt;' );
    }

    function rememberOriginal() {
      if ( originalParent ) {
        return;
      }
      originalParent = switcher.parentNode;
      originalNext = switcher.nextSibling;
    }

    function moveToMobile() {
      rememberOriginal();
      bodyMount.appendChild( switcher );
      shell.classList.add( 'is-active-layout' );
      shell.setAttribute( 'aria-hidden', 'false' );
      document.body.classList.add( 'pdt-lang-mobile-on' );
      switcher.classList.add( 'pdt-lang-in-drawer' );
    }

    function moveToDesktop() {
      closeDrawer();
      if ( ! originalParent ) {
        return;
      }
      switcher.classList.remove( 'pdt-lang-in-drawer' );
      if ( originalNext ) {
        originalParent.insertBefore( switcher, originalNext );
      } else {
        originalParent.appendChild( switcher );
      }
      shell.classList.remove( 'is-active-layout' );
      shell.setAttribute( 'aria-hidden', 'true' );
      document.body.classList.remove( 'pdt-lang-mobile-on' );
    }

    function openDrawer() {
      drawer.classList.add( 'is-open' );
      fab.setAttribute( 'aria-expanded', 'true' );
      drawer.setAttribute( 'aria-hidden', 'false' );
      document.body.classList.add( 'pdt-lang-drawer-open' );
    }

    function closeDrawer() {
      drawer.classList.remove( 'is-open' );
      fab.setAttribute( 'aria-expanded', 'false' );
      drawer.setAttribute( 'aria-hidden', 'true' );
      document.body.classList.remove( 'pdt-lang-drawer-open' );
    }

    function toggleDrawer() {
      if ( drawer.classList.contains( 'is-open' ) ) {
        closeDrawer();
      } else {
        openDrawer();
      }
    }

    fab.addEventListener( 'click', toggleDrawer );
    backdrop.addEventListener( 'click', closeDrawer );
    closeBtn.addEventListener( 'click', closeDrawer );

    document.addEventListener( 'keydown', function( ev ) {
      if ( ev.key === 'Escape' && drawer.classList.contains( 'is-open' ) ) {
        closeDrawer();
      }
    } );

    function applyLayout() {
      if ( mq.matches ) {
        moveToMobile();
      } else {
        moveToDesktop();
      }
    }

    if ( typeof mq.addEventListener === 'function' ) {
      mq.addEventListener( 'change', applyLayout );
    } else if ( typeof mq.addListener === 'function' ) {
      mq.addListener( applyLayout );
    }

    applyLayout();
  }

  function initRecaptchaV3() {
    if ( typeof window.grecaptcha === 'undefined' ) {
      return;
    }

    var tokens = document.querySelectorAll( '.pdt-recaptcha-v3-token' );
    tokens.forEach( function( node ) {
      var siteKey = node.getAttribute( 'data-site-key' );
      var action = node.getAttribute( 'data-action' ) || 'login';
      if ( ! siteKey ) {
        return;
      }
      window.grecaptcha.ready( function() {
        window.grecaptcha.execute( siteKey, { action: action } ).then( function( token ) {
          node.value = token;
        } );
      } );
    } );
  }

  function boot() {
    applyTheme();
    buildSplitLayout();
    initLanguageDrawer();
    initRecaptchaV3();

    if ( typeof window.requestAnimationFrame === 'function' ) {
      window.requestAnimationFrame( markReady );
    } else {
      markReady();
    }
  }

  function getFormTitle( form, config ) {
    var strings = ( config && config.strings ) ? config.strings : {};
    var fallback = strings.signIn || 'Sign In';
    var formId = form && form.id ? form.id : '';
    var action = '';

    try {
      action = new URLSearchParams( window.location.search ).get( 'action' ) || '';
    } catch ( e ) {
      action = '';
    }

    if ( formId === 'registerform' ) {
      return strings.register || fallback;
    }

    if ( formId === 'lostpasswordform' || action === 'lostpassword' || action === 'retrievepassword' ) {
      return strings.lostPassword || fallback;
    }

    if ( formId === 'resetpassform' || action === 'rp' || action === 'resetpass' ) {
      return strings.resetPassword || fallback;
    }

    return fallback;
  }

  if ( document.readyState === 'loading' ) {
    document.addEventListener( 'DOMContentLoaded', boot );
  } else {
    boot();
  }
}() );
