<?php
/**
 * Login Page Customization Module
 *
 * @package Polanger_Dashboard_Tools_Pro
 * @since 4.1.0
 */

if ( ! defined( 'ABSPATH' ) ) {
  exit;
}

/**
 * PDT Login Page Class
 */
class PDT_Login_Page {

  /**
   * Option name for login page settings
   */
  const OPTION_NAME = 'pdt_login_page_settings';

  /**
   * Flag to track if wp-login.php was requested
   */
  private $wp_login_php = false;

  /**
   * Constructor
   */
  public function __construct() {
    add_action( 'admin_init', array( $this, 'register_settings' ) );
    add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
    
    // Login URL modification hooks
    add_action( 'plugins_loaded', array( $this, 'plugins_loaded' ), 9999 );
    add_action( 'wp_loaded', array( $this, 'wp_loaded' ) );
    add_filter( 'site_url', array( $this, 'site_url' ), 10, 4 );
    add_filter( 'network_site_url', array( $this, 'network_site_url' ), 10, 3 );
    add_filter( 'wp_redirect', array( $this, 'filter_wp_redirect' ), 10, 2 );
    add_filter( 'login_url', array( $this, 'login_url' ), 10, 3 );
    
    // Remove default redirect
    remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
    
    // Login page customization hooks
    add_action( 'login_enqueue_scripts', array( $this, 'enqueue_login_styles' ) );
    add_filter( 'login_headerurl', array( $this, 'custom_login_logo_url' ) );
    add_filter( 'login_headertext', array( $this, 'custom_login_logo_title' ) );
    add_filter( 'login_display_language_dropdown', array( $this, 'maybe_hide_language_dropdown' ) );
    add_filter( 'login_language_dropdown_args', array( $this, 'filter_login_language_dropdown_args' ) );
    
    // reCAPTCHA hooks
    add_action( 'login_form', array( $this, 'add_recaptcha_to_login' ) );
    add_action( 'register_form', array( $this, 'add_recaptcha_to_register' ) );
    add_action( 'lostpassword_form', array( $this, 'add_recaptcha_to_lostpassword' ) );
    add_filter( 'wp_authenticate_user', array( $this, 'verify_recaptcha_login' ), 10, 2 );
    add_filter( 'registration_errors', array( $this, 'verify_recaptcha_register' ), 10, 3 );
    add_action( 'lostpassword_post', array( $this, 'verify_recaptcha_lostpassword' ) );
  }

  /**
   * Register settings
   */
  public function register_settings() {
    register_setting(
      'pdt_login_page_settings_group',
      self::OPTION_NAME,
      array(
        'type' => 'array',
        'sanitize_callback' => array( $this, 'sanitize_settings' ),
      )
    );
  }

  /**
   * Sanitize settings
   */
  public function sanitize_settings( $input ) {
    $sanitized = array();

    if ( ! is_array( $input ) ) {
      return $sanitized;
    }

    $previous = get_option( self::OPTION_NAME, array() );
    if ( ! is_array( $previous ) ) {
      $previous = array();
    }

    // Enable custom login URL
    $sanitized['enable_custom_login'] = ! empty( $input['enable_custom_login'] ) ? '1' : '';

    // Custom login slug
    if ( ! empty( $input['login_slug'] ) ) {
      $slug = sanitize_title_with_dashes( $input['login_slug'] );
      
      // Prevent forbidden slugs
      if ( ! in_array( $slug, $this->get_forbidden_slugs(), true ) 
           && strpos( $slug, 'wp-login' ) === false 
           && strpos( $slug, 'wp-admin' ) === false ) {
        $sanitized['login_slug'] = $slug;
      } else {
        $sanitized['login_slug'] = 'my-login';
      }
    } else {
      $sanitized['login_slug'] = 'my-login';
    }

    // Redirect slug (where to redirect unauthorized access)
    if ( ! empty( $input['redirect_slug'] ) ) {
      $sanitized['redirect_slug'] = sanitize_title_with_dashes( $input['redirect_slug'] );
    } else {
      $sanitized['redirect_slug'] = '404';
    }

    // Enable login customization
    $sanitized['enable_login_customization'] = ! empty( $input['enable_login_customization'] ) ? '1' : '';

    // Custom logo URL
    $sanitized['custom_logo_url'] = isset( $input['custom_logo_url'] ) ? esc_url_raw( $input['custom_logo_url'] ) : '';

    // Logo link URL
    $sanitized['logo_link_url'] = isset( $input['logo_link_url'] ) ? esc_url_raw( $input['logo_link_url'] ) : '';

    // Background type (color or image)
    $sanitized['bg_type'] = isset( $input['bg_type'] ) && in_array( $input['bg_type'], array( 'color', 'image', 'gradient' ), true ) ? $input['bg_type'] : 'color';

    // Background color
    $sanitized['bg_color'] = isset( $input['bg_color'] ) ? sanitize_hex_color( $input['bg_color'] ) : '#0f172a';

    // Background gradient start
    $sanitized['bg_gradient_start'] = isset( $input['bg_gradient_start'] ) ? sanitize_hex_color( $input['bg_gradient_start'] ) : '#6366f1';

    // Background gradient end
    $sanitized['bg_gradient_end'] = isset( $input['bg_gradient_end'] ) ? sanitize_hex_color( $input['bg_gradient_end'] ) : '#8b5cf6';

    // Background image URL
    $sanitized['bg_image_url'] = isset( $input['bg_image_url'] ) ? esc_url_raw( $input['bg_image_url'] ) : '';

    // Primary color
    $sanitized['primary_color'] = isset( $input['primary_color'] ) ? sanitize_hex_color( $input['primary_color'] ) : '#6366f1';

    // Form background color
    $sanitized['form_bg_color'] = isset( $input['form_bg_color'] ) ? sanitize_hex_color( $input['form_bg_color'] ) : '#ffffff';

    // Hide language switcher on login page
    $sanitized['hide_language_switcher'] = ! empty( $input['hide_language_switcher'] ) ? '1' : '';

    // reCAPTCHA settings
    $sanitized['enable_recaptcha'] = ! empty( $input['enable_recaptcha'] ) ? '1' : '';
    $sanitized['recaptcha_site_key'] = isset( $input['recaptcha_site_key'] ) ? sanitize_text_field( $input['recaptcha_site_key'] ) : '';
    $sanitized['recaptcha_secret_key'] = isset( $input['recaptcha_secret_key'] ) ? sanitize_text_field( $input['recaptcha_secret_key'] ) : '';
    $sanitized['recaptcha_version'] = isset( $input['recaptcha_version'] ) && in_array( $input['recaptcha_version'], array( 'v2', 'v3' ), true ) ? $input['recaptcha_version'] : 'v2';
    
    // reCAPTCHA locations
    $sanitized['recaptcha_login'] = ! empty( $input['recaptcha_login'] ) ? '1' : '';
    $sanitized['recaptcha_register'] = ! empty( $input['recaptcha_register'] ) ? '1' : '';
    $sanitized['recaptcha_lostpassword'] = ! empty( $input['recaptcha_lostpassword'] ) ? '1' : '';

    $rewrite_keys = array( 'enable_custom_login', 'login_slug', 'redirect_slug' );
    foreach ( $rewrite_keys as $rewrite_key ) {
      $previous_value  = isset( $previous[ $rewrite_key ] ) ? (string) $previous[ $rewrite_key ] : '';
      $sanitized_value = isset( $sanitized[ $rewrite_key ] ) ? (string) $sanitized[ $rewrite_key ] : '';

      if ( $previous_value !== $sanitized_value ) {
        flush_rewrite_rules( false );
        break;
      }
    }

    return $sanitized;
  }

