<?php
/**
 * Dashboard Widgets Manager Addon
 *
 * Manage dashboard widgets visibility and admin notices.
 *
 * @package Polanger_Dashboard_Tools_Pro
 * @since 4.3.0
 */

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

/**
 * PDT Dashboard Widgets Class
 */
class PDT_Dashboard_Widgets {

  /**
   * Option name for settings
   */
  const OPTION_NAME = 'pdt_dashboard_widgets_settings';

  /**
   * Default settings
   */
  private $default_settings = array(
    // Widget Visibility
    'hide_welcome'           => false,
    'hide_quick_draft'       => false,
    'hide_activity'          => false,
    'hide_primary'           => false, // WordPress Events and News
    'hide_site_health'       => false,
    'hide_at_a_glance'       => false,
    'hide_recent_comments'   => false,
    'hide_recent_drafts'     => false,
    'hide_browser_nag'       => false,
    'hide_php_nag'           => false,
    'hide_plugins_widget'    => false,
    'hide_incoming_links'    => false,
    'hidden_widgets'         => array(), // Dynamic: array of widget IDs to hide
    'auto_hide_new_widgets'  => false,   // Auto-hide all future 3rd party widgets
    'widget_whitelist'       => array(), // Whitelisted widget IDs (shown even with auto-hide)
    'widget_user_visibility' => array(), // user_id => array of hidden widgets
    
    // Admin Notices
    'hide_all_notices'       => false,
    'notice_exception'       => 'super_admin', // none, super_admin, dashboard_only
    'log_hidden_notices'     => false,
    'notice_whitelist'       => array(), // plugin slugs to whitelist
    
    // Custom Widgets (multiple)
    'custom_widgets' => array(), // Array of custom widgets: [ { id, title, content, position, enabled } ]
  );

  /**
   * Core WordPress widget IDs
   */
  private $core_widgets = array(
    'dashboard_quick_press',
    'dashboard_activity', 
    'dashboard_primary',
    'dashboard_site_health',
    'dashboard_right_now',
    'dashboard_recent_comments',
    'dashboard_incoming_links',
    'dashboard_plugins',
    'dashboard_recent_drafts',
    'dashboard_browser_nag',
    'dashboard_php_nag',
  );

  /**
   * Hidden notices log (transient)
   */
  private $hidden_notices = array();
  private $notice_buffer_started = false;

  /**
   * Constructor
   */
  public function __construct() {
    add_action( 'admin_init', array( $this, 'register_settings' ) );
    add_action( 'wp_dashboard_setup', array( $this, 'manage_dashboard_widgets' ), 999 );
    add_action( 'wp_dashboard_setup', array( $this, 'detect_all_widgets' ), 99999 ); // Run last to catch all
    add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
    add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_runtime_assets' ) );
    add_filter( 'admin_body_class', array( $this, 'filter_admin_body_class' ) );
    
    // Admin notices management
    add_action( 'admin_notices', array( $this, 'capture_notices' ), 0 );
    add_action( 'all_admin_notices', array( $this, 'capture_notices' ), 0 );
    
    // Custom welcome widget
    add_action( 'wp_dashboard_setup', array( $this, 'add_custom_welcome_widget' ), 1 );
  }

  /**
   * Detect all registered dashboard widgets (including 3rd party)
   */
  public function detect_all_widgets() {
    global $wp_meta_boxes;

    if ( empty( $wp_meta_boxes['dashboard'] ) ) {
      return;
    }

    $detected_widgets = array();

    // Scan all contexts and priorities
    foreach ( $wp_meta_boxes['dashboard'] as $context => $priorities ) {
      if ( ! is_array( $priorities ) ) {
        continue;
      }
      foreach ( $priorities as $priority => $widgets ) {
        if ( ! is_array( $widgets ) ) {
          continue;
        }
        foreach ( $widgets as $widget_id => $widget_data ) {
          if ( empty( $widget_id ) || $widget_id === false || ! is_array( $widget_data ) ) {
            continue;
          }
          
          // Skip our own custom widgets (pdt_custom_ prefix)
          if ( strpos( $widget_id, 'pdt_custom_' ) === 0 ) {
            continue;
          }

          $detected_widgets[ $widget_id ] = array(
            'id'       => $widget_id,
            'title'    => isset( $widget_data['title'] ) ? wp_strip_all_tags( $widget_data['title'] ) : $widget_id,
            'context'  => $context,
            'priority' => $priority,
            'is_core'  => in_array( $widget_id, $this->core_widgets, true ) || strpos( $widget_id, 'dashboard_' ) === 0,
          );
        }
      }
    }

    // Merge with existing detected widgets (don't lose previously detected ones)
    $existing_widgets = get_transient( 'pdt_detected_widgets' );
    if ( is_array( $existing_widgets ) ) {
      $detected_widgets = array_merge( $existing_widgets, $detected_widgets );
    }

    // Save detected widgets to transient (refresh every day)
    set_transient( 'pdt_detected_widgets', $detected_widgets, DAY_IN_SECONDS );
  }

  /**
   * Get all detected widgets
   */
  public function get_detected_widgets() {
    $widgets = get_transient( 'pdt_detected_widgets' );
    
    if ( false === $widgets || ! is_array( $widgets ) ) {
      return array();
    }

    return $widgets;
  }

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

