<?php
/**
 * Design System settings page.
 *
 * @package Polanger_Dashboard_Tools
 */

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

/**
 * Renders and saves addon settings.
 */
class PDT_Design_Preview {
  /**
   * @var PDT_Design_Settings
   */
  private $settings;

  /**
   * @var PDT_Design_Generator
   */
  private $generator;

  /**
   * Constructor.
   *
   * @param PDT_Design_Settings  $settings  Settings helper.
   * @param PDT_Design_Generator $generator CSS generator.
   */
  public function __construct( $settings, $generator ) {
    $this->settings  = $settings;
    $this->generator = $generator;
  }

  /**
   * Register submenu in Polanger main menu.
   *
   * @return void
   */
  public function register_menu() {
    if ( ! current_user_can( 'manage_options' ) ) {
      return;
    }

    add_submenu_page(
      'polanger-dashboard',
      __( 'Design System', 'polanger-admin-menu-manager' ),
      __( 'Design System', 'polanger-admin-menu-manager' ),
      'manage_options',
      'polanger-design-system',
      array( $this, 'render_page' )
    );
  }

  /**
   * Load settings page assets.
   *
   * @return void
   */
  public function enqueue_page_assets() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
    if ( 'polanger-design-system' !== $page ) {
      return;
    }

    wp_enqueue_style(
      'pdt-admin-style',
      plugin_dir_url( PDT_PLUGIN_FILE ) . 'assets/css/pdt.css',
      array(),
      PDT_VERSION
    );
    wp_enqueue_style(
      'pdt-settings-style',
      plugin_dir_url( PDT_PLUGIN_FILE ) . 'assets/css/settings-page.css',
      array( 'pdt-admin-style' ),
      PDT_VERSION
    );
		wp_enqueue_style(
			'pdt-design-ui',
			plugin_dir_url( dirname( __FILE__ ) ) . 'assets/ui.css',
			array( 'pdt-admin-style', 'pdt-settings-style' ),
			PDT_VERSION
		);

		if ( class_exists( 'PDT_Design_Themes' ) ) {
			foreach ( PDT_Design_Themes::get_assets( 'preview.css' ) as $preset => $asset ) {
				wp_enqueue_style(
					'pdt-design-preview-theme-' . sanitize_key( $preset ),
					set_url_scheme( $asset['url'] ),
					array( 'pdt-design-ui' ),
					$asset['version']
				);
			}
		}