  /**
   * Get settings
   */
  public function get_settings() {
    $defaults = array(
      'enable_custom_login'        => '',
      'login_slug'                 => 'my-login',
      'redirect_slug'              => '404',
      'enable_login_customization' => '',
      'custom_logo_url'            => '',
      'logo_link_url'              => '',
      'bg_type'                    => 'color',
      'bg_color'                   => '#0f172a',
      'bg_gradient_start'          => '#6366f1',
      'bg_gradient_end'            => '#8b5cf6',
      'bg_image_url'               => '',
      'primary_color'              => '#6366f1',
      'form_bg_color'              => '#ffffff',
      'hide_language_switcher'     => '',
      'enable_recaptcha'           => '',
      'recaptcha_site_key'         => '',
      'recaptcha_secret_key'       => '',
      'recaptcha_version'          => 'v2',
      'recaptcha_login'            => '',
      'recaptcha_register'         => '',
      'recaptcha_lostpassword'     => '',
    );
    $settings = wp_parse_args( get_option( self::OPTION_NAME, array() ), $defaults );

    return apply_filters( 'polanger_effective_settings', $settings, self::OPTION_NAME, $defaults, 'login-page' );
  }

  /**
   * Get the current wp-login.php action.
   *
   * @return string
   */
  private function get_login_screen_action() {
    if ( isset( $_REQUEST['action'] ) ) {
      return sanitize_key( wp_unslash( $_REQUEST['action'] ) );
    }

    global $action;

    if ( ! empty( $action ) && is_string( $action ) ) {
      return sanitize_key( $action );
    }

    return 'login';
  }

  /**
   * Determine whether the split login customization should load.
   *
   * Special interstitial screens such as confirm_admin_email should keep the
   * default WordPress layout so their native actions and buttons stay intact.
   *
   * @return bool
   */
  private function should_customize_login_screen() {
    $supported_actions = array(
      'login',
      'register',
      'lostpassword',
      'retrievepassword',
      'rp',
      'resetpass',
    );

    return in_array( $this->get_login_screen_action(), $supported_actions, true );
  }

  /**
   * Check if custom login is enabled
   */
  private function is_enabled() {
    $settings = $this->get_settings();
    return ! empty( $settings['enable_custom_login'] );
  }

  /**
   * Get new login slug
   */
  private function new_login_slug() {
    $settings = $this->get_settings();
    return ! empty( $settings['login_slug'] ) ? $settings['login_slug'] : 'my-login';
  }

  /**
   * Get redirect slug
   */
  private function new_redirect_slug() {
    $settings = $this->get_settings();
    return ! empty( $settings['redirect_slug'] ) ? $settings['redirect_slug'] : '404';
  }

  /**
   * Check if using trailing slashes
   */
  private function use_trailing_slashes() {
    return ( '/' === substr( get_option( 'permalink_structure' ), -1, 1 ) );
  }

  /**
   * Add or remove trailing slash based on permalink structure
   */
  private function user_trailingslashit( $string ) {
    return $this->use_trailing_slashes() ? trailingslashit( $string ) : untrailingslashit( $string );
  }

  /**
   * Get new login URL
   */
  public function new_login_url( $scheme = null ) {
    $url = home_url( '/', $scheme );

    if ( get_option( 'permalink_structure' ) ) {
      return $this->user_trailingslashit( $url . $this->new_login_slug() );
    } else {
      return $url . '?' . $this->new_login_slug();
    }
  }

  /**
   * Get redirect URL for unauthorized access
   */
  private function new_redirect_url( $scheme = null ) {
    $redirect_slug = $this->new_redirect_slug();
    
    if ( $redirect_slug === '404' ) {
      return home_url( '/404', $scheme );
    }

    if ( get_option( 'permalink_structure' ) ) {
      return $this->user_trailingslashit( home_url( '/', $scheme ) . $redirect_slug );
    } else {
      return home_url( '/', $scheme ) . '?' . $redirect_slug;
    }
  }

  /**
   * Render the built-in theme-independent 404 screen.
   */
  private function render_security_404() {
    global $wp_query;

    if ( ! $wp_query instanceof WP_Query ) {
      $wp_query = new WP_Query();
    }

    $wp_query->set_404();
    status_header( 404 );
    nocache_headers();

    wp_enqueue_style(
      'pdt-login-guard-404',
      plugins_url( 'assets/css/login-guard-404.css', PDT_PLUGIN_FILE ),
      array(),
      PDT_VERSION
    );

    $pdt_login_guard_404_context = $this->get_security_404_context();

    include PDT_PLUGIN_DIR . 'templates/login-guard-404.php';
    exit;
  }

  /**
   * Plugins loaded hook - detect wp-login.php access
   */
  public function plugins_loaded() {
    if ( ! $this->is_enabled() ) {
      return;
    }

    global $pagenow;

    // phpcs:disable WordPress.Security.NonceVerification.Recommended
    $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
    // phpcs:enable WordPress.Security.NonceVerification.Recommended
    $request = wp_parse_url( rawurldecode( $request_uri ) );

    // Check if accessing wp-login.php directly
    if ( ( strpos( rawurldecode( $request_uri ), 'wp-login.php' ) !== false
           || ( isset( $request['path'] ) && untrailingslashit( $request['path'] ) === site_url( 'wp-login', 'relative' ) ) )
         && ! is_admin() ) {

      $this->wp_login_php = true;

      $_SERVER['REQUEST_URI'] = $this->user_trailingslashit( '/' . str_repeat( '-/', 10 ) );

      $pagenow = 'index.php';

    // phpcs:disable WordPress.Security.NonceVerification.Recommended
    } elseif ( ( isset( $request['path'] ) && untrailingslashit( $request['path'] ) === home_url( $this->new_login_slug(), 'relative' ) )
               || ( ! get_option( 'permalink_structure' )
                    && isset( $_GET[ $this->new_login_slug() ] )
                    && empty( $_GET[ $this->new_login_slug() ] ) ) ) {
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

      $_SERVER['SCRIPT_NAME'] = $this->new_login_slug();

      $pagenow = 'wp-login.php';

    } elseif ( ( strpos( rawurldecode( $request_uri ), 'wp-register.php' ) !== false
                 || ( isset( $request['path'] ) && untrailingslashit( $request['path'] ) === site_url( 'wp-register', 'relative' ) ) )
               && ! is_admin() ) {

      $this->wp_login_php = true;

      $_SERVER['REQUEST_URI'] = $this->user_trailingslashit( '/' . str_repeat( '-/', 10 ) );

      $pagenow = 'index.php';
    }
  }