  /**
   * Sanitize settings
   */
  public function sanitize_settings( $input ) {
    // Get existing settings to preserve values from other tabs
    $existing = get_option( self::OPTION_NAME, array() );
    $existing = wp_parse_args( $existing, $this->default_settings );

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

    // Determine which tab is being saved.
    $active_tab = isset( $input['active_tab'] ) ? sanitize_key( $input['active_tab'] ) : '';

    if ( in_array( $active_tab, array( 'widgets', 'notices', 'custom' ), true ) ) {
      $saving_widgets_tab = ( 'widgets' === $active_tab );
      $saving_notices_tab = ( 'notices' === $active_tab );
      $saving_custom_tab  = ( 'custom' === $active_tab );
    } else {
      // Backward-compatible fallback if active_tab is missing.
      $saving_widgets_tab = array_key_exists( 'hide_welcome', $input ) || array_key_exists( 'hidden_widgets', $input ) || array_key_exists( 'auto_hide_new_widgets', $input );
      $saving_notices_tab = array_key_exists( 'hide_all_notices', $input ) || array_key_exists( 'notice_exception', $input );
      $saving_custom_tab  = array_key_exists( 'custom_widgets', $input );
    }

    $sanitized = $existing; // Start with existing values

    // Widget visibility toggles (only update if widgets tab is being saved)
    if ( $saving_widgets_tab ) {
      $sanitized['hide_welcome']     = ! empty( $input['hide_welcome'] );
      $sanitized['hide_quick_draft'] = ! empty( $input['hide_quick_draft'] );
      $sanitized['hide_activity']    = ! empty( $input['hide_activity'] );
      $sanitized['hide_primary']     = ! empty( $input['hide_primary'] );
      $sanitized['hide_site_health'] = ! empty( $input['hide_site_health'] );
      $sanitized['hide_at_a_glance'] = ! empty( $input['hide_at_a_glance'] );
      $sanitized['hide_recent_comments'] = ! empty( $input['hide_recent_comments'] );
      $sanitized['hide_recent_drafts'] = ! empty( $input['hide_recent_drafts'] );
      $sanitized['hide_browser_nag'] = ! empty( $input['hide_browser_nag'] );
      $sanitized['hide_php_nag'] = ! empty( $input['hide_php_nag'] );
      $sanitized['hide_plugins_widget'] = ! empty( $input['hide_plugins_widget'] );
      $sanitized['hide_incoming_links'] = ! empty( $input['hide_incoming_links'] );

      // Dynamic hidden widgets (3rd party)
      $sanitized['hidden_widgets'] = array();
      if ( isset( $input['hidden_widgets'] ) && is_array( $input['hidden_widgets'] ) ) {
        $sanitized['hidden_widgets'] = array_map( 'sanitize_text_field', $input['hidden_widgets'] );
      }

      // Auto-hide new widgets
      $sanitized['auto_hide_new_widgets'] = ! empty( $input['auto_hide_new_widgets'] );

      // Widget whitelist (allowed even with auto-hide)
      $sanitized['widget_whitelist'] = array();
      if ( isset( $input['widget_whitelist'] ) && is_array( $input['widget_whitelist'] ) ) {
        $sanitized['widget_whitelist'] = array_map( 'sanitize_text_field', $input['widget_whitelist'] );
      }

      // User-specific widget visibility
      $sanitized['widget_user_visibility'] = array();
      if ( isset( $input['widget_user_visibility'] ) && is_array( $input['widget_user_visibility'] ) ) {
        foreach ( $input['widget_user_visibility'] as $user_id => $widgets ) {
          $user_id = absint( $user_id );
          if ( $user_id > 0 && is_array( $widgets ) ) {
            $sanitized['widget_user_visibility'][ $user_id ] = array_map( 'sanitize_text_field', $widgets );
          }
        }
      }
    }

    // Admin notices settings (only update if notices tab is being saved)
    if ( $saving_notices_tab ) {
      $sanitized['hide_all_notices']   = ! empty( $input['hide_all_notices'] );
      $sanitized['notice_exception']   = isset( $input['notice_exception'] ) && in_array( $input['notice_exception'], array( 'none', 'super_admin', 'dashboard_only' ), true ) ? sanitize_text_field( $input['notice_exception'] ) : 'super_admin';
      $sanitized['log_hidden_notices'] = ! empty( $input['log_hidden_notices'] );

      // Notice whitelist
      $sanitized['notice_whitelist'] = array();
      if ( isset( $input['notice_whitelist'] ) && is_array( $input['notice_whitelist'] ) ) {
        $sanitized['notice_whitelist'] = array_map( 'sanitize_text_field', $input['notice_whitelist'] );
      } elseif ( isset( $input['notice_whitelist_text'] ) ) {
        $raw_whitelist = sanitize_textarea_field( $input['notice_whitelist_text'] );
        // Support users pasting "\n" sequences as line breaks.
        $raw_whitelist = str_replace( '\n', "\n", $raw_whitelist );
        $parts = preg_split( '/[\r\n,]+/', $raw_whitelist );
        if ( is_array( $parts ) ) {
          $sanitized['notice_whitelist'] = array_filter(
            array_map(
              'sanitize_text_field',
              array_map( 'trim', $parts )
            )
          );
        }
      }
    }

    // Custom widgets (only update if custom tab is being saved)
    if ( $saving_custom_tab ) {
      $sanitized['custom_widgets'] = array();
      if ( isset( $input['custom_widgets'] ) && is_array( $input['custom_widgets'] ) ) {
        foreach ( $input['custom_widgets'] as $index => $widget ) {
          if ( ! empty( $widget['title'] ) ) {
            $sanitized['custom_widgets'][] = array(
              'id'       => isset( $widget['id'] ) ? sanitize_key( $widget['id'] ) : 'pdt_custom_' . uniqid(),
              'title'    => sanitize_text_field( $widget['title'] ),
              'content'  => isset( $widget['content'] ) ? $this->sanitize_custom_widget_content( $widget['content'] ) : '',
              'position' => isset( $widget['position'] ) ? sanitize_text_field( $widget['position'] ) : 'normal',
              'enabled'  => ! empty( $widget['enabled'] ),
            );
          }
        }
      }
    }

    return $sanitized;
  }

  /**
   * Get settings
   */
  public function get_settings() {
    $settings = get_option( self::OPTION_NAME, array() );
    $settings = wp_parse_args( $settings, $this->default_settings );

    return apply_filters( 'polanger_effective_settings', $settings, self::OPTION_NAME, $this->default_settings, 'dashboard-widgets' );
  }

  /**
   * Check if current user is super admin
   */
  private function is_super_admin() {
    $current_user_id = get_current_user_id();
    if ( ! $current_user_id ) {
      return false;
    }
    if ( is_multisite() ) {
      return is_super_admin( $current_user_id );
    }
    return user_can( $current_user_id, 'manage_options' );
  }

