<?php
/**
 * Admin Bar Manager Module
 *
 * @package Polanger_Dashboard_Tools_Pro
 * @since 3.1.0
 */

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

/**
 * Admin Bar Manager Class
 */
class PDT_Admin_Bar {

  /**
   * Option name for admin bar settings
   */
  const OPTION_NAME = 'pdt_admin_bar_settings';

  /**
   * Constructor
   */
  public function __construct() {
    add_action( 'admin_init', array( $this, 'register_settings' ) );
    add_action( 'admin_init', array( $this, 'handle_cache_clear' ) );
    
    // Capture nodes at multiple points to catch all items (including late additions like Elementor)
    add_action( 'admin_bar_menu', array( $this, 'capture_admin_bar_nodes' ), 999999 );
    add_action( 'wp_before_admin_bar_render', array( $this, 'capture_admin_bar_nodes_final' ), 999999 );
    
    // Apply customizations
    add_action( 'wp_before_admin_bar_render', array( $this, 'customize_admin_bar' ), 1000 );
    add_action( 'wp_before_admin_bar_render', array( $this, 'add_custom_links_to_admin_bar' ), 1001 );
    add_action( 'wp_before_admin_bar_render', array( $this, 'apply_admin_bar_item_modifications' ), 1002 );
    add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
    add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_runtime_styles' ) );
    add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_styles' ) );
    add_filter( 'admin_body_class', array( $this, 'filter_admin_body_class' ) );
  }