  /**
   * WP Loaded hook - handle redirects
   */
  public function wp_loaded() {
    if ( ! $this->is_enabled() ) {
      return;
    }

    global $pagenow;

    // phpcs:disable WordPress.Security.NonceVerification.Recommended
    $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
    // phpcs:enable WordPress.Security.NonceVerification.Recommended
    $request = wp_parse_url( rawurldecode( $request_uri ) );

    // Skip password protected post handling
    // phpcs:disable WordPress.Security.NonceVerification.Recommended,WordPress.Security.NonceVerification.Missing
    if ( isset( $_GET['action'] ) && 'postpass' === sanitize_text_field( wp_unslash( $_GET['action'] ) ) && isset( $_POST['post_password'] ) ) {
      return;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended,WordPress.Security.NonceVerification.Missing

    // Redirect non-logged-in users trying to access wp-admin
    if ( is_admin() && ! is_user_logged_in() && ! defined( 'WP_CLI' ) && ! defined( 'DOING_AJAX' ) && ! defined( 'DOING_CRON' ) && $pagenow !== 'admin-post.php' && ( ! isset( $request['path'] ) || $request['path'] !== '/wp-admin/options.php' ) ) {
      $this->do_redirect();
    }

    // Handle wp-login.php access
    if ( $pagenow === 'wp-login.php' && isset( $request['path'] ) && $request['path'] !== $this->user_trailingslashit( $request['path'] ) && get_option( 'permalink_structure' ) ) {
      // phpcs:disable WordPress.Security.NonceVerification.Recommended
      $query_string = ! empty( $_SERVER['QUERY_STRING'] ) ? sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ) : '';
      // phpcs:enable WordPress.Security.NonceVerification.Recommended
      wp_safe_redirect( $this->user_trailingslashit( $this->new_login_url() ) . ( '' !== $query_string ? '?' . $query_string : '' ) );
      die;

    } elseif ( $this->wp_login_php ) {
      // Show 404 for direct wp-login.php access
      $this->render_security_404();

    } elseif ( $pagenow === 'wp-login.php' ) {
      // Load actual login page for custom URL
      global $error, $interim_login, $action, $user_login;

      $redirect_to = admin_url();

      $requested_redirect_to = '';
      // phpcs:disable WordPress.Security.NonceVerification.Recommended
      if ( isset( $_REQUEST['redirect_to'] ) ) {
        $requested_redirect_to = sanitize_text_field( wp_unslash( $_REQUEST['redirect_to'] ) );
      }
      // phpcs:enable WordPress.Security.NonceVerification.Recommended

      if ( is_user_logged_in() ) {
        $user = wp_get_current_user();
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( ! isset( $_REQUEST['action'] ) ) {
          wp_safe_redirect( $redirect_to );
          die();
        }
      }

      @require_once ABSPATH . 'wp-login.php';

      die;
    }
  }

  /**
   * Do redirect for unauthorized access
   */
  private function do_redirect() {
    $redirect_slug = $this->new_redirect_slug();
    
    if ( $redirect_slug === '404' ) {
      $this->render_security_404();
    } else {
      wp_safe_redirect( $this->new_redirect_url() );
      die;
    }
  }

  /**
   * Build the context used by the built-in protected 404 screen.
   *
   * @return array<string,string>
   */
  private function get_security_404_context() {
    $settings        = $this->get_settings();
    $site_title      = wp_strip_all_tags( get_bloginfo( 'name' ), true );
    $site_icon_url   = get_site_icon_url( 192 );
    $custom_logo_url = ! empty( $settings['custom_logo_url'] ) ? esc_url_raw( $settings['custom_logo_url'] ) : '';
    $primary_color   = ! empty( $settings['primary_color'] ) ? $settings['primary_color'] : '#6366f1';
    $surface_color   = ! empty( $settings['form_bg_color'] ) ? $settings['form_bg_color'] : '#ffffff';
    $surface_rgb     = $this->hex_to_rgb_components( $surface_color );

    $context = array(
      'page_title'        => sprintf(
        /* translators: %s: Site title. */
        __( 'Page not found - %s', 'polanger-admin-menu-manager' ),
        $site_title
      ),
      'eyebrow'           => '',
      'title'             => __( 'Looks like we wandered off the map.', 'polanger-admin-menu-manager' ),
      'message'           => __( 'We could not find the address you were looking for, but that does not mean the road ends here.', 'polanger-admin-menu-manager' ),
      'supporting_text'   => __( 'There may be a typo, or the page may have been updated. We will guide you back to a safe path right away. Use the link below to return to the homepage.', 'polanger-admin-menu-manager' ),
      'home_label'        => __( 'Return to homepage', 'polanger-admin-menu-manager' ),
      'home_url'          => home_url( '/' ),
      'site_title'        => $site_title,
      'site_icon_url'     => $site_icon_url ? esc_url_raw( $site_icon_url ) : '',
      'logo_url'          => $custom_logo_url,
      'body_style'        => $this->build_security_404_body_style( $settings, $primary_color, $surface_color, $surface_rgb ),
    );

    return apply_filters( 'pdt_login_security_404_context', $context, $settings );
  }

  /**
   * Build inline CSS variables for the protected 404 screen.
   *
   * @param array  $settings      Login page settings.
   * @param string $primary_color Primary accent color.
   * @param string $surface_color Card surface color.
   * @param string $surface_rgb   Surface RGB string.
   * @return string
   */
  private function build_security_404_body_style( $settings, $primary_color, $surface_color, $surface_rgb ) {
    $secondary_color = ! empty( $settings['bg_gradient_end'] ) ? $settings['bg_gradient_end'] : $this->adjust_brightness( $primary_color, 28 );
    $text_color      = '#0f172a';
    $muted_color     = '#475569';
    $background_css  = $this->build_security_404_background( $settings );

    $styles = array(
      '--pdt-login-404-primary:' . $primary_color,
      '--pdt-login-404-primary-strong:' . $this->adjust_brightness( $primary_color, -26 ),
      '--pdt-login-404-secondary:' . $secondary_color,
      '--pdt-login-404-surface:' . $surface_color,
      '--pdt-login-404-surface-rgb:' . $surface_rgb,
      '--pdt-login-404-text:' . $text_color,
      '--pdt-login-404-muted:' . $muted_color,
      '--pdt-login-404-shell-bg:' . $background_css,
    );

    return implode( ';', $styles ) . ';';
  }

  /**
   * Build the background used by the protected 404 screen.
   *
   * @param array $settings Login page settings.
   * @return string
   */
  private function build_security_404_background( $settings ) {
    $bg_type           = ! empty( $settings['bg_type'] ) ? $settings['bg_type'] : 'color';
    $primary_color     = ! empty( $settings['primary_color'] ) ? $settings['primary_color'] : '#6366f1';
    $fallback_start    = ! empty( $settings['bg_gradient_start'] ) ? $settings['bg_gradient_start'] : $primary_color;
    $fallback_end      = ! empty( $settings['bg_gradient_end'] ) ? $settings['bg_gradient_end'] : '#8b5cf6';
    $fallback_solid    = ! empty( $settings['bg_color'] ) ? $settings['bg_color'] : '#0f172a';
    $background_image  = ! empty( $settings['bg_image_url'] ) ? esc_url_raw( $settings['bg_image_url'] ) : '';

    if ( 'image' === $bg_type && ! empty( $background_image ) ) {
      return sprintf(
        'linear-gradient(135deg, rgba(15, 23, 42, 0.88) 0%%, rgba(49, 46, 129, 0.74) 100%%), url("%s") center/cover fixed no-repeat',
        $background_image
      );
    }

    if ( 'gradient' === $bg_type ) {
      return sprintf( 'linear-gradient(135deg, %1$s 0%%, %2$s 100%%)', $fallback_start, $fallback_end );
    }

    return sprintf(
      'linear-gradient(145deg, %1$s 0%%, %2$s 100%%)',
      $fallback_solid,
      $this->adjust_brightness( $fallback_solid, -36 )
    );
  }

  /**
   * Filter site_url
   */
  public function site_url( $url, $path, $scheme, $blog_id ) {
    if ( ! $this->is_enabled() ) {
      return $url;
    }
    return $this->filter_wp_login_php( $url, $scheme );
  }

  /**
   * Filter network_site_url
   */
  public function network_site_url( $url, $path, $scheme ) {
    if ( ! $this->is_enabled() ) {
      return $url;
    }
    return $this->filter_wp_login_php( $url, $scheme );
  }

  /**
   * Filter wp_redirect
   */
  public function filter_wp_redirect( $location, $status ) {
    if ( ! $this->is_enabled() ) {
      return $location;
    }
    return $this->filter_wp_login_php( $location );
  }

  /**
   * Filter login_url
   */
  public function login_url( $login_url, $redirect, $force_reauth ) {
    if ( ! $this->is_enabled() ) {
      return $login_url;
    }

    if ( is_404() ) {
      return '#';
    }

    if ( $force_reauth === false ) {
      return $login_url;
    }

    if ( empty( $redirect ) ) {
      return $login_url;
    }

    $redirect = explode( '?', $redirect );

    if ( $redirect[0] === admin_url( 'options.php' ) ) {
      $login_url = admin_url();
    }

    return $login_url;
  }