  /**
   * Manage dashboard widgets visibility
   */
  public function manage_dashboard_widgets() {
    $settings = $this->get_settings();
    $current_user_id = get_current_user_id();

    // Global core/default widget hiding.
    if ( ! empty( $settings['hide_welcome'] ) ) {
      remove_meta_box( 'welcome-panel', 'dashboard', 'normal' );
      remove_action( 'welcome_panel', 'wp_welcome_panel' );
    }

    $core_widget_map = array(
      'hide_quick_draft'     => 'dashboard_quick_press',
      'hide_activity'        => 'dashboard_activity',
      'hide_primary'         => 'dashboard_primary',
      'hide_site_health'     => 'dashboard_site_health',
      'hide_at_a_glance'     => 'dashboard_right_now',
      'hide_recent_comments' => 'dashboard_recent_comments',
      'hide_recent_drafts'   => 'dashboard_recent_drafts',
      'hide_browser_nag'     => 'dashboard_browser_nag',
      'hide_php_nag'         => 'dashboard_php_nag',
      'hide_plugins_widget'  => 'dashboard_plugins',
      'hide_incoming_links'  => 'dashboard_incoming_links',
    );

    foreach ( $core_widget_map as $setting_key => $widget_id ) {
      if ( ! empty( $settings[ $setting_key ] ) ) {
        remove_meta_box( $widget_id, 'dashboard', 'normal' );
        remove_meta_box( $widget_id, 'dashboard', 'side' );
        remove_meta_box( $widget_id, 'dashboard', 'column3' );
        remove_meta_box( $widget_id, 'dashboard', 'column4' );
        remove_meta_box( $widget_id, 'dashboard', 'advanced' );
      }
    }

    // Dynamic 3rd party widget hiding (manual selection)
    if ( ! empty( $settings['hidden_widgets'] ) && is_array( $settings['hidden_widgets'] ) ) {
      foreach ( $settings['hidden_widgets'] as $widget_id ) {
        // Remove from all possible contexts
        remove_meta_box( $widget_id, 'dashboard', 'normal' );
        remove_meta_box( $widget_id, 'dashboard', 'side' );
        remove_meta_box( $widget_id, 'dashboard', 'column3' );
        remove_meta_box( $widget_id, 'dashboard', 'column4' );
        remove_meta_box( $widget_id, 'dashboard', 'advanced' );
      }
    }

    // Auto-hide ALL 3rd party widgets (except whitelist)
    if ( ! empty( $settings['auto_hide_new_widgets'] ) ) {
      global $wp_meta_boxes;
      
      if ( ! empty( $wp_meta_boxes['dashboard'] ) ) {
        $whitelist = isset( $settings['widget_whitelist'] ) ? $settings['widget_whitelist'] : array();
        
        foreach ( $wp_meta_boxes['dashboard'] as $context => $priorities ) {
          if ( ! is_array( $priorities ) ) {
            continue;
          }
          foreach ( $priorities as $priority => $widgets ) {
            if ( ! is_array( $widgets ) ) {
              continue;
            }
            foreach ( $widgets as $widget_id => $widget_data ) {
              if ( empty( $widget_id ) || $widget_id === false ) {
                continue;
              }
              
              // Skip our own custom widgets (pdt_custom_ prefix)
              if ( strpos( $widget_id, 'pdt_custom_' ) === 0 ) {
                continue;
              }
              
              // Skip core WordPress widgets
              if ( in_array( $widget_id, $this->core_widgets, true ) || strpos( $widget_id, 'dashboard_' ) === 0 ) {
                continue;
              }
              
              // Skip whitelisted widgets
              if ( in_array( $widget_id, $whitelist, true ) ) {
                continue;
              }
              
              // Hide this 3rd party widget
              remove_meta_box( $widget_id, 'dashboard', $context );
            }
          }
        }
      }
    }

    // User-specific widget hiding
    if ( isset( $settings['widget_user_visibility'][ $current_user_id ] ) ) {
      $user_hidden = $settings['widget_user_visibility'][ $current_user_id ];
      
      foreach ( $user_hidden as $widget_id ) {
        remove_meta_box( $widget_id, 'dashboard', 'normal' );
        remove_meta_box( $widget_id, 'dashboard', 'side' );
        remove_meta_box( $widget_id, 'dashboard', 'column3' );
        remove_meta_box( $widget_id, 'dashboard', 'column4' );
      }
    }
  }

  /**
   * Capture and optionally log hidden notices
   */
  public function capture_notices() {
    $settings = $this->get_settings();

    if ( ! $this->should_apply_notice_hiding( $settings ) ) {
      return;
    }

    // Start output buffering once to mark whitelisted notices and log hidden count.
    if ( $this->notice_buffer_started ) {
      return;
    }
    $this->notice_buffer_started = true;
    ob_start( array( $this, 'filter_notices_buffer' ) );
  }

  /**
   * Filter notices HTML buffer: mark whitelisted notices and log hidden count.
   *
   * @param string $buffer Buffered output.
   * @return string
   */
  public function filter_notices_buffer( $buffer ) {
    $settings = $this->get_settings();
    $whitelist = isset( $settings['notice_whitelist'] ) && is_array( $settings['notice_whitelist'] ) ? $settings['notice_whitelist'] : array();
    $normalized_whitelist = array_filter( array_map( 'strtolower', array_map( 'trim', $whitelist ) ) );

    $notice_tag_pattern = '/<div\b[^>]*class=(["\'])[^"\']*(?:notice|updated|update-nag|error|is-dismissible)[^"\']*\1[^>]*>/i';
    $all_notice_count = 0;
    if ( preg_match_all( $notice_tag_pattern, $buffer, $all_matches ) ) {
      foreach ( $all_matches[0] as $matched_notice_tag ) {
        if ( false !== stripos( $matched_notice_tag, 'update-message' ) ) {
          continue;
        }
        $all_notice_count++;
      }
    }
    $whitelisted_count = 0;

    if ( ! empty( $normalized_whitelist ) ) {
      $buffer = preg_replace_callback(
        $notice_tag_pattern,
        function( $matches ) use ( $normalized_whitelist, &$whitelisted_count ) {
          $tag = $matches[0];

          // Keep inline WordPress update rows visible on plugins/themes screens.
          if ( false !== stripos( $tag, 'update-message' ) ) {
            return $tag;
          }

          $tag_lc = strtolower( $tag );
          foreach ( $normalized_whitelist as $slug ) {
            if ( '' !== $slug && false !== strpos( $tag_lc, $slug ) ) {
              $whitelisted_count++;
              if ( false === strpos( $tag, 'pdt-whitelist-notice' ) ) {
                $tag = preg_replace(
                  '/class=(["\'])([^"\']*)\1/i',
                  'class=$1$2 pdt-whitelist-notice$1',
                  $tag,
                  1
                );
              }
              break;
            }
          }
          return $tag;
        },
        $buffer
      );
    }

    $hidden_count = max( 0, (int) $all_notice_count - (int) $whitelisted_count );
    if ( ! empty( $settings['log_hidden_notices'] ) && $hidden_count > 0 ) {
      global $pdt_activity_log;
      if ( $pdt_activity_log && method_exists( $pdt_activity_log, 'log' ) ) {
        $pdt_activity_log->log(
          'admin_notices_hidden',
          'admin_notice',
          null,
          __( 'Hidden admin notices', 'polanger-admin-menu-manager' ),
          array(
            'hidden_count' => $hidden_count,
            'whitelisted_count' => $whitelisted_count,
            'screen' => function_exists( 'get_current_screen' ) && get_current_screen() ? get_current_screen()->id : '',
          )
        );
      }
    }

    return $buffer;
  }

  /**
   * Add custom widgets to dashboard
   */
  public function add_custom_welcome_widget() {
    $settings = $this->get_settings();

    if ( empty( $settings['custom_widgets'] ) ) {
      return;
    }

    foreach ( $settings['custom_widgets'] as $index => $widget ) {
      if ( empty( $widget['enabled'] ) || empty( $widget['title'] ) ) {
        continue;
      }

      $widget_id = ! empty( $widget['id'] ) ? $widget['id'] : 'pdt_custom_' . $index;
      $position  = ! empty( $widget['position'] ) ? $widget['position'] : 'normal';

      wp_add_dashboard_widget(
        $widget_id,
        $widget['title'],
        function() use ( $widget ) {
          $this->render_custom_widget_content( $widget );
        },
        null,
        null,
        $position,
        'high'
      );
    }
  }

  /**
   * Render custom widget content
   */
  private function render_custom_widget_content( $widget ) {
    ?>
    <div class="pdt-custom-widget-content">
      <?php if ( ! empty( $widget['content'] ) ) : ?>
        <?php echo wp_kses( $widget['content'], $this->get_custom_widget_allowed_html() ); ?>
      <?php else : ?>
        <p class="pdt-widget-empty"><?php esc_html_e( 'No content added yet.', 'polanger-admin-menu-manager' ); ?></p>
      <?php endif; ?>
    </div>
    <?php
  }