  /**
   * Handle cache clear request
   */
  public function handle_cache_clear() {
    if ( ! isset( $_GET['clear_frontend_cache'] ) || ! isset( $_GET['_wpnonce'] ) ) {
      return;
    }
    
    if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'pdt_clear_frontend_cache' ) ) {
      return;
    }
    
    if ( ! current_user_can( 'manage_options' ) ) {
      return;
    }
    
    // Clear frontend transient
    delete_transient( 'pdt_admin_bar_nodes_frontend' );
    
    // Redirect back without the query args
    wp_safe_redirect( admin_url( 'admin.php?page=polanger-admin-bar&cache_cleared=1' ) );
    exit;
  }

  /**
   * Register settings
   */
  public function register_settings() {
    register_setting(
      'pdt_admin_bar_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;
    }

    // WP Logo settings
    $sanitized['hide_wp_logo'] = ( isset( $input['hide_wp_logo'] ) && $input['hide_wp_logo'] === '1' ) ? '1' : '';
    
    // Custom logo URL
    $sanitized['custom_logo_url'] = isset( $input['custom_logo_url'] ) ? esc_url_raw( $input['custom_logo_url'] ) : '';
    
    // Custom logo link
    $sanitized['custom_logo_link'] = isset( $input['custom_logo_link'] ) ? esc_url_raw( $input['custom_logo_link'] ) : '';

    // Submenu items to hide
    $submenu_items = array(
      'hide_about_wordpress',
      'hide_get_involved',
      'hide_wordpress_org',
      'hide_documentation',
      'hide_learn_wordpress',
      'hide_support',
      'hide_feedback',
      'hide_help_tab',
      'hide_screen_options'
    );

    foreach ( $submenu_items as $item ) {
      $sanitized[ $item ] = ( isset( $input[ $item ] ) && $input[ $item ] === '1' ) ? '1' : '';
    }

    // Custom Links
    $sanitized['links'] = array();
    if ( ! empty( $input['links'] ) && is_array( $input['links'] ) ) {
      foreach ( $input['links'] as $index => $link ) {
        if ( empty( $link['title'] ) || empty( $link['url'] ) ) {
          continue;
        }

        $sanitized_link = array(
          'title'  => sanitize_text_field( $link['title'] ),
          'url'    => esc_url_raw( $link['url'] ),
          'icon'   => sanitize_text_field( $link['icon'] ?? 'dashicons-admin-links' ),
          'target' => isset( $link['target'] ) && $link['target'] === '_blank' ? '_blank' : '_self',
        );

        // Handle submenus
        if ( ! empty( $link['submenu'] ) && is_array( $link['submenu'] ) ) {
          $sanitized_link['submenu'] = array();
          foreach ( $link['submenu'] as $sublink ) {
            if ( empty( $sublink['title'] ) || empty( $sublink['url'] ) ) {
              continue;
            }
            $sanitized_link['submenu'][] = array(
              'title'  => sanitize_text_field( $sublink['title'] ),
              'url'    => esc_url_raw( $sublink['url'] ),
              'icon'   => sanitize_text_field( $sublink['icon'] ?? '' ),
              'target' => isset( $sublink['target'] ) && $sublink['target'] === '_blank' ? '_blank' : '_self',
            );
          }
        }

        $sanitized['links'][] = $sanitized_link;
      }
    }

    // Hidden admin bar items
    if ( ! empty( $input['hidden_items'] ) && is_array( $input['hidden_items'] ) ) {
      $sanitized['hidden_items'] = array_map( 'sanitize_text_field', $input['hidden_items'] );
    } else {
      $sanitized['hidden_items'] = array();
    }

    // Renamed admin bar items
    $sanitized['renamed_items'] = array();
    if ( ! empty( $input['renamed_items'] ) && is_array( $input['renamed_items'] ) ) {
      foreach ( $input['renamed_items'] as $node_id => $new_title ) {
        if ( ! empty( $new_title ) ) {
          $sanitized['renamed_items'][ sanitize_text_field( $node_id ) ] = sanitize_text_field( $new_title );
        }
      }
    }

    return $sanitized;
  }

  /**
   * Get settings
   */
  public function get_settings() {
    $settings = get_option( self::OPTION_NAME, array() );
    $settings = is_array( $settings ) ? $settings : array();

    return apply_filters( 'polanger_effective_settings', $settings, self::OPTION_NAME, array(), 'admin-bar' );
  }

  /**
   * Customize admin bar
   */
  public function customize_admin_bar() {
    global $wp_admin_bar;
    
    if ( ! is_object( $wp_admin_bar ) ) {
      return;
    }
    
    $settings = $this->get_settings();

    // Hide WP Logo completely (check first, before custom logo)
    if ( ! empty( $settings['hide_wp_logo'] ) ) {
      $wp_admin_bar->remove_node( 'wp-logo' );
      return;
    }

    // Custom logo with link - modify existing wp-logo node
    if ( ! empty( $settings['custom_logo_url'] ) ) {
      $logo_link = ! empty( $settings['custom_logo_link'] ) ? $settings['custom_logo_link'] : admin_url();
      
      // Update the existing wp-logo node with custom logo using img tag
      $logo_url = esc_url( $settings['custom_logo_url'] );
      $wp_admin_bar->add_node( array(
        'id'     => 'wp-logo',
        'title'  => '<img src="' . $logo_url . '" alt="' . esc_attr( get_bloginfo( 'name' ) ) . '" class="pdt-custom-logo-img" />',
        'href'   => $logo_link,
        'meta'   => array(
          'title' => get_bloginfo( 'name' ),
        ),
      ) );
    }

    // Hide submenu items based on settings
    if ( ! empty( $settings['hide_about_wordpress'] ) ) {
      $wp_admin_bar->remove_node( 'about' );
    }

    if ( ! empty( $settings['hide_get_involved'] ) ) {
      $wp_admin_bar->remove_node( 'contribute' );
    }

    if ( ! empty( $settings['hide_wordpress_org'] ) ) {
      $wp_admin_bar->remove_node( 'wporg' );
    }

    if ( ! empty( $settings['hide_documentation'] ) ) {
      $wp_admin_bar->remove_node( 'documentation' );
    }

    if ( ! empty( $settings['hide_learn_wordpress'] ) ) {
      $wp_admin_bar->remove_node( 'learn' );
    }

    if ( ! empty( $settings['hide_support'] ) ) {
      $wp_admin_bar->remove_node( 'support-forums' );
    }

    if ( ! empty( $settings['hide_feedback'] ) ) {
      $wp_admin_bar->remove_node( 'feedback' );
    }
  }

  /**
   * Add admin body classes for runtime style toggles.
   *
   * @param string $classes Existing classes.
   * @return string
   */
  public function filter_admin_body_class( $classes ) {
    $settings = $this->get_settings();

    if ( ! empty( $settings['hide_help_tab'] ) ) {
      $classes .= ' pdt-hide-help-tab';
    }

    if ( ! empty( $settings['hide_screen_options'] ) ) {
      $classes .= ' pdt-hide-screen-options';
    }

    return $classes;
  }

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

    wp_enqueue_media();
    
    // Main admin bar script (logo upload)
    wp_enqueue_script(
      'pdt-admin-bar-script',
      plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/admin-bar.js',
      array( 'jquery' ),
      '3.3.0',
      true
    );
    wp_localize_script(
      'pdt-admin-bar-script',
      'pdtAdminBarI18n',
      array(
        'mediaTitle'        => __( 'Select Logo', 'polanger-admin-menu-manager' ),
        'mediaButtonText'   => __( 'Use this logo', 'polanger-admin-menu-manager' ),
        'customLogoAlt'     => __( 'Custom Logo', 'polanger-admin-menu-manager' ),
      )
    );
    
    // Custom links script
    wp_enqueue_script(
      'pdt-admin-bar-links-script',
      plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/admin-bar-links.js',
      array( 'jquery' ),
      '3.3.0',
      true
    );
    wp_localize_script(
      'pdt-admin-bar-links-script',
      'pdtAdminBarLinksI18n',
      array(
        'newLinkText'             => __( 'New Link', 'polanger-admin-menu-manager' ),
        'removeConfirm'           => __( 'Are you sure you want to remove this link?', 'polanger-admin-menu-manager' ),
        'removeText'              => __( 'Remove', 'polanger-admin-menu-manager' ),
        'titleLabel'              => __( 'Title', 'polanger-admin-menu-manager' ),
        'titlePlaceholder'        => __( 'Link Title', 'polanger-admin-menu-manager' ),
        'urlLabel'                => __( 'URL', 'polanger-admin-menu-manager' ),
        'iconLabel'               => __( 'Icon', 'polanger-admin-menu-manager' ),
        'selectIconText'          => __( 'Select Icon', 'polanger-admin-menu-manager' ),
        'openInLabel'             => __( 'Open in', 'polanger-admin-menu-manager' ),
        'urlPlaceholder'          => __( 'https://example.com', 'polanger-admin-menu-manager' ),
        'sameWindowText'          => __( 'Same Window', 'polanger-admin-menu-manager' ),
        'newTabText'              => __( 'New Tab', 'polanger-admin-menu-manager' ),
        'submenuItemsText'        => __( 'Submenu Items', 'polanger-admin-menu-manager' ),
        'addSubmenuItemText'      => __( 'Add Submenu Item', 'polanger-admin-menu-manager' ),
        'submenuTitlePlaceholder' => __( 'Submenu Title', 'polanger-admin-menu-manager' ),
        'sameText'                => __( 'Same', 'polanger-admin-menu-manager' ),
        'searchIconsPlaceholder'  => __( 'Search icons...', 'polanger-admin-menu-manager' ),
      )
    );
    
    // Admin bar manager script
    wp_enqueue_script(
      'pdt-admin-bar-manager-script',
      plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/admin-bar-manager.js',
      array( 'jquery' ),
      '3.3.0',
      true
    );
    
    wp_enqueue_style(
      'pdt-admin-bar-style',
      plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/admin-bar.css',
      array(),
      '3.3.0'
    );
  }

  /**
   * Enqueue frontend styles for custom logo
   */
  public function enqueue_frontend_styles() {
    if ( ! is_admin_bar_showing() ) {
      return;
    }

    $settings = $this->get_settings();
    if ( ! empty( $settings['custom_logo_url'] ) ) {
      wp_enqueue_style(
        'pdt-admin-bar-runtime-style',
        plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/admin-bar-runtime.css',
        array(),
        PDT_VERSION
      );
    }
  }

  /**
   * Enqueue runtime admin styles when needed.
   *
   * @return void
   */
  public function enqueue_admin_runtime_styles() {
    $settings = $this->get_settings();

    if ( empty( $settings['custom_logo_url'] ) && empty( $settings['hide_help_tab'] ) && empty( $settings['hide_screen_options'] ) ) {
      return;
    }

    wp_enqueue_style(
      'pdt-admin-bar-runtime-style',
      plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/admin-bar-runtime.css',
      array(),
      PDT_VERSION
    );
  }

  /**
   * Render settings page content
   */
  public function render_settings_page() {
    $settings = $this->get_settings();
    ?>
    <form method="post" action="options.php" class="pdt-admin-bar-form">
      <?php settings_fields( 'pdt_admin_bar_settings_group' ); ?>
      <input type="hidden" name="_wp_http_referer" value="<?php echo esc_attr( admin_url( 'admin.php?page=polanger-admin-bar' ) ); ?>" />

      <!-- WP Logo Section -->
      <div class="pdt-ab-section">
        <h3 class="pdt-ab-section-title">
          <span class="dashicons dashicons-wordpress"></span>
          <?php esc_html_e( 'WordPress Logo', 'polanger-admin-menu-manager' ); ?>
        </h3>
        
        <div class="pdt-ab-card">
          <!-- Hide WP Logo -->
          <div class="pdt-ab-option">
            <label class="pdt-ab-toggle">
              <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_wp_logo]" value="1" <?php checked( ! empty( $settings['hide_wp_logo'] ) ); ?> id="pdt-hide-wp-logo" />
              <span class="pdt-ab-toggle-slider"></span>
            </label>
            <div class="pdt-ab-option-content">
              <span class="pdt-ab-option-label"><?php esc_html_e( 'Hide WordPress Logo', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-ab-option-desc"><?php esc_html_e( 'Completely hide the WordPress logo from admin bar', 'polanger-admin-menu-manager' ); ?></span>
            </div>
          </div>

          <!-- Custom Logo -->
          <div class="pdt-ab-option pdt-ab-logo-upload" id="pdt-custom-logo-section">
            <div class="pdt-ab-option-content pdt-ab-full-width">
              <span class="pdt-ab-option-label"><?php esc_html_e( 'Custom Logo', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-ab-option-desc"><?php esc_html_e( 'Replace WordPress logo with your own (recommended: 20x20px or 40x40px)', 'polanger-admin-menu-manager' ); ?></span>
              
              <div class="pdt-ab-logo-preview-wrapper">
                <div class="pdt-ab-logo-preview" id="pdt-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-ab-logo-actions">
                  <button type="button" class="button pdt-ab-upload-btn" id="pdt-upload-logo">
                    <span class="dashicons dashicons-upload"></span>
                    <?php esc_html_e( 'Upload Logo', 'polanger-admin-menu-manager' ); ?>
                  </button>
                  <button type="button" class="button pdt-ab-remove-btn<?php echo empty( $settings['custom_logo_url'] ) ? ' pdt-is-hidden' : ''; ?>" id="pdt-remove-logo">
                    <span class="dashicons dashicons-trash"></span>
                    <?php esc_html_e( 'Remove', 'polanger-admin-menu-manager' ); ?>
                  </button>
                </div>
              </div>
              <input type="hidden" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_logo_url]" id="pdt-custom-logo-url" value="<?php echo esc_attr( $settings['custom_logo_url'] ?? '' ); ?>" />
            </div>
          </div>

          <!-- Custom Logo Link -->
          <div class="pdt-ab-option" id="pdt-logo-link-section">
            <div class="pdt-ab-option-content pdt-ab-full-width">
              <span class="pdt-ab-option-label"><?php esc_html_e( 'Logo Link URL', 'polanger-admin-menu-manager' ); ?></span>
              <span class="pdt-ab-option-desc"><?php esc_html_e( 'Where should the logo link to? Leave empty for dashboard.', 'polanger-admin-menu-manager' ); ?></span>
              <input type="url" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_logo_link]" class="pdt-ab-input" placeholder="<?php esc_attr_e( 'https://example.com', 'polanger-admin-menu-manager' ); ?>" value="<?php echo esc_attr( $settings['custom_logo_link'] ?? '' ); ?>" />
            </div>
          </div>
        </div>
      </div>

      <!-- Submenu Items Section -->
      <div class="pdt-ab-section" id="pdt-logo-submenu-section">
        <h3 class="pdt-ab-section-title">
          <span class="dashicons dashicons-menu-alt3"></span>
          <?php esc_html_e( 'Logo Submenu Items', 'polanger-admin-menu-manager' ); ?>
        </h3>
        
        <div class="pdt-ab-card">
          <p class="pdt-ab-card-desc"><?php esc_html_e( 'Hide specific items from the WordPress logo dropdown menu.', 'polanger-admin-menu-manager' ); ?></p>
          
          <div class="pdt-ab-submenu-grid">
            <!-- About WordPress -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_about_wordpress]" value="1" <?php checked( ! empty( $settings['hide_about_wordpress'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'About WordPress', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>

            <!-- Get Involved -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_get_involved]" value="1" <?php checked( ! empty( $settings['hide_get_involved'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'Get Involved', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>

            <!-- WordPress.org -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_wordpress_org]" value="1" <?php checked( ! empty( $settings['hide_wordpress_org'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'WordPress.org', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>

            <!-- Documentation -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_documentation]" value="1" <?php checked( ! empty( $settings['hide_documentation'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'Documentation', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>

            <!-- Learn WordPress -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_learn_wordpress]" value="1" <?php checked( ! empty( $settings['hide_learn_wordpress'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'Learn WordPress', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>

            <!-- Support -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_support]" value="1" <?php checked( ! empty( $settings['hide_support'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'Support', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>

            <!-- Feedback -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_feedback]" value="1" <?php checked( ! empty( $settings['hide_feedback'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'Feedback', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- Screen Options & Help Section -->
      <div class="pdt-ab-section">
        <h3 class="pdt-ab-section-title">
          <span class="dashicons dashicons-admin-generic"></span>
          <?php esc_html_e( 'Screen Options & Help Tabs', 'polanger-admin-menu-manager' ); ?>
        </h3>
        
        <div class="pdt-ab-card">
          <p class="pdt-ab-card-desc"><?php esc_html_e( 'Hide the Screen Options and Help tabs from the admin pages.', 'polanger-admin-menu-manager' ); ?></p>
          
          <div class="pdt-ab-submenu-grid">
            <!-- Hide Help Tab -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_help_tab]" value="1" <?php checked( ! empty( $settings['hide_help_tab'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'Hide Help Tab', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>

            <!-- Hide Screen Options -->
            <div class="pdt-ab-submenu-item">
              <label class="pdt-ab-checkbox">
                <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_screen_options]" value="1" <?php checked( ! empty( $settings['hide_screen_options'] ) ); ?> />
                <span class="pdt-ab-checkmark"></span>
                <span><?php esc_html_e( 'Hide Screen Options', 'polanger-admin-menu-manager' ); ?></span>
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- Custom Links Section (same form) -->
      <?php $this->render_custom_links_section(); ?>

      <!-- Admin Bar Items Manager Section (same form) -->
      <?php $this->render_admin_bar_items_section(); ?>

      <!-- Frontend Admin Bar Items Section -->
      <?php $this->render_frontend_admin_bar_items_section(); ?>

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

  /**
   * Render custom links section
   */
  public function render_custom_links_section() {
    $settings = $this->get_settings();
    $links = isset( $settings['links'] ) ? $settings['links'] : array();
    ?>
    <div class="pdt-ab-section">
      <h3 class="pdt-ab-section-title">
        <span class="dashicons dashicons-admin-links"></span>
        <?php esc_html_e( 'Custom Links', 'polanger-admin-menu-manager' ); ?>
      </h3>
      
      <div class="pdt-ab-card">
        <p class="pdt-ab-card-desc"><?php esc_html_e( 'Add custom links to the admin bar. You can create menu items with submenus.', 'polanger-admin-menu-manager' ); ?></p>
        
        <div id="pdt-custom-links-container">
          <?php if ( ! empty( $links ) ) : ?>
            <?php foreach ( $links as $index => $link ) : ?>
              <?php $this->render_link_item( $index, $link ); ?>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
        
        <div class="pdt-ab-add-link-wrapper">
          <button type="button" class="button button-secondary" id="pdt-add-new-link">
            <span class="dashicons dashicons-plus-alt2"></span>
            <?php esc_html_e( 'Add New Link', 'polanger-admin-menu-manager' ); ?>
          </button>
        </div>
      </div>
    </div>
    <?php
  }

  /**
   * Render single link item
   */
  public function render_link_item( $index, $link = array() ) {
    $defaults = array(
      'title'   => '',
      'url'     => '',
      'icon'    => 'dashicons-admin-links',
      'target'  => '_self',
      'submenu' => array(),
    );
    $link = wp_parse_args( $link, $defaults );
    ?>
    <div class="pdt-link-item" data-index="<?php echo esc_attr( $index ); ?>">
      <div class="pdt-link-header">
        <span class="pdt-link-drag-handle dashicons dashicons-menu"></span>
        <span class="pdt-link-title-preview"><?php echo esc_html( $link['title'] ?: __( 'New Link', 'polanger-admin-menu-manager' ) ); ?></span>
        <button type="button" class="pdt-link-toggle" aria-expanded="false">
          <span class="dashicons dashicons-arrow-down-alt2"></span>
        </button>
        <button type="button" class="pdt-link-remove" title="<?php esc_attr_e( 'Remove', 'polanger-admin-menu-manager' ); ?>">
          <span class="dashicons dashicons-trash"></span>
        </button>
      </div>
      
      <div class="pdt-link-content pdt-is-hidden">
        <div class="pdt-link-row">
          <div class="pdt-link-field">
            <label><?php esc_html_e( 'Title', 'polanger-admin-menu-manager' ); ?></label>
            <input type="text" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[links][<?php echo esc_attr( $index ); ?>][title]" value="<?php echo esc_attr( $link['title'] ); ?>" class="pdt-link-title-input" placeholder="<?php esc_attr_e( 'Link Title', 'polanger-admin-menu-manager' ); ?>" />
          </div>
          <div class="pdt-link-field">
            <label><?php esc_html_e( 'URL', 'polanger-admin-menu-manager' ); ?></label>
            <input type="url" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[links][<?php echo esc_attr( $index ); ?>][url]" value="<?php echo esc_attr( $link['url'] ); ?>" placeholder="<?php esc_attr_e( 'https://example.com', 'polanger-admin-menu-manager' ); ?>" />
          </div>
        </div>
        
        <div class="pdt-link-row">
          <div class="pdt-link-field">
            <label><?php esc_html_e( 'Icon', 'polanger-admin-menu-manager' ); ?></label>
            <div class="pdt-icon-selector">
              <button type="button" class="pdt-icon-picker-btn">
                <span class="dashicons <?php echo esc_attr( $link['icon'] ); ?>"></span>
                <span class="pdt-icon-picker-label"><?php esc_html_e( 'Select Icon', 'polanger-admin-menu-manager' ); ?></span>
              </button>
              <input type="hidden" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[links][<?php echo esc_attr( $index ); ?>][icon]" value="<?php echo esc_attr( $link['icon'] ); ?>" class="pdt-icon-input" />
            </div>
          </div>
          <div class="pdt-link-field">
            <label><?php esc_html_e( 'Open in', 'polanger-admin-menu-manager' ); ?></label>
            <select name="<?php echo esc_attr( self::OPTION_NAME ); ?>[links][<?php echo esc_attr( $index ); ?>][target]">
              <option value="_self" <?php selected( $link['target'], '_self' ); ?>><?php esc_html_e( 'Same Window', 'polanger-admin-menu-manager' ); ?></option>
              <option value="_blank" <?php selected( $link['target'], '_blank' ); ?>><?php esc_html_e( 'New Tab', 'polanger-admin-menu-manager' ); ?></option>
            </select>
          </div>
        </div>
        
        <!-- Submenus -->
        <div class="pdt-submenu-section">
          <h4><?php esc_html_e( 'Submenu Items', 'polanger-admin-menu-manager' ); ?></h4>
          <div class="pdt-submenu-items" data-parent="<?php echo esc_attr( $index ); ?>">
            <?php if ( ! empty( $link['submenu'] ) ) : ?>
              <?php foreach ( $link['submenu'] as $sub_index => $sublink ) : ?>
                <?php $this->render_submenu_item( $index, $sub_index, $sublink ); ?>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
          <button type="button" class="button pdt-add-submenu-btn">
            <span class="dashicons dashicons-plus"></span>
            <?php esc_html_e( 'Add Submenu Item', 'polanger-admin-menu-manager' ); ?>
          </button>
        </div>
      </div>
    </div>
    <?php
  }

  /**
   * Render submenu item
   */
  public function render_submenu_item( $parent_index, $sub_index, $sublink = array() ) {
    $defaults = array(
      'title'  => '',
      'url'    => '',
      'icon'   => '',
      'target' => '_self',
    );
    $sublink = wp_parse_args( $sublink, $defaults );
    ?>
    <div class="pdt-submenu-item" data-sub-index="<?php echo esc_attr( $sub_index ); ?>">
      <div class="pdt-submenu-row">
        <input type="text" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[links][<?php echo esc_attr( $parent_index ); ?>][submenu][<?php echo esc_attr( $sub_index ); ?>][title]" value="<?php echo esc_attr( $sublink['title'] ); ?>" placeholder="<?php esc_attr_e( 'Submenu Title', 'polanger-admin-menu-manager' ); ?>" />
        <input type="url" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[links][<?php echo esc_attr( $parent_index ); ?>][submenu][<?php echo esc_attr( $sub_index ); ?>][url]" value="<?php echo esc_attr( $sublink['url'] ); ?>" placeholder="<?php esc_attr_e( 'https://example.com', 'polanger-admin-menu-manager' ); ?>" />
        <select name="<?php echo esc_attr( self::OPTION_NAME ); ?>[links][<?php echo esc_attr( $parent_index ); ?>][submenu][<?php echo esc_attr( $sub_index ); ?>][target]">
          <option value="_self" <?php selected( $sublink['target'], '_self' ); ?>><?php esc_html_e( 'Same', 'polanger-admin-menu-manager' ); ?></option>
          <option value="_blank" <?php selected( $sublink['target'], '_blank' ); ?>><?php esc_html_e( 'New Tab', 'polanger-admin-menu-manager' ); ?></option>
        </select>
        <button type="button" class="pdt-remove-submenu-btn" title="<?php esc_attr_e( 'Remove', 'polanger-admin-menu-manager' ); ?>">
          <span class="dashicons dashicons-no-alt"></span>
        </button>
      </div>
    </div>
    <?php
  }

  /**
   * Add custom links to admin bar
   */
  public function add_custom_links_to_admin_bar() {
    global $wp_admin_bar;

    if ( ! is_object( $wp_admin_bar ) ) {
      return;
    }

    $settings = $this->get_settings();
    $links = isset( $settings['links'] ) ? $settings['links'] : array();

    if ( empty( $links ) ) {
      return;
    }

    foreach ( $links as $index => $link ) {
      $node_id = 'pdt-custom-link-' . $index;
      
      // Add parent menu item
      $wp_admin_bar->add_node( array(
        'id'     => $node_id,
        'title'  => '<span class="ab-icon dashicons ' . esc_attr( $link['icon'] ) . '"></span><span class="ab-label">' . esc_html( $link['title'] ) . '</span>',
        'href'   => esc_url( $link['url'] ),
        'meta'   => array(
          'target' => $link['target'],
          'title'  => esc_attr( $link['title'] ),
          'class'  => 'pdt-custom-link',
        ),
      ) );

      // Add submenu items
      if ( ! empty( $link['submenu'] ) ) {
        foreach ( $link['submenu'] as $sub_index => $sublink ) {
          $sub_node_id = $node_id . '-sub-' . $sub_index;
          
          $sub_title = esc_html( $sublink['title'] );
          if ( ! empty( $sublink['icon'] ) ) {
            $sub_title = '<span class="dashicons pdt-ab-submenu-icon ' . esc_attr( $sublink['icon'] ) . '"></span>' . $sub_title;
          }
          
          $wp_admin_bar->add_node( array(
            'id'     => $sub_node_id,
            'title'  => $sub_title,
            'href'   => esc_url( $sublink['url'] ),
            'parent' => $node_id,
            'meta'   => array(
              'target' => $sublink['target'],
              'title'  => esc_attr( $sublink['title'] ),
            ),
          ) );
        }
      }
    }
  }

  /**
   * Render admin bar items management section
   */
  public function render_admin_bar_items_section() {
    $settings = $this->get_settings();
    $hidden_items = isset( $settings['hidden_items'] ) ? $settings['hidden_items'] : array();
    $renamed_items = isset( $settings['renamed_items'] ) ? $settings['renamed_items'] : array();
    
    // Get admin bar nodes from transient
    $nodes = get_transient( 'pdt_admin_bar_nodes' );
    if ( empty( $nodes ) ) {
      $nodes = $this->get_default_admin_bar_nodes();
    }
    
    $organized = $this->organize_nodes_by_parent( $nodes );
    ?>
    <div class="pdt-ab-section">
      <h3 class="pdt-ab-section-title">
        <span class="dashicons dashicons-visibility"></span>
        <?php esc_html_e( 'Manage Admin Bar Items', 'polanger-admin-menu-manager' ); ?>
      </h3>
      
      <div class="pdt-ab-card">
        <p class="pdt-ab-card-desc"><?php esc_html_e( 'Hide or rename existing admin bar items added by WordPress, themes, or plugins.', 'polanger-admin-menu-manager' ); ?></p>
        
        <div class="pdt-abm-refresh-notice">
          <span class="dashicons dashicons-info"></span>
          <?php esc_html_e( 'Items are detected automatically. If you don\'t see an item, refresh the page.', 'polanger-admin-menu-manager' ); ?>
        </div>

        <div class="pdt-abm-items-container">
          <?php if ( ! empty( $organized['root'] ) ) : ?>
            <?php foreach ( $organized['root'] as $node_id => $node ) : ?>
              <?php 
              // Skip wp-logo as it's managed separately
              if ( $node_id === 'wp-logo' ) {
                continue;
              }
              $this->render_admin_bar_node_item( $node, $organized['children'], $hidden_items, $renamed_items ); 
              ?>
            <?php endforeach; ?>
          <?php else : ?>
            <p class="pdt-abm-no-items"><?php esc_html_e( 'No admin bar items detected. Please refresh the page.', 'polanger-admin-menu-manager' ); ?></p>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php
  }

  /**
   * Render single admin bar node item
   */
  private function render_admin_bar_node_item( $node, $children, $hidden_items, $renamed_items, $depth = 0 ) {
    $node_id = $node->id;
    $is_hidden = in_array( $node_id, $hidden_items, true );
    $renamed_title = isset( $renamed_items[ $node_id ] ) ? $renamed_items[ $node_id ] : '';
    $original_title = $this->get_clean_node_title( $node->title );
    $has_children = isset( $children[ $node_id ] ) && ! empty( $children[ $node_id ] );
    ?>
    <div class="pdt-abm-item <?php echo $is_hidden ? 'pdt-abm-item-hidden' : ''; ?> <?php echo $depth > 0 ? 'pdt-abm-item-child' : ''; ?>" data-node-id="<?php echo esc_attr( $node_id ); ?>" data-depth="<?php echo esc_attr( $depth ); ?>">
      <div class="pdt-abm-item-header">
        <div class="pdt-abm-item-info">
          <?php if ( $has_children ) : ?>
            <button type="button" class="pdt-abm-expand-btn" aria-expanded="false">
              <span class="dashicons dashicons-arrow-right-alt2"></span>
            </button>
          <?php else : ?>
            <span class="pdt-abm-item-bullet"></span>
          <?php endif; ?>
          <span class="pdt-abm-item-title"><?php echo esc_html( $original_title ); ?></span>
          <code class="pdt-abm-item-id"><?php echo esc_html( $node_id ); ?></code>
        </div>
        <div class="pdt-abm-item-actions">
          <label class="pdt-abm-hide-toggle" title="<?php esc_attr_e( 'Hide this item', 'polanger-admin-menu-manager' ); ?>">
            <input type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hidden_items][]" value="<?php echo esc_attr( $node_id ); ?>" <?php checked( $is_hidden ); ?> />
            <span class="dashicons <?php echo $is_hidden ? 'dashicons-hidden' : 'dashicons-visibility'; ?>"></span>
          </label>
          <button type="button" class="pdt-abm-rename-btn <?php echo ! empty( $renamed_title ) ? 'active' : ''; ?>" title="<?php esc_attr_e( 'Rename this item', 'polanger-admin-menu-manager' ); ?>">
            <span class="dashicons dashicons-edit"></span>
          </button>
        </div>
      </div>
      
      <div class="pdt-abm-item-rename<?php echo ! empty( $renamed_title ) ? '' : ' pdt-is-hidden'; ?>">
        <input type="text" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[renamed_items][<?php echo esc_attr( $node_id ); ?>]" value="<?php echo esc_attr( $renamed_title ); ?>" placeholder="<?php echo esc_attr( $original_title ); ?>" />
        <span class="pdt-abm-rename-hint"><?php esc_html_e( 'Leave empty to use original title', 'polanger-admin-menu-manager' ); ?></span>
      </div>

      <?php if ( $has_children ) : ?>
        <div class="pdt-abm-item-children pdt-is-hidden">
          <?php foreach ( $children[ $node_id ] as $child_node ) : ?>
            <?php $this->render_admin_bar_node_item( $child_node, $children, $hidden_items, $renamed_items, $depth + 1 ); ?>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
    <?php
  }

  /**
   * Get clean title from node title (strip HTML)
   */
  private function get_clean_node_title( $title ) {
    $clean = wp_strip_all_tags( $title );
    $clean = html_entity_decode( $clean, ENT_QUOTES, 'UTF-8' );
    $clean = preg_replace( '/\s+/u', ' ', (string) $clean );
    $clean = trim( (string) $clean );

    // WordPress admin bar titles may include both visible badge count and
    // screen-reader count text. After stripping HTML this can produce
    // duplicated prefixes like "11 updates" (for 1) or "00 comments" (for 0).
    if ( preg_match( '/^(\d+)\s*\1(\s+.*)$/u', $clean, $matches ) ) {
      $clean = $matches[1] . $matches[2];
      $clean = trim( $clean );
    }

    return $clean ?: __( '(No title)', 'polanger-admin-menu-manager' );
  }

  /**
   * Organize nodes by parent
   */
  private function organize_nodes_by_parent( $nodes ) {
    $organized = array(
      'root' => array(),
      'children' => array(),
    );

    foreach ( $nodes as $node_id => $node ) {
      if ( isset( $node->group ) && $node->group ) {
        continue;
      }

      if ( empty( $node->parent ) || $node->parent === false ) {
        $organized['root'][ $node_id ] = $node;
      } else {
        if ( ! isset( $organized['children'][ $node->parent ] ) ) {
          $organized['children'][ $node->parent ] = array();
        }
        $organized['children'][ $node->parent ][ $node_id ] = $node;
      }
    }

    return $organized;
  }

  /**
   * Get default admin bar nodes
   */
  private function get_default_admin_bar_nodes() {
    return array(
      'site-name' => (object) array(
        'id' => 'site-name',
        'title' => get_bloginfo( 'name' ),
        'parent' => false,
      ),
      'comments' => (object) array(
        'id' => 'comments',
        'title' => __( 'Comments', 'polanger-admin-menu-manager' ),
        'parent' => false,
      ),
      'new-content' => (object) array(
        'id' => 'new-content',
        'title' => __( 'New', 'polanger-admin-menu-manager' ),
        'parent' => false,
      ),
      'my-account' => (object) array(
        'id' => 'my-account',
        'title' => __( 'My Account', 'polanger-admin-menu-manager' ),
        'parent' => false,
      ),
    );
  }

  /**
   * Render frontend admin bar items management section
   */
  public function render_frontend_admin_bar_items_section() {
    $settings = $this->get_settings();
    $hidden_items = isset( $settings['hidden_items'] ) ? $settings['hidden_items'] : array();
    $renamed_items = isset( $settings['renamed_items'] ) ? $settings['renamed_items'] : array();
    
    // Get frontend admin bar nodes from transient
    $frontend_nodes = get_transient( 'pdt_admin_bar_nodes_frontend' );
    $admin_nodes = get_transient( 'pdt_admin_bar_nodes' );
    if ( ! is_array( $admin_nodes ) ) {
      $admin_nodes = array();
    }
    
    // Show ALL frontend items, but mark which ones are frontend-only
    $frontend_display_nodes = array();
    if ( ! empty( $frontend_nodes ) ) {
      foreach ( $frontend_nodes as $node_id => $node ) {
        // Skip wp-logo as it's managed separately
        if ( $node_id === 'wp-logo' ) {
          continue;
        }
        // Skip group nodes
        if ( isset( $node->group ) && $node->group ) {
          continue;
        }
        // Mark if this is frontend-only (not in admin)
        $node->is_frontend_only = ! isset( $admin_nodes[ $node_id ] );
        $frontend_display_nodes[ $node_id ] = $node;
      }
    }
    
    $organized = $this->organize_nodes_by_parent( $frontend_display_nodes );
    ?>
    <div class="pdt-ab-section">
      <h3 class="pdt-ab-section-title">
        <span class="dashicons dashicons-admin-site-alt3"></span>
        <?php esc_html_e( 'Frontend Admin Bar Items', 'polanger-admin-menu-manager' ); ?>
      </h3>
      
      <div class="pdt-ab-card">
        <p class="pdt-ab-card-desc"><?php esc_html_e( 'Manage all admin bar items that appear on the frontend (public-facing pages). Hide or rename items like "Edit Post", "Edit with Elementor", "Customize", and any items added by themes or plugins.', 'polanger-admin-menu-manager' ); ?></p>
        
        <div class="pdt-abm-refresh-notice pdt-abm-frontend-notice">
          <span class="dashicons dashicons-info"></span>
          <div class="pdt-abm-notice-content">
            <p><?php esc_html_e( 'To detect all frontend items, visit different page types on your site while logged in:', 'polanger-admin-menu-manager' ); ?></p>
            <ul>
              <li><?php esc_html_e( 'A single post/page (to detect "Edit Post", "Edit with Elementor", etc.)', 'polanger-admin-menu-manager' ); ?></li>
              <li><?php esc_html_e( 'The homepage (to detect theme-specific items)', 'polanger-admin-menu-manager' ); ?></li>
              <li><?php esc_html_e( 'Archive pages (to detect archive-specific items)', 'polanger-admin-menu-manager' ); ?></li>
            </ul>
            <p><strong><?php esc_html_e( 'Items are accumulated from all visited pages.', 'polanger-admin-menu-manager' ); ?></strong></p>
          </div>
        </div>
        
        <?php 
        // Show last detection info
        $frontend_nodes = get_transient( 'pdt_admin_bar_nodes_frontend' );
        $node_count = is_array( $frontend_nodes ) ? count( $frontend_nodes ) : 0;
        ?>
        <div class="pdt-abm-detection-status">
          <span class="dashicons dashicons-yes-alt"></span>
          <span>
            <?php
            /* translators: %d: Number of detected frontend admin bar items. */
            printf( esc_html__( '%d frontend items detected', 'polanger-admin-menu-manager' ), absint( $node_count ) );
            ?>
          </span>
          <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=polanger-admin-bar&clear_frontend_cache=1' ), 'pdt_clear_frontend_cache' ) ); ?>" class="button button-small">
            <span class="dashicons dashicons-update"></span>
            <?php esc_html_e( 'Reset & Re-detect', 'polanger-admin-menu-manager' ); ?>
          </a>
        </div>

        <div class="pdt-abm-items-container">
          <?php if ( ! empty( $organized['root'] ) ) : ?>
            <?php foreach ( $organized['root'] as $node_id => $node ) : ?>
              <?php $this->render_admin_bar_node_item( $node, $organized['children'], $hidden_items, $renamed_items ); ?>
            <?php endforeach; ?>
          <?php else : ?>
            <div class="pdt-abm-no-items-box">
              <span class="dashicons dashicons-admin-site-alt3"></span>
              <p><?php esc_html_e( 'No frontend-only admin bar items detected yet.', 'polanger-admin-menu-manager' ); ?></p>
              <p class="pdt-abm-hint"><?php esc_html_e( 'Visit your site\'s frontend while logged in to detect items like "Edit Post", "Customize", etc.', 'polanger-admin-menu-manager' ); ?></p>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php
  }

  /**
   * Capture admin bar nodes for settings page (first pass via admin_bar_menu)
   */
  public function capture_admin_bar_nodes( $wp_admin_bar = null ) {
    if ( ! is_object( $wp_admin_bar ) ) {
      global $wp_admin_bar;
    }

    if ( ! is_object( $wp_admin_bar ) ) {
      return;
    }

    $nodes = $wp_admin_bar->get_nodes();
    if ( empty( $nodes ) ) {
      return;
    }

    $this->save_captured_nodes( $nodes );
  }

  /**
   * Final capture of admin bar nodes (catches late additions like Elementor)
   */
  public function capture_admin_bar_nodes_final() {
    global $wp_admin_bar;

    if ( ! is_object( $wp_admin_bar ) ) {
      return;
    }

    $nodes = $wp_admin_bar->get_nodes();
    if ( empty( $nodes ) ) {
      return;
    }

    $this->save_captured_nodes( $nodes );
  }

  /**
   * Save captured nodes to transient, merging with existing
   */
  private function save_captured_nodes( $nodes ) {
    $transient_key = is_admin() ? 'pdt_admin_bar_nodes' : 'pdt_admin_bar_nodes_frontend';
    
    // Get existing nodes
    $existing_nodes = get_transient( $transient_key );
    if ( ! is_array( $existing_nodes ) ) {
      $existing_nodes = array();
    }
    
    // Merge new nodes with existing (new nodes take precedence)
    foreach ( $nodes as $node_id => $node ) {
      $existing_nodes[ $node_id ] = $node;
    }
    
    set_transient( $transient_key, $existing_nodes, DAY_IN_SECONDS );
  }

  /**
   * Apply hidden/renamed items to admin bar
   */
  public function apply_admin_bar_item_modifications() {
    global $wp_admin_bar;

    if ( ! is_object( $wp_admin_bar ) ) {
      return;
    }

    $settings = $this->get_settings();

    // Hide items
    if ( ! empty( $settings['hidden_items'] ) ) {
      foreach ( $settings['hidden_items'] as $node_id ) {
        $wp_admin_bar->remove_node( $node_id );
      }
    }

    // Rename items
    if ( ! empty( $settings['renamed_items'] ) ) {
      foreach ( $settings['renamed_items'] as $node_id => $new_title ) {
        $node = $wp_admin_bar->get_node( $node_id );
        if ( $node ) {
          $wp_admin_bar->add_node( array(
            'id'    => $node_id,
            'title' => $new_title,
          ) );
        }
      }
    }
  }
}