  /**
   * Replace wp-login.php in URLs
   */
  private function filter_wp_login_php( $url, $scheme = null ) {
    if ( strpos( $url, 'wp-login.php?action=postpass' ) !== false ) {
      return $url;
    }

    if ( strpos( $url, 'wp-login.php' ) !== false && strpos( wp_get_referer(), 'wp-login.php' ) === false ) {

      if ( is_ssl() ) {
        $scheme = 'https';
      }

      $args = explode( '?', $url );

      if ( isset( $args[1] ) ) {
        parse_str( $args[1], $args );

        if ( isset( $args['login'] ) ) {
          $args['login'] = rawurlencode( $args['login'] );
        }

        $url = add_query_arg( $args, $this->new_login_url( $scheme ) );
      } else {
        $url = $this->new_login_url( $scheme );
      }
    }

    return $url;
  }

  /**
   * Get forbidden slugs
   */
  private function get_forbidden_slugs() {
    $wp = new WP;
    return array_merge( $wp->public_query_vars, $wp->private_query_vars );
  }

  /**
   * Enqueue assets
   */
  public function enqueue_assets() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( ! isset( $_GET['page'] ) || 'polanger-login-page' !== sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {
      return;
    }

    wp_enqueue_media();

    wp_enqueue_style(
      'pdt-login-page-style',
      plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/login-page.css',
      array(),
      PDT_VERSION
    );

    wp_enqueue_script(
      'pdt-login-page-script',
      plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/login-page.js',
      array( 'jquery' ),
      PDT_VERSION,
      true
    );
    wp_localize_script(
      'pdt-login-page-script',
      'pdtLoginPageAdminI18n',
      array(
        'selectLogoTitle'        => __( 'Select Logo', 'polanger-admin-menu-manager' ),
        'useLogoButton'          => __( 'Use this logo', 'polanger-admin-menu-manager' ),
        'selectBackgroundTitle'  => __( 'Select Background Image', 'polanger-admin-menu-manager' ),
        'useBackgroundButton'    => __( 'Use this image', 'polanger-admin-menu-manager' ),
        'logoAlt'                => __( 'Logo', 'polanger-admin-menu-manager' ),
        'backgroundAlt'          => __( 'Background', 'polanger-admin-menu-manager' ),
      )
    );
  }

  /**
   * Render settings page
   */
  public function render_settings_page() {
    $settings = $this->get_settings();
    $login_slug = ! empty( $settings['login_slug'] ) ? $settings['login_slug'] : 'my-login';
    $redirect_slug = ! empty( $settings['redirect_slug'] ) ? $settings['redirect_slug'] : '404';
    ?>
    <form method="post" action="options.php" class="pdt-login-page-form">
      <?php settings_fields( 'pdt_login_page_settings_group' ); ?>
      <input type="hidden" name="_wp_http_referer" value="<?php echo esc_attr( admin_url( 'admin.php?page=polanger-login-page' ) ); ?>" />

      <!-- Custom Login URL Section -->
      <div class="pdt-lp-section">
        <h3 class="pdt-lp-section-title">
          <span class="dashicons dashicons-admin-network"></span>
          <?php esc_html_e( 'Custom Login URL', 'polanger-admin-menu-manager' ); ?>
        </h3>
        
        <div class="pdt-lp-card">
          <p class="pdt-lp-card-desc"><?php esc_html_e( 'Protect your website by changing the login URL and preventing access to wp-login.php and wp-admin directory while not logged in.', 'polanger-admin-menu-manager' ); ?></p>
          
          <!-- Enable Custom Login -->
          <div class="pdt-lp-option">
            <label class="pdt-lp-toggle">
              <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[enable_custom_login]" value="1" <?php checked( ! empty( $settings['enable_custom_login'] ) ); ?> id="pdt-enable-custom-login" />
              <span class="pdt-lp-toggle-slider"></span>
            </label>
            <div class="pdt-lp-option-content">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Enable Custom Login URL', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-lp-option-desc"><?php esc_html_e( 'When enabled, wp-login.php and wp-admin will redirect to 404 for non-logged-in users.', 'polanger-admin-menu-manager' ); ?></span>
            </div>
          </div>

          <!-- Login URL Input -->
          <div class="pdt-lp-option pdt-lp-url-input" id="pdt-login-url-section">
            <div class="pdt-lp-option-content pdt-lp-full-width">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Login URL', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-lp-option-desc"><?php esc_html_e( 'Enter the new login URL slug. This will be your new login page address.', 'polanger-admin-menu-manager' ); ?></span>
              
              <div class="pdt-lp-url-wrapper">
                <code><?php echo esc_html( trailingslashit( home_url() ) ); ?></code>
                <input type="text" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[login_slug]" value="<?php echo esc_attr( $login_slug ); ?>" placeholder="<?php esc_attr_e( 'my-login', 'polanger-admin-menu-manager' ); ?>" class="pdt-lp-slug-input" />
                <?php if ( $this->use_trailing_slashes() ) : ?>
                  <code>/</code>
                <?php endif; ?>
              </div>
              
              <?php if ( ! empty( $settings['enable_custom_login'] ) ) : ?>
                <p class="pdt-lp-current-url">
                  <strong><?php esc_html_e( 'Your current login URL:', 'polanger-admin-menu-manager' ); ?></strong>
                  <a href="<?php echo esc_url( $this->new_login_url() ); ?>" target="_blank"><?php echo esc_html( $this->new_login_url() ); ?></a>
                  <span class="pdt-lp-bookmark-hint"><?php esc_html_e( '← Bookmark this!', 'polanger-admin-menu-manager' ); ?></span>
                </p>
              <?php endif; ?>
            </div>
          </div>

          <!-- Redirect URL Input -->
          <div class="pdt-lp-option pdt-lp-url-input" id="pdt-redirect-url-section">
            <div class="pdt-lp-option-content pdt-lp-full-width">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Redirect URL', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-lp-option-desc"><?php esc_html_e( 'Where to redirect users who try to access wp-login.php or wp-admin directly. Use "404" to show a 404 page.', 'polanger-admin-menu-manager' ); ?></span>
              
              <div class="pdt-lp-url-wrapper">
                <code><?php echo esc_html( trailingslashit( home_url() ) ); ?></code>
                <input type="text" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[redirect_slug]" value="<?php echo esc_attr( $redirect_slug ); ?>" placeholder="<?php esc_attr_e( '404', 'polanger-admin-menu-manager' ); ?>" class="pdt-lp-slug-input" />
                <?php if ( $this->use_trailing_slashes() ) : ?>
                  <code>/</code>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Warning Notice -->
      <?php if ( ! empty( $settings['enable_custom_login'] ) ) : ?>
      <div class="pdt-lp-warning">
        <span class="dashicons dashicons-warning"></span>
        <div>
          <strong><?php esc_html_e( 'Important!', 'polanger-admin-menu-manager' ); ?></strong>
          <p><?php esc_html_e( 'Make sure to bookmark your new login URL before saving. If you forget your custom login URL, you will need to disable this plugin via FTP or phpMyAdmin.', 'polanger-admin-menu-manager' ); ?></p>
        </div>
      </div>
      <?php endif; ?>

      <!-- Login Page Customization Section -->
      <div class="pdt-lp-section">
        <h3 class="pdt-lp-section-title">
          <span class="dashicons dashicons-art"></span>
          <?php esc_html_e( 'Login Page Design', 'polanger-admin-menu-manager' ); ?>
        </h3>
        
        <div class="pdt-lp-card">
          <p class="pdt-lp-card-desc"><?php esc_html_e( 'Customize the appearance of your login page with custom logo, colors, and background.', 'polanger-admin-menu-manager' ); ?></p>
          
          <!-- Enable Login Customization -->
          <div class="pdt-lp-option">
            <label class="pdt-lp-toggle">
              <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[enable_login_customization]" value="1" <?php checked( ! empty( $settings['enable_login_customization'] ) ); ?> />
              <span class="pdt-lp-toggle-slider"></span>
            </label>
            <div class="pdt-lp-option-content">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Enable Login Page Customization', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-lp-option-desc"><?php esc_html_e( 'Apply custom styling to your WordPress login page.', 'polanger-admin-menu-manager' ); ?></span>
            </div>
          </div>

          <!-- Custom Logo -->
          <div class="pdt-lp-option pdt-lp-url-input">
            <div class="pdt-lp-option-content pdt-lp-full-width">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Custom Logo', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-lp-option-desc"><?php esc_html_e( 'Upload a custom logo to replace the WordPress logo on the login page.', 'polanger-admin-menu-manager' ); ?></span>
              
              <div class="pdt-lp-logo-upload">
                <div class="pdt-lp-logo-preview" id="pdt-login-logo-preview">
                  <?php if ( ! empty( $settings['custom_logo_url'] ) ) : ?>
                    <img src="<?php echo esc_url( $settings['custom_logo_url'] ); ?>" alt="<?php echo esc_attr__( 'Custom Logo', 'polanger-admin-menu-manager' ); ?>" />
                  <?php else : ?>
                    <span class="dashicons dashicons-format-image"></span>
                  <?php endif; ?>
                </div>
                <div class="pdt-lp-logo-actions">
                  <button type="button" class="button pdt-lp-upload-btn" id="pdt-upload-login-logo">
                    <span class="dashicons dashicons-upload"></span>
                    <?php esc_html_e( 'Upload Logo', 'polanger-admin-menu-manager' ); ?>
                  </button>
                  <button type="button" class="button pdt-lp-remove-btn<?php echo empty( $settings['custom_logo_url'] ) ? ' pdt-lp-hidden' : ''; ?>" id="pdt-remove-login-logo">
                    <span class="dashicons dashicons-trash"></span>
                    <?php esc_html_e( 'Remove', 'polanger-admin-menu-manager' ); ?>
                  </button>
                </div>
                <input type="hidden" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_logo_url]" id="pdt-login-logo-url" value="<?php echo esc_attr( $settings['custom_logo_url'] ?? '' ); ?>" />
              </div>
              