  /**
   * Sanitize custom widget content with safe extended HTML support.
   *
   * @param string $content Raw widget content.
   * @return string
   */
  private function sanitize_custom_widget_content( $content ) {
    return wp_kses( (string) $content, $this->get_custom_widget_allowed_html() );
  }

  /**
   * Allow safe HTML tags/attributes for custom widgets.
   *
   * @return array<string, array|string>
   */
  private function get_custom_widget_allowed_html() {
    $allowed_html = wp_kses_allowed_html( 'post' );
    $allowed_html['style'] = array(
      'id'    => true,
      'class' => true,
      'media' => true,
      'type'  => true,
    );
    return $allowed_html;
  }

  /**
   * Enqueue assets
   */
  public function enqueue_assets( $hook ) {
    // Only on our settings page
    if ( 'polanger_page_polanger-dashboard-widgets' !== $hook ) {
      return;
    }

    wp_enqueue_style(
      'pdt-dashboard-widgets',
      plugin_dir_url( __FILE__ ) . 'css/dashboard-widgets.css',
      array(),
      '1.0.0'
    );

    wp_enqueue_script(
      'pdt-dashboard-widgets',
      plugin_dir_url( __FILE__ ) . 'js/dashboard-widgets.js',
      array( 'jquery' ),
      '1.0.0',
      true
    );

    wp_localize_script(
      'pdt-dashboard-widgets',
      'pdtDashboardWidgetsI18n',
      array(
        'hiddenLabel'         => __( 'Hidden', 'polanger-admin-menu-manager' ),
        'visibleLabel'        => __( 'Visible', 'polanger-admin-menu-manager' ),
        'removeWidgetConfirm' => __( 'Are you sure you want to remove this widget?', 'polanger-admin-menu-manager' ),
        'untitledWidget'      => __( 'Untitled Widget', 'polanger-admin-menu-manager' ),
        'unsavedChanges'      => __( 'You have unsaved changes. Are you sure you want to leave?', 'polanger-admin-menu-manager' ),
      )
    );
  }

  /**
   * Enqueue runtime assets used on admin pages.
   */
  public function enqueue_runtime_assets() {
    $settings = $this->get_settings();

    if ( ! $this->should_apply_notice_hiding( $settings ) ) {
      return;
    }

    wp_enqueue_style(
      'pdt-dashboard-notices-runtime',
      plugin_dir_url( __FILE__ ) . 'css/admin-notices-runtime.css',
      array(),
      PDT_VERSION
    );
  }