		wp_enqueue_script(
			'pdt-design-preview',
			plugin_dir_url( dirname( __FILE__ ) ) . 'assets/preview.js',
      array(),
      PDT_VERSION,
      true
    );
    wp_localize_script(
      'pdt-design-preview',
      'pdtDesignPresets',
      array(
        'presets' => $this->settings->get_presets(),
      )
    );
  }

  /**
   * Render settings page.
   *
   * @return void
   */
  public function render_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
      return;
    }

    $settings = $this->settings->get_settings();
    if ( isset( $_POST['pdt_design_save'] ) && check_admin_referer( 'pdt_design_save' ) ) {
      $raw = isset( $_POST['pdt_design'] ) ? wp_unslash( $_POST['pdt_design'] ) : array();
      $settings = $this->settings->save_settings( $raw );
      $this->generator->compile_if_needed( $settings );
      echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Design settings saved.', 'polanger-admin-menu-manager' ) . '</p></div>';
    }

    $resolved = $this->generator->resolve_tokens( $settings );
    $selected_screens = isset( $settings['selected_screens'] ) && is_array( $settings['selected_screens'] ) ? $settings['selected_screens'] : array();
    $screen_options = $this->settings->get_screen_options();
    $scope_options = $this->settings->get_scope_options();
    ?>
    <div id="pdt-wrap" class="pdt-design-wrap">
      <div class="pdt-header">
        <h2 class="pdt-title"><?php esc_html_e( 'Design System', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="pdt-subtitle"><?php esc_html_e( 'A richer token-based admin design engine with WCAG-aware contrast, scope targeting, semantic colors, typography controls, and a live preview playground.', 'polanger-admin-menu-manager' ); ?></p>
      </div>

      <form method="post" class="pdt-settings-form pdt-design-form">
        <?php wp_nonce_field( 'pdt_design_save' ); ?>
        <input type="hidden" name="pdt_design_save" value="1" />

        <div class="pdt-settings-section">
          <h3><?php esc_html_e( 'General', 'polanger-admin-menu-manager' ); ?></h3>

          <div class="pdt-form-row">
            <label class="pdt-toggle-switch">
              <input type="checkbox" name="pdt_design[enabled]" value="1" <?php checked( ! empty( $settings['enabled'] ) ); ?> />
              <span class="pdt-toggle-slider"></span>
              <span class="pdt-toggle-label"><?php esc_html_e( 'Enable Design System', 'polanger-admin-menu-manager' ); ?></span>
            </label>
          </div>

          <div class="pdt-form-row">
            <label class="pdt-toggle-switch">
              <input type="checkbox" name="pdt_design[smart_contrast]" value="1" <?php checked( ! empty( $settings['smart_contrast'] ) ); ?> />
              <span class="pdt-toggle-slider"></span>
              <span class="pdt-toggle-label"><?php esc_html_e( 'Enable Smart Contrast Correction', 'polanger-admin-menu-manager' ); ?></span>
            </label>
            <p class="description"><?php esc_html_e( 'Uses WCAG contrast ratios to improve readability on common admin surfaces such as cards, tables, notices, and inputs.', 'polanger-admin-menu-manager' ); ?></p>
          </div>

          <?php $this->render_select_field( 'scope', __( 'Apply Scope', 'polanger-admin-menu-manager' ), $settings['scope'], $scope_options ); ?>

          <div id="pdt-design-selected-screens" class="pdt-design-screen-grid-wrap<?php echo ( 'selected_screens' === $settings['scope'] ) ? ' is-visible' : ''; ?>">
            <span class="pdt-design-field-label">
              <label><?php esc_html_e( 'Selected Screens', 'polanger-admin-menu-manager' ); ?></label>
              <?php $this->render_help_tooltip( 'selected_screens' ); ?>
            </span>
            <div class="pdt-design-screen-grid">
              <?php foreach ( $screen_options as $screen_key => $screen_label ) : ?>
                <label class="pdt-design-screen-chip">
                  <input type="checkbox" name="pdt_design[selected_screens][]" value="<?php echo esc_attr( $screen_key ); ?>" <?php checked( in_array( $screen_key, $selected_screens, true ) ); ?> />
                  <span><?php echo esc_html( $screen_label ); ?></span>
                </label>
              <?php endforeach; ?>
            </div>
            <p class="description"><?php esc_html_e( 'Use this mode to target only the parts of wp-admin you actually want to style, such as Dashboard, Posts, Settings, or only Polanger screens.', 'polanger-admin-menu-manager' ); ?></p>
          </div>

          <div class="pdt-form-row pdt-form-row--inline-actions">
            <span class="pdt-design-field-label">
              <label for="pdt-design-preset"><?php esc_html_e( 'Preset', 'polanger-admin-menu-manager' ); ?></label>
              <?php $this->render_help_tooltip( 'preset' ); ?>
            </span>
            <div class="pdt-design-inline-control">
              <select id="pdt-design-preset" name="pdt_design[preset]">
                <?php foreach ( $this->get_preset_select_options() as $option_value => $option_label ) : ?>
                  <option value="<?php echo esc_attr( $option_value ); ?>" <?php selected( $settings['preset'], $option_value ); ?>><?php echo esc_html( $option_label ); ?></option>
                <?php endforeach; ?>
              </select>
              <button type="button" class="button" id="pdt-design-apply-preset"><?php esc_html_e( 'Apply Preset', 'polanger-admin-menu-manager' ); ?></button>
            </div>
          </div>
        </div>

        <div class="pdt-settings-section">
          <h3><?php esc_html_e( 'Core Colors', 'polanger-admin-menu-manager' ); ?></h3>
          <?php $this->render_color_field( 'color_primary', __( 'Primary', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_color_field( 'color_bg', __( 'Background', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_color_field( 'color_surface', __( 'Surface', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_color_field( 'color_text', __( 'Text', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_color_field( 'color_muted', __( 'Muted Text', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_dual_color_field( 'sidebar_bg', __( 'Sidebar Background', 'polanger-admin-menu-manager' ), 'sidebar_text', __( 'Sidebar Text Color', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_dual_color_field( 'adminbar_bg', __( 'Admin Bar Background', 'polanger-admin-menu-manager' ), 'adminbar_text', __( 'Admin Bar Text Color', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_dual_color_field( 'adminbar_submenu_bg', __( 'Admin Bar Submenu Background', 'polanger-admin-menu-manager' ), 'adminbar_submenu_text', __( 'Admin Bar Submenu Text Color', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
        </div>

        <div class="pdt-settings-section">
          <h3><?php esc_html_e( 'Semantic Colors', 'polanger-admin-menu-manager' ); ?></h3>
          <p class="description"><?php esc_html_e( 'These advanced tokens let you fine-tune specific UI surfaces instead of relying on broad overrides only.', 'polanger-admin-menu-manager' ); ?></p>
          <?php $this->render_dual_color_field( 'color_border', __( 'Border', 'polanger-admin-menu-manager' ), 'color_hover', __( 'Hover Surface', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_dual_color_field( 'color_focus', __( 'Focus Ring', 'polanger-admin-menu-manager' ), 'color_input_bg', __( 'Input Background', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_dual_color_field( 'color_table_head', __( 'Table Header', 'polanger-admin-menu-manager' ), 'color_success', __( 'Success Accent', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_dual_color_field( 'color_warning', __( 'Warning Accent', 'polanger-admin-menu-manager' ), 'color_error', __( 'Error Accent', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
        </div>

        <div class="pdt-settings-section">
          <h3><?php esc_html_e( 'Links', 'polanger-admin-menu-manager' ); ?></h3>
          <p class="description"><?php esc_html_e( 'Customize link colors, hover behavior, underline style and weight. The admin menu, admin bar, and WordPress buttons are never affected.', 'polanger-admin-menu-manager' ); ?></p>

          <div class="pdt-form-row">
            <label class="pdt-toggle-switch">
              <input id="pdt-design-link-enabled" type="checkbox" name="pdt_design[link_enabled]" value="1" <?php checked( ! empty( $settings['link_enabled'] ) ); ?> />
              <span class="pdt-toggle-slider"></span>
              <span class="pdt-toggle-label"><?php esc_html_e( 'Enable custom link styling', 'polanger-admin-menu-manager' ); ?></span>
            </label>
            <p class="description"><?php esc_html_e( 'When disabled, links continue to inherit the Primary color.', 'polanger-admin-menu-manager' ); ?></p>
          </div>

          <?php $this->render_select_field( 'link_scope', __( 'Apply To', 'polanger-admin-menu-manager' ), $settings['link_scope'], array( 'content_only' => __( 'Content areas only', 'polanger-admin-menu-manager' ), 'all_admin' => __( 'All admin content (except menu, admin bar, and buttons)', 'polanger-admin-menu-manager' ) ) ); ?>
          <?php $this->render_color_field( 'link_color', __( 'Link Color', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_color_field( 'link_hover', __( 'Hover Color', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_color_field( 'link_visited', __( 'Visited Color', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_color_field( 'link_active', __( 'Active / Focus Color', 'polanger-admin-menu-manager' ), $settings, $resolved ); ?>
          <?php $this->render_select_field( 'link_decoration', __( 'Underline', 'polanger-admin-menu-manager' ), $settings['link_decoration'], array( 'none' => __( 'Never', 'polanger-admin-menu-manager' ), 'hover' => __( 'Only on hover', 'polanger-admin-menu-manager' ), 'underline' => __( 'Always', 'polanger-admin-menu-manager' ) ) ); ?>
          <?php $this->render_select_field( 'link_weight', __( 'Font Weight', 'polanger-admin-menu-manager' ), $settings['link_weight'], array( 'inherit' => __( 'Default (inherit)', 'polanger-admin-menu-manager' ), '400' => __( 'Regular (400)', 'polanger-admin-menu-manager' ), '500' => __( 'Medium (500)', 'polanger-admin-menu-manager' ), '600' => __( 'Semi-Bold (600)', 'polanger-admin-menu-manager' ), '700' => __( 'Bold (700)', 'polanger-admin-menu-manager' ) ) ); ?>
        </div>

        <div class="pdt-settings-section">
          <h3><?php esc_html_e( 'Typography & Shape', 'polanger-admin-menu-manager' ); ?></h3>
          <?php $this->render_select_field( 'font_family', __( 'Font Family', 'polanger-admin-menu-manager' ), $settings['font_family'], $this->settings->get_font_options() ); ?>
          <?php $this->render_select_field( 'type_scale', __( 'Type Scale', 'polanger-admin-menu-manager' ), $settings['type_scale'], $this->settings->get_type_scale_options() ); ?>
          <?php $this->render_select_field( 'density', __( 'Density', 'polanger-admin-menu-manager' ), $settings['density'], $this->settings->get_density_options() ); ?>
          <?php $this->render_select_field( 'spacing_scale', __( 'Spacing Scale', 'polanger-admin-menu-manager' ), $settings['spacing_scale'], $this->settings->get_spacing_scale_options() ); ?>
          <?php $this->render_select_field( 'button_radius_preset', __( 'Button Radius Preset', 'polanger-admin-menu-manager' ), $settings['button_radius_preset'], $this->settings->get_button_radius_options() ); ?>

          <div class="pdt-form-row">
            <span class="pdt-design-field-label">
              <label for="pdt-design-border_radius"><?php esc_html_e( 'Global Border Radius (px)', 'polanger-admin-menu-manager' ); ?></label>
              <?php $this->render_help_tooltip( 'border_radius' ); ?>
            </span>
            <input id="pdt-design-border_radius" type="number" min="0" max="24" name="pdt_design[border_radius]" value="<?php echo esc_attr( $settings['border_radius'] ); ?>" />
          </div>
        </div>

        <div class="pdt-settings-section">
          <h3><?php esc_html_e( 'Live Playground', 'polanger-admin-menu-manager' ); ?></h3>
          <p class="description"><?php esc_html_e( 'Preview how sidebar, admin bar, notices, tables, forms, buttons, and content links will look before saving.', 'polanger-admin-menu-manager' ); ?></p>

					<div id="pdt-design-playground" class="pdt-design-playground" data-pdt-design-preset="<?php echo esc_attr( $settings['preset'] ); ?>" style="<?php echo esc_attr( $this->get_playground_style( $resolved ) ); ?>">
            <div class="pdt-design-playground__adminbar">
              <div class="pdt-design-playground__adminbar-group">
                <span class="pdt-design-playground__adminbar-logo">W</span>
                <span class="pdt-design-playground__adminbar-link"><?php esc_html_e( 'Site', 'polanger-admin-menu-manager' ); ?></span>
                <span class="pdt-design-playground__adminbar-link"><?php esc_html_e( 'Comments', 'polanger-admin-menu-manager' ); ?></span>
              </div>
              <div class="pdt-design-playground__adminbar-group">
                <span class="pdt-design-playground__adminbar-link"><?php esc_html_e( 'Howdy, Admin', 'polanger-admin-menu-manager' ); ?></span>
              </div>
            </div>

            <div class="pdt-design-playground__shell">
              <aside class="pdt-design-playground__sidebar">
                <div class="pdt-design-playground__sidebar-title"><?php esc_html_e( 'Polanger', 'polanger-admin-menu-manager' ); ?></div>
                <a href="#" class="pdt-design-playground__menu-item is-current"><?php esc_html_e( 'Dashboard', 'polanger-admin-menu-manager' ); ?></a>
                <a href="#" class="pdt-design-playground__menu-item"><?php esc_html_e( 'Posts', 'polanger-admin-menu-manager' ); ?></a>
                <a href="#" class="pdt-design-playground__menu-item"><?php esc_html_e( 'Appearance', 'polanger-admin-menu-manager' ); ?></a>
                <a href="#" class="pdt-design-playground__menu-item"><?php esc_html_e( 'Settings', 'polanger-admin-menu-manager' ); ?></a>
              </aside>

              <div class="pdt-design-playground__content">
                <div class="pdt-design-playground__toolbar">
                  <div>
                    <h4><?php esc_html_e( 'Design Playground', 'polanger-admin-menu-manager' ); ?></h4>
                    <p><?php esc_html_e( 'This simulates a real admin screen with cards, tables, forms, and notices.', 'polanger-admin-menu-manager' ); ?></p>
                  </div>
                  <div class="pdt-design-playground__actions">
                    <button type="button" class="button button-secondary"><?php esc_html_e( 'Secondary', 'polanger-admin-menu-manager' ); ?></button>
                    <button type="button" class="button button-primary"><?php esc_html_e( 'Save Changes', 'polanger-admin-menu-manager' ); ?></button>
                  </div>
                </div>

                <div class="pdt-design-playground__notice-row">
                  <div class="pdt-design-playground__notice pdt-design-playground__notice--success"><?php esc_html_e( 'Success notice', 'polanger-admin-menu-manager' ); ?></div>
                  <div class="pdt-design-playground__notice pdt-design-playground__notice--warning"><?php esc_html_e( 'Warning notice', 'polanger-admin-menu-manager' ); ?></div>
                  <div class="pdt-design-playground__notice pdt-design-playground__notice--error"><?php esc_html_e( 'Error notice', 'polanger-admin-menu-manager' ); ?></div>
                </div>

                <div class="pdt-design-playground__grid">
                  <section class="pdt-design-playground__card">
                    <div class="pdt-design-playground__card-header">
                      <h5><?php esc_html_e( 'Table & Card Surface', 'polanger-admin-menu-manager' ); ?></h5>
                      <span class="pdt-design-playground__badge"><?php esc_html_e( 'Surface', 'polanger-admin-menu-manager' ); ?></span>
                    </div>
                    <p><?php esc_html_e( 'Card text, borders, and table headers should all remain readable under light or dark themes.', 'polanger-admin-menu-manager' ); ?></p>
                    <table class="pdt-design-playground__table">
                      <thead>
                        <tr>
                          <th><?php esc_html_e( 'Label', 'polanger-admin-menu-manager' ); ?></th>
                          <th><?php esc_html_e( 'Status', 'polanger-admin-menu-manager' ); ?></th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td><?php esc_html_e( 'Primary button', 'polanger-admin-menu-manager' ); ?></td>
                          <td><?php esc_html_e( 'Visible', 'polanger-admin-menu-manager' ); ?></td>
                        </tr>
                        <tr>
                          <td><?php esc_html_e( 'Hover state', 'polanger-admin-menu-manager' ); ?></td>
                          <td><?php esc_html_e( 'Readable', 'polanger-admin-menu-manager' ); ?></td>
                        </tr>
                      </tbody>
                    </table>
                  </section>

                  <section class="pdt-design-playground__card">
                    <div class="pdt-design-playground__card-header">
                      <h5><?php esc_html_e( 'Form & Links', 'polanger-admin-menu-manager' ); ?></h5>
                      <span class="pdt-design-playground__badge"><?php esc_html_e( 'Inputs', 'polanger-admin-menu-manager' ); ?></span>
                    </div>
                    <div class="pdt-design-playground__field">
                      <label><?php esc_html_e( 'Sample input', 'polanger-admin-menu-manager' ); ?></label>
                      <input type="text" value="<?php echo esc_attr__( 'Readable input background', 'polanger-admin-menu-manager' ); ?>" readonly />
                    </div>
                    <div class="pdt-design-playground__field">
                      <label><?php esc_html_e( 'Sample select', 'polanger-admin-menu-manager' ); ?></label>
                      <select>
                        <option><?php esc_html_e( 'Default option', 'polanger-admin-menu-manager' ); ?></option>
                      </select>
                    </div>
                    <p class="pdt-design-playground__link-copy">
                      <?php
                      printf(
                        /* translators: %s: sample preview link */
                        esc_html__( 'Need to preview content links too? Open this %s to inspect your current link styling.', 'polanger-admin-menu-manager' ),
                        '<a href="#" class="pdt-design-playground__link pdt-design-link-preview__link" data-pdt-link-preview="1">' . esc_html__( 'sample link', 'polanger-admin-menu-manager' ) . '</a>'
                      );
                      ?>
                    </p>
                  </section>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="pdt-settings-section">
          <h3><?php esc_html_e( 'Developer', 'polanger-admin-menu-manager' ); ?></h3>
          <div class="pdt-form-row pdt-form-row--textarea">
            <span class="pdt-design-field-label pdt-design-field-label--top">
              <label for="pdt-design-custom_css"><?php esc_html_e( 'Custom CSS (appended last)', 'polanger-admin-menu-manager' ); ?></label>
              <?php $this->render_help_tooltip( 'custom_css' ); ?>
            </span>
            <textarea id="pdt-design-custom_css" name="pdt_design[custom_css]" rows="10" class="pdt-design-code"><?php echo esc_textarea( $settings['custom_css'] ); ?></textarea>
            <p class="description"><?php esc_html_e( 'This CSS is appended after the generated stylesheet, so it can be used for final overrides or agency-specific tweaks.', 'polanger-admin-menu-manager' ); ?></p>
          </div>
        </div>

        <p class="submit">
          <button type="submit" class="button button-primary"><?php esc_html_e( 'Save Design Settings', 'polanger-admin-menu-manager' ); ?></button>
        </p>
      </form>
    </div>
    <?php
  }

  /**
   * Render reusable color field row.
   *
   * @param string $key Field key.
   * @param string $label Label.
   * @param array  $settings Current settings.
   * @param array  $resolved Resolved settings.
   * @return void
   */
  private function render_color_field( $key, $label, $settings, $resolved ) {
    $value = $this->get_display_color_value( $key, $settings, $resolved );
    ?>
    <p class="pdt-design-color-row">
      <span class="pdt-design-field-label">
        <label for="<?php echo esc_attr( 'pdt-design-' . $key ); ?>"><?php echo esc_html( $label ); ?></label>
        <?php $this->render_help_tooltip( $key ); ?>
      </span>
      <input id="<?php echo esc_attr( 'pdt-design-' . $key ); ?>" type="color" name="<?php echo esc_attr( 'pdt_design[' . $key . ']' ); ?>" value="<?php echo esc_attr( $value ); ?>" />
    </p>
    <?php
  }

  /**
   * Render two related color controls on the same row.
   *
   * @param string $left_key Left field key.
   * @param string $left_label Left field label.
   * @param string $right_key Right field key.
   * @param string $right_label Right field label.
   * @param array  $settings Current settings.
   * @param array  $resolved Resolved settings.
   * @return void
   */
  private function render_dual_color_field( $left_key, $left_label, $right_key, $right_label, $settings, $resolved ) {
    ?>
    <div class="pdt-design-color-pair">
      <div class="pdt-design-color-pair__item">
        <?php $this->render_color_field( $left_key, $left_label, $settings, $resolved ); ?>
      </div>
      <div class="pdt-design-color-pair__item">
        <?php $this->render_color_field( $right_key, $right_label, $settings, $resolved ); ?>
      </div>
    </div>
    <?php
  }

  /**
   * Render select field row.
   *
   * @param string $key Field key.
   * @param string $label Field label.
   * @param string $value Current value.
   * @param array  $options Select options.
   * @param bool   $show_description Whether to show the field description paragraph.
   * @return void
   */
  private function render_select_field( $key, $label, $value, $options, $show_description = true ) {
    ?>
    <div class="pdt-form-row">
      <span class="pdt-design-field-label">
        <label for="<?php echo esc_attr( 'pdt-design-' . $key ); ?>"><?php echo esc_html( $label ); ?></label>
        <?php $this->render_help_tooltip( $key ); ?>
      </span>
      <select id="<?php echo esc_attr( 'pdt-design-' . $key ); ?>" name="<?php echo esc_attr( 'pdt_design[' . $key . ']' ); ?>">
        <?php foreach ( $options as $option_value => $option_label ) : ?>
          <option value="<?php echo esc_attr( $option_value ); ?>" <?php selected( $value, $option_value ); ?>><?php echo esc_html( $option_label ); ?></option>
        <?php endforeach; ?>
      </select>
      <?php if ( $show_description ) : ?>
        <p class="description"><?php echo esc_html( $this->get_field_description( $key ) ); ?></p>
      <?php endif; ?>
    </div>
    <?php
  }

  /**
   * Render field help tooltip.
   *
   * @param string $key Field key.
   * @return void
   */
  private function render_help_tooltip( $key ) {
    $description = $this->get_field_description( $key );
    if ( '' === $description ) {
      return;
    }

    $tooltip_id = 'pdt-design-help-' . $key;
    ?>
    <span class="pdt-help-tooltip">
      <button
        type="button"
        class="pdt-help-tooltip__toggle"
        aria-label="<?php esc_attr_e( 'Field description', 'polanger-admin-menu-manager' ); ?>"
        aria-describedby="<?php echo esc_attr( $tooltip_id ); ?>"
      >i</button>
      <span id="<?php echo esc_attr( $tooltip_id ); ?>" class="pdt-help-tooltip__content" role="tooltip">
        <?php echo esc_html( $description ); ?>
      </span>
    </span>
    <?php
  }

  /**
   * Return field description text.
   *
   * @param string $key Field key.
   * @return string
   */
  private function get_field_description( $key ) {
    $descriptions = array(
      'scope' => __( 'Choose whether the design system should affect only Polanger screens, all of wp-admin, selected sections such as Dashboard or Posts, or all admin screens except plugin-owned pages.', 'polanger-admin-menu-manager' ),
      'selected_screens' => __( 'Only used when the scope is set to selected screens. This is the safest mode when you want fine-grained control and fewer third-party conflicts.', 'polanger-admin-menu-manager' ),
      'preset' => __( 'Quick-start design profiles. Presets now also include semantic colors and typography tuning so the whole interface stays more consistent.', 'polanger-admin-menu-manager' ),
      'color_primary' => __( 'Used for primary buttons, active states, selected menu items, and the strongest accent points.', 'polanger-admin-menu-manager' ),
      'color_bg' => __( 'Controls the broad page background behind admin cards and content layouts.', 'polanger-admin-menu-manager' ),
      'color_surface' => __( 'Used for cards, tables, settings panels, and most boxed content areas.', 'polanger-admin-menu-manager' ),
      'color_text' => __( 'Sets the default text color for body copy and headings across the admin interface.', 'polanger-admin-menu-manager' ),
      'color_muted' => __( 'Used for descriptions, helper copy, and less prominent labels.', 'polanger-admin-menu-manager' ),
      'sidebar_bg' => __( 'Changes the background color of the left admin sidebar.', 'polanger-admin-menu-manager' ),
      'sidebar_text' => __( 'Controls the icon and text color used inside the left admin sidebar.', 'polanger-admin-menu-manager' ),
      'adminbar_bg' => __( 'Changes the top WordPress admin bar background.', 'polanger-admin-menu-manager' ),
      'adminbar_text' => __( 'Controls icon and text color inside the top admin bar.', 'polanger-admin-menu-manager' ),
      'adminbar_submenu_bg' => __( 'Sets the background color for dropdown panels opened from the admin bar.', 'polanger-admin-menu-manager' ),
      'adminbar_submenu_text' => __( 'Sets text and icon colors inside admin bar submenu panels.', 'polanger-admin-menu-manager' ),
      'color_border' => __( 'Fine-tunes borders for cards, tables, inputs, and other boxed UI surfaces.', 'polanger-admin-menu-manager' ),
      'color_hover' => __( 'Used for hover states on tables, secondary buttons, and soft interactive surfaces.', 'polanger-admin-menu-manager' ),
      'color_focus' => __( 'Used for focus outlines and focus rings on form fields and keyboard navigation states.', 'polanger-admin-menu-manager' ),
      'color_success' => __( 'Accent color for success notices and positive UI feedback.', 'polanger-admin-menu-manager' ),
      'color_warning' => __( 'Accent color for warning notices and caution states.', 'polanger-admin-menu-manager' ),
      'color_error' => __( 'Accent color for errors, destructive notices, and critical UI feedback.', 'polanger-admin-menu-manager' ),
      'color_table_head' => __( 'Controls the background tone of table headers and structured list headings.', 'polanger-admin-menu-manager' ),
      'color_input_bg' => __( 'Controls the background tone for text fields, selects, and textareas.', 'polanger-admin-menu-manager' ),
      'link_scope' => __( 'Limit custom links to content areas only, or expand them to all admin content except menu, admin bar, and button controls.', 'polanger-admin-menu-manager' ),
      'link_color' => __( 'Default color used for content links.', 'polanger-admin-menu-manager' ),
      'link_hover' => __( 'Color used when a content link is hovered.', 'polanger-admin-menu-manager' ),
      'link_visited' => __( 'Color used for visited links so repeat navigation can feel more intentional.', 'polanger-admin-menu-manager' ),
      'link_active' => __( 'Color used while a link is focused or being clicked.', 'polanger-admin-menu-manager' ),
      'link_decoration' => __( 'Controls whether content links are underlined never, on hover, or all the time.', 'polanger-admin-menu-manager' ),
      'link_weight' => __( 'Lets you make links lighter or bolder without changing the rest of the typography.', 'polanger-admin-menu-manager' ),
      'font_family' => __( 'Sets the main typeface used by the design system.', 'polanger-admin-menu-manager' ),
      'type_scale' => __( 'Scales the overall size rhythm of the interface for better readability or denser layouts.', 'polanger-admin-menu-manager' ),
      'density' => __( 'Changes how compact or roomy common controls and surfaces feel.', 'polanger-admin-menu-manager' ),
      'spacing_scale' => __( 'Scales padding and gap values to create tighter or more relaxed layouts.', 'polanger-admin-menu-manager' ),
      'button_radius_preset' => __( 'Lets buttons follow the global radius, feel softly rounded, become more rounded, or switch to pill styling.', 'polanger-admin-menu-manager' ),
      'border_radius' => __( 'Base radius used by cards, inputs, and other rounded surfaces.', 'polanger-admin-menu-manager' ),
      'custom_css' => __( 'Advanced CSS appended after the generated stylesheet. Ideal for agency overrides or project-specific tweaks.', 'polanger-admin-menu-manager' ),
    );

    return isset( $descriptions[ $key ] ) ? $descriptions[ $key ] : '';
  }

  /**
   * Build preset select options.
   *
   * @return array<string,string>
   */
  private function get_preset_select_options() {
    $labels  = $this->settings->get_preset_labels();
    $options = array();
    foreach ( $this->settings->get_presets() as $slug => $preset ) {
      unset( $preset );
      $options[ $slug ] = isset( $labels[ $slug ] ) ? $labels[ $slug ] : ucfirst( $slug );
    }
    return $options;
  }

  /**
   * Resolve the color value shown in the form.
   *
   * @param string $key Field key.
   * @param array  $settings Current settings.
   * @param array  $resolved Resolved settings.
   * @return string
   */
  private function get_display_color_value( $key, $settings, $resolved ) {
    if ( isset( $resolved[ $key ] ) && ! empty( $resolved[ $key ] ) ) {
      return $resolved[ $key ];
    }

    if ( isset( $settings[ $key ] ) && ! empty( $settings[ $key ] ) ) {
      return $settings[ $key ];
    }

    return '#000000';
  }

  /**
   * Build inline CSS variable string for the live playground.
   *
   * @param array $resolved Resolved settings.
   * @return string
   */
  private function get_playground_style( $resolved ) {
    $map = array(
      '--pg-primary'                => $resolved['color_primary'],
      '--pg-bg'                     => $resolved['color_bg'],
      '--pg-surface'                => $resolved['color_surface'],
      '--pg-text'                   => $resolved['color_text'],
      '--pg-muted'                  => $resolved['color_muted'],
      '--pg-sidebar'                => $resolved['sidebar_bg'],
      '--pg-adminbar'               => $resolved['adminbar_bg'],
      '--pg-adminbar-submenu'       => $resolved['adminbar_submenu_bg'],
      '--pg-border'                 => $resolved['color_border'],
      '--pg-hover'                  => $resolved['color_hover'],
      '--pg-focus'                  => $resolved['color_focus'],
      '--pg-success'                => $resolved['color_success'],
      '--pg-warning'                => $resolved['color_warning'],
      '--pg-error'                  => $resolved['color_error'],
      '--pg-table-head'             => $resolved['color_table_head'],
      '--pg-input-bg'               => $resolved['color_input_bg'],
      '--pg-radius'                 => $resolved['border_radius'] . 'px',
      '--pg-button-radius'          => $resolved['resolved_button_radius'],
      '--pg-font'                   => $resolved['font_family'],
      '--pg-font-scale'             => $resolved['resolved_type_scale'],
      '--pg-space-scale'            => $resolved['resolved_space_scale'],
      '--pg-density-scale'          => $resolved['resolved_density_scale'],
      '--pg-on-primary'             => $resolved['resolved_on_primary'],
      '--pg-on-surface'             => $resolved['resolved_on_surface'],
      '--pg-on-sidebar'             => $resolved['resolved_on_sidebar'],
      '--pg-on-adminbar'            => $resolved['resolved_on_adminbar'],
      '--pg-on-adminbar-submenu'    => $resolved['resolved_on_adminbar_submenu'],
      '--pg-focus-shadow'           => $resolved['resolved_focus_shadow'],
      '--pg-surface-hover'          => $resolved['resolved_surface_hover'],
      '--pg-sidebar-hover'          => $resolved['resolved_sidebar_hover'],
      '--pg-notice-success-bg'      => $resolved['resolved_notice_success_bg'],
      '--pg-notice-warning-bg'      => $resolved['resolved_notice_warning_bg'],
      '--pg-notice-error-bg'        => $resolved['resolved_notice_error_bg'],
      '--pg-notice-success-text'    => $resolved['resolved_notice_success_text'],
      '--pg-notice-warning-text'    => $resolved['resolved_notice_warning_text'],
      '--pg-notice-error-text'      => $resolved['resolved_notice_error_text'],
      '--pg-link'                   => $resolved['link_color'],
      '--pg-link-hover'             => $resolved['link_hover'],
      '--pg-link-active'            => $resolved['link_active'],
      '--pg-link-visited'           => $resolved['link_visited'],
      '--pg-table-head-text'        => $resolved['resolved_table_head_text'],
    );

    $style = '';
    foreach ( $map as $property => $value ) {
      $style .= $property . ':' . $value . ';';
    }

    return $style;
  }
}