              <div class="pdt-lp-url-wrapper pdt-lp-url-wrapper-lg">
                <span class="pdt-lp-option-label pdt-lp-option-label-spaced"><?php esc_html_e( 'Logo Link URL', 'polanger-admin-menu-manager' ); ?></span>
                <input type="url" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[logo_link_url]" value="<?php echo esc_attr( $settings['logo_link_url'] ?? home_url() ); ?>" placeholder="<?php echo esc_attr( home_url() ); ?>" class="pdt-lp-slug-input pdt-lp-slug-input-full" />
              </div>
            </div>
          </div>

          <!-- Background Type -->
          <div class="pdt-lp-option pdt-lp-url-input">
            <div class="pdt-lp-option-content pdt-lp-full-width">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Background Type', 'polanger-admin-menu-manager' ); ?></span>
              <div class="pdt-lp-radio-group">
                <label class="pdt-lp-radio">
                  <input type="radio" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[bg_type]" value="color" <?php checked( ( $settings['bg_type'] ?? 'color' ), 'color' ); ?> />
                  <span><?php esc_html_e( 'Solid Color', 'polanger-admin-menu-manager' ); ?></span>
                </label>
                <label class="pdt-lp-radio">
                  <input type="radio" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[bg_type]" value="gradient" <?php checked( ( $settings['bg_type'] ?? 'color' ), 'gradient' ); ?> />
                  <span><?php esc_html_e( 'Gradient', 'polanger-admin-menu-manager' ); ?></span>
                </label>
                <label class="pdt-lp-radio">
                  <input type="radio" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[bg_type]" value="image" <?php checked( ( $settings['bg_type'] ?? 'color' ), 'image' ); ?> />
                  <span><?php esc_html_e( 'Image', 'polanger-admin-menu-manager' ); ?></span>
                </label>
              </div>
            </div>
          </div>

          <!-- Background Color -->
          <div class="pdt-lp-option pdt-lp-color-option" id="pdt-bg-color-section">
            <div class="pdt-lp-option-content">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Background Color', 'polanger-admin-menu-manager' ); ?></span>
              <input type="color" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[bg_color]" value="<?php echo esc_attr( $settings['bg_color'] ?? '#0f172a' ); ?>" class="pdt-lp-color-input" />
            </div>
          </div>

          <!-- Gradient Colors -->
          <div class="pdt-lp-option pdt-lp-color-option<?php echo ( 'gradient' === ( $settings['bg_type'] ?? 'color' ) ) ? '' : ' pdt-lp-hidden'; ?>" id="pdt-bg-gradient-section">
            <div class="pdt-lp-option-content">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Gradient Start', 'polanger-admin-menu-manager' ); ?></span>
              <input type="color" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[bg_gradient_start]" value="<?php echo esc_attr( $settings['bg_gradient_start'] ?? '#6366f1' ); ?>" class="pdt-lp-color-input" />
            </div>
            <div class="pdt-lp-option-content">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Gradient End', 'polanger-admin-menu-manager' ); ?></span>
              <input type="color" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[bg_gradient_end]" value="<?php echo esc_attr( $settings['bg_gradient_end'] ?? '#8b5cf6' ); ?>" class="pdt-lp-color-input" />
            </div>
          </div>

          <!-- Background Image -->
          <div class="pdt-lp-option pdt-lp-url-input<?php echo ( 'image' === ( $settings['bg_type'] ?? 'color' ) ) ? '' : ' pdt-lp-hidden'; ?>" id="pdt-bg-image-section">
            <div class="pdt-lp-option-content pdt-lp-full-width">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Background Image', 'polanger-admin-menu-manager' ); ?></span>
              <div class="pdt-lp-logo-upload">
                <div class="pdt-lp-logo-preview pdt-lp-bg-preview" id="pdt-login-bg-preview">
                  <?php if ( ! empty( $settings['bg_image_url'] ) ) : ?>
                    <img src="<?php echo esc_url( $settings['bg_image_url'] ); ?>" alt="<?php echo esc_attr__( 'Background', 'polanger-admin-menu-manager' ); ?>" />
                  <?php else : ?>
                    <span class="dashicons dashicons-format-image"></span>
                  <?php endif; ?>
                </div>
                <div class="pdt-lp-logo-actions">
                  <button type="button" class="button pdt-lp-upload-btn" id="pdt-upload-login-bg">
                    <span class="dashicons dashicons-upload"></span>
                    <?php esc_html_e( 'Upload Image', 'polanger-admin-menu-manager' ); ?>
                  </button>
                  <button type="button" class="button pdt-lp-remove-btn<?php echo empty( $settings['bg_image_url'] ) ? ' pdt-lp-hidden' : ''; ?>" id="pdt-remove-login-bg">
                    <span class="dashicons dashicons-trash"></span>
                    <?php esc_html_e( 'Remove', 'polanger-admin-menu-manager' ); ?>
                  </button>
                </div>
                <input type="hidden" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[bg_image_url]" id="pdt-login-bg-url" value="<?php echo esc_attr( $settings['bg_image_url'] ?? '' ); ?>" />
              </div>
            </div>
          </div>

          <!-- Primary Color -->
          <div class="pdt-lp-option pdt-lp-color-option">
            <div class="pdt-lp-option-content">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Primary Color (Buttons)', 'polanger-admin-menu-manager' ); ?></span>
              <input type="color" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[primary_color]" value="<?php echo esc_attr( $settings['primary_color'] ?? '#6366f1' ); ?>" class="pdt-lp-color-input" />
            </div>
          </div>