  /**
   * Get current tab
   */
  private function get_current_tab() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    return isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'widgets';
  }

  /**
   * Determine whether notice hiding should run on current request.
   *
   * @param array $settings Settings array.
   * @return bool
   */
  private function should_apply_notice_hiding( $settings ) {
    if ( empty( $settings['hide_all_notices'] ) ) {
      return false;
    }

    // Super admin exception.
    if ( isset( $settings['notice_exception'] ) && $settings['notice_exception'] === 'super_admin' && $this->is_super_admin() ) {
      return false;
    }

    // Dashboard-only exception.
    if ( isset( $settings['notice_exception'] ) && $settings['notice_exception'] === 'dashboard_only' ) {
      global $pagenow;
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended
      $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
      if ( $pagenow === 'index.php' && '' === $page ) {
        return false;
      }
    }

    return true;
  }

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

    if ( ! $this->should_apply_notice_hiding( $settings ) ) {
      return $classes;
    }

    return trim( $classes . ' pdt-hide-admin-notices' );
  }

  /**
   * Render settings page
   */
  public function render_settings_page() {
    $settings    = $this->get_settings();
    $current_tab = $this->get_current_tab();

    $tabs = array(
      'widgets'  => __( 'Widget Visibility', 'polanger-admin-menu-manager' ),
      'notices'  => __( 'Admin Notices', 'polanger-admin-menu-manager' ),
      'custom'   => __( 'Custom Widgets', 'polanger-admin-menu-manager' ),
    );
    ?>
    <div class="pdt-dw-container">
      <!-- Tab Navigation -->
      <div class="pdt-dw-tabs">
        <?php foreach ( $tabs as $tab_id => $tab_label ) : ?>
          <a href="<?php echo esc_url( admin_url( 'admin.php?page=polanger-dashboard-widgets&tab=' . $tab_id ) ); ?>" 
             class="pdt-dw-tab <?php echo $current_tab === $tab_id ? 'active' : ''; ?>">
            <?php if ( $tab_id === 'widgets' ) : ?>
              <span class="dashicons dashicons-screenoptions"></span>
            <?php elseif ( $tab_id === 'notices' ) : ?>
              <span class="dashicons dashicons-bell"></span>
            <?php elseif ( $tab_id === 'custom' ) : ?>
              <span class="dashicons dashicons-plus-alt"></span>
            <?php endif; ?>
            <?php echo esc_html( $tab_label ); ?>
          </a>
        <?php endforeach; ?>
      </div>

      <!-- Tab Content -->
      <form method="post" action="options.php" class="pdt-dw-form">
        <?php settings_fields( 'pdt_dashboard_widgets_group' ); ?>
        <input type="hidden" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[active_tab]" value="<?php echo esc_attr( $current_tab ); ?>" />

        <div class="pdt-dw-content">
          <?php
          switch ( $current_tab ) {
            case 'notices':
              $this->render_notices_tab( $settings );
              break;
            case 'custom':
              $this->render_welcome_tab( $settings );
              break;
            default:
              $this->render_widgets_tab( $settings );
              break;
          }
          ?>
        </div>

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

  /**
   * Render Widgets tab
   */
  private function render_widgets_tab( $settings ) {
    $default_widgets = array(
      'welcome'           => array(
        'id'    => 'hide_welcome',
        'label' => __( 'Welcome Panel', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'The "Welcome to WordPress" panel shown to new users', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-admin-home',
      ),
      'quick_draft'       => array(
        'id'    => 'hide_quick_draft',
        'label' => __( 'Quick Draft', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Quick post drafting widget', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-edit',
      ),
      'activity'          => array(
        'id'    => 'hide_activity',
        'label' => __( 'Activity', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Recent comments and published posts', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-chart-area',
      ),
      'primary'           => array(
        'id'    => 'hide_primary',
        'label' => __( 'WordPress Events and News', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'WordPress community events and news feed', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-wordpress',
      ),
      'site_health'       => array(
        'id'    => 'hide_site_health',
        'label' => __( 'Site Health Status', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Site health and performance information', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-heart',
      ),
      'at_a_glance'       => array(
        'id'    => 'hide_at_a_glance',
        'label' => __( 'At a Glance', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Overview of posts, pages, comments, and WordPress version', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-chart-bar',
      ),
      'recent_comments'   => array(
        'id'    => 'hide_recent_comments',
        'label' => __( 'Recent Comments', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Latest comments moderation and quick actions', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-admin-comments',
      ),
      'recent_drafts'     => array(
        'id'    => 'hide_recent_drafts',
        'label' => __( 'Recent Drafts', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Recently saved draft posts', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-media-text',
      ),
      'browser_nag'       => array(
        'id'    => 'hide_browser_nag',
        'label' => __( 'Browser Upgrade Notice', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'WordPress browser compatibility recommendation', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-warning',
      ),
      'php_nag'           => array(
        'id'    => 'hide_php_nag',
        'label' => __( 'PHP Update Recommended', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Core recommendation to update PHP version', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-warning',
      ),
      'plugins'           => array(
        'id'    => 'hide_plugins_widget',
        'label' => __( 'Plugins', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Recently active plugins and plugin-related updates', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-admin-plugins',
      ),
      'incoming_links'    => array(
        'id'    => 'hide_incoming_links',
        'label' => __( 'Incoming Links (Legacy)', 'polanger-admin-menu-manager' ),
        'desc'  => __( 'Legacy incoming links widget used by older setups', 'polanger-admin-menu-manager' ),
        'icon'  => 'dashicons-admin-links',
      ),
    );
    ?>
    <div class="pdt-dw-section">
      <h3 class="pdt-dw-section-title">
        <span class="dashicons dashicons-visibility"></span>
        <?php esc_html_e( 'Hide Default Widgets', 'polanger-admin-menu-manager' ); ?>
      </h3>
      <p class="pdt-dw-section-desc"><?php esc_html_e( 'Select which default dashboard widgets to hide from all users.', 'polanger-admin-menu-manager' ); ?></p>

      <div class="pdt-dw-widget-grid">
        <?php foreach ( $default_widgets as $widget ) : ?>
          <label class="pdt-dw-widget-card <?php echo ! empty( $settings[ $widget['id'] ] ) ? 'is-hidden' : ''; ?>">
            <div class="pdt-dw-widget-header">
              <span class="dashicons <?php echo esc_attr( $widget['icon'] ); ?>"></span>
              <span class="pdt-dw-widget-title"><?php echo esc_html( $widget['label'] ); ?></span>
            </div>
            <p class="pdt-dw-widget-desc"><?php echo esc_html( $widget['desc'] ); ?></p>
            <div class="pdt-dw-widget-toggle">
              <input type="checkbox" 
                     name="<?php echo esc_attr( self::OPTION_NAME ); ?>[<?php echo esc_attr( $widget['id'] ); ?>]" 
                     value="1" 
                     <?php checked( ! empty( $settings[ $widget['id'] ] ) ); ?> />
              <span class="pdt-dw-toggle-label">
                <?php echo ! empty( $settings[ $widget['id'] ] ) ? esc_html__( 'Hidden', 'polanger-admin-menu-manager' ) : esc_html__( 'Visible', 'polanger-admin-menu-manager' ); ?>
              </span>
            </div>
          </label>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Auto-hide Future Widgets Section -->
    <div class="pdt-dw-section pdt-dw-section-spaced">
      <h3 class="pdt-dw-section-title">
        <span class="dashicons dashicons-shield"></span>
        <?php esc_html_e( 'Auto-Hide Future Widgets', 'polanger-admin-menu-manager' ); ?>
      </h3>
      <p class="pdt-dw-section-desc"><?php esc_html_e( 'Automatically hide all third-party widgets added by plugins and themes. Keep your dashboard clean!', 'polanger-admin-menu-manager' ); ?></p>

      <div class="pdt-dw-option-card pdt-dw-main-toggle pdt-dw-auto-hide-card">
        <div class="pdt-dw-option-header">
          <label class="pdt-dw-switch">
            <input type="checkbox" 
                   name="<?php echo esc_attr( self::OPTION_NAME ); ?>[auto_hide_new_widgets]" 
                   value="1" 
                   id="pdt-auto-hide-widgets"
                   <?php checked( ! empty( $settings['auto_hide_new_widgets'] ) ); ?> />
            <span class="pdt-dw-switch-slider"></span>
          </label>
          <div class="pdt-dw-option-text">
            <strong><?php esc_html_e( 'Auto-Hide All Third-Party Widgets', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'When enabled, any widget added by plugins or themes will be automatically hidden. Use the whitelist below to allow specific widgets.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      </div>

      <!-- Whitelist Section -->
      <div class="pdt-dw-sub-options <?php echo ! empty( $settings['auto_hide_new_widgets'] ) ? '' : 'pdt-dw-is-hidden'; ?>" id="pdt-whitelist-options">
        <div class="pdt-dw-option-card">
          <h4>
            <span class="dashicons dashicons-yes-alt pdt-dw-icon-success"></span>
            <?php esc_html_e( 'Widget Whitelist', 'polanger-admin-menu-manager' ); ?>
          </h4>
          <p class="description"><?php esc_html_e( 'Select which third-party widgets should remain visible even with auto-hide enabled. Perfect for important widgets like WooCommerce status.', 'polanger-admin-menu-manager' ); ?></p>
          
          <?php
          // Get detected 3rd party widgets for whitelist
          $detected_for_whitelist = $this->get_detected_widgets();
          $whitelist = isset( $settings['widget_whitelist'] ) ? $settings['widget_whitelist'] : array();
          $third_party_for_whitelist = array();
          
          $core_ids = array(
            'dashboard_quick_press', 'dashboard_activity', 'dashboard_primary',
            'dashboard_site_health', 'dashboard_right_now', 'dashboard_recent_comments', 'welcome-panel',
          );
          
          foreach ( $detected_for_whitelist as $wid => $wdata ) {
            if ( ! in_array( $wid, $core_ids, true ) && ! $wdata['is_core'] ) {
              $third_party_for_whitelist[ $wid ] = $wdata;
            }
          }
          
          if ( ! empty( $third_party_for_whitelist ) ) :
          ?>
          <div class="pdt-dw-whitelist-grid">
            <?php foreach ( $third_party_for_whitelist as $wid => $wdata ) : 
              $is_whitelisted = in_array( $wid, $whitelist, true );
            ?>
              <label class="pdt-dw-whitelist-item <?php echo $is_whitelisted ? 'is-whitelisted' : ''; ?>">
                <input type="checkbox" 
                       name="<?php echo esc_attr( self::OPTION_NAME ); ?>[widget_whitelist][]" 
                       value="<?php echo esc_attr( $wid ); ?>" 
                       <?php checked( $is_whitelisted ); ?> />
                <span class="dashicons <?php echo $is_whitelisted ? 'dashicons-yes-alt' : 'dashicons-marker'; ?>"></span>
                <span class="pdt-dw-whitelist-title"><?php echo esc_html( $wdata['title'] ); ?></span>
              </label>
            <?php endforeach; ?>
          </div>
          <?php else : ?>
          <div class="pdt-dw-no-widgets-notice">
            <span class="dashicons dashicons-info-outline"></span>
            <p><?php esc_html_e( 'No third-party widgets detected yet. Visit your Dashboard first, then return here to configure the whitelist.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
          <?php endif; ?>
        </div>
      </div>

      <div class="pdt-dw-info-box pdt-dw-info-success pdt-dw-info-tight">
        <span class="dashicons dashicons-yes-alt"></span>
        <div>
          <strong><?php esc_html_e( 'Clean Dashboard Guarantee', 'polanger-admin-menu-manager' ); ?></strong>
          <p><?php esc_html_e( 'With auto-hide enabled, your dashboard stays clean even when you install new plugins. Only whitelisted widgets (like WooCommerce) will appear.', 'polanger-admin-menu-manager' ); ?></p>
        </div>
      </div>
    </div>

    <?php
    // Get detected 3rd party widgets
    $detected_widgets = $this->get_detected_widgets();
    $third_party_widgets = array();
    
    // Filter out core widgets
    $core_widget_ids = array(
      'dashboard_quick_press',
      'dashboard_activity',
      'dashboard_primary',
      'dashboard_site_health',
      'dashboard_right_now',
      'dashboard_recent_comments',
      'welcome-panel',
    );
    
    foreach ( $detected_widgets as $widget_id => $widget_data ) {
      if ( ! in_array( $widget_id, $core_widget_ids, true ) && ! $widget_data['is_core'] ) {
        $third_party_widgets[ $widget_id ] = $widget_data;
      }
    }
    
    $hidden_widgets = isset( $settings['hidden_widgets'] ) ? $settings['hidden_widgets'] : array();
    
    if ( ! empty( $third_party_widgets ) ) :
    ?>
    <div class="pdt-dw-section pdt-dw-section-spaced">
      <h3 class="pdt-dw-section-title">
        <span class="dashicons dashicons-admin-plugins"></span>
        <?php esc_html_e( 'Third-Party Widgets', 'polanger-admin-menu-manager' ); ?>
      </h3>
      <p class="pdt-dw-section-desc"><?php esc_html_e( 'Widgets added by plugins and themes. These are automatically detected from your dashboard.', 'polanger-admin-menu-manager' ); ?></p>

      <div class="pdt-dw-widget-grid">
        <?php foreach ( $third_party_widgets as $widget_id => $widget_data ) : 
          $is_hidden = in_array( $widget_id, $hidden_widgets, true );
        ?>
          <label class="pdt-dw-widget-card pdt-dw-third-party <?php echo $is_hidden ? 'is-hidden' : ''; ?>">
            <div class="pdt-dw-widget-header">
              <span class="dashicons dashicons-admin-plugins"></span>
              <span class="pdt-dw-widget-title"><?php echo esc_html( $widget_data['title'] ); ?></span>
            </div>
            <p class="pdt-dw-widget-desc">
              <?php 
              /* translators: %s: Dashboard widget ID wrapped in code tags. */
              printf( 
                /* translators: %s: Dashboard widget ID. */
                wp_kses_post( __( 'Widget ID: %s', 'polanger-admin-menu-manager' ) ),
                '<code>' . esc_html( $widget_id ) . '</code>' 
              ); 
              ?>
            </p>
            <div class="pdt-dw-widget-toggle">
              <input type="checkbox" 
                     name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hidden_widgets][]" 
                     value="<?php echo esc_attr( $widget_id ); ?>" 
                     <?php checked( $is_hidden ); ?> />
              <span class="pdt-dw-toggle-label">
                <?php echo $is_hidden ? esc_html__( 'Hidden', 'polanger-admin-menu-manager' ) : esc_html__( 'Visible', 'polanger-admin-menu-manager' ); ?>
              </span>
            </div>
          </label>
        <?php endforeach; ?>
      </div>
    </div>
    <?php else : ?>
    <div class="pdt-dw-info-box">
      <span class="dashicons dashicons-info-outline"></span>
      <div>
        <strong><?php esc_html_e( 'Third-Party Widgets', 'polanger-admin-menu-manager' ); ?></strong>
        <p><?php esc_html_e( 'No third-party widgets detected yet. Visit your Dashboard first to detect widgets added by plugins and themes, then return here to manage them.', 'polanger-admin-menu-manager' ); ?></p>
        <p class="pdt-dw-paragraph-spaced">
          <a href="<?php echo esc_url( admin_url( 'index.php' ) ); ?>" class="button">
            <span class="dashicons dashicons-dashboard pdt-dw-icon-dashboard"></span>
            <?php esc_html_e( 'Go to Dashboard to Detect Widgets', 'polanger-admin-menu-manager' ); ?>
          </a>
        </p>
      </div>
    </div>
    <?php endif; ?>

    <div class="pdt-dw-info-box pdt-dw-info-medium">
      <span class="dashicons dashicons-lightbulb"></span>
      <div>
        <strong><?php esc_html_e( 'How It Works', 'polanger-admin-menu-manager' ); ?></strong>
        <p><?php esc_html_e( 'Widgets are automatically detected when you visit the Dashboard. Any new widgets added by plugins will appear here after you visit the Dashboard page.', 'polanger-admin-menu-manager' ); ?></p>
      </div>
    </div>
    <?php
  }

  /**
   * Render Notices tab
   */
  private function render_notices_tab( $settings ) {
    ?>
    <div class="pdt-dw-section">
      <h3 class="pdt-dw-section-title">
        <span class="dashicons dashicons-bell"></span>
        <?php esc_html_e( 'Admin Notice Manager', 'polanger-admin-menu-manager' ); ?>
      </h3>
      <p class="pdt-dw-section-desc"><?php esc_html_e( 'Control the visibility of admin notices and alerts from plugins and themes.', 'polanger-admin-menu-manager' ); ?></p>

      <!-- Main Toggle -->
      <div class="pdt-dw-option-card pdt-dw-main-toggle">
        <div class="pdt-dw-option-header">
          <label class="pdt-dw-switch">
            <input type="checkbox" 
                   name="<?php echo esc_attr( self::OPTION_NAME ); ?>[hide_all_notices]" 
                   value="1" 
                   id="pdt-hide-all-notices"
                   <?php checked( $settings['hide_all_notices'] ); ?> />
            <span class="pdt-dw-switch-slider"></span>
          </label>
          <div class="pdt-dw-option-text">
            <strong><?php esc_html_e( 'Hide All Admin Notices', 'polanger-admin-menu-manager' ); ?></strong>
            <p><?php esc_html_e( 'Hide all plugin and theme notices, warnings, and update nags from the admin area.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      </div>

      <!-- Exception Settings -->
      <div class="pdt-dw-sub-options <?php echo $settings['hide_all_notices'] ? '' : 'pdt-dw-is-hidden'; ?>" id="pdt-notice-options">
        
        <div class="pdt-dw-option-card">
          <h4><?php esc_html_e( 'Exception Rule', 'polanger-admin-menu-manager' ); ?></h4>
          <p class="description"><?php esc_html_e( 'Choose who can still see admin notices.', 'polanger-admin-menu-manager' ); ?></p>
          
          <div class="pdt-dw-radio-group">
            <label class="pdt-dw-radio">
              <input type="radio" 
                     name="<?php echo esc_attr( self::OPTION_NAME ); ?>[notice_exception]" 
                     value="none" 
                     <?php checked( $settings['notice_exception'], 'none' ); ?> />
              <span class="pdt-dw-radio-mark"></span>
              <span class="pdt-dw-radio-text">
                <strong><?php esc_html_e( 'Hide from everyone', 'polanger-admin-menu-manager' ); ?></strong>
                <small><?php esc_html_e( 'No one will see admin notices', 'polanger-admin-menu-manager' ); ?></small>
              </span>
            </label>
            
            <label class="pdt-dw-radio">
              <input type="radio" 
                     name="<?php echo esc_attr( self::OPTION_NAME ); ?>[notice_exception]" 
                     value="super_admin" 
                     <?php checked( $settings['notice_exception'], 'super_admin' ); ?> />
              <span class="pdt-dw-radio-mark"></span>
              <span class="pdt-dw-radio-text">
                <strong><?php esc_html_e( 'Super Admin can see all', 'polanger-admin-menu-manager' ); ?></strong>
                <small><?php esc_html_e( 'Only Super Admin sees notices (recommended)', 'polanger-admin-menu-manager' ); ?></small>
              </span>
            </label>
            
            <label class="pdt-dw-radio">
              <input type="radio" 
                     name="<?php echo esc_attr( self::OPTION_NAME ); ?>[notice_exception]" 
                     value="dashboard_only" 
                     <?php checked( $settings['notice_exception'], 'dashboard_only' ); ?> />
              <span class="pdt-dw-radio-mark"></span>
              <span class="pdt-dw-radio-text">
                <strong><?php esc_html_e( 'Show on Dashboard only', 'polanger-admin-menu-manager' ); ?></strong>
                <small><?php esc_html_e( 'Notices visible only on the main dashboard page', 'polanger-admin-menu-manager' ); ?></small>
              </span>
            </label>
          </div>
        </div>

        <div class="pdt-dw-option-card">
          <div class="pdt-dw-option-header">
            <label class="pdt-dw-switch pdt-dw-switch-small">
              <input type="checkbox" 
                     name="<?php echo esc_attr( self::OPTION_NAME ); ?>[log_hidden_notices]" 
                     value="1" 
                     <?php checked( $settings['log_hidden_notices'] ); ?> />
              <span class="pdt-dw-switch-slider"></span>
            </label>
            <div class="pdt-dw-option-text">
              <strong><?php esc_html_e( 'Log Hidden Notices', 'polanger-admin-menu-manager' ); ?></strong>
              <p><?php esc_html_e( 'Keep a record of hidden notices in the Activity Log for review.', 'polanger-admin-menu-manager' ); ?></p>
            </div>
          </div>
        </div>

        <div class="pdt-dw-option-card">
          <h4><?php esc_html_e( 'Notice Whitelist (Optional)', 'polanger-admin-menu-manager' ); ?></h4>
          <p class="description"><?php esc_html_e( 'Add class/id/plugin slugs to keep specific notices visible even when hide mode is enabled. Enter one value per line (or comma-separated). Example: woocommerce, rank-math, elementor', 'polanger-admin-menu-manager' ); ?></p>
          <textarea
            name="<?php echo esc_attr( self::OPTION_NAME ); ?>[notice_whitelist_text]"
            rows="4"
            class="large-text"
            placeholder="<?php echo esc_attr__( "woocommerce\nrank-math\nelementor", 'polanger-admin-menu-manager' ); ?>"><?php echo esc_textarea( implode( "\n", isset( $settings['notice_whitelist'] ) && is_array( $settings['notice_whitelist'] ) ? $settings['notice_whitelist'] : array() ) ); ?></textarea>
        </div>
      </div>
    </div>

    <div class="pdt-dw-info-box pdt-dw-info-warning">
      <span class="dashicons dashicons-warning"></span>
      <div>
        <strong><?php esc_html_e( 'Important Security Note', 'polanger-admin-menu-manager' ); ?></strong>
        <p><?php esc_html_e( 'Some notices contain critical security or update information. We recommend keeping "Super Admin can see all" enabled to ensure important alerts are not missed.', 'polanger-admin-menu-manager' ); ?></p>
      </div>
    </div>
    <?php
  }

  /**
   * Render Custom Widgets tab
   */
  private function render_welcome_tab( $settings ) {
    $custom_widgets = isset( $settings['custom_widgets'] ) ? $settings['custom_widgets'] : array();
    ?>
    <div class="pdt-dw-section">
      <h3 class="pdt-dw-section-title">
        <span class="dashicons dashicons-plus-alt"></span>
        <?php esc_html_e( 'Custom Widgets', 'polanger-admin-menu-manager' ); ?>
      </h3>
      <p class="pdt-dw-section-desc"><?php esc_html_e( 'Create custom dashboard widgets with your own content. Perfect for welcome messages, quick links, or important information.', 'polanger-admin-menu-manager' ); ?></p>

      <!-- Existing Widgets -->
      <div id="pdt-custom-widgets-list">
        <?php if ( ! empty( $custom_widgets ) ) : ?>
          <?php foreach ( $custom_widgets as $index => $widget ) : ?>
            <div class="pdt-dw-custom-widget-card" data-index="<?php echo esc_attr( $index ); ?>">
              <div class="pdt-dw-widget-card-header">
                <div class="pdt-dw-widget-card-title">
                  <span class="dashicons dashicons-screenoptions"></span>
                  <span class="pdt-dw-widget-name"><?php echo esc_html( $widget['title'] ?: __( 'Untitled Widget', 'polanger-admin-menu-manager' ) ); ?></span>
                </div>
                <div class="pdt-dw-widget-card-actions">
                  <label class="pdt-dw-mini-switch" title="<?php esc_attr_e( 'Enable/Disable', 'polanger-admin-menu-manager' ); ?>">
                    <input type="checkbox" 
                           name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][<?php echo esc_attr( $index ); ?>][enabled]" 
                           value="1" 
                           <?php checked( ! empty( $widget['enabled'] ) ); ?> />
                    <span class="pdt-dw-mini-slider"></span>
                  </label>
                  <button type="button" class="pdt-dw-toggle-widget" title="<?php esc_attr_e( 'Expand/Collapse', 'polanger-admin-menu-manager' ); ?>">
                    <span class="dashicons dashicons-arrow-down-alt2"></span>
                  </button>
                  <button type="button" class="pdt-dw-remove-widget" title="<?php esc_attr_e( 'Remove Widget', 'polanger-admin-menu-manager' ); ?>">
                    <span class="dashicons dashicons-trash"></span>
                  </button>
                </div>
              </div>
              <div class="pdt-dw-widget-card-body pdt-dw-is-hidden">
                <input type="hidden" 
                       name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][<?php echo esc_attr( $index ); ?>][id]" 
                       value="<?php echo esc_attr( $widget['id'] ?? 'pdt_custom_' . $index ); ?>" />
                
                <div class="pdt-dw-field-row">
                  <label class="pdt-dw-field-label"><?php esc_html_e( 'Widget Title', 'polanger-admin-menu-manager' ); ?></label>
                  <input type="text" 
                         name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][<?php echo esc_attr( $index ); ?>][title]" 
                         value="<?php echo esc_attr( $widget['title'] ); ?>" 
                         placeholder="<?php esc_attr_e( 'My Custom Widget', 'polanger-admin-menu-manager' ); ?>"
                         class="pdt-dw-input pdt-dw-widget-title-input" />
                </div>

                <div class="pdt-dw-field-row">
                  <label class="pdt-dw-field-label"><?php esc_html_e( 'Position', 'polanger-admin-menu-manager' ); ?></label>
                  <select name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][<?php echo esc_attr( $index ); ?>][position]" class="pdt-dw-select">
                    <option value="normal" <?php selected( $widget['position'] ?? 'normal', 'normal' ); ?>><?php esc_html_e( 'Left Column (Normal)', 'polanger-admin-menu-manager' ); ?></option>
                    <option value="side" <?php selected( $widget['position'] ?? 'normal', 'side' ); ?>><?php esc_html_e( 'Right Column (Side)', 'polanger-admin-menu-manager' ); ?></option>
                  </select>
                </div>

                <div class="pdt-dw-field-row">
                  <label class="pdt-dw-field-label"><?php esc_html_e( 'Content', 'polanger-admin-menu-manager' ); ?></label>
                  <?php
                  $editor_id = 'pdt_widget_content_' . $index;
                  $editor_settings = array(
                    'textarea_name' => self::OPTION_NAME . '[custom_widgets][' . $index . '][content]',
                    'textarea_rows' => 8,
                    'media_buttons' => true,
                    'teeny'         => false,
                    'quicktags'     => true,
                    'tinymce'       => array(
                      'toolbar1' => 'formatselect,bold,italic,underline,strikethrough,bullist,numlist,blockquote,hr,alignleft,aligncenter,alignright,link,unlink,wp_adv',
                      'toolbar2' => 'fontselect,fontsizeselect,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo',
                    ),
                  );
                  wp_editor( $widget['content'] ?? '', $editor_id, $editor_settings );
                  ?>
                  <p class="description pdt-dw-description-spaced"><?php esc_html_e( 'Use the visual editor to add formatted content, images, links, and more.', 'polanger-admin-menu-manager' ); ?></p>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>

      <!-- Add New Widget Button -->
      <button type="button" class="button button-primary pdt-dw-add-widget" id="pdt-add-custom-widget">
        <span class="dashicons dashicons-plus-alt2"></span>
        <?php esc_html_e( 'Add New Widget', 'polanger-admin-menu-manager' ); ?>
      </button>
    </div>

    <div class="pdt-dw-info-box pdt-dw-info-top">
      <span class="dashicons dashicons-lightbulb"></span>
      <div>
        <strong><?php esc_html_e( 'Pro Tips', 'polanger-admin-menu-manager' ); ?></strong>
        <ul class="pdt-dw-pro-tips-list">
          <li><?php esc_html_e( 'Create a "Welcome" widget with your agency branding and support info', 'polanger-admin-menu-manager' ); ?></li>
          <li><?php esc_html_e( 'Add a "Quick Links" widget with shortcuts to frequently used pages', 'polanger-admin-menu-manager' ); ?></li>
          <li><?php esc_html_e( 'Use HTML to add images, buttons, or formatted content', 'polanger-admin-menu-manager' ); ?></li>
        </ul>
      </div>
    </div>

    <!-- Widget Template (hidden, used by JS) -->
    <template id="pdt-widget-template">
      <div class="pdt-dw-custom-widget-card" data-index="{{INDEX}}">
        <div class="pdt-dw-widget-card-header">
          <div class="pdt-dw-widget-card-title">
            <span class="dashicons dashicons-screenoptions"></span>
            <span class="pdt-dw-widget-name"><?php esc_html_e( 'New Widget', 'polanger-admin-menu-manager' ); ?></span>
          </div>
          <div class="pdt-dw-widget-card-actions">
            <label class="pdt-dw-mini-switch" title="<?php esc_attr_e( 'Enable/Disable', 'polanger-admin-menu-manager' ); ?>">
              <input type="checkbox" 
                     name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][{{INDEX}}][enabled]" 
                     value="1" 
                     checked />
              <span class="pdt-dw-mini-slider"></span>
            </label>
            <button type="button" class="pdt-dw-toggle-widget" title="<?php esc_attr_e( 'Expand/Collapse', 'polanger-admin-menu-manager' ); ?>">
              <span class="dashicons dashicons-arrow-down-alt2"></span>
            </button>
            <button type="button" class="pdt-dw-remove-widget" title="<?php esc_attr_e( 'Remove Widget', 'polanger-admin-menu-manager' ); ?>">
              <span class="dashicons dashicons-trash"></span>
            </button>
          </div>
        </div>
        <div class="pdt-dw-widget-card-body">
          <input type="hidden" 
                 name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][{{INDEX}}][id]" 
                 value="pdt_custom_{{INDEX}}" />
          
          <div class="pdt-dw-field-row">
            <label class="pdt-dw-field-label"><?php esc_html_e( 'Widget Title', 'polanger-admin-menu-manager' ); ?></label>
            <input type="text" 
                   name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][{{INDEX}}][title]" 
                   value="" 
                   placeholder="<?php esc_attr_e( 'My Custom Widget', 'polanger-admin-menu-manager' ); ?>"
                   class="pdt-dw-input pdt-dw-widget-title-input" />
          </div>

          <div class="pdt-dw-field-row">
            <label class="pdt-dw-field-label"><?php esc_html_e( 'Position', 'polanger-admin-menu-manager' ); ?></label>
            <select name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][{{INDEX}}][position]" class="pdt-dw-select">
              <option value="normal"><?php esc_html_e( 'Left Column (Normal)', 'polanger-admin-menu-manager' ); ?></option>
              <option value="side"><?php esc_html_e( 'Right Column (Side)', 'polanger-admin-menu-manager' ); ?></option>
            </select>
          </div>

          <div class="pdt-dw-field-row">
            <label class="pdt-dw-field-label"><?php esc_html_e( 'Content', 'polanger-admin-menu-manager' ); ?></label>
            <textarea name="<?php echo esc_attr( self::OPTION_NAME ); ?>[custom_widgets][{{INDEX}}][content]" 
                      rows="8" 
                      class="pdt-dw-textarea pdt-dw-content-textarea"
                      placeholder="<?php esc_attr_e( 'Enter your widget content here. HTML is supported.', 'polanger-admin-menu-manager' ); ?>"></textarea>
            <p class="description"><?php esc_html_e( 'Save to enable the visual editor with full formatting options.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>
      </div>
    </template>
    <?php
  }
}