          <!-- Form Background Color -->
          <div class="pdt-lp-option pdt-lp-color-option">
            <div class="pdt-lp-option-content">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Form Background Color', 'polanger-admin-menu-manager' ); ?></span>
              <input type="color" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[form_bg_color]" value="<?php echo esc_attr( $settings['form_bg_color'] ?? '#ffffff' ); ?>" class="pdt-lp-color-input" />
            </div>
          </div>

          <!-- Hide Language Switcher -->
          <div class="pdt-lp-option">
            <label class="pdt-lp-toggle">
              <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_language_switcher]" value="1" <?php checked( ! empty( $settings['hide_language_switcher'] ) ); ?> />
              <span class="pdt-lp-toggle-slider"></span>
            </label>
            <div class="pdt-lp-option-content">
              <span class="pdt-lp-option-label"><?php esc_html_e( 'Hide Language Switcher', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-lp-option-desc"><?php esc_html_e( 'Completely hide the language selector on the login screen for both desktop and mobile.', 'polanger-admin-menu-manager' ); ?></span>
            </div>
          </div>
        </div>
      </div>

      <!-- reCAPTCHA Section -->
      <div class="pdt-lp-section">
        <h3 class="pdt-lp-section-title">
          <span class="dashicons dashicons-shield"></span>
          <?php esc_html_e( 'reCAPTCHA Protection', 'polanger-admin-menu-manager' ); ?>
        </h3>
        
        <div class="pdt-lp-card">
          <?php
          // Check reCAPTCHA addon status
          $recaptcha_addon_active = class_exists( 'PDT_Recaptcha' );
          $recaptcha_configured = false;
          $recaptcha_login_enabled = false;
          
          if ( $recaptcha_addon_active && class_exists( 'PDT_Recaptcha_Settings' ) ) {
            $recaptcha_settings_obj = new PDT_Recaptcha_Settings();
            $recaptcha_addon_settings = $recaptcha_settings_obj->get_settings();
            $recaptcha_configured = ! empty( $recaptcha_addon_settings['site_key'] ) && ! empty( $recaptcha_addon_settings['secret_key'] );
            $recaptcha_login_enabled = ! empty( $recaptcha_addon_settings['login'] );
          }
          
          $settings_url = admin_url( 'admin.php?page=polanger-settings&tab=recaptcha' );
          $addons_url = admin_url( 'admin.php?page=polanger-settings&tab=addons' );
          ?>
          
          <?php if ( $recaptcha_addon_active && $recaptcha_configured && $recaptcha_login_enabled ) : ?>
            <!-- reCAPTCHA Active and Working -->
            <div class="pdt-lp-recaptcha-status pdt-lp-recaptcha-success">
              <span class="dashicons dashicons-yes-alt"></span>
              <div>
                <strong><?php esc_html_e( 'reCAPTCHA Active', 'polanger-admin-menu-manager' ); ?></strong>
                <p><?php esc_html_e( 'reCAPTCHA protection is enabled and working on your login form. All reCAPTCHA settings are now managed from the dedicated reCAPTCHA addon.', 'polanger-admin-menu-manager' ); ?></p>
                <a href="<?php echo esc_url( $settings_url ); ?>" class="button button-secondary pdt-lp-status-action">
                  <span class="dashicons dashicons-admin-generic"></span>
                  <?php esc_html_e( 'Manage reCAPTCHA Settings', 'polanger-admin-menu-manager' ); ?>
                </a>
              </div>
            </div>
          <?php elseif ( $recaptcha_addon_active && $recaptcha_configured && ! $recaptcha_login_enabled ) : ?>
            <!-- reCAPTCHA Configured but Login not enabled -->
            <div class="pdt-lp-recaptcha-status pdt-lp-recaptcha-warning">
              <span class="dashicons dashicons-warning"></span>
              <div>
                <strong><?php esc_html_e( 'Login Protection Not Enabled', 'polanger-admin-menu-manager' ); ?></strong>
                <p><?php esc_html_e( 'reCAPTCHA addon is configured but login form protection is not enabled. Enable "Login Form" in the reCAPTCHA settings to protect your login page.', 'polanger-admin-menu-manager' ); ?></p>
                <a href="<?php echo esc_url( $settings_url ); ?>" class="button button-primary pdt-lp-status-action">
                  <span class="dashicons dashicons-shield"></span>
                  <?php esc_html_e( 'Enable Login Protection', 'polanger-admin-menu-manager' ); ?>
                </a>
              </div>
            </div>
          <?php elseif ( $recaptcha_addon_active && ! $recaptcha_configured ) : ?>
            <!-- reCAPTCHA Addon active but not configured -->
            <div class="pdt-lp-recaptcha-status pdt-lp-recaptcha-warning">
              <span class="dashicons dashicons-warning"></span>
              <div>
                <strong><?php esc_html_e( 'reCAPTCHA Not Configured', 'polanger-admin-menu-manager' ); ?></strong>
                <p><?php esc_html_e( 'The reCAPTCHA addon is active but API keys are not configured. Add your Google reCAPTCHA site key and secret key to enable protection.', 'polanger-admin-menu-manager' ); ?></p>
                <a href="<?php echo esc_url( $settings_url ); ?>" class="button button-primary pdt-lp-status-action">
                  <span class="dashicons dashicons-admin-network"></span>
                  <?php esc_html_e( 'Configure reCAPTCHA', 'polanger-admin-menu-manager' ); ?>
                </a>
              </div>
            </div>
          <?php else : ?>
            <!-- reCAPTCHA Addon not active -->
            <div class="pdt-lp-recaptcha-status pdt-lp-recaptcha-info">
              <span class="dashicons dashicons-info"></span>
              <div>
                <strong><?php esc_html_e( 'reCAPTCHA Addon Available', 'polanger-admin-menu-manager' ); ?></strong>
                <p><?php esc_html_e( 'Protect your login, registration, and password reset forms with Google reCAPTCHA. Activate the reCAPTCHA addon to enable this feature.', 'polanger-admin-menu-manager' ); ?></p>
                <p class="pdt-lp-status-note">
                  <?php esc_html_e( 'The reCAPTCHA addon provides centralized key management for all forms including login, registration, lost password, and comments.', 'polanger-admin-menu-manager' ); ?>
                </p>
                <a href="<?php echo esc_url( $addons_url ); ?>" class="button button-primary pdt-lp-status-action">
                  <span class="dashicons dashicons-admin-plugins"></span>
                  <?php esc_html_e( 'Go to Addons', 'polanger-admin-menu-manager' ); ?>
                </a>
              </div>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <div class="pdt-lp-submit">
        <?php submit_button( __( 'Save Changes', 'polanger-admin-menu-manager' ), 'primary', 'submit', false ); ?>
      </div>
    </form>
    <?php
  }

  /**
   * Enqueue login page styles
   */
  public function enqueue_login_styles() {
    $settings = $this->get_settings();
    $recaptcha_enabled = ! empty( $settings['enable_recaptcha'] ) && ! empty( $settings['recaptcha_site_key'] );
    $recaptcha_version = $settings['recaptcha_version'] ?? 'v2';
    $login_customization_enabled = ! empty( $settings['enable_login_customization'] );
    $should_customize_login_screen = $login_customization_enabled && $this->should_customize_login_screen();

    // Check if there's anything to load
    if ( ! $should_customize_login_screen && ! $recaptcha_enabled ) {
      return;
    }

    if ( $should_customize_login_screen ) {
      wp_enqueue_script(
        'pdt-login-bootstrap',
        plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/login-bootstrap.js',
        array(),
        PDT_VERSION,
        false
      );

      wp_enqueue_style(
        'pdt-login-frontend-style',
        plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/login-frontend.css',
        array(),
        PDT_VERSION
      );

      wp_enqueue_script(
        'pdt-login-runtime',
        plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/login-runtime.js',
        array(),
        PDT_VERSION,
        false
      );

      $site_title = get_bloginfo( 'name' );
      $tagline = get_bloginfo( 'description' );
      $custom_logo_url = $settings['custom_logo_url'] ?? '';
      $logo_link_url = ! empty( $settings['logo_link_url'] ) ? $settings['logo_link_url'] : home_url();
      $logo_html = '';

      if ( ! empty( $custom_logo_url ) ) {
        $logo_html = sprintf(
          '<a href="%1$s" class="pdt-login-logo"><img src="%2$s" alt="%3$s"></a>',
          esc_url( $logo_link_url ),
          esc_url( $custom_logo_url ),
          esc_attr( $site_title )
        );
      }

      wp_localize_script(
        'pdt-login-runtime',
        'pdtLoginPageConfig',
        array(
          'bgType'             => $settings['bg_type'] ?? 'color',
          'bgColor'            => $settings['bg_color'] ?? '#0f172a',
          'bgGradientStart'    => $settings['bg_gradient_start'] ?? '#6366f1',
          'bgGradientEnd'      => $settings['bg_gradient_end'] ?? '#8b5cf6',
          'bgImageUrl'         => $settings['bg_image_url'] ?? '',
          'primaryColor'       => $settings['primary_color'] ?? '#6366f1',
          'primaryHoverColor'  => $this->adjust_brightness( $settings['primary_color'] ?? '#6366f1', -20 ),
          'leftGradientEnd'    => $this->adjust_brightness( $settings['primary_color'] ?? '#6366f1', 30 ),
          'cardBackground'     => $this->hex_to_rgba( $settings['form_bg_color'] ?? '#ffffff', 0.95 ),
          'customLogoUrl'      => $custom_logo_url,
          'logoHtml'           => $logo_html,
          'enableSplitLayout'  => true,
          'siteTitle'          => $site_title,
          'tagline'            => $tagline,
          'hideLanguageSwitcher' => ! empty( $settings['hide_language_switcher'] ),
          'strings'            => array(
            'signIn'         => __( 'Sign In', 'polanger-admin-menu-manager' ),
            'register'       => __( 'Create Account', 'polanger-admin-menu-manager' ),
            'lostPassword'   => __( 'Reset Password', 'polanger-admin-menu-manager' ),
            'resetPassword'  => __( 'Set New Password', 'polanger-admin-menu-manager' ),
            'usernameOrEmail'=> __( 'Username or Email Address', 'polanger-admin-menu-manager' ),
            'password'       => __( 'Password', 'polanger-admin-menu-manager' ),
            'emailAddress'   => __( 'Email Address', 'polanger-admin-menu-manager' ),
            'languageFab'    => __( 'Choose site language', 'polanger-admin-menu-manager' ),
            'languageTitle'  => __( 'Site language', 'polanger-admin-menu-manager' ),
            'close'          => __( 'Close', 'polanger-admin-menu-manager' ),
          ),
        )
      );
    }

    if ( $recaptcha_enabled && ! $should_customize_login_screen ) {
      wp_enqueue_style(
        'pdt-login-recaptcha-style',
        plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/login-recaptcha.css',
        array(),
        PDT_VERSION
      );
    }

    // Enqueue reCAPTCHA if enabled (works for both v2 and v3)
    if ( $recaptcha_enabled ) {
      $recaptcha_url = 'https://www.google.com/recaptcha/api.js';
      if ( 'v3' === $recaptcha_version ) {
        $recaptcha_url .= '?render=' . esc_attr( $settings['recaptcha_site_key'] );
      }
      wp_enqueue_script( 'google-recaptcha', $recaptcha_url, array(), null, true );
    }
  }

  /**
   * Custom login logo URL
   */
  public function custom_login_logo_url() {
    $settings = $this->get_settings();
    
    if ( empty( $settings['enable_login_customization'] ) ) {
      return 'https://wordpress.org/';
    }

    return ! empty( $settings['logo_link_url'] ) ? $settings['logo_link_url'] : home_url();
  }

  /**
   * Custom login logo title
   */
  public function custom_login_logo_title() {
    return get_bloginfo( 'name' );
  }

  /**
   * Hide the login screen language switcher when the admin has opted in.
   *
   * Hooked into `login_display_language_dropdown` (WP 5.9+). Returning false
   * prevents WordPress from rendering the `.language-switcher` markup at all,
   * so the front-end FAB / drawer JS also has nothing to wire up.
   *
   * @param bool $display Whether to display the language dropdown.
   * @return bool
   */
  public function maybe_hide_language_dropdown( $display ) {
    $settings = $this->get_settings();

    if ( ! empty( $settings['hide_language_switcher'] ) ) {
      return false;
    }

    return $display;
  }

  /**
   * Keep the login language selector local-only so WordPress does not call
   * the remote translations API on servers without outbound HTTPS access.
   *
   * WordPress passes `show_available_translations => false` on the login
   * screen, but `wp_dropdown_languages()` still fetches the full translation
   * index when no `translations` array is provided. Supplying installed
   * language metadata here avoids the remote lookup entirely.
   *
   * @param array $args Dropdown arguments from wp-login.php.
   * @return array
   */
  public function filter_login_language_dropdown_args( $args ) {
    if ( ! is_array( $args ) ) {
      return array();
    }

    $languages = array();

    if ( ! empty( $args['languages'] ) && is_array( $args['languages'] ) ) {
      $languages = array_values( array_filter( $args['languages'], 'is_string' ) );
    } else {
      $languages = get_available_languages();
    }

    $args['languages']                   = $languages;
    $args['translations']                = $this->get_installed_login_translations( $languages );
    $args['show_available_translations'] = false;

    return $args;
  }

  /**
   * Build a local translation map for installed login languages.
   *
   * @param array<int,string> $languages Installed locales from WordPress.
   * @return array<string,array<string,mixed>>
   */
  private function get_installed_login_translations( $languages ) {
    $translations = array();

    foreach ( $languages as $locale ) {
      $normalized_locale = is_string( $locale ) ? sanitize_locale_name( $locale ) : '';

      if ( '' === $normalized_locale ) {
        continue;
      }

      $translations[ $normalized_locale ] = array(
        'language'    => $normalized_locale,
        'native_name' => $this->get_locale_display_name( $normalized_locale ),
        'iso'         => array( strtolower( substr( $normalized_locale, 0, 2 ) ) ),
      );
    }

    return $translations;
  }

  /**
   * Convert a locale code into a human-readable label without remote requests.
   *
   * @param string $locale Locale code like tr_TR.
   * @return string
   */
  private function get_locale_display_name( $locale ) {
    $locale_tag  = str_replace( '_', '-', $locale );

    if ( class_exists( 'Locale' ) && method_exists( 'Locale', 'getDisplayName' ) ) {
      $display_name = \Locale::getDisplayName( $locale_tag, $locale_tag );

      if ( is_string( $display_name ) && '' !== trim( $display_name ) ) {
        return $display_name;
      }
    }

    $parts         = explode( '_', $locale );
    $language_code = strtolower( $parts[0] ?? '' );
    $region_code   = strtoupper( $parts[1] ?? '' );

    $language_names = array(
      'ar' => 'العربية',
      'de' => 'Deutsch',
      'en' => 'English',
      'es' => 'Español',
      'fa' => 'فارسی',
      'fr' => 'Français',
      'it' => 'Italiano',
      'nl' => 'Nederlands',
      'pl' => 'Polski',
      'pt' => 'Português',
      'ru' => 'Русский',
      'tr' => 'Türkçe',
      'uk' => 'Українська',
      'zh' => '中文',
    );

    $region_names = array(
      'BR' => 'Brasil',
      'CN' => '中国',
      'DE' => 'Deutschland',
      'ES' => 'España',
      'FR' => 'France',
      'GB' => 'United Kingdom',
      'IT' => 'Italia',
      'MX' => 'México',
      'NL' => 'Nederland',
      'PL' => 'Polska',
      'PT' => 'Portugal',
      'RU' => 'Россия',
      'TR' => 'Türkiye',
      'UA' => 'Україна',
      'US' => 'United States',
    );

    if ( isset( $language_names[ $language_code ] ) ) {
      if ( $region_code && isset( $region_names[ $region_code ] ) ) {
        return $language_names[ $language_code ] . ' (' . $region_names[ $region_code ] . ')';
      }

      return $language_names[ $language_code ];
    }

    return str_replace( '_', ' ', $locale );
  }

  /**
   * Add reCAPTCHA to login form
   */
  public function add_recaptcha_to_login() {
    $this->render_recaptcha( 'login' );
  }

  /**
   * Add reCAPTCHA to registration form
   */
  public function add_recaptcha_to_register() {
    $this->render_recaptcha( 'register' );
  }

  /**
   * Add reCAPTCHA to lost password form
   */
  public function add_recaptcha_to_lostpassword() {
    $this->render_recaptcha( 'lostpassword' );
  }

  /**
   * Render reCAPTCHA
   */
  private function render_recaptcha( $form_type ) {
    $settings = $this->get_settings();
    
    if ( empty( $settings['enable_recaptcha'] ) || empty( $settings['recaptcha_site_key'] ) ) {
      return;
    }

    $location_key = 'recaptcha_' . $form_type;
    if ( empty( $settings[ $location_key ] ) ) {
      return;
    }

    $version = $settings['recaptcha_version'] ?? 'v2';
    $site_key = $settings['recaptcha_site_key'];

    if ( $version === 'v2' ) {
      echo '<div class="pdt-recaptcha-wrap">';
      echo '<div class="g-recaptcha" data-sitekey="' . esc_attr( $site_key ) . '"></div>';
      echo '</div>';
    } else {
      echo '<input type="hidden" class="pdt-recaptcha-v3-token" name="g-recaptcha-response" id="g-recaptcha-response-' . esc_attr( $form_type ) . '" data-action="' . esc_attr( $form_type ) . '" data-site-key="' . esc_attr( $site_key ) . '" />';
    }
  }

  /**
   * Verify reCAPTCHA on login
   */
  public function verify_recaptcha_login( $user, $password ) {
    if ( ! $this->should_verify_recaptcha( 'login' ) ) {
      return $user;
    }

    if ( ! $this->verify_recaptcha_response( 'login' ) ) {
      return new WP_Error( 'recaptcha_failed', __( 'reCAPTCHA verification failed. Please try again.', 'polanger-admin-menu-manager' ) );
    }

    return $user;
  }

  /**
   * Verify reCAPTCHA on registration
   */
  public function verify_recaptcha_register( $errors, $sanitized_user_login, $user_email ) {
    if ( ! $this->should_verify_recaptcha( 'register' ) ) {
      return $errors;
    }

    if ( ! $this->verify_recaptcha_response( 'register' ) ) {
      $errors->add( 'recaptcha_failed', __( 'reCAPTCHA verification failed. Please try again.', 'polanger-admin-menu-manager' ) );
    }

    return $errors;
  }

  /**
   * Verify reCAPTCHA on lost password
   */
  public function verify_recaptcha_lostpassword( $errors ) {
    if ( ! $this->should_verify_recaptcha( 'lostpassword' ) ) {
      return;
    }

    if ( ! $this->verify_recaptcha_response( 'lostpassword' ) ) {
      wp_die(
        esc_html__( 'reCAPTCHA verification failed. Please try again.', 'polanger-admin-menu-manager' ),
        esc_html__( 'reCAPTCHA Error', 'polanger-admin-menu-manager' ),
        array( 'back_link' => true )
      );
    }
  }

  /**
   * Check if should verify reCAPTCHA
   */
  private function should_verify_recaptcha( $form_type ) {
    $settings = $this->get_settings();
    
    if ( empty( $settings['enable_recaptcha'] ) || empty( $settings['recaptcha_secret_key'] ) ) {
      return false;
    }

    $location_key = 'recaptcha_' . $form_type;
    return ! empty( $settings[ $location_key ] );
  }

  /**
   * Verify reCAPTCHA response
   */
  private function verify_recaptcha_response( $form_type = '' ) {
    $settings = $this->get_settings();
    $secret_key = $settings['recaptcha_secret_key'] ?? '';
    
    // phpcs:ignore WordPress.Security.NonceVerification.Missing
    $recaptcha_response = isset( $_POST['g-recaptcha-response'] ) ? sanitize_text_field( wp_unslash( $_POST['g-recaptcha-response'] ) ) : '';
    
    if ( empty( $recaptcha_response ) ) {
      return false;
    }

    $response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', array(
      'timeout' => 10,
      'body' => array(
        'secret'   => $secret_key,
        'response' => $recaptcha_response,
        'remoteip' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
      ),
    ) );

    if ( is_wp_error( $response ) ) {
      return false;
    }

    $body = json_decode( wp_remote_retrieve_body( $response ), true );

    if ( ! isset( $body['success'] ) || ! $body['success'] ) {
      return false;
    }

    // For v3, check score
    $version = $settings['recaptcha_version'] ?? 'v2';
    if ( $version === 'v3' && isset( $body['score'] ) && $body['score'] < 0.5 ) {
      return false;
    }

    // For v3, also verify returned action matches the requested form action.
    if ( $version === 'v3' && ! empty( $form_type ) && isset( $body['action'] ) && $body['action'] !== $form_type ) {
      return false;
    }

    // Validate hostname when available.
    if ( isset( $body['hostname'] ) ) {
      $expected_host = wp_parse_url( home_url(), PHP_URL_HOST );
      $response_host = sanitize_text_field( $body['hostname'] );

      if ( ! empty( $expected_host ) ) {
        $normalize_host = static function( $host ) {
          $host = strtolower( trim( (string) $host ) );
          return preg_replace( '/^www\./', '', $host );
        };

        if ( $normalize_host( $expected_host ) !== $normalize_host( $response_host ) ) {
          return false;
        }
      }
    }

    return true;
  }

  /**
   * Adjust color brightness
   */
  private function adjust_brightness( $hex, $steps ) {
    $hex = str_replace( '#', '', $hex );
    
    $r = hexdec( substr( $hex, 0, 2 ) );
    $g = hexdec( substr( $hex, 2, 2 ) );
    $b = hexdec( substr( $hex, 4, 2 ) );
    
    $r = max( 0, min( 255, $r + $steps ) );
    $g = max( 0, min( 255, $g + $steps ) );
    $b = max( 0, min( 255, $b + $steps ) );
    
    return '#' . sprintf( '%02x%02x%02x', $r, $g, $b );
  }

  /**
   * Convert hex to rgba
   */
  private function hex_to_rgba( $hex, $alpha = 1 ) {
    $hex = str_replace( '#', '', $hex );
    
    $r = hexdec( substr( $hex, 0, 2 ) );
    $g = hexdec( substr( $hex, 2, 2 ) );
    $b = hexdec( substr( $hex, 4, 2 ) );
    
    return "rgba($r, $g, $b, $alpha)";
  }

  /**
   * Convert hex color to comma-separated RGB components.
   *
   * @param string $hex Hex color string.
   * @return string
   */
  private function hex_to_rgb_components( $hex ) {
    $hex = str_replace( '#', '', $hex );

    $r = hexdec( substr( $hex, 0, 2 ) );
    $g = hexdec( substr( $hex, 2, 2 ) );
    $b = hexdec( substr( $hex, 4, 2 ) );

    return $r . ', ' . $g . ', ' . $b;
  }
}
