<?php
if (!defined('ABSPATH')) exit;

/**
 * CAS Installation Doctor
 */

if (!function_exists('custausu_admin_doctor_severity_label')) {
  function custausu_admin_doctor_severity_label(string $severity, callable $T): string {
    return match ($severity) {
      'critical'  => $T('Critical', 'Critico'),
      'warning'   => $T('Warning', 'Warning'),
      'attention' => $T('Attention', 'Attenzione'),
      'info'      => $T('Info', 'Info'),
      'ok'        => $T('Ready', 'Pronto'),
      default     => ucfirst($severity),
    };
  }
}

if (!function_exists('custausu_admin_doctor_phase_label')) {
  function custausu_admin_doctor_phase_label(string $phase, callable $T): string {
    return match ($phase) {
      'first_install' => $T('First install', 'Prima installazione'),
      'setup_in_progress' => $T('Setup in progress', 'Setup in corso'),
      'configured' => $T('Setup configured', 'Setup configurato'),
      default => $T('Site check', 'Controllo sito'),
    };
  }
}

if (!function_exists('custausu_admin_doctor_item_message')) {
  function custausu_admin_doctor_item_message(array $item, callable $T): string {
    $is_it = function_exists('custausu_admin_is_it') && custausu_admin_is_it();

    if ($is_it && !empty($item['message_it'])) return (string)$item['message_it'];
    if (!$is_it && !empty($item['message_en'])) return (string)$item['message_en'];

    return (string)($item['message_en'] ?? $item['message_it'] ?? '');
  }
}

if (!function_exists('custausu_admin_doctor_item_recommendation')) {
  function custausu_admin_doctor_item_recommendation(array $item, callable $T): string {
    $is_it = function_exists('custausu_admin_is_it') && custausu_admin_is_it();

    if ($is_it && !empty($item['recommendation_it'])) return (string)$item['recommendation_it'];
    if (!$is_it && !empty($item['recommendation_en'])) return (string)$item['recommendation_en'];

    return (string)($item['recommendation_en'] ?? $item['recommendation_it'] ?? '');
  }
}

if (!function_exists('custausu_admin_doctor_cache_section_label')) {
  function custausu_admin_doctor_cache_section_label(array $section, callable $T): string {
    $is_it = function_exists('custausu_admin_is_it') && custausu_admin_is_it();

    return $is_it
      ? (string)($section['label_it'] ?? $section['label_en'] ?? '')
      : (string)($section['label_en'] ?? $section['label_it'] ?? '');
  }
}

if (!function_exists('custausu_admin_doctor_cache_section_reason')) {
  function custausu_admin_doctor_cache_section_reason(array $section, callable $T): string {
    $is_it = function_exists('custausu_admin_is_it') && custausu_admin_is_it();

    return $is_it
      ? (string)($section['reason_it'] ?? $section['reason_en'] ?? '')
      : (string)($section['reason_en'] ?? $section['reason_it'] ?? '');
  }
}

if (!function_exists('custausu_admin_doctor_support_locale_is_it')) {
  function custausu_admin_doctor_support_locale_is_it(): bool {
    $locale = function_exists('get_user_locale') ? get_user_locale() : get_locale();
    $locale = strtolower(trim((string) $locale));

    return $locale === 'it' || strpos($locale, 'it_') === 0 || strpos($locale, 'it-') === 0;
  }
}

if (!function_exists('custausu_admin_doctor_support_default_url')) {
  function custausu_admin_doctor_support_default_url(): string {
    return custausu_admin_doctor_support_locale_is_it()
      ? 'https://customauthsuite.com/it/supporto/'
      : 'https://customauthsuite.com/support/';
  }
}

if (!function_exists('custausu_admin_doctor_support_url_base')) {
  function custausu_admin_doctor_support_url_base(): string {
    $base = '';

    /*
     * Doctor support requests should go to the official CAS Support Desk intake.
     * Locale-aware default:
     * - Italian admin UI: /it/supporto/
     * - English and every other locale: /support/
     */
    $default = custausu_admin_doctor_support_default_url();

    if (defined('CUSTAUSU_BUILD_SUPPORT_URL')) {
      $base = trim((string) CUSTAUSU_BUILD_SUPPORT_URL);
    }

    if ($base === '' && defined('CUSTAUSU_BUILD_UPGRADE_URL')) {
      $base = trim((string) CUSTAUSU_BUILD_UPGRADE_URL);
    }

    if ($base === '') {
      $base = $default;
    }

    $base = esc_url_raw($base);

    if ($base === '') {
      $base = $default;
    }

    /*
     * If the build URL points to the standard customauthsuite.com support area,
     * keep it aligned with the current admin language.
     */
    $host = wp_parse_url($base, PHP_URL_HOST);
    $path = wp_parse_url($base, PHP_URL_PATH);

    if (is_string($host) && preg_match('/(^|\.)customauthsuite\.com$/i', $host)) {
      $clean_path = '/' . trim((string) $path, '/') . '/';

      if (in_array($clean_path, ['/support/', '/it/supporto/', '//'], true)) {
        $base = $default;
      }
    }

    /**
     * Allows CAS commercial builds / special editions to point the Doctor
     * to a dedicated CAS Support Desk intake page.
     *
     * The filter receives the locale-aware default URL as second argument.
     */
    return (string) apply_filters('custausu_doctor_support_request_base_url', $base, $default);
  }
}

if (!function_exists('custausu_admin_doctor_public_site_url')) {
  function custausu_admin_doctor_public_site_url(): string {
    $url = home_url('/');

    if (!is_string($url) || trim($url) === '') {
      $url = site_url('/');
    }

    return esc_url_raw((string) $url);
  }
}

if (!function_exists('custausu_admin_doctor_public_host')) {
  function custausu_admin_doctor_public_host(): string {
    $url = custausu_admin_doctor_public_site_url();
    $host = wp_parse_url($url, PHP_URL_HOST);

    if (!is_string($host) || trim($host) === '') {
      return '';
    }

    $host = strtolower(trim($host));
    $host = preg_replace('/^www\./', '', $host);

    return sanitize_text_field((string) $host);
  }
}

if (!function_exists('custausu_admin_doctor_version')) {
  function custausu_admin_doctor_version(): string {
    $candidates = [];

    if (defined('CUSTAUSU_VERSION')) {
      $candidates[] = (string) CUSTAUSU_VERSION;
    }

    if (defined('CUSTOM_AUTH_SUITE_VERSION')) {
      $candidates[] = (string) CUSTOM_AUTH_SUITE_VERSION;
    }

    if (defined('CUSTAUSU_PLUGIN_VERSION')) {
      $candidates[] = (string) CUSTAUSU_PLUGIN_VERSION;
    }

    foreach ($candidates as $candidate) {
      $version = trim(sanitize_text_field($candidate));

      if ($version !== '') {
        return $version;
      }
    }

    if (
      defined('CUSTAUSU_PLUGIN_DIR') &&
      file_exists(CUSTAUSU_PLUGIN_DIR . 'custom-auth-suite.php')
    ) {
      if (!function_exists('get_plugin_data')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
      }

      if (function_exists('get_plugin_data')) {
        $data = get_plugin_data(CUSTAUSU_PLUGIN_DIR . 'custom-auth-suite.php', false, false);
        $version = isset($data['Version']) ? trim(sanitize_text_field((string) $data['Version'])) : '';

        if ($version !== '') {
          return $version;
        }
      }
    }

    return '';
  }
}

if (!function_exists('custausu_admin_doctor_license_status_from_state')) {
  function custausu_admin_doctor_license_status_from_state(array $state): string {
    $status = '';

    if (isset($state['license']) && is_array($state['license']) && isset($state['license']['status'])) {
      $status = (string) $state['license']['status'];
    } elseif (isset($state['status'])) {
      $status = (string) $state['status'];
    } elseif (isset($state['license_status'])) {
      $status = (string) $state['license_status'];
    }

    $status = sanitize_key($status);

    return $status !== '' ? $status : 'unknown';
  }
}

if (!function_exists('custausu_admin_doctor_license_tail_from_raw_key')) {
  function custausu_admin_doctor_license_tail_from_raw_key($raw): string {
    if (is_array($raw) || is_object($raw)) {
      return '';
    }

    $raw = trim((string) $raw);
    if ($raw === '') {
      return '';
    }

    $raw = preg_replace('/\s+/', '', $raw);
    $parts = preg_split('/[^A-Z0-9]+/i', $raw, -1, PREG_SPLIT_NO_EMPTY);
    $candidate = '';

    if (is_array($parts) && !empty($parts)) {
      $candidate = (string) end($parts);
    }

    if ($candidate === '') {
      $candidate = $raw;
    }

    $candidate = strtoupper(preg_replace('/[^A-Z0-9]/i', '', $candidate));

    if ($candidate === '') {
      return '';
    }

    if (strlen($candidate) > 12) {
      $candidate = substr($candidate, -6);
    }

    if (strlen($candidate) < 4) {
      return '';
    }

    return sanitize_text_field($candidate);
  }
}

if (!function_exists('custausu_admin_doctor_license_tail_from_state')) {
  /**
   * Return only a redacted historical key tail for support correlation.
   * The Free package never exposes or validates the complete product key.
   */
  function custausu_admin_doctor_license_tail_from_state(array $state): string {
    $candidates = [
      $state['license_key_tail'] ?? '',
      $state['key_tail'] ?? '',
      $state['tail'] ?? '',
    ];
    if (isset($state['license']) && is_array($state['license'])) {
      $candidates[] = $state['license']['license_key_tail'] ?? '';
      $candidates[] = $state['license']['key_tail'] ?? '';
      $candidates[] = $state['license']['tail'] ?? '';
    }
    foreach ($candidates as $candidate) {
      $tail = strtoupper(preg_replace('/[^A-Z0-9]/i', '', (string)$candidate));
      if ($tail !== '' && strlen($tail) >= 4 && strlen($tail) <= 12) {
        return sanitize_text_field($tail);
      }
    }
    return function_exists('custausu_free_package_historical_key_tail')
      ? custausu_free_package_historical_key_tail()
      : '';
  }
}

if (!function_exists('custausu_admin_doctor_reference_string')) {
  function custausu_admin_doctor_reference_string($value, int $max = 80): string {
    if (is_array($value) || is_object($value)) {
      return '';
    }

    $value = trim(wp_strip_all_tags((string) $value));
    if ($value === '') {
      return '';
    }

    $value = preg_replace('/\s+/', ' ', $value);
    $value = preg_replace('/[^A-Za-z0-9_\-#:.\/ ]/', '', $value);
    $value = substr((string) $value, 0, max(10, $max));

    return sanitize_text_field($value);
  }
}

if (!function_exists('custausu_admin_doctor_pick_reference_from_state')) {
  function custausu_admin_doctor_pick_reference_from_state(array $state, array $keys): string {
    $containers = [$state];

    foreach (['license', 'order', 'purchase', 'support', 'customer', 'commerce', 'subscription'] as $container_key) {
      if (isset($state[$container_key]) && is_array($state[$container_key])) {
        $containers[] = $state[$container_key];
      }
    }

    foreach ($containers as $container) {
      foreach ($keys as $key) {
        if (!array_key_exists($key, $container)) {
          continue;
        }

        $value = custausu_admin_doctor_reference_string($container[$key]);
        if ($value !== '') {
          return $value;
        }
      }
    }

    return '';
  }
}

if (!function_exists('custausu_admin_doctor_support_reference_from_state')) {
  function custausu_admin_doctor_support_reference_from_state(array $state): array {
    $license_status = function_exists('custausu_admin_doctor_license_status_from_state')
      ? custausu_admin_doctor_license_status_from_state($state)
      : 'none';

    $license_tail = function_exists('custausu_admin_doctor_license_tail_from_state')
      ? custausu_admin_doctor_license_tail_from_state($state)
      : '';

    $order_reference = custausu_admin_doctor_pick_reference_from_state($state, [
      'order_reference',
      'order_ref',
      'order_number',
      'order_id',
      'wc_order_id',
      'source_ref',
      'source_reference',
    ]);

    $support_reference = custausu_admin_doctor_pick_reference_from_state($state, [
      'support_reference',
      'support_ref',
      'support_entitlement_ref',
      'entitlement_ref',
      'support_order_ref',
      'case_id',
    ]);

    $license = isset($state['license']) && is_array($state['license'])
      ? $state['license']
      : [];

    $support_context = isset($license['support_context']) && is_array($license['support_context'])
      ? $license['support_context']
      : [];

    if (empty($support_context)) {
      $client_state = function_exists('custausu_free_package_runtime_context')
        ? custausu_free_package_runtime_context()
        : [];

      if (is_array($client_state) && isset($client_state['license']['support_context']) && is_array($client_state['license']['support_context'])) {
        $support_context = $client_state['license']['support_context'];
      }
    }

    $license_type = sanitize_key((string) ($license['license_type'] ?? ($support_context['license_type'] ?? '')));

    if ($order_reference === '' && !empty($support_context['order_reference']) && is_scalar($support_context['order_reference'])) {
      $order_reference = (string) $support_context['order_reference'];
    }

    if ($support_reference === '' && !empty($support_context['support_reference']) && is_scalar($support_context['support_reference'])) {
      $support_reference = (string) $support_context['support_reference'];
    }

    if ($license_tail === '' && !empty($support_context['license_tail']) && is_scalar($support_context['license_tail'])) {
      $license_tail = (string) $support_context['license_tail'];
    }

    if ($order_reference === '' || $support_reference === '') {
      if ($license_type === 'gift') {
        if ($order_reference === '') {
          $order_reference = 'Gift / Complimentary';
        }

        if ($support_reference === '') {
          $support_reference = 'Complimentary license';
        }
      } elseif ($license_type === 'developer') {
        if ($order_reference === '') {
          $order_reference = 'Developer license';
        }

        if ($support_reference === '') {
          $support_reference = 'Developer / staging license';
        }
      } elseif ($license_type === 'internal') {
        if ($order_reference === '') {
          $order_reference = 'Internal license';
        }

        if ($support_reference === '') {
          $support_reference = 'Internal CAS license';
        }
      } elseif ($license_type === 'special') {
        if ($order_reference === '') {
          $order_reference = 'Special / OET license';
        }

        if ($support_reference === '') {
          $support_reference = 'Special CAS license';
        }
      }
    }

    /**
     * Future bridge point:
     * CAS LS / ecommerce adapters may inject customer-readable references here.
     * Never inject full license keys, private tokens or secrets.
     */
    $order_reference = apply_filters('custausu_doctor_support_order_reference', $order_reference, $state);
    $support_reference = apply_filters('custausu_doctor_support_reference', $support_reference, $state, $license_tail, $order_reference);

    $order_reference = custausu_admin_doctor_reference_string($order_reference, 80);
    $support_reference = custausu_admin_doctor_reference_string($support_reference, 80);

    return [
      'license_status'    => sanitize_key($license_status ?: 'none'),
      'license_tail'      => custausu_admin_doctor_reference_string($license_tail, 20),
      'order_reference'   => $order_reference,
      'support_reference' => $support_reference,
    ];
  }
}









/* Doctor report handoff REST bridge lives in inc/core/doctor-report-handoff.php. */

if (!function_exists('custausu_admin_doctor_support_url')) {
  function custausu_admin_doctor_support_url(array $scan = []): string {
    $base = custausu_admin_doctor_support_url_base();
    if ($base === '' && function_exists('custausu_admin_doctor_support_default_url')) {
      $base = custausu_admin_doctor_support_default_url();
    }

    $state = function_exists('custausu_free_package_runtime_context') ? custausu_free_package_runtime_context() : [];
    $state = is_array($state) ? $state : [];

    $plan = sanitize_key((string)($state['effective_plan'] ?? 'freemium'));
    if ($plan === '') {
      $plan = 'freemium';
    }

    $edition = function_exists('custausu_build_edition')
      ? sanitize_key((string) custausu_build_edition())
      : '';

    $package = function_exists('custausu_build_package_plan')
      ? sanitize_key((string) custausu_build_package_plan())
      : '';

    $license_type_for_support = '';
    if (isset($state['license']) && is_array($state['license'])) {
      $license_type_for_support = sanitize_key((string) ($state['license']['license_type'] ?? ''));
    }

    $license_status = custausu_admin_doctor_license_status_from_state($state);
    $license_tail   = custausu_admin_doctor_license_tail_from_state($state);
    $support_reference = function_exists('custausu_admin_doctor_support_reference_from_state')
      ? custausu_admin_doctor_support_reference_from_state($state)
      : [];
    if (is_array($support_reference) && !empty($support_reference['license_tail'])) {
      $license_tail = (string) $support_reference['license_tail'];
    }

    $readiness = is_array($scan['support_readiness'] ?? null) ? $scan['support_readiness'] : [];
    $phase = sanitize_key((string)($readiness['phase'] ?? ($scan['setup_context']['phase'] ?? '')));

    $doctor_status = sanitize_key((string)($scan['overall'] ?? $scan['status'] ?? ''));
    $doctor_grade  = sanitize_key((string)($scan['health_profile']['grade'] ?? ''));

    $args = [
      'cas_ticket_type'  => 'technical',
      'cas_source'       => 'cas_plugin',
      'cas_entry'        => 'installation_doctor',
      'cas_intent'       => 'technical_support',
      'site_url'         => custausu_admin_doctor_public_site_url(),
      'site_host'        => custausu_admin_doctor_public_host(),
      'cas_version'      => custausu_admin_doctor_version(),
      'custausu_edition'      => $edition,
      'cas_package'      => $package,
      'cas_plan'         => $plan,
      'license_status'   => $license_status,
      'license_type'     => $license_type_for_support,
      'cas_license_type' => $license_type_for_support,
      'license_tail'     => $license_tail,
      'license_key_tail' => $license_tail,
      'cas_license_tail' => $license_tail,
      'cas_order_reference'   => (string) ($support_reference['order_reference'] ?? ''),
      'cas_support_reference' => (string) ($support_reference['support_reference'] ?? ''),
      'wp_version'       => get_bloginfo('version'),
      'php_version'      => PHP_VERSION,
      'locale'           => function_exists('get_user_locale') ? get_user_locale() : get_locale(),
      'cas_phase'        => $phase,
      'doctor_status'    => $doctor_status,
      'doctor_grade'     => $doctor_grade,
      'report_available' => '1',
    ];

    $args = array_filter($args, static function ($value): bool {
      return is_scalar($value) && trim((string) $value) !== '';
    });

    /**
     * Final chance to remove/add safe prefill values before opening CAS Support Desk.
     *
     * Never add complete license keys, nonces, cookies, auth headers,
     * API secrets, private keys, or diagnostic support tokens here.
     */
    if (function_exists('custausu_admin_doctor_create_report_handoff')) {
      $handoff = custausu_admin_doctor_create_report_handoff();

      if (!empty($handoff['url'])) {
        $args['cas_report_available']  = '1';
        $args['cas_report_fetch_url']  = (string) $handoff['url'];
        $args['cas_report_filename']   = !empty($handoff['filename']) ? (string) $handoff['filename'] : '';
        $args['cas_report_handoff_ttl'] = !empty($handoff['ttl']) ? (string) absint($handoff['ttl']) : '';
      }
    }

    $args = apply_filters('custausu_doctor_support_request_args', $args, $scan, $state);

    if (!is_array($args)) {
      $args = [];
    }

    return add_query_arg($args, $base);
  }
}

if (!function_exists('custausu_admin_doctor_support_ticket_image_html')) {
  function custausu_admin_doctor_support_ticket_image_html(callable $T): string {
    if (!defined('CUSTAUSU_PLUGIN_DIR') || !defined('CUSTAUSU_PLUGIN_URL')) {
      return '';
    }

    $desktop_rel = 'inc/assets/images/custausu-doctor-ticket-support.webm';
    $mobile_rel  = 'inc/assets/images/custausu-doctor-ticket-support-mobile.webm';

    $desktop_path = CUSTAUSU_PLUGIN_DIR . $desktop_rel;
    $mobile_path  = CUSTAUSU_PLUGIN_DIR . $mobile_rel;

    $desktop_exists = file_exists($desktop_path);
    $mobile_exists  = file_exists($mobile_path);

    /*
     * CAS RM is the primary Doctor support visual layer.
     * Do not pass .webm as RM image fallback unless RM renderer is video-aware.
     */
    if (function_exists('custausu_rm_render')) {
      ob_start();

      custausu_rm_render('doctor_support', [
        'fallback_desktop' => '',
        'fallback_mobile'  => '',
      ]);

      $rm_html = trim((string) ob_get_clean());

      if ($rm_html !== '') {
        return '<div class="custausu-doctor-support-preview custausu-doctor-support-preview--rm">' . $rm_html . '</div>';
      }
    }

    if (!$desktop_exists && !$mobile_exists) {
      return '';
    }

    $desktop_url = $desktop_exists ? CUSTAUSU_PLUGIN_URL . $desktop_rel : '';
    $mobile_url  = $mobile_exists ? CUSTAUSU_PLUGIN_URL . $mobile_rel : '';

    if ($desktop_url !== '') {
      $desktop_url = add_query_arg('v', (string) filemtime($desktop_path), $desktop_url);
    }

    if ($mobile_url !== '') {
      $mobile_url = add_query_arg('v', (string) filemtime($mobile_path), $mobile_url);
    }

    $alt = $T(
      'CAS support request workflow preview',
      'Anteprima del processo richiesta supporto CAS'
    );

    $video_id = 'custausu-doctor-support-video-' . wp_generate_uuid4();
    $card_id  = 'custausu-doctor-support-fallback-card-' . wp_generate_uuid4();

    ob_start();
    ?>
    <div class="custausu-doctor-support-preview custausu-doctor-support-preview--fallback" aria-label="<?php echo esc_attr($alt); ?>">
      <div class="custausu-rm-placement custausu-rm-placement--doctor_support custausu-rm-layout--hero">
        <article
          id="<?php echo esc_attr($card_id); ?>"
          class="custausu-doctor-support-fallback-card"
        >
          <div class="custausu-rm-doctor-support-card__media">
            <video
              id="<?php echo esc_attr($video_id); ?>"
              class="custausu-rm-doctor-support-card__img"
              muted
              playsinline
              preload="none"
              data-desktop-src="<?php echo esc_url($desktop_url); ?>"
              data-mobile-src="<?php echo esc_url($mobile_url); ?>"
              data-max-plays="2"
            ></video>
          </div>
        </article>
      </div>
    </div>
    <?php

    return trim((string) ob_get_clean());
  }
}

if (!function_exists('custausu_admin_doctor_icon_html')) {
  function custausu_admin_doctor_icon_html(string $ring_text = ''): string {
    $rel = 'inc/assets/images/custausu-installation-doctor-icon.png';

    $ring_text = trim(wp_strip_all_tags($ring_text));
    $halo_html = '';

    if ($ring_text !== '') {
      $halo_id = 'custausu-doctor-halo-text-path-' . substr(md5($ring_text), 0, 8);

      $halo_html = '<span class="custausu-doctor-summary__halo" aria-hidden="true">'
        . '<svg class="custausu-doctor-summary__halo-svg" viewBox="0 0 160 160" focusable="false" role="presentation">'
        . '<defs>'
        . '<path id="' . esc_attr($halo_id) . '" d="M 34 56 A 54 54 0 0 1 126 56"></path>'
        . '</defs>'
        . '<circle class="custausu-doctor-summary__halo-ring" cx="80" cy="79" r="66"></circle>'
        . '<g class="custausu-doctor-summary__halo-cursor-orbit">'
        . '<circle class="custausu-doctor-summary__halo-cursor" cx="80" cy="13" r="5.8"></circle>'
        . '</g>'
        . '<text class="custausu-doctor-summary__halo-text" textLength="112" lengthAdjust="spacingAndGlyphs">'
        . '<textPath href="#' . esc_attr($halo_id) . '" startOffset="50%" text-anchor="middle">' . esc_html($ring_text) . '</textPath>'
        . '</text>'
        . '</svg>'
        . '</span>';
    }

    if (
      defined('CUSTAUSU_PLUGIN_DIR') &&
      defined('CUSTAUSU_PLUGIN_URL') &&
      file_exists(CUSTAUSU_PLUGIN_DIR . $rel)
    ) {
      return '<span class="custausu-doctor-summary__icon custausu-doctor-summary__icon--image" aria-hidden="true">'
        . $halo_html
        . '<img class="custausu-doctor-summary__icon-img" src="' . esc_url(CUSTAUSU_PLUGIN_URL . $rel) . '" alt="">'
        . '</span>';
    }

    return '<span class="custausu-doctor-summary__icon custausu-doctor-summary__icon--fallback" aria-hidden="true">'
      . $halo_html
      . '<span class="dashicons dashicons-admin-tools"></span>'
      . '</span>';
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_is_acknowledgeable')) {
  function custausu_admin_doctor_plugin_warning_is_acknowledgeable(array $item): bool {
    $severity = sanitize_key((string)($item['severity'] ?? ''));
    $plugin_file = trim((string)($item['plugin_file'] ?? ''));

    return $severity === 'warning' && $plugin_file !== '';
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_key')) {
  function custausu_admin_doctor_plugin_warning_key(array $item): string {
    if (!custausu_admin_doctor_plugin_warning_is_acknowledgeable($item)) {
      return '';
    }

    $identity = [
      'type'        => sanitize_key((string)($item['type'] ?? 'plugin')),
      'category'    => sanitize_key((string)($item['category'] ?? 'other')),
      'plugin_file' => strtolower(trim((string)($item['plugin_file'] ?? ''))),
    ];

    return hash('sha256', (string)wp_json_encode($identity));
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_normalize_context')) {
  function custausu_admin_doctor_plugin_warning_normalize_context($value) {
    if (!is_array($value)) {
      if (is_bool($value)) {
        return $value ? 1 : 0;
      }

      if (is_scalar($value) || $value === null) {
        return $value;
      }

      return (string)$value;
    }

    $keys = array_keys($value);
    $is_list = $keys === range(0, count($value) - 1);

    if (!$is_list) {
      ksort($value, SORT_STRING);
    }

    $normalized = [];

    foreach ($value as $key => $item) {
      $normalized[$key] = custausu_admin_doctor_plugin_warning_normalize_context($item);
    }

    return $normalized;
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_fingerprint')) {
  function custausu_admin_doctor_plugin_warning_fingerprint(array $item, array $scan = []): string {
    if (!custausu_admin_doctor_plugin_warning_is_acknowledgeable($item)) {
      return '';
    }

    $context = [
      'contract'          => 1,
      'cas_version'       => defined('CUSTAUSU_VERSION') ? (string)CUSTAUSU_VERSION : '',
      'type'              => sanitize_key((string)($item['type'] ?? 'plugin')),
      'category'          => sanitize_key((string)($item['category'] ?? 'other')),
      'plugin_file'       => strtolower(trim((string)($item['plugin_file'] ?? ''))),
      'plugin_version'    => trim((string)($item['plugin_version'] ?? '')),
      'message_en'        => trim((string)($item['message_en'] ?? '')),
      'message_it'        => trim((string)($item['message_it'] ?? '')),
      'recommendation_en' => trim((string)($item['recommendation_en'] ?? '')),
      'recommendation_it' => trim((string)($item['recommendation_it'] ?? '')),
      'cache_guidance'    => is_array($scan['cache_guidance'] ?? null)
        ? $scan['cache_guidance']
        : [],
    ];

    $context = custausu_admin_doctor_plugin_warning_normalize_context($context);
    $json = wp_json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    return hash('sha256', is_string($json) ? $json : '');
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_acknowledged')) {
  function custausu_admin_doctor_plugin_warning_acknowledged(array $item, array $scan = [], ?array $acknowledgements = null): bool {
    $key = custausu_admin_doctor_plugin_warning_key($item);
    $fingerprint = custausu_admin_doctor_plugin_warning_fingerprint($item, $scan);

    if ($key === '' || $fingerprint === '') {
      return false;
    }

    $acknowledgements = is_array($acknowledgements)
      ? $acknowledgements
      : custausu_admin_doctor_plugin_warning_acknowledgements();

    $stored = is_array($acknowledgements[$key] ?? null)
      ? $acknowledgements[$key]
      : [];

    $stored_fingerprint = (string)($stored['fingerprint'] ?? '');

    return $stored_fingerprint !== '' && hash_equals($fingerprint, $stored_fingerprint);
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_save_acknowledgement')) {
  function custausu_admin_doctor_plugin_warning_save_acknowledgement(array $item, array $scan = []): bool {
    $key = custausu_admin_doctor_plugin_warning_key($item);
    $fingerprint = custausu_admin_doctor_plugin_warning_fingerprint($item, $scan);
    $plugin_file = trim((string)($item['plugin_file'] ?? ''));

    if ($key === '' || $fingerprint === '' || $plugin_file === '') {
      return false;
    }

    $rows = custausu_admin_doctor_plugin_warning_acknowledgements();
    $rows[$key] = [
      'fingerprint'     => $fingerprint,
      'plugin_file'     => $plugin_file,
      'acknowledged_at' => gmdate('c'),
    ];

    if (count($rows) > 100) {
      uasort($rows, static function(array $left, array $right): int {
        return strcmp(
          (string)($right['acknowledged_at'] ?? ''),
          (string)($left['acknowledged_at'] ?? '')
        );
      });

      $rows = array_slice($rows, 0, 100, true);
    }

    return update_option(
      custausu_admin_doctor_plugin_warning_ack_option_name(),
      $rows,
      false
    ) || custausu_admin_doctor_plugin_warning_acknowledged($item, $scan, $rows);
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_clear_acknowledgement')) {
  function custausu_admin_doctor_plugin_warning_clear_acknowledgement(array $item): bool {
    $key = custausu_admin_doctor_plugin_warning_key($item);

    if ($key === '') {
      return false;
    }

    $rows = custausu_admin_doctor_plugin_warning_acknowledgements();

    if (!isset($rows[$key])) {
      return true;
    }

    unset($rows[$key]);

    if (empty($rows)) {
      return delete_option(custausu_admin_doctor_plugin_warning_ack_option_name());
    }

    return update_option(
      custausu_admin_doctor_plugin_warning_ack_option_name(),
      $rows,
      false
    );
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_state')) {
  function custausu_admin_doctor_plugin_warning_state(array $items, array $scan = []): array {
    $state = [
      'warning_total' => 0,
      'acknowledgeable' => 0,
      'acknowledged' => 0,
      'unresolved' => 0,
    ];

    $acknowledgements = custausu_admin_doctor_plugin_warning_acknowledgements();

    foreach ($items as $item) {
      if (!is_array($item) || sanitize_key((string)($item['severity'] ?? '')) !== 'warning') {
        continue;
      }

      $state['warning_total']++;

      if (!custausu_admin_doctor_plugin_warning_is_acknowledgeable($item)) {
        $state['unresolved']++;
        continue;
      }

      $state['acknowledgeable']++;

      if (custausu_admin_doctor_plugin_warning_acknowledged($item, $scan, $acknowledgements)) {
        $state['acknowledged']++;
      } else {
        $state['unresolved']++;
      }
    }

    return $state;
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_find_current')) {
  function custausu_admin_doctor_plugin_warning_find_current(string $key, array $scan): array {
    if (!preg_match('/^[a-f0-9]{64}$/', $key)) {
      return [];
    }

    $items = is_array($scan['items'] ?? null) ? $scan['items'] : [];

    foreach ($items as $item) {
      if (!is_array($item) || !custausu_admin_doctor_plugin_warning_is_acknowledgeable($item)) {
        continue;
      }

      if (hash_equals($key, custausu_admin_doctor_plugin_warning_key($item))) {
        return $item;
      }
    }

    return [];
  }
}

if (!function_exists('custausu_admin_doctor_plugin_warning_action_url')) {
  function custausu_admin_doctor_plugin_warning_action_url(array $item, array $scan, string $mode): string {
    $mode = $mode === 'review' ? 'review' : 'acknowledge';
    $key = custausu_admin_doctor_plugin_warning_key($item);
    $fingerprint = custausu_admin_doctor_plugin_warning_fingerprint($item, $scan);

    if ($key === '' || $fingerprint === '') {
      return '';
    }

    $url = add_query_arg([
      'action' => 'custausu_doctor_plugin_warning_ack',
      'mode' => $mode,
      'warning_key' => $key,
      'warning_fingerprint' => $fingerprint,
    ], admin_url('admin-post.php'));

    return wp_nonce_url($url, 'custausu_doctor_plugin_warning_ack_' . $key);
  }
}

if (!function_exists('custausu_admin_doctor_render_plugin_warning_acknowledgement')) {
  function custausu_admin_doctor_render_plugin_warning_acknowledgement(array $item, array $scan, callable $T): string {
    if (!custausu_admin_doctor_plugin_warning_is_acknowledgeable($item)) {
      return '';
    }

    $acknowledgements = custausu_admin_doctor_plugin_warning_acknowledgements();
    $acknowledged = custausu_admin_doctor_plugin_warning_acknowledged($item, $scan, $acknowledgements);
    $key = custausu_admin_doctor_plugin_warning_key($item);
    $stored = is_array($acknowledgements[$key] ?? null) ? $acknowledgements[$key] : [];
    $acknowledged_at = trim((string)($stored['acknowledged_at'] ?? ''));
    $acknowledged_label = '';

    if ($acknowledged && $acknowledged_at !== '') {
      $timestamp = strtotime($acknowledged_at);

      if (is_int($timestamp) && $timestamp > 0) {
        $acknowledged_label = wp_date(
          get_option('date_format') . ' ' . get_option('time_format'),
          $timestamp
        );
      }
    }

    $mode = $acknowledged ? 'review' : 'acknowledge';
    $url = custausu_admin_doctor_plugin_warning_action_url($item, $scan, $mode);

    if ($url === '') {
      return '';
    }

    $source = trim((string)($item['plugin_name'] ?? $item['plugin_file'] ?? 'Plugin'));
    $html = '<div class="custausu-doctor-warning-ack ' . ($acknowledged ? 'is-acknowledged' : 'is-pending') . '">';

    if ($acknowledged) {
      $html .= '<span class="custausu-doctor-warning-ack__status">'
        . '<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>'
        . esc_html($T(
          'Compatibility measures marked as verified. The warning remains visible for reference.',
          'Misure di compatibilità dichiarate come verificate. Il warning resta visibile come riferimento.'
        ));

      if ($acknowledged_label !== '') {
        $html .= '<span class="custausu-doctor-warning-ack__date">'
          . esc_html(sprintf(
            $T('Verified on %s.', 'Verificato il %s.'),
            $acknowledged_label
          ))
          . '</span>';
      }

      $html .= '</span>';
      $html .= '<a class="button button-small custausu-doctor-warning-ack__action" href="' . esc_url($url) . '">'
        . esc_html($T('Review again', 'Verifica nuovamente'))
        . '</a>';
    } else {
      $html .= '<p class="custausu-doctor-warning-ack__help">'
        . esc_html($T(
          'After applying the recommendation, confirm that you reviewed this plugin warning.',
          'Dopo aver applicato la raccomandazione, conferma di aver verificato questo warning del plugin.'
        ))
        . '</p>';
      $html .= '<a class="button button-small custausu-doctor-warning-ack__action" href="' . esc_url($url) . '" data-custausu-doctor-warning-confirm="1" aria-label="' . esc_attr(sprintf(
        $T('Confirm the compatibility warning for %s', 'Conferma il warning di compatibilità per %s'),
        $source
      )) . '">'
        . esc_html($T('I verified this warning', 'Ho verificato questo warning'))
        . '</a>';
    }

    $html .= '</div>';

    return $html;
  }
}

if (!function_exists('custausu_admin_handle_doctor_plugin_warning_ack_action')) {
  function custausu_admin_handle_doctor_plugin_warning_ack_action(): void {
    if (!is_admin() || !current_user_can('manage_options')) {
      wp_die('Forbidden');
    }

    $key = isset($_GET['warning_key'])
      ? strtolower(sanitize_text_field(wp_unslash((string)$_GET['warning_key'])))
      : '';
    $fingerprint = isset($_GET['warning_fingerprint'])
      ? strtolower(sanitize_text_field(wp_unslash((string)$_GET['warning_fingerprint'])))
      : '';
    $mode = isset($_GET['mode'])
      ? sanitize_key(wp_unslash((string)$_GET['mode']))
      : 'acknowledge';

    if (!preg_match('/^[a-f0-9]{64}$/', $key) || !preg_match('/^[a-f0-9]{64}$/', $fingerprint)) {
      wp_die('Invalid warning reference.');
    }

    check_admin_referer('custausu_doctor_plugin_warning_ack_' . $key);

    $scan = function_exists('custausu_compatibility_scan') ? custausu_compatibility_scan() : [];
    $item = custausu_admin_doctor_plugin_warning_find_current($key, $scan);

    if (empty($item)) {
      wp_die('Compatibility warning is no longer active.');
    }

    $current_fingerprint = custausu_admin_doctor_plugin_warning_fingerprint($item, $scan);

    if ($current_fingerprint === '' || !hash_equals($current_fingerprint, $fingerprint)) {
      wp_die('Compatibility warning context changed. Review the current recommendation first.');
    }

    $status = 'error';

    if ($mode === 'review') {
      $status = custausu_admin_doctor_plugin_warning_clear_acknowledgement($item)
        ? 'review'
        : 'error';
    } else {
      $status = custausu_admin_doctor_plugin_warning_save_acknowledgement($item, $scan)
        ? 'acknowledged'
        : 'error';
    }

    $redirect = wp_get_referer();

    if (!$redirect) {
      $redirect = admin_url('admin.php?page=custausu-settings');
    }

    $redirect = strtok($redirect, '#');
    $redirect = remove_query_arg([
      '_wpnonce',
      'action',
      'mode',
      'warning_key',
      'warning_fingerprint',
      'custausu_doctor_warning_ack',
      'custausu_doctor_warning_ack_notice_nonce',
    ], $redirect);
    $redirect = add_query_arg([
      'custausu_doctor_warning_ack' => $status,
      'custausu_doctor_warning_ack_notice_nonce' => wp_create_nonce(
        'custausu_doctor_warning_ack_notice'
      ),
    ], $redirect);

    wp_safe_redirect($redirect . '#custausu-section-installation-doctor');
    exit;
  }
}

if (!function_exists('custausu_admin_doctor_item_group')) {
  function custausu_admin_doctor_item_group(array $item): string {
    $type = sanitize_key((string)($item['type'] ?? ''));
    $category = sanitize_key((string)($item['category'] ?? ''));

    if ($type === 'environment') {
      return 'server';
    }

    if (in_array($category, ['wp_memory', 'debug', 'custausu_debug', 'https', 'permalinks', 'php', 'object_cache'], true)) {
      return 'server';
    }

    if (in_array($type, ['plugin', 'plugin_hygiene', 'plugin_change', 'forms'], true)) {
      return 'plugins';
    }

    if ($type === 'asset_host') {
      return 'assets';
    }

    return 'other';
  }
}

if (!function_exists('custausu_admin_doctor_group_label')) {
  function custausu_admin_doctor_group_label(string $group, callable $T): string {
    return match ($group) {
      'server'  => $T('Site / Server', 'Sito / Server'),
      'plugins' => $T('Plugins & integrations', 'Plugin e integrazioni'),
      'assets'  => $T('Assets & URLs', 'Asset e URL'),
      default   => $T('Other checks', 'Altri controlli'),
    };
  }
}

if (!function_exists('custausu_admin_doctor_counts_for_items')) {
  function custausu_admin_doctor_counts_for_items(array $items): array {
    $counts = [
      'critical'  => 0,
      'warning'   => 0,
      'attention' => 0,
      'info'      => 0,
    ];

    foreach ($items as $item) {
      $sev = sanitize_key((string)($item['severity'] ?? 'info'));

      if (!isset($counts[$sev])) {
        $sev = 'info';
      }

      $counts[$sev]++;
    }

    return $counts;
  }
}

if (!function_exists('custausu_admin_doctor_counts_badges_html')) {
  function custausu_admin_doctor_counts_badges_html(array $counts, callable $T): string {
    $html = '';

    $map = [
      'critical'  => ['label' => $T('Critical', 'Critici'),  'class' => 'error'],
      'warning'   => ['label' => $T('Warning', 'Warning'),   'class' => 'warn'],
      'attention' => ['label' => $T('Attention', 'Attenzione'), 'class' => 'info'],
      'info'      => ['label' => $T('Info', 'Info'),         'class' => 'muted'],
    ];

    $has_any = false;

    foreach ($map as $key => $meta) {
      $n = (int)($counts[$key] ?? 0);
      if ($n <= 0) {
        continue;
      }

      $has_any = true;

      $html .= '<span class="custausu-badge custausu-badge--' . esc_attr($meta['class']) . '">'
        . esc_html($meta['label'] . ': ' . $n)
        . '</span>';
    }

    if (!$has_any) {
      $html .= '<span class="custausu-badge custausu-badge--ok">'
        . esc_html($T('No issues', 'Nessun problema'))
        . '</span>';
    }

    return $html;
  }
}

if (!function_exists('custausu_admin_doctor_health_profile')) {
  function custausu_admin_doctor_health_profile(array $scan, callable $T, array $warning_state = []): array {
    $counts = is_array($scan['counts'] ?? null) ? $scan['counts'] : [];
    $context = is_array($scan['setup_context'] ?? null) ? $scan['setup_context'] : [];

    $critical  = (int)($counts['critical'] ?? 0);
    $warning   = (int)($counts['warning'] ?? 0);
    $warning_unresolved = array_key_exists('unresolved', $warning_state)
      ? (int)$warning_state['unresolved']
      : $warning;
    $warning_acknowledged = (int)($warning_state['acknowledged'] ?? 0);
    $attention = (int)($counts['attention'] ?? 0);
    $phase     = sanitize_key((string)($context['phase'] ?? 'unknown'));

    if ($critical > 0) {
      return [
        'grade' => 'weak',
        'label' => $T('Needs care', 'Da curare'),
        'title' => $T(
          'The Doctor found issues that should be fixed first.',
          'Il Doctor ha trovato problemi da correggere prima di proseguire.'
        ),
        'message' => $T(
          'CAS can help you, but the environment needs attention before relying on authentication flows.',
          'CAS può aiutarti, ma l’ambiente deve essere sistemato prima di fare affidamento sui flussi di autenticazione.'
        ),
      ];
    }

    if ($phase === 'first_install') {
      return [
        'grade' => 'good',
        'label' => $T('Setup required', 'Setup richiesto'),
        'title' => $T(
          'CAS is not configured yet.',
          'CAS non è ancora configurato.'
        ),
        'message' => $T(
          'Start from the Wizard and configure the core authentication routes. The Doctor will keep checking the environment while you prepare the site.',
          'Parti dal Wizard e configura le route principali di autenticazione. Il Doctor continuerà a controllare l’ambiente mentre prepari il sito.'
        ),
      ];
    }

    if ($phase === 'setup_in_progress') {
      return [
        'grade' => 'fair',
        'label' => $T('Setup in progress', 'Setup in corso'),
        'title' => $T(
          'CAS setup is in progress.',
          'Il setup CAS è in corso.'
        ),
        'message' => $T(
          'Some core routes or settings are still missing. Complete the Wizard steps, then re-run the Doctor before production.',
          'Alcune route o impostazioni principali sono ancora mancanti. Completa gli step del Wizard, poi riesegui il Doctor prima della produzione.'
        ),
      ];
    }

    if ($warning_unresolved > 0) {
      return [
        'grade' => 'fair',
        'label' => $T('Fair', 'Discreto'),
        'title' => $T(
          'The Doctor says the environment is usable, but a few things should be improved.',
          'Il Doctor dice che l’ambiente è utilizzabile, ma alcune cose andrebbero migliorate.'
        ),
        'message' => sprintf(
          $T(
            'CAS setup can continue, but review %d warning item(s) before production.',
            'Il setup CAS può continuare, ma controlla %d warning prima della produzione.'
          ),
          $warning_unresolved
        ),
      ];
    }

    if ($warning > 0 && $warning_acknowledged === $warning) {
      return [
        'grade' => 'good',
        'label' => $T('Verified', 'Verificato'),
        'title' => $T(
          'The Doctor says the environment is usable and the plugin warnings were verified.',
          'Il Doctor dice che l’ambiente è utilizzabile e i warning dei plugin sono stati verificati.'
        ),
        'message' => sprintf(
          $T(
            '%d plugin warning(s) remain visible for reference. CAS will ask for a new review when the plugin, CAS version or relevant guidance changes.',
            '%d warning dei plugin restano visibili come riferimento. CAS richiederà una nuova verifica quando cambiano il plugin, la versione CAS o le indicazioni pertinenti.'
          ),
          $warning_acknowledged
        ),
      ];
    }

    if ($attention > 0) {
      return [
        'grade' => 'good',
        'label' => $T('Good', 'Buono'),
        'title' => $T(
          'The Doctor says your configured CAS environment looks good.',
          'Il Doctor dice che l’ambiente CAS configurato è buono.'
        ),
        'message' => sprintf(
          $T(
            'CAS is configured and no blocking issues were found. Review %d improvement item(s) when you can.',
            'CAS è configurato e non ci sono errori bloccanti. Controlla %d aspetto/i migliorabile/i quando puoi.'
          ),
          $attention
        ),
      ];
    }

    return [
      'grade' => 'excellent',
      'label' => $T('Excellent', 'Ottimo'),
      'title' => $T(
        'The Doctor says your configured CAS environment looks excellent.',
        'Il Doctor dice che l’ambiente CAS configurato è ottimo.'
      ),
      'message' => $T(
        'CAS is configured and no relevant compatibility issue was detected. Keep going.',
        'CAS è configurato e non sono stati rilevati problemi di compatibilità rilevanti. Continua così.'
      ),
    ];
  }
}

if (!function_exists('custausu_admin_doctor_render_items_table')) {
  function custausu_admin_doctor_render_items_table(array $items, callable $T, array $scan = []): string {
    if (empty($items)) {
      return '<p class="custausu-doctor-empty">' . esc_html($T(
        'No relevant items in this area.',
        'Nessun elemento rilevante in quest’area.'
      )) . '</p>';
    }

    ob_start();

    echo '<div class="custausu-table-wrap">';
    echo '<table class="widefat striped custausu-doctor-table">';
    echo '<thead><tr>';
    echo '<th>' . esc_html($T('Severity', 'Severità')) . '</th>';
    echo '<th>' . esc_html($T('Source', 'Sorgente')) . '</th>';
    echo '<th>' . esc_html($T('What to do', 'Cosa fare')) . '</th>';
    echo '</tr></thead>';
    echo '<tbody>';

    foreach ($items as $item) {
      if (!is_array($item)) {
        continue;
      }

      $sev = sanitize_key((string)($item['severity'] ?? 'info'));
      if (!in_array($sev, ['critical', 'warning', 'attention', 'info'], true)) {
        $sev = 'info';
      }

      $source = (string)($item['plugin_name'] ?? $item['label'] ?? $item['category'] ?? 'CAS');
      $version = (string)($item['plugin_version'] ?? '');

      if ($version !== '') {
        $source .= ' ' . $version;
      }

      $message = custausu_admin_doctor_item_message($item, $T);
      $recommendation = custausu_admin_doctor_item_recommendation($item, $T);

      echo '<tr class="custausu-doctor-row custausu-doctor-row--' . esc_attr($sev) . '">';
      echo '<td><span class="custausu-doctor-severity custausu-doctor-severity--' . esc_attr($sev) . '">'
        . esc_html(custausu_admin_doctor_severity_label($sev, $T))
        . '</span></td>';
      echo '<td>' . esc_html($source) . '</td>';
      echo '<td>';
      echo '<strong>' . esc_html($message) . '</strong>';

      if ($recommendation !== '') {
        echo '<br><span class="custausu-doctor-recommendation">' . esc_html($recommendation) . '</span>';
      }

      echo wp_kses( custausu_admin_doctor_render_plugin_warning_acknowledgement($item, $scan, $T), custausu_admin_allowed_output_html() );

      echo '</td>';
      echo '</tr>';
    }

    echo '</tbody></table>';
    echo '</div>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_doctor_render_group_cards')) {
  function custausu_admin_doctor_render_group_cards(array $items, callable $T, array $scan = []): string {
    $groups = [
      'server'  => [],
      'plugins' => [],
      'assets'  => [],
      'other'   => [],
    ];

    foreach ($items as $item) {
      if (!is_array($item)) {
        continue;
      }

      $group = custausu_admin_doctor_item_group($item);

      if (!isset($groups[$group])) {
        $group = 'other';
      }

      $groups[$group][] = $item;
    }

    ob_start();

    echo '<div class="custausu-doctor-category-grid">';

    foreach ($groups as $group => $group_items) {
      if (empty($group_items) && $group === 'other') {
        continue;
      }

      $counts = custausu_admin_doctor_counts_for_items($group_items);
      $warning_state = custausu_admin_doctor_plugin_warning_state($group_items, $scan);
      $has_strong = ((int)$counts['critical'] > 0 || (int)$warning_state['unresolved'] > 0);
      $open_attr = $has_strong ? 'open' : '';

      echo '<details class="custausu-doctor-category-card custausu-doctor-category-card--' . esc_attr($group) . '"' . ($open_attr !== '' ? ' ' . esc_attr($open_attr) : '') . '>';
      echo '<summary class="custausu-doctor-category-card__summary">';
      echo '<span class="custausu-doctor-category-card__title">' . esc_html(custausu_admin_doctor_group_label($group, $T)) . '</span>';
      echo '<span class="custausu-doctor-category-card__badges">';
      // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Doctor counts badges renderer returns controlled escaped admin HTML.
      echo wp_kses( custausu_admin_doctor_counts_badges_html($counts, $T), custausu_admin_allowed_output_html() );

      if ((int)$warning_state['acknowledged'] > 0) {
        echo '<span class="custausu-badge custausu-badge--ok">'
          . esc_html($T('Verified', 'Verificati') . ': ' . (int)$warning_state['acknowledged'])
          . '</span>';
      }
      echo '</span>';
      echo '</summary>';

      echo '<div class="custausu-doctor-category-card__body">';
      // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Doctor items table renderer returns controlled escaped admin HTML.
      echo wp_kses( custausu_admin_doctor_render_items_table($group_items, $T, $scan), custausu_admin_allowed_output_html() );
      echo '</div>';

      echo '</details>';
    }

    echo '</div>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_doctor_cache_section_howto')) {
  function custausu_admin_doctor_cache_section_howto(string $key, callable $T): string {
    $key = sanitize_key($key);

    return match ($key) {
      'auth_routes' => $T(
        'In your cache/CDN plugin, look for options such as “Never cache URLs”, “Page cache exclusions”, “Rejected URLs” or “Bypass cache”. Add these paths one per line. Login, registration and password recovery pages should remain dynamic.',
        'Nel plugin cache/CDN cerca opzioni come “Never cache URLs”, “Page cache exclusions”, “Rejected URLs”, “Escludi URL” o “Bypass cache”. Aggiungi questi path uno per riga. Le pagine login, registrazione e recupero password devono restare dinamiche.'
      ),

      'protected_paths' => $T(
        'Add these paths to the page-cache exclusion list. Protected content should not be served from public cache after CAS checks whether a visitor is logged in.',
        'Aggiungi questi path alla lista di esclusione della cache pagina. I contenuti protetti non devono essere serviti da cache pubblica dopo che CAS ha controllato se il visitatore è autenticato.'
      ),

      'dynamic_endpoints' => $T(
        'These endpoints should not be blocked, cached aggressively, or redirected by security/cache rules. If your hosting panel, cache/CDN layer, firewall or security plugin lets you configure REST API, AJAX or bot-protection rules, make sure these endpoints remain reachable.',
        'Questi endpoint non devono essere bloccati, messi in cache aggressiva o rediretti da regole security/cache. Se il tuo hosting, il pannello cache/CDN, il firewall o un plugin di sicurezza permettono di configurare regole per REST API, AJAX o protezione bot, assicurati che questi endpoint restino raggiungibili.'
      ),

      'custausu_assets' => $T(
        'For these files, page cache is usually fine, but aggressive JS optimization can create problems. In optimization plugins, add these files to “Exclude from delay/defer/minify/combine JavaScript” when Passkeys, reCAPTCHA or CAS popups do not behave correctly.',
        'Per questi file la cache statica di solito va bene, ma ottimizzazioni JS aggressive possono creare problemi. Nei plugin di ottimizzazione aggiungi questi file a “Escludi da delay/defer/minify/combine JavaScript” quando Passkey, reCAPTCHA o popup CAS non si comportano correttamente.'
      ),

      default => $T(
        'Use the list below as a starting point. Cache and security plugins use different names for the same idea: exclude, bypass, never cache, rejected URLs, or optimization exclusions.',
        'Usa la lista qui sotto come punto di partenza. Plugin cache e security usano nomi diversi per la stessa idea: exclude, bypass, never cache, rejected URLs o esclusioni ottimizzazione.'
      ),
    };
  }
}

if (!function_exists('custausu_admin_doctor_render_cache_guidance_cards')) {
  function custausu_admin_doctor_render_cache_guidance_cards(array $cache_guidance, callable $T): string {
    if (empty($cache_guidance)) {
      return '<p class="custausu-doctor-empty">' . esc_html($T(
        'No cache guidance available yet.',
        'Nessuna guida cache disponibile per ora.'
      )) . '</p>';
    }

    ob_start();

    echo '<div class="custausu-doctor-cache-grid">';

    foreach ($cache_guidance as $key => $section) {
      if (!is_array($section)) {
        continue;
      }

      $label = custausu_admin_doctor_cache_section_label($section, $T);
      $reason = custausu_admin_doctor_cache_section_reason($section, $T);
      $paths = is_array($section['items'] ?? null)
        ? array_values(array_filter(array_map('strval', $section['items'])))
        : [];

echo '<details class="custausu-doctor-cache-card">';
      echo '<summary class="custausu-doctor-cache-card__summary">';
      echo '<span class="custausu-doctor-cache-card__title">' . esc_html($label) . '</span>';
      $path_count = count($paths);
      $path_label = $path_count === 1 ? 'path' : 'paths';

      echo '<span class="custausu-badge custausu-badge--muted">' . esc_html($path_count . ' ' . $path_label) . '</span>';
      echo '</summary>';

      echo '<div class="custausu-doctor-cache-card__body">';

      if ($reason !== '') {
      echo '<p>' . esc_html($reason) . '</p>';
      }

      $howto = custausu_admin_doctor_cache_section_howto((string)$key, $T);

      if ($howto !== '') {
      echo '<p class="custausu-doctor-cache-card__howto">';
      echo '<strong>' . esc_html($T('How to use this:', 'Come usarlo:')) . '</strong> ';
      echo esc_html($howto);
      echo '</p>';
      }

      if (empty($paths)) {
        echo '<code class="custausu-doctor-code custausu-doctor-code--muted">'
          . esc_html($T('No paths detected yet.', 'Nessun path rilevato per ora.'))
          . '</code>';
      } else {
        echo '<div class="custausu-doctor-code-list">';
        foreach ($paths as $path) {
          echo '<code class="custausu-doctor-code">' . esc_html($path) . '</code>';
        }
        echo '</div>';
      }

      echo '</div>';
      echo '</details>';
    }

    echo '</div>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_doctor_change_text')) {
  function custausu_admin_doctor_change_text(array $change, string $field): string {
    $is_it = function_exists('custausu_admin_is_it') && custausu_admin_is_it();

    if ($is_it && !empty($change[$field . '_it'])) {
      return (string) $change[$field . '_it'];
    }

    if (!$is_it && !empty($change[$field . '_en'])) {
      return (string) $change[$field . '_en'];
    }

    return (string)($change[$field . '_en'] ?? $change[$field . '_it'] ?? '');
  }
}

if (!function_exists('custausu_admin_doctor_render_change_tracking_card')) {
  function custausu_admin_doctor_render_change_tracking_card(array $change_tracking, callable $T): string {
    if (empty($change_tracking['previous_scan_present'])) {
      return '';
    }

    $changes = is_array($change_tracking['changes'] ?? null) ? $change_tracking['changes'] : [];
    $count = (int)($change_tracking['changes_count'] ?? count($changes));

    if ($count <= 0 || empty($changes)) {
      return '';
    }

    ob_start();

    echo '<div class="custausu-doctor-change-card">';
    echo '<div class="custausu-doctor-change-card__head">';
    echo '<div>';
    echo '<h3>' . esc_html($T('Recent CAS/site changes detected', 'Modifiche recenti CAS/sito rilevate')) . '</h3>';
    echo '<p>' . esc_html($T(
      'The Doctor noticed that something relevant changed since the previous scan. Review these notes before production checks or support escalation.',
      'Il Doctor ha notato che qualcosa di rilevante è cambiato dall’ultimo scan. Controlla queste note prima dei test di produzione o di aprire supporto.'
    )) . '</p>';
    echo '</div>';
    echo '<span class="custausu-badge custausu-badge--warn">' . esc_html(sprintf($T('%d change(s)', '%d modifica/e'), $count)) . '</span>';
    echo '</div>';

    echo '<ul class="custausu-doctor-change-list">';

    foreach (array_slice($changes, 0, 10) as $change) {
      if (!is_array($change)) {
        continue;
      }

      $severity = sanitize_key((string)($change['severity'] ?? 'info'));
      if (!in_array($severity, ['critical', 'warning', 'attention', 'info'], true)) {
        $severity = 'info';
      }

      $label = custausu_admin_doctor_change_text($change, 'label');
      $message = custausu_admin_doctor_change_text($change, 'message');
      $from = (string)($change['from'] ?? '');
      $to = (string)($change['to'] ?? '');

      echo '<li class="custausu-doctor-change-list__item custausu-doctor-change-list__item--' . esc_attr($severity) . '">';
      echo '<span class="custausu-doctor-severity custausu-doctor-severity--' . esc_attr($severity) . '">'
        . esc_html(custausu_admin_doctor_severity_label($severity, $T))
        . '</span>';
      echo '<span class="custausu-doctor-change-list__content">';
      echo '<strong>' . esc_html($label !== '' ? $label : $T('Change detected', 'Modifica rilevata')) . '</strong>';

      if ($from !== '' || $to !== '') {
        echo '<span class="custausu-doctor-change-list__delta">';
        echo esc_html($from !== '' ? $from : '—');
        echo ' → ';
        echo esc_html($to !== '' ? $to : '—');
        echo '</span>';
      }

      if ($message !== '') {
        echo '<span class="custausu-doctor-change-list__message">' . esc_html($message) . '</span>';
      }

      echo '</span>';
      echo '</li>';
    }

    if ($count > 10) {
      echo '<li class="custausu-doctor-change-list__more">';
      echo esc_html(sprintf(
        $T('And %d more change(s) in the exported report.', 'E altre %d modifica/e nel report esportato.'),
        $count - 10
      ));
      echo '</li>';
    }

    echo '</ul>';
    echo '</div>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_doctor_setup_card_title')) {
  function custausu_admin_doctor_setup_card_title(string $phase, callable $T): string {
    return match ($phase) {
      'first_install' => $T('First install', 'Prima installazione'),
      'setup_in_progress' => $T('Setup in progress', 'Setup in corso'),
      'configured' => $T('CAS setup configured', 'Setup CAS configurato'),
      default => $T('CAS setup status', 'Stato setup CAS'),
    };
  }
}

if (!function_exists('custausu_admin_doctor_setup_card_message')) {
  function custausu_admin_doctor_setup_card_message(string $phase, callable $T): string {
    return match ($phase) {
      'first_install' => $T(
        'Before setup, use the Doctor to understand whether the site/server is ready. If something is required, fix it first; if it is only recommended, you can continue with awareness.',
        'Prima del setup, usa il Doctor per capire se sito/server sono pronti. Se qualcosa è obbligatorio, correggilo prima; se è solo consigliato, puoi proseguire con consapevolezza.'
      ),
      'setup_in_progress' => $T(
        'CAS setup has started but is not complete yet. Complete the core routes and protected paths, then re-run the Doctor before production.',
        'Il setup CAS è iniziato ma non è ancora completo. Completa route core e percorsi protetti, poi ricontrolla il Doctor prima della produzione.'
      ),
      'configured' => $T(
        'CAS appears configured. Re-check the Doctor after license changes, route changes, cache changes, plugin updates or before opening a technical support request.',
        'CAS risulta configurato. Ricontrolla il Doctor dopo modifiche a licenza, route, cache, aggiornamenti plugin o prima di aprire una richiesta tecnica di supporto.'
      ),
      default => $T(
        'Use this area to understand the current CAS setup state before production or support.',
        'Usa quest’area per capire lo stato attuale del setup CAS prima della produzione o del supporto.'
      ),
    };
  }
}

if (!function_exists('custausu_admin_doctor_history_text')) {
  function custausu_admin_doctor_history_text(array $event, string $key, callable $T): string {
    $is_it = function_exists('custausu_admin_is_it') && custausu_admin_is_it();

    if ($is_it && !empty($event[$key . '_it'])) return (string)$event[$key . '_it'];
    if (!$is_it && !empty($event[$key . '_en'])) return (string)$event[$key . '_en'];

    return (string)($event[$key . '_en'] ?? $event[$key . '_it'] ?? '');
  }
}

if (!function_exists('custausu_admin_doctor_format_local_datetime')) {
  function custausu_admin_doctor_format_local_datetime(string $utc_datetime, callable $T): string {
    $utc_datetime = trim($utc_datetime);

    if ($utc_datetime === '') {
      return '';
    }

    try {
      $dt = new DateTimeImmutable($utc_datetime, new DateTimeZone('UTC'));
      $timestamp = $dt->getTimestamp();
    } catch (Throwable $e) {
      return $utc_datetime;
    }

    $timezone = function_exists('wp_timezone') ? wp_timezone() : new DateTimeZone('UTC');
    $locale = function_exists('get_user_locale') ? get_user_locale() : get_locale();

    $formatted = '';

    if (function_exists('switch_to_locale') && function_exists('restore_previous_locale')) {
      $switched = switch_to_locale($locale);

      $formatted = wp_date('j F Y H:i', $timestamp, $timezone);

      if ($switched) {
        restore_previous_locale();
      }
    } else {
      $formatted = wp_date('j F Y H:i', $timestamp, $timezone);
    }

    if (function_exists('custausu_admin_is_it') && custausu_admin_is_it()) {
      $months = [
        'January' => 'gennaio',
        'February' => 'febbraio',
        'March' => 'marzo',
        'April' => 'aprile',
        'May' => 'maggio',
        'June' => 'giugno',
        'July' => 'luglio',
        'August' => 'agosto',
        'September' => 'settembre',
        'October' => 'ottobre',
        'November' => 'novembre',
        'December' => 'dicembre',
        'Jan' => 'gen',
        'Feb' => 'feb',
        'Mar' => 'mar',
        'Apr' => 'apr',
        'Jun' => 'giu',
        'Jul' => 'lug',
        'Aug' => 'ago',
        'Sep' => 'set',
        'Oct' => 'ott',
        'Nov' => 'nov',
        'Dec' => 'dic',
      ];

      $formatted = strtr($formatted, $months);
    }

    return $formatted;
  }
}

if (!function_exists('custausu_admin_doctor_render_change_history')) {
  function custausu_admin_doctor_render_change_history(array $history, callable $T): string {
    $history = array_values(array_filter($history, 'is_array'));
    $latest = array_reverse(array_slice($history, -12));

    ob_start();

    echo '<div class="custausu-doctor-history">';
    echo '<div class="custausu-doctor-history__head">';
    echo '<strong>' . esc_html($T('Recent Doctor memory', 'Memoria recente del Doctor')) . '</strong>';

    $history_count = count($history);
    $history_limit = function_exists('custausu_compatibility_doctor_history_limit')
      ? (int) custausu_compatibility_doctor_history_limit()
      : 120;

    if ($history_limit <= 0) {
      $history_limit = 120;
    }

    $history_limit_reached = ($history_count >= $history_limit);

    $history_badge = (function_exists('custausu_admin_is_it') && custausu_admin_is_it())
      ? sprintf('%d eventi', $history_count)
      : sprintf('%d events', $history_count);

    echo '<span class="custausu-doctor-history__head-actions">';
    echo '<span class="custausu-badge custausu-badge--muted">' . esc_html($history_badge) . '</span>';

    if ($history_limit_reached) {
      echo '<span class="custausu-badge custausu-badge--warn">'
        . esc_html(sprintf(
          $T('Max %d reached', 'Max %d raggiunto'),
          $history_limit
        ))
        . '</span>';
    }

    echo '</span>';
    echo '</div>';

    if (empty($latest)) {
      echo '<p class="custausu-doctor-history__empty">' . esc_html($T(
        'No relevant change has been recorded yet.',
        'Nessuna modifica rilevante registrata per ora.'
      )) . '</p>';
      echo '</div>';

      return (string) ob_get_clean();
    }

    echo '<div class="custausu-doctor-history__list">';

    foreach ($latest as $event) {
      $severity = sanitize_key((string)($event['severity'] ?? 'info'));
      if (!in_array($severity, ['info', 'attention', 'warning'], true)) {
        $severity = 'info';
      }

      $title = custausu_admin_doctor_history_text($event, 'title', $T);
      $message = custausu_admin_doctor_history_text($event, 'message', $T);
      $from = trim((string)($event['from'] ?? ''));
      $to = trim((string)($event['to'] ?? ''));
      $date = trim((string)($event['detected_at_utc'] ?? ''));

      echo '<div class="custausu-doctor-history__item custausu-doctor-history__item--' . esc_attr($severity) . '">';
      echo '<span class="custausu-doctor-history__severity">' . esc_html($severity === 'attention' ? $T('Attention', 'Attenzione') : strtoupper($severity)) . '</span>';
      echo '<span class="custausu-doctor-history__content">';
      echo '<strong class="custausu-doctor-history__title">' . esc_html($title) . '</strong>';

      if ($from !== '' || $to !== '') {
        echo '<span class="custausu-doctor-history__delta">' . esc_html($from . ' → ' . $to) . '</span>';
      }

      if ($message !== '') {
        echo '<span class="custausu-doctor-history__message">' . esc_html($message) . '</span>';
      }

      if ($date !== '') {
        $local_date = custausu_admin_doctor_format_local_datetime($date, $T);

        echo '<span class="custausu-doctor-history__date" title="' . esc_attr($date . ' UTC') . '">'
          . esc_html($local_date)
          . '</span>';
      }

      echo '</span>';
      echo '</div>';
    }

    echo '</div>';

    if (!empty($history_limit_reached)) {
      $reset_url = wp_nonce_url(
        admin_url('admin-post.php?action=custausu_reset_doctor_history'),
        'custausu_reset_doctor_history'
      );

      echo '<div class="custausu-doctor-history__limit-box">';
      echo '<p>';
      echo '<strong>' . esc_html($T('Memory limit reached.', 'Limite memoria raggiunto.')) . '</strong> ';
      echo esc_html($T(
        'Reset the Doctor memory only if you want to record new events and you believe they will be useful for the report to submit to the Support Desk.',
        'Azzera la memoria solo se vuoi registrare nuovi eventi e pensi siano utili per il report da presentare al Support Desk.'
      ));
      echo '</p>';
      echo '<a class="button button-small custausu-doctor-history__reset" href="' . esc_url($reset_url) . '">'
        . esc_html($T('Reset Doctor memory', 'Azzera memoria Doctor'))
        . '</a>';
      echo '</div>';
    }

    echo '</div>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_doctor_render_setup_card')) {
  function custausu_admin_doctor_render_setup_card(array $scan, callable $T): string {
    $setup_context = is_array($scan['setup_context'] ?? null) ? $scan['setup_context'] : [];
    $phase = sanitize_key((string)($setup_context['phase'] ?? 'unknown'));
    $history = is_array($scan['change_history'] ?? null) ? $scan['change_history'] : [];

    ob_start();

    echo '<div class="custausu-doctor-life-card custausu-doctor-life-card--setup">';
    echo '<h3>' . esc_html(custausu_admin_doctor_setup_card_title($phase, $T)) . '</h3>';
    echo '<p>' . esc_html(custausu_admin_doctor_setup_card_message($phase, $T)) . '</p>';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Doctor change history renderer returns controlled escaped admin HTML.
    echo wp_kses( custausu_admin_doctor_render_change_history($history, $T), custausu_admin_allowed_output_html() );
    echo '</div>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_doctor_safe_mode_source_label')) {
  function custausu_admin_doctor_safe_mode_source_label(string $source, callable $T): string {
    $source = sanitize_key($source);

    return match ($source) {
      'off' => $T('Off', 'Disattivato'),
      'option' => $T('Backend / database option', 'Opzione backend / database'),
      'wp-config' => 'wp-config.php',
      default => $source !== '' ? str_replace('_', ' ', $source) : $T('Unknown', 'Sconosciuta'),
    };
  }
}

if (!function_exists('custausu_admin_doctor_safe_mode_reason_label')) {
  function custausu_admin_doctor_safe_mode_reason_label(string $reason, callable $T): string {
    $reason = sanitize_key($reason);

    return match ($reason) {
      'admin' => $T('Enabled from the CAS admin panel', 'Attivato dal pannello admin CAS'),
      'manual' => $T('Manual activation', 'Attivazione manuale'),
      'wp_cli' => 'WP-CLI',
      'wp_cli_test' => $T('WP-CLI test activation', 'Attivazione test da WP-CLI'),
      'forced_by_wp_config' => $T('Forced by wp-config.php', 'Forzato da wp-config.php'),
      default => $reason !== '' ? str_replace('_', ' ', $reason) : $T('Not available', 'Non disponibile'),
    };
  }
}

if (!function_exists('custausu_admin_doctor_recovery_status_label')) {
  function custausu_admin_doctor_recovery_status_label(string $status, callable $T): string {
    $status = sanitize_key($status);

    return match ($status) {
      'ready' => $T('Ready', 'Pronto'),
      'limited' => $T('Limited', 'Limitato'),
      'safe_mode_active' => $T('Safe Mode active', 'Safe Mode attivo'),
      'recovery_active' => $T('Recovery active', 'Recupero attivo'),
      default => $status !== '' ? str_replace('_', ' ', $status) : $T('Unknown', 'Sconosciuto'),
    };
  }
}

if (!function_exists('custausu_admin_doctor_render_recovery_readiness_block')) {
  function custausu_admin_doctor_render_recovery_readiness_block(callable $T): string {
    $recovery = function_exists('custausu_compatibility_recovery_readiness')
      ? custausu_compatibility_recovery_readiness()
      : [];

    if (!is_array($recovery) || empty($recovery)) {
      return '';
    }

    $status = sanitize_key((string)($recovery['status'] ?? 'unknown'));
    $safe = is_array($recovery['safe_mode'] ?? null) ? $recovery['safe_mode'] : [];
    $rollback = is_array($recovery['rollback']['wp_rollback_plugin'] ?? null) ? $recovery['rollback']['wp_rollback_plugin'] : [];
    $wp_cli = is_array($recovery['wp_cli'] ?? null) ? $recovery['wp_cli'] : [];

    $rollback_label = $T('Not detected', 'Non rilevato');
    if (!empty($rollback['active'])) {
      $rollback_label = $T('Active', 'Attivo');
    } elseif (!empty($rollback['installed'])) {
      $rollback_label = $T('Installed, not active', 'Installato, non attivo');
    }

    ob_start();

    echo '<div class="custausu-doctor-recovery-readiness">';
    echo '<h4>' . esc_html($T('Recovery readiness', 'Prontezza recupero')) . '</h4>';

    echo '<ul>';
    echo '<li>' . esc_html(sprintf(
      $T('Status: %s', 'Stato: %s'),
      custausu_admin_doctor_recovery_status_label($status, $T)
    )) . '</li>';

    echo '<li>' . esc_html(sprintf(
      $T('Safe Mode force constant: %s', 'Costante force Safe Mode: %s'),
      (string)($safe['wp_config_constant'] ?? 'CUSTAUSU_SAFE_MODE_FORCE')
    )) . '</li>';

    echo '<li>' . esc_html(sprintf(
      $T('WP Rollback plugin: %s', 'Plugin WP Rollback: %s'),
      $rollback_label
    )) . '</li>';

    echo '<li>' . esc_html(sprintf(
      $T('WP-CLI report callable: %s', 'Report WP-CLI disponibile: %s'),
      !empty($wp_cli['support_report_callable']) ? 'YES' : 'NO'
    )) . '</li>';

    echo '</ul>';

    echo '<div class="custausu-doctor-recovery-rollback-note">';
    echo '<strong>' . esc_html($T('Rollback and backups', 'Rollback e backup')) . '</strong>';
    echo '<p>' . esc_html($T(
      'Rollback is not automatic. If a recovery is needed, use a tested hosting backup, a tested backup/restore flow such as UpdraftPlus or Duplicator, or a rollback plugin such as WP Rollback when appropriate. Export the Doctor report before any recovery action.',
      'Il rollback non è automatico. Se serve un recupero, usa un backup hosting testato, un flusso backup/ripristino già testato come UpdraftPlus o Duplicator, oppure un plugin rollback come WP Rollback quando appropriato. Esporta il report Doctor prima di qualsiasi azione di recupero.'
    )) . '</p>';
    echo '</div>';


    echo '<details class="custausu-doctor-recovery-details">';
    echo '<summary>' . esc_html($T('Recovery commands and instructions', 'Comandi recupero ed istruzioni')) . '</summary>';

    echo '<div class="custausu-doctor-recovery-guide-card">';
    echo '<h4>' . esc_html($T('How to use these recovery commands', 'Come usare questi comandi di recupero')) . '</h4>';
    echo '<p>' . esc_html($T(
      'These commands are not normal settings. Use them only when CAS routes, redirects, cache or login conflicts make the site difficult to access.',
      'Questi comandi non sono impostazioni normali. Usali solo quando conflitti su route, redirect, cache o login rendono difficile accedere al sito.'
    )) . '</p>';

    echo '<ol class="custausu-doctor-recovery-guide-list">';

    echo '<li>';
    echo '<strong>' . esc_html($T('Force Safe Mode from wp-config.php', 'Forzare Safe Mode da wp-config.php')) . '</strong>';
    echo '<br><span>' . wp_kses_post($T(
      'Use this when you cannot reliably enter the WordPress admin area. Add the <code>CUSTAUSU_SAFE_MODE_FORCE</code> line inside <code>wp-config.php</code>, preferably before the “That’s all, stop editing” comment. Remove it again after recovery.',
      'Usalo quando non riesci ad accedere in modo affidabile all’area admin WordPress. Inserisci la riga <code>CUSTAUSU_SAFE_MODE_FORCE</code> dentro <code>wp-config.php</code>, preferibilmente prima del commento “That’s all, stop editing”. Rimuovila di nuovo dopo il recupero.'
    )) . '</span>';
    echo '</li>';

    echo '<li>';
    echo '<strong>' . esc_html($T('Enable Safe Mode from WP-CLI', 'Attivare Safe Mode da WP-CLI')) . '</strong>';
    echo '<br><span>' . wp_kses_post($T(
      'Use this from a terminal, SSH session or Local shell, while you are inside the WordPress root folder. It enables CAS Safe Mode without editing files.',
      'Usalo da terminale, sessione SSH o shell di Local, mentre ti trovi nella cartella principale di WordPress. Attiva CAS Safe Mode senza modificare file.'
    )) . '</span>';
    echo '</li>';

    echo '<li>';
    echo '<strong>' . esc_html($T('Disable Safe Mode after the fix', 'Disattivare Safe Mode dopo la correzione')) . '</strong>';
    echo '<br><span>' . esc_html($T(
      'Run the disable command only after login, routes and cache exclusions are working again.',
      'Esegui il comando di disattivazione solo dopo aver verificato che login, route ed esclusioni cache funzionino di nuovo.'
    )) . '</span>';
    echo '</li>';

    echo '<li>';
    echo '<strong>' . esc_html($T('Generate a Doctor Report for support', 'Generare un Doctor Report per il supporto')) . '</strong>';
    echo '<br><span>' . esc_html($T(
      'Use the report command when support asks for a diagnostic snapshot. It prints a redacted JSON report that can be copied or attached to a ticket.',
      'Usa il comando report quando il supporto richiede uno snapshot diagnostico. Stampa un report JSON redatto che può essere copiato o allegato a un ticket.'
    )) . '</span>';
    echo '</li>';

    echo '</ol>';

    echo '<p class="custausu-doctor-recovery-guide-note">' . esc_html($T(
      'If you are not comfortable with wp-config.php, SSH or WP-CLI, send this section to your hosting provider, developer or CAS Support Desk instead of trying commands blindly.',
      'Se non ti senti sicuro con wp-config.php, SSH o WP-CLI, invia questa sezione al tuo hosting, sviluppatore o al CAS Support Desk invece di eseguire comandi alla cieca.'
    )) . '</p>';

    echo '</div>';

    echo '<div class="custausu-doctor-code-list">';
    echo '<code class="custausu-doctor-code">define(&#039;CUSTAUSU_SAFE_MODE_FORCE&#039;, true);</code>';
    echo '<code class="custausu-doctor-code">wp eval &#039;custausu_safe_mode_enable(&quot;wp_cli_recovery&quot;);&#039;</code>';
    echo '<code class="custausu-doctor-code">wp eval &#039;custausu_safe_mode_disable();&#039;</code>';
    echo '<code class="custausu-doctor-code">wp eval &#039;$r = custausu_support_report_generate(); echo wp_json_encode($r, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);&#039;</code>';
    echo '</div>';
    echo '</details>';


    echo '</div>';

    return (string) ob_get_clean();
  }
}


if (!function_exists('custausu_admin_doctor_safe_mode_is_enabled_safe')) {
  function custausu_admin_doctor_safe_mode_is_enabled_safe(): bool {
    return function_exists('custausu_safe_mode_is_enabled')
      ? (bool) call_user_func('custausu_safe_mode_is_enabled')
      : false;
  }
}

if (!function_exists('custausu_admin_doctor_safe_mode_is_forced_safe')) {
  function custausu_admin_doctor_safe_mode_is_forced_safe(): bool {
    return function_exists('custausu_safe_mode_is_forced')
      ? (bool) call_user_func('custausu_safe_mode_is_forced')
      : false;
  }
}

if (!function_exists('custausu_admin_doctor_safe_mode_source_safe')) {
  function custausu_admin_doctor_safe_mode_source_safe(): string {
    if (!function_exists('custausu_safe_mode_source')) {
      return 'unknown';
    }

    $source = call_user_func('custausu_safe_mode_source');

    return is_scalar($source) ? sanitize_key((string) $source) : 'unknown';
  }
}

if (!function_exists('custausu_admin_doctor_safe_mode_reason_safe')) {
  function custausu_admin_doctor_safe_mode_reason_safe(): string {
    if (!function_exists('custausu_safe_mode_reason')) {
      return '';
    }

    $reason = call_user_func('custausu_safe_mode_reason');

    return is_scalar($reason) ? sanitize_key((string) $reason) : '';
  }
}

if (!function_exists('custausu_admin_doctor_render_safety_card')) {
  function custausu_admin_doctor_render_safety_card(callable $T): string {
    $safe_available = function_exists('custausu_safe_mode_is_enabled');
    $safe_enabled = custausu_admin_doctor_safe_mode_is_enabled_safe();
    $safe_forced = custausu_admin_doctor_safe_mode_is_forced_safe();

    $safe_source_raw = custausu_admin_doctor_safe_mode_source_safe();
    $safe_reason_raw = $safe_enabled ? custausu_admin_doctor_safe_mode_reason_safe() : '';

    $safe_source = custausu_admin_doctor_safe_mode_source_label($safe_source_raw, $T);
    $safe_reason = $safe_reason_raw !== ''
      ? custausu_admin_doctor_safe_mode_reason_label($safe_reason_raw, $T)
      : '';

    $enable_url = wp_nonce_url(
      admin_url('admin-post.php?action=custausu_enable_safe_mode'),
      'custausu_safe_mode_action'
    );

    $disable_url = wp_nonce_url(
      admin_url('admin-post.php?action=custausu_disable_safe_mode'),
      'custausu_safe_mode_action'
    );

    $classes = [
      'custausu-doctor-life-card',
      'custausu-doctor-life-card--safety',
    ];

    if ($safe_enabled) {
      $classes[] = 'custausu-doctor-life-card--safety-active';
    }

    if ($safe_forced) {
      $classes[] = 'custausu-doctor-life-card--safety-forced';
    }

    ob_start();

    echo '<div class="' . esc_attr(implode(' ', $classes)) . '">';
    echo '<h3>' . esc_html($T('Safety & Recovery', 'Sicurezza e recupero')) . '</h3>';

    if (!$safe_available) {
      echo '<p>' . esc_html($T(
        'CAS Safe Mode is not available in this build.',
        'CAS Safe Mode non è disponibile in questa build.'
      )) . '</p>';
      echo '</div>';

      return (string) ob_get_clean();
    }

    if ($safe_enabled) {
      echo '<p>';
      echo '<strong>' . esc_html($T('Safe Mode is active.', 'Safe Mode è attivo.')) . '</strong> ';
      echo esc_html($T(
        'CAS custom redirects are bypassed and protected paths fall back to the native WordPress login.',
        'I redirect custom CAS sono bypassati e i percorsi protetti usano il login WordPress nativo.'
      ));
      echo '</p>';
    } else {
      echo '<p>';
      echo '<strong>' . esc_html($T('Safe Mode is off.', 'Safe Mode è disattivato.')) . '</strong> ';
      echo esc_html($T(
        'Use it only when you need to recover from route, redirect, cache or login conflicts.',
        'Usalo solo quando devi recuperare da conflitti su route, redirect, cache o login.'
      ));
      echo '</p>';
    }

    echo '<p class="custausu-doctor-card__intro">';
    echo esc_html(sprintf(
      $T('Source: %s', 'Origine: %s'),
      $safe_source
    ));

    if ($safe_reason !== '') {
      echo '<br>' . esc_html(sprintf(
        $T('Reason: %s', 'Motivo: %s'),
        $safe_reason
      ));
    }

    echo '</p>';

    echo '<div class="custausu-doctor-life-card__actions">';

    if ($safe_enabled) {
      if ($safe_forced) {
        echo '<span class="custausu-badge custausu-badge--warn">';
        echo esc_html($T(
          'Forced by wp-config.php',
          'Forzato da wp-config.php'
        ));
        echo '</span>';
      } else {
        echo '<a class="button button-secondary" href="' . esc_url($disable_url) . '">';
        echo esc_html($T('Disable Safe Mode', 'Disattiva Safe Mode'));
        echo '</a>';
      }
    } else {
    echo '<a class="button button-secondary custausu-doctor-safe-mode-enable" href="' . esc_url($enable_url) . '">';
    echo esc_html($T('Enable Safe Mode', 'Attiva Safe Mode'));
    echo '</a>';
    }

    echo '</div>';

    echo wp_kses( custausu_admin_doctor_render_recovery_readiness_block($T), custausu_admin_allowed_output_html() );

    if ($safe_forced) {
      echo '<p class="custausu-doctor-card__intro">';
      echo esc_html($T(
        'To disable it, remove CUSTAUSU_SAFE_MODE_FORCE from wp-config.php or set it to false.',
        'Per disattivarlo, rimuovi CUSTAUSU_SAFE_MODE_FORCE da wp-config.php oppure impostalo a false.'
      ));
      echo '</p>';
    }

    echo '</div>';

    return (string) ob_get_clean();
  }
}

/* -----------------------------------------------------------------------------
   CAS Installation Doctor - readable HTML support report export
----------------------------------------------------------------------------- */

if (!function_exists('custausu_admin_doctor_report_is_assoc')) {
  function custausu_admin_doctor_report_is_assoc(array $arr): bool {
    if ($arr === []) {
      return false;
    }

    return array_keys($arr) !== range(0, count($arr) - 1);
  }
}

if (!function_exists('custausu_admin_doctor_report_label')) {
  function custausu_admin_doctor_report_label($key): string {
    $key = (string) $key;
    $key = preg_replace('/[_\-]+/', ' ', $key);
    $key = trim((string) $key);

    if ($key === '') {
      return 'Item';
    }

    return ucwords($key);
  }
}

if (!function_exists('custausu_admin_doctor_report_status_class')) {
  function custausu_admin_doctor_report_status_class($value): string {
    $v = strtolower(trim((string) $value));

    if ($v === '') {
      return 'custausu-rpt-pill--neutral';
    }

    /*
     * Negative states must be checked before positive substrings.
     * Example: "not connected" contains "connected"; "inactive" contains "active".
     */
    if (
      str_contains($v, 'not connected') ||
      str_contains($v, 'disconnected') ||
      str_contains($v, 'error') ||
      str_contains($v, 'critical') ||
      str_contains($v, 'invalid') ||
      str_contains($v, 'missing') ||
      str_contains($v, 'failed') ||
      str_contains($v, 'blocked') ||
      str_contains($v, 'expired') ||
      str_contains($v, 'revoked')
    ) {
      return 'custausu-rpt-pill--error';
    }

    if (
      str_contains($v, 'inactive') ||
      str_contains($v, 'deactivated') ||
      str_contains($v, 'not active') ||
      str_contains($v, 'warn') ||
      str_contains($v, 'attention') ||
      str_contains($v, 'review') ||
      str_contains($v, 'limited') ||
      str_contains($v, 'fallback')
    ) {
      return 'custausu-rpt-pill--warn';
    }

    if (
      str_contains($v, 'ok') ||
      str_contains($v, 'good') ||
      str_contains($v, 'valid') ||
      str_contains($v, 'active') ||
      str_contains($v, 'configured') ||
      str_contains($v, 'connected') ||
      str_contains($v, 'success')
    ) {
      return 'custausu-rpt-pill--ok';
    }

    if (
      str_contains($v, 'info') ||
      str_contains($v, 'notice') ||
      str_contains($v, 'debug')
    ) {
      return 'custausu-rpt-pill--info';
    }

    return 'custausu-rpt-pill--neutral';
  }
}

if (!function_exists('custausu_admin_doctor_report_scalar_html')) {
  function custausu_admin_doctor_report_scalar_html($value, string $key = ''): string {
    if (is_bool($value)) {
      return $value
        ? '<span class="custausu-rpt-pill custausu-rpt-pill--ok">yes</span>'
        : '<span class="custausu-rpt-pill custausu-rpt-pill--neutral">no</span>';
    }

    if ($value === null) {
      return '<span class="custausu-rpt-muted">null</span>';
    }

    if (is_int($value) || is_float($value)) {
      return '<span class="custausu-rpt-code">' . esc_html((string) $value) . '</span>';
    }

    $string = (string) $value;
    $lower_key = strtolower($key);

    if (
      in_array($lower_key, ['status', 'state', 'severity', 'level', 'result', 'mode'], true) ||
      str_contains($lower_key, 'status') ||
      str_contains($lower_key, 'severity')
    ) {
      $class = custausu_admin_doctor_report_status_class($string);

      return '<span class="custausu-rpt-pill ' . esc_attr($class) . '">' . esc_html($string) . '</span>';
    }

    if (filter_var($string, FILTER_VALIDATE_URL)) {
      return '<a href="' . esc_url($string) . '" target="_blank" rel="noopener noreferrer">'
        . esc_html($string)
        . '</a>';
    }

    if (strlen($string) > 180 || str_contains($string, "\n")) {
      return '<pre class="custausu-rpt-pre">' . esc_html($string) . '</pre>';
    }

    if ($string === '') {
      return '<span class="custausu-rpt-muted">empty</span>';
    }

    return esc_html($string);
  }
}

if (!function_exists('custausu_admin_doctor_report_plugin_inventory_html')) {
  function custausu_admin_doctor_report_plugin_inventory_html(array $inventory): string {
    $buckets = [
      'known_cas_relevant' => 'Plugins recognized as CAS-relevant',
      'other' => 'Other unclassified plugins',
    ];

    $groups = [
      'active' => 'Active',
      'inactive' => 'Inactive',
      'network_active' => 'Network active',
      'must_use' => 'Must-use',
      'drop_ins' => 'Drop-ins',
    ];

    $html = '<div class="custausu-rpt-plugin-inventory">';
    $html .= '<p class="custausu-rpt-muted">Informational inventory only. Compatibility warnings and recommendations remain in the separate compatibility scan.</p>';

    foreach ($buckets as $bucket => $bucket_label) {
      $html .= '<section class="custausu-rpt-subcard">';
      $html .= '<h3>' . esc_html($bucket_label) . '</h3>';

      foreach ($groups as $group => $group_label) {
        $items = (array)($inventory[$bucket][$group] ?? []);
        $html .= '<details>';
        $html .= '<summary>'
          . esc_html($group_label)
          . ' (' . esc_html((string)count($items)) . ')'
          . '</summary>';

        if ($items === []) {
          $html .= '<p class="custausu-rpt-muted">No plugins.</p>';
          $html .= '</details>';
          continue;
        }

        $html .= '<table class="custausu-rpt-table"><thead><tr>';
        $html .= '<th>Name</th>';
        $html .= '<th>Slug</th>';
        $html .= '<th>Version</th>';
        $html .= '<th>Status</th>';
        $html .= '</tr></thead><tbody>';

        foreach ($items as $item) {
          $item = is_array($item) ? $item : [];

          $html .= '<tr>';
          $html .= '<td>' . esc_html((string)($item['name'] ?? '')) . '</td>';
          $html .= '<td><code>' . esc_html((string)($item['slug'] ?? '')) . '</code></td>';
          $html .= '<td><code>' . esc_html((string)($item['version'] ?? '')) . '</code></td>';
          $html .= '<td>' . esc_html((string)($item['status'] ?? '')) . '</td>';
          $html .= '</tr>';
        }

        $html .= '</tbody></table>';
        $html .= '</details>';
      }

      $html .= '</section>';
    }

    $html .= '</div>';

    return $html;
  }
}

if (!function_exists('custausu_admin_doctor_report_value_html')) {
  function custausu_admin_doctor_report_value_html($value, string $key = '', int $depth = 0): string {
    if (!is_array($value)) {
      return custausu_admin_doctor_report_scalar_html($value, $key);
    }

    if ($value === []) {
      return '<span class="custausu-rpt-muted">Nessun dato</span>';
    }

    if (
      $key === 'plugin_inventory'
      && function_exists('custausu_admin_doctor_report_plugin_inventory_html')
    ) {
      return custausu_admin_doctor_report_plugin_inventory_html($value);
    }

    if ($depth > 7) {
      return '<pre class="custausu-rpt-pre">' . esc_html(wp_json_encode(
        $value,
        JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
      )) . '</pre>';
    }

    $is_assoc = custausu_admin_doctor_report_is_assoc($value);

    /*
     * Root / shallow associative arrays can be tables.
     * Deep associative arrays must NOT become nested fixed tables:
     * they become readable vertical key/value cards.
     */
    if ($is_assoc) {
      if ($depth >= 2) {
        $html = '<div class="custausu-rpt-kv-list">';

        foreach ($value as $k => $v) {
          $html .= '<div class="custausu-rpt-kv-item">';
          $html .= '<div class="custausu-rpt-kv-label">' . esc_html(custausu_admin_doctor_report_label($k)) . '</div>';
          $html .= '<div class="custausu-rpt-kv-value">' . custausu_admin_doctor_report_value_html($v, (string) $k, $depth + 1) . '</div>';
          $html .= '</div>';
        }

        $html .= '</div>';

        return $html;
      }

      $html = '<table class="custausu-rpt-table"><tbody>';

      foreach ($value as $k => $v) {
        $html .= '<tr>';
        $html .= '<th>' . esc_html(custausu_admin_doctor_report_label($k)) . '</th>';
        $html .= '<td>' . custausu_admin_doctor_report_value_html($v, (string) $k, $depth + 1) . '</td>';
        $html .= '</tr>';
      }

      $html .= '</tbody></table>';

      return $html;
    }

    $all_scalar = true;

    foreach ($value as $item) {
      if (is_array($item)) {
        $all_scalar = false;
        break;
      }
    }

    if ($all_scalar) {
      $html = '<ul class="custausu-rpt-list">';

      foreach ($value as $item) {
        $html .= '<li>' . custausu_admin_doctor_report_scalar_html($item, $key) . '</li>';
      }

      $html .= '</ul>';

      return $html;
    }

    $html = '<div class="custausu-rpt-card-list">';

    foreach ($value as $index => $item) {
      $html .= '<div class="custausu-rpt-subcard">';
      $html .= '<h3>' . esc_html(custausu_admin_doctor_report_label($key)) . ' #' . esc_html((string) ($index + 1)) . '</h3>';
      $html .= custausu_admin_doctor_report_value_html($item, $key, $depth + 1);
      $html .= '</div>';
    }

    $html .= '</div>';

    return $html;
  }
}

if (!function_exists('custausu_admin_doctor_report_pick_first')) {
  function custausu_admin_doctor_report_pick_first(array $report, array $keys): string {
    foreach ($keys as $key) {
      if (isset($report[$key]) && !is_array($report[$key])) {
        return (string) $report[$key];
      }
    }

    return '';
  }
}

if (!function_exists('custausu_admin_doctor_report_to_readable_html')) {
  function custausu_admin_doctor_report_to_readable_html(array $report): string {
    $site_name = get_bloginfo('name');
    $generated = gmdate('Y-m-d H:i:s') . ' UTC';

    $is_it = function_exists('custausu_admin_is_it') && custausu_admin_is_it();

    $txt = [
      'html_lang' => $is_it ? 'it' : 'en',
      'title' => $is_it
        ? 'Custom Auth Suite™ - Report Doctor per il supporto'
        : 'Custom Auth Suite™ - Doctor Support Report',
      'hero_title' => $is_it
        ? 'Custom Auth Suite™ - Report Doctor per il supporto'
        : 'Custom Auth Suite™ - Doctor Support Report',
      'hero_desc' => $is_it
        ? 'Report leggibile generato dal CAS Installation Doctor. Pensato per assistenza, support readiness, cache guidance e troubleshooting senza esporre segreti completi.'
        : 'Readable report generated by the CAS Installation Doctor. Designed for support, support readiness, cache guidance and troubleshooting without exposing complete secrets.',
      'hero_note' => $is_it
        ? 'Verifica sempre che il report non contenga dati non necessari prima di condividerlo fuori dal tuo team/supporto.'
        : 'Always verify that the report does not contain unnecessary data before sharing it outside your team/support channel.',
      'site' => $is_it ? 'Sito' : 'Site',
      'generated' => $is_it ? 'Generato il' : 'Generated at',
      'doctor_status' => $is_it ? 'Stato Doctor' : 'Doctor status',
      'technical_json' => $is_it ? 'JSON tecnico redatto' : 'Redacted technical JSON',
      'footer' => $is_it
        ? 'Generato da Custom Auth Suite™ Installation Doctor'
        : 'Generated by Custom Auth Suite™ Installation Doctor',
    ];

    $status = custausu_admin_doctor_report_pick_first($report, [
      'status',
      'doctor_status',
      'health_status',
      'support_readiness',
    ]);

    $package = custausu_admin_doctor_report_pick_first($report, [
      'package_plan',
      'package',
      'build_package_plan',
    ]);

    $effective_plan = custausu_admin_doctor_report_pick_first($report, [
      'effective_plan',
      'plan',
      'runtime_plan',
    ]);

    $plugin_version = custausu_admin_doctor_report_pick_first($report, [
      'plugin_version',
      'version',
      'cas_version',
    ]);

    $json = wp_json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $json = is_string($json) ? $json : '{}';

    $summary_items = [
      $txt['site'] => $site_name,
      $txt['generated'] => $generated,
      $txt['doctor_status'] => $status,
      'Effective plan' => $effective_plan,
      'Package plan' => $package,
      'Plugin version' => $plugin_version,
    ];

    $summary_html = '';

    foreach ($summary_items as $label => $value) {
      if ((string) $value === '') {
        continue;
      }

      $summary_html .= '<div class="custausu-rpt-summary-item">';
      $summary_html .= '<span>' . esc_html($label) . '</span>';
      $summary_html .= '<strong>' . custausu_admin_doctor_report_scalar_html($value, $label) . '</strong>';
      $summary_html .= '</div>';
    }

    $sections_html = '';

    foreach ($report as $key => $value) {
      $sections_html .= '<section class="custausu-rpt-section">';
      $sections_html .= '<h2>' . esc_html(custausu_admin_doctor_report_label($key)) . '</h2>';
      $sections_html .= custausu_admin_doctor_report_value_html($value, (string) $key, 1);
      $sections_html .= '</section>';
    }

    return '<!doctype html>
<html lang="' . esc_attr($txt['html_lang']) . '">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>' . esc_html($txt['title']) . '</title>
' . (function_exists('custausu_asset_enqueued_stylesheet_link_html')
  ? custausu_asset_enqueued_stylesheet_link_html(
      'custausu-doctor-report',
      'inc/css/custausu-doctor-report.css'
    )
  : '') . '
</head>
<body>
  <main class="custausu-rpt-wrap">
    <header class="custausu-rpt-hero">
      <h1>' . esc_html($txt['hero_title']) . '</h1>
      <p>' . esc_html($txt['hero_desc']) . '</p>
      <div class="custausu-rpt-note">' . esc_html($txt['hero_note']) . '</div>
    </header>

    <section class="custausu-rpt-summary">
      ' . $summary_html . '
    </section>

    ' . $sections_html . '

    <details class="custausu-rpt-json">
      <summary>' . esc_html($txt['technical_json']) . '</summary>
      <div class="custausu-rpt-json-body">
        <pre class="custausu-rpt-pre">' . esc_html($json) . '</pre>
      </div>
    </details>

    <footer class="custausu-rpt-footer">
      ' . esc_html($txt['footer']) . ' - ' . esc_html($generated) . '
    </footer>
  </main>
</body>
</html>';
  }
}


if (!function_exists('custausu_admin_doctor_export_safe_scalar')) {
  function custausu_admin_doctor_export_safe_scalar($value) {
    if (is_bool($value) || is_int($value) || $value === null) {
      return $value;
    }

    if (is_float($value)) {
      return round($value, 4);
    }

    if (is_string($value)) {
      $value = sanitize_text_field($value);

      if (strlen($value) > 500) {
        $value = substr($value, 0, 500) . '…';
      }

      return $value;
    }

    return null;
  }
}

if (!function_exists('custausu_admin_doctor_export_safe_settings_summary')) {
  function custausu_admin_doctor_export_safe_settings_summary(array $settings): array {
    $allowed_keys = [
      'routes_default_lang'      => true,
      'protected_paths'          => true,
      'auth_theme'               => true,
      'email_theme'              => true,
      'email_tpl'                => true,
      'keep_data_on_uninstall'   => true,
      'routes_paths'             => true,
      'routes_page_ids'          => true,
      'legal_links'              => true,
      'routes_logout_redirect'   => true,
    ];

    $blocked_fragments = [
      'secret',
      'token',
      'api_key',
      'apikey',
      'password',
      'passphrase',
      'nonce',
      'license_key',
      'private',
    ];

    $summary = [];

    foreach ($settings as $key => $value) {
      $key_string = strtolower((string) $key);

      if (!isset($allowed_keys[$key_string])) {
        continue;
      }

      $blocked = false;

      foreach ($blocked_fragments as $fragment) {
        if (in_array($fragment, ['password', 'passphrase'], true)) {
          $tokens = preg_split('/[^a-z0-9]+/', $key_string);
          $tokens = is_array($tokens) ? array_filter($tokens) : [];

          if (in_array($fragment, $tokens, true)) {
            $blocked = true;
            break;
          }

          continue;
        }

        if (strpos($key_string, $fragment) !== false) {
          $blocked = true;
          break;
        }
      }

      if ($blocked) {
        $summary[$key] = '[redacted]';
        continue;
      }

      if (is_array($value)) {
        $summary[$key] = [
          'type'  => 'array',
          'count' => count($value),
        ];
        continue;
      }

      $safe = custausu_admin_doctor_export_safe_scalar($value);

      if ($safe !== null || $value === null) {
        $summary[$key] = $safe;
      }
    }

    return $summary;
  }
}

if (!function_exists('custausu_admin_doctor_generate_support_report_safe')) {
  function custausu_admin_doctor_generate_support_report_safe(): array {
    global $wp_version;

    $settings = get_option('custausu_global_settings', []);
    $settings = is_array($settings) ? $settings : [];

    $theme = wp_get_theme();
    $upload_dir = wp_upload_dir();

    $admin_email = (string) get_option('admin_email', '');
    $admin_email_hash = $admin_email !== ''
      ? hash('sha256', strtolower(trim($admin_email)) . '|' . wp_salt('auth'))
      : '';

    $protected_paths_export = [];

    if (function_exists('custausu_admin_health_check_collect_protected_paths')) {
      $protected_paths_export = custausu_admin_health_check_collect_protected_paths($settings);
    } else {
      $protected_paths_raw = $settings['protected_paths'] ?? '';

      if (is_array($protected_paths_raw)) {
        $protected_paths_export = array_values(array_filter(array_map(
          static fn($path): string => is_scalar($path) ? trim((string) $path) : '',
          $protected_paths_raw
        )));
      } else {
        $protected_paths_export = preg_split(
          '/(?:\r\n|\r|\n|[\t ,;]+)/',
          is_scalar($protected_paths_raw) ? trim((string) $protected_paths_raw) : ''
        );

        $protected_paths_export = array_values(array_filter(array_map(
          static fn($path): string => trim((string) $path),
          (array) $protected_paths_export
        )));
      }
    }

    $report = [
      'meta' => [
        'report_type'      => 'custom-auth-suite-doctor-support-report',
        'generated_at_utc' => gmdate('c'),
        'generated_by'     => 'Custom Auth Suite Doctor',
      ],
      'site' => [
        'home_url'         => home_url('/'),
        'site_url'         => site_url('/'),
        'name'             => get_bloginfo('name'),
        'locale'           => get_locale(),
        'timezone'         => wp_timezone_string(),
        'is_multisite'     => is_multisite(),
        'admin_email_hash' => $admin_email_hash,
      ],
      'environment' => [
        'wordpress_version' => isset($wp_version) ? (string) $wp_version : '',
        'php_version'       => PHP_VERSION,
        'environment_type'  => function_exists('wp_get_environment_type') ? wp_get_environment_type() : '',
        'debug'             => defined('WP_DEBUG') ? (bool) WP_DEBUG : false,
        'debug_log'         => defined('WP_DEBUG_LOG') ? (bool) WP_DEBUG_LOG : false,
        'memory_limit'      => ini_get('memory_limit'),
        'max_execution_time'=> ini_get('max_execution_time'),
      ],
      'plugin' => [
        'version'          => defined('CUSTAUSU_VERSION') ? (string) CUSTAUSU_VERSION : '',
        'plugin_file'      => defined('CUSTAUSU_PLUGIN_FILE') ? basename((string) CUSTAUSU_PLUGIN_FILE) : 'custom-auth-suite.php',
        'plugin_basename'  => defined('CUSTAUSU_PLUGIN_BASENAME') ? (string) CUSTAUSU_PLUGIN_BASENAME : '',
        'package'          => function_exists('custausu_build_package_plan')
          ? (string) custausu_build_package_plan()
          : (
            function_exists('custausu_get_package')
              ? (string) custausu_get_package()
              : (defined('CUSTAUSU_PACKAGE') ? (string) CUSTAUSU_PACKAGE : 'freemium')
          ),
        'edition'          => function_exists('custausu_build_edition')
          ? (string) custausu_build_edition()
          : (
            function_exists('custausu_get_edition')
              ? (string) custausu_get_edition()
              : (defined('CUSTAUSU_EDITION') ? (string) CUSTAUSU_EDITION : 'freemium_wporg')
          ),
        'build_package_plan' => function_exists('custausu_build_package_plan')
          ? (string) custausu_build_package_plan()
          : '',
        'build_edition'      => function_exists('custausu_build_edition')
          ? (string) custausu_build_edition()
          : '',
      ],
      'theme' => [
        'name'       => $theme ? $theme->get('Name') : '',
        'version'    => $theme ? $theme->get('Version') : '',
        'stylesheet' => get_stylesheet(),
        'template'   => get_template(),
      ],
      'plugin_inventory' => function_exists('custausu_support_report_plugin_inventory')
        ? custausu_support_report_plugin_inventory()
        : [],
      'uploads' => [
        'basedir_writable' => !empty($upload_dir['basedir']) ? wp_is_writable($upload_dir['basedir']) : false,
        'baseurl_present'  => !empty($upload_dir['baseurl']),
      ],
      'custausu_settings_summary' => custausu_admin_doctor_export_safe_settings_summary($settings),
      'routes' => [
        'default_lang' => isset($settings['routes_default_lang'])
          ? custausu_admin_doctor_export_safe_scalar($settings['routes_default_lang'])
          : '',
        'paths' => isset($settings['routes_paths']) && is_array($settings['routes_paths'])
          ? $settings['routes_paths']
          : [],
        'page_ids' => isset($settings['routes_page_ids']) && is_array($settings['routes_page_ids'])
          ? $settings['routes_page_ids']
          : [],
      ],
      'protected_paths' => $protected_paths_export,
    ];

    if (function_exists('custausu_admin_health_check_items')) {
      try {
        $health_items = custausu_admin_health_check_items();
        if (is_array($health_items)) {
          $report['health_check'] = $health_items;
        }
      } catch (Throwable $e) {
        $report['health_check_error'] = $e->getMessage();
      }
    }

    /**
     * Allows internal modules to add safe diagnostic data to the Doctor export.
     */
    return apply_filters('custausu_admin_doctor_support_report_safe', $report);
  }
}


if (!function_exists('custausu_admin_handle_export_support_report_action')) {
  function custausu_admin_handle_export_support_report_action(): void {
    if (!is_admin() || !current_user_can('manage_options')) {
      wp_die('Forbidden');
    }

    check_admin_referer('custausu_export_support_report');

    $report = custausu_admin_doctor_generate_support_report_safe();

    if (empty($report)) {
      wp_die('CAS support report generator unavailable or unable to generate report.');
    }

    $format = isset($_GET['format'])
      ? sanitize_key(wp_unslash((string) $_GET['format']))
      : 'json';

    if (!in_array($format, ['json', 'html'], true)) {
      $format = 'json';
    }

    $base_filename = 'custom-auth-suite-doctor-report-' . gmdate('Ymd-His');

    if (function_exists('nocache_headers')) {
      nocache_headers();
    }

    header('X-Content-Type-Options: nosniff');

    if ($format === 'html') {
      $html_safe = function_exists('custausu_admin_doctor_report_to_readable_html')
        ? custausu_admin_doctor_report_to_readable_html($report)
        : '<!doctype html><html><body><pre>' . esc_html(wp_json_encode(
            $report,
            JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
          )) . '</pre></body></html>';

      header('Content-Type: text/html; charset=UTF-8');
      header('Content-Disposition: attachment; filename="' . $base_filename . '.html"');

      // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $html_safe is the controlled complete HTML report download; escaping the complete document would corrupt it.
      echo $html_safe;
      exit;
    }

    $json_encoded_safe = wp_json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    if (!is_string($json_encoded_safe) || $json_encoded_safe === '') {
      wp_die('Unable to generate CAS support report.');
    }

    header('Content-Type: application/json; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $base_filename . '.json"');

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $json_encoded_safe is produced by wp_json_encode() for an application/json download.
    echo $json_encoded_safe;
    exit;
  }
}

if (!function_exists('custausu_admin_doctor_render_plugin_inventory_card')) {
  function custausu_admin_doctor_render_plugin_inventory_card(
    array $inventory,
    callable $T
  ): string {
    $bucket_labels = [
      'known_cas_relevant' => $T(
        'Plugins recognized as CAS-relevant',
        'Plugin riconosciuti come rilevanti per CAS'
      ),
      'other' => $T(
        'Other unclassified plugins',
        'Altri plugin non classificati'
      ),
    ];

    $group_labels = [
      'active' => $T('Active', 'Attivi'),
      'inactive' => $T('Inactive', 'Inattivi'),
      'network_active' => $T(
        'Network active',
        'Attivi sul network'
      ),
      'must_use' => $T('Must-use', 'Must-use'),
      'drop_ins' => $T('Drop-ins', 'Drop-in'),
    ];

    ob_start();

    echo '<div class="custausu-doctor-card custausu-doctor-card--full custausu-doctor-plugin-inventory">';
    echo '<h3>' . esc_html($T(
      'Installed plugin inventory',
      'Inventario plugin installati'
    )) . '</h3>';
    echo '<p class="custausu-doctor-card__intro">' . esc_html($T(
      'Neutral inventory of installed plugins. Compatibility warnings and recommendations remain in the separate Compatibility Scan.',
      'Inventario neutro dei plugin installati. Warning e raccomandazioni restano nello Scan compatibilità separato.'
    )) . '</p>';

    foreach ($bucket_labels as $bucket => $bucket_label) {
      echo '<details class="custausu-doctor-category-card">';
      echo '<summary class="custausu-doctor-category-card__summary">';
      echo '<span class="custausu-doctor-category-card__title">'
        . esc_html($bucket_label)
        . '</span>';
      echo '</summary>';
      echo '<div class="custausu-doctor-category-card__body">';

      foreach ($group_labels as $group => $group_label) {
        $items = (array)($inventory[$bucket][$group] ?? []);

        echo '<details class="custausu-doctor-cache-card">';
        echo '<summary class="custausu-doctor-cache-card__summary">';
        echo '<span class="custausu-doctor-cache-card__title">'
          . esc_html($group_label)
          . ' (' . esc_html((string)count($items)) . ')'
          . '</span>';
        echo '</summary>';
        echo '<div class="custausu-doctor-cache-card__body">';

        if ($items === []) {
          echo '<p class="custausu-doctor-empty">'
            . esc_html($T('No plugins.', 'Nessun plugin.'))
            . '</p>';
        } else {
          echo '<div class="custausu-table-wrap">';
          echo '<table class="widefat striped custausu-doctor-table">';
          echo '<thead><tr>';
          echo '<th>' . esc_html($T('Name', 'Nome')) . '</th>';
          echo '<th>Slug</th>';
          echo '<th>' . esc_html($T('Version', 'Versione')) . '</th>';
          echo '<th>' . esc_html($T('Status', 'Stato')) . '</th>';
          echo '</tr></thead><tbody>';

          foreach ($items as $item) {
            $item = is_array($item) ? $item : [];

            echo '<tr>';
            echo '<td>' . esc_html((string)($item['name'] ?? '')) . '</td>';
            echo '<td><code>' . esc_html((string)($item['slug'] ?? '')) . '</code></td>';
            echo '<td><code>' . esc_html((string)($item['version'] ?? '')) . '</code></td>';
            echo '<td>' . esc_html((string)($item['status'] ?? '')) . '</td>';
            echo '</tr>';
          }

          echo '</tbody></table>';
          echo '</div>';
        }

        echo '</div>';
        echo '</details>';
      }

      echo '</div>';
      echo '</details>';
    }

    echo '<p class="description">' . esc_html($T(
      'Only name, slug, version and status are shown. Settings, paths, keys and tokens are never included.',
      'Sono mostrati soltanto nome, slug, versione e stato. Impostazioni, percorsi, chiavi e token non vengono mai inclusi.'
    )) . '</p>';
    echo '</div>';

    return (string)ob_get_clean();
  }
}

if (!function_exists('custausu_admin_render_installation_doctor_section')) {
  function custausu_admin_render_installation_doctor_section(callable $T): string {
    $scan = function_exists('custausu_compatibility_scan')
      ? custausu_compatibility_scan()
      : [
          'items' => [],
          'counts' => [
            'critical' => 0,
            'warning' => 0,
            'attention' => 0,
            'info' => 0,
          ],
          'cache_guidance' => [],
          'setup_context' => [
            'phase' => 'unknown',
          ],
          'support_readiness' => [
            'status' => 'ready',
          ],
        ];

    $items = is_array($scan['items'] ?? null) ? $scan['items'] : [];
    $counts = is_array($scan['counts'] ?? null) ? $scan['counts'] : [];
    $cache_guidance = is_array($scan['cache_guidance'] ?? null) ? $scan['cache_guidance'] : [];
    $setup_context = is_array($scan['setup_context'] ?? null) ? $scan['setup_context'] : [];
    $readiness = is_array($scan['support_readiness'] ?? null) ? $scan['support_readiness'] : [];
    $change_tracking = is_array($scan['change_tracking'] ?? null) ? $scan['change_tracking'] : [];
    $plugin_inventory = function_exists('custausu_support_report_plugin_inventory')
      ? custausu_support_report_plugin_inventory()
      : [];

    $critical = (int)($counts['critical'] ?? 0);
    $warning = (int)($counts['warning'] ?? 0);
    $warning_state = custausu_admin_doctor_plugin_warning_state($items, $scan);
    $warning_unresolved = (int)($warning_state['unresolved'] ?? $warning);
    $warning_acknowledged = (int)($warning_state['acknowledged'] ?? 0);
    $attention = (int)($counts['attention'] ?? 0);
    $info = (int)($counts['info'] ?? 0);

    $phase = sanitize_key((string)($setup_context['phase'] ?? 'unknown'));

    $overall = 'ok';
    if ($critical > 0) {
      $overall = 'critical';
    } elseif ($warning_unresolved > 0) {
      $overall = 'warning';
    } elseif ($attention > 0) {
      $overall = 'attention';
    } elseif ($warning_acknowledged > 0 || $info > 0) {
      $overall = 'info';
    }

    if ($phase === 'first_install' && $overall === 'ok') {
      $overall = 'info';
    } elseif ($phase === 'setup_in_progress' && in_array($overall, ['ok', 'info'], true)) {
      $overall = 'attention';
    }

    $should_open = in_array($phase, ['first_install', 'setup_in_progress'], true) || $critical > 0 || $warning_unresolved > 0;

    $doctor_standby = (
      $phase === 'configured' &&
      $critical <= 0 &&
      $warning_unresolved <= 0
    );

    $export_url = wp_nonce_url(
      admin_url('admin-post.php?action=custausu_export_support_report'),
      'custausu_export_support_report'
    );
    $export_html_url = add_query_arg('format', 'html', $export_url);

    $assisted_support_enabled = function_exists('custausu_admin_doctor_assisted_support_enabled')
      && custausu_admin_doctor_assisted_support_enabled();

    $support_url = $assisted_support_enabled
      ? custausu_admin_doctor_support_url($scan)
      : '';

    $license_state_for_support = function_exists('custausu_free_package_runtime_context') ? custausu_free_package_runtime_context() : [];
    $support_reference_for_ui = function_exists('custausu_admin_doctor_support_reference_from_state')
      ? custausu_admin_doctor_support_reference_from_state($license_state_for_support)
      : [];
    $health_profile = custausu_admin_doctor_health_profile($scan, $T, $warning_state);
    $health_grade   = sanitize_html_class((string)($health_profile['grade'] ?? 'good'));
    $health_label   = (string)($health_profile['label'] ?? '');
    $health_title   = (string)($health_profile['title'] ?? '');
    $health_message = (string)($health_profile['message'] ?? '');

    ob_start();

    $panel_classes = [
      'custausu-doctor-panel',
      'custausu-doctor-panel--' . $overall,
    ];

    if ($doctor_standby) {
      $panel_classes[] = 'custausu-doctor-panel--standby';
    }

    echo '<details id="custausu-section-installation-doctor" class="' . esc_attr(implode(' ', $panel_classes)) . '"' . ($should_open ? ' open' : '') . '>';

    echo '<summary class="custausu-doctor-summary">';
    $doctor_launcher_label = $T('Need Doctor?', 'Bisogno di Doctor?');
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Doctor icon renderer returns controlled escaped SVG/admin HTML.
    echo wp_kses( custausu_admin_doctor_icon_html($doctor_standby ? $doctor_launcher_label : ''), custausu_admin_allowed_output_html() );
    if ($doctor_standby) {
      echo '<span class="screen-reader-text">' . esc_html($doctor_launcher_label) . '</span>';
    }

    echo '<span class="custausu-doctor-summary__main custausu-doctor-summary__main--welcome">';
    $summary_title = $T('Welcome to CAS Installation Doctor', 'Benvenuto in CAS Installation Doctor');
    $summary_desc = $health_title . ' ' . $health_message;
    echo '<h1 class="custausu-doctor-summary__title custausu-doctor-summary__title--welcome">' . esc_html($summary_title) . '</h1>';

    if (!$doctor_standby) {
      echo '<span class="custausu-doctor-summary__desc">' . esc_html($summary_desc) . '</span>';
    }

    echo '</span>';
    echo '<span class="custausu-doctor-summary__badges">';
    echo '<span class="custausu-badge custausu-doctor-badge custausu-doctor-badge--health-' . esc_attr($health_grade) . '">'
    . esc_html(sprintf($T('Environment: %s', 'Ambiente: %s'), $health_label))
    . '</span>';
    echo '<span class="custausu-badge custausu-doctor-badge custausu-doctor-badge--phase-' . esc_attr($phase) . '">'
    . esc_html(custausu_admin_doctor_phase_label($phase, $T))
    . '</span>';
    echo '</span>';
    echo '</summary>';

    echo '<div class="custausu-doctor-panel__body">';

    $ack_notice = '';

    if (
      isset($_GET['custausu_doctor_warning_ack_notice_nonce'])
      && wp_verify_nonce(
        sanitize_text_field(
          wp_unslash(
            (string)$_GET['custausu_doctor_warning_ack_notice_nonce']
          )
        ),
        'custausu_doctor_warning_ack_notice'
      )
    ) {
      $ack_notice = isset($_GET['custausu_doctor_warning_ack'])
        ? sanitize_key(
          wp_unslash(
            (string)$_GET['custausu_doctor_warning_ack']
          )
        )
        : '';
    }

    if (in_array($ack_notice, ['acknowledged', 'review', 'error'], true)) {
      $notice_class = $ack_notice === 'error' ? 'notice-error' : 'notice-success';
      $notice_text = match ($ack_notice) {
        'acknowledged' => $T(
          'Plugin warning marked as verified. It remains visible and will be reopened automatically when its context changes.',
          'Warning del plugin dichiarato come verificato. Resta visibile e verrà riaperto automaticamente quando cambia il suo contesto.'
        ),
        'review' => $T(
          'Plugin warning returned to review status.',
          'Warning del plugin riportato allo stato da verificare.'
        ),
        default => $T(
          'The plugin warning acknowledgement could not be updated.',
          'Non è stato possibile aggiornare la presa di consapevolezza del warning del plugin.'
        ),
      };

      echo '<div class="notice ' . esc_attr($notice_class) . ' inline custausu-doctor-warning-ack-notice"><p>'
        . esc_html($notice_text)
        . '</p></div>';
    }

    echo '<div class="custausu-doctor-panel__head">';
    echo '<div>';
    echo '<h2 class="custausu-doctor-panel__title">';
    echo esc_html($health_title);
    echo '</h2>';
    echo '<p class="custausu-doctor-panel__desc">';
    echo esc_html($health_message . ' ' . $T(
    'The Doctor does not change your site: it helps you prevent problems before they become support tickets.',
    'Il Doctor non modifica il sito: ti aiuta a prevenire i problemi prima che diventino ticket di supporto.'
    ));                 
    echo '</p>';

    if (function_exists('custausu_rm_render')) {
      echo '<div class="custausu-doctor-rm-summary-small">';
      custausu_rm_render('doctor_summary', [
        'doctor_status' => $overall,
        'doctor_phase'  => $phase,
      ]);
      echo '</div>';
    }

    echo '</div>';

    echo '<div class="custausu-doctor-panel__actions">';
    echo '<a class="button button-primary custausu-doctor-export-btn" href="' . esc_url($export_url) . '">';
    echo esc_html($T('Export support report', 'Esporta report supporto'));
    echo '</a>';
    echo '</div>';
    echo '</div>';


    $status_label = ($critical <= 0 && $warning > 0 && $warning_unresolved <= 0)
      ? $T('Verified warnings', 'Warning verificati')
      : custausu_admin_doctor_severity_label($overall, $T);

    echo '<div class="custausu-doctor-badges">';
    echo '<span class="custausu-badge custausu-doctor-badge custausu-doctor-badge--' . esc_attr($overall) . '">'
      . esc_html($T('Status: ', 'Stato: ') . $status_label)
      . '</span>';
    echo '<span class="custausu-badge custausu-badge--error">' . esc_html('Critical: ' . $critical) . '</span>';
    echo '<span class="custausu-badge custausu-badge--warn">' . esc_html('Warning: ' . $warning) . '</span>';
    if ($warning_acknowledged > 0) {
      echo '<span class="custausu-badge custausu-badge--ok">'
        . esc_html($T('Verified', 'Verificati') . ': ' . $warning_acknowledged)
        . '</span>';
    }
    echo '<span class="custausu-badge custausu-badge--info">' . esc_html('Attention: ' . $attention) . '</span>';
    echo '<span class="custausu-badge custausu-badge--muted">' . esc_html('Info: ' . $info) . '</span>';
    echo '</div>';

    if (function_exists('custausu_admin_render_community_feedback_panel')) {
      custausu_admin_render_community_feedback_panel(
        $T,
        $support_url,
        $assisted_support_enabled
      );
    }

    echo '<div class="custausu-doctor-life-grid">';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Doctor setup card renderer returns controlled escaped admin HTML.
    echo wp_kses( custausu_admin_doctor_render_setup_card($scan, $T), custausu_admin_allowed_output_html() );
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Doctor safety card renderer returns controlled escaped admin HTML.
    echo wp_kses( custausu_admin_doctor_render_safety_card($T), custausu_admin_allowed_output_html() );

    echo '<div class="custausu-doctor-life-card custausu-doctor-life-card--support">';
    echo '<h3>' . esc_html($T('Need support?', 'Hai bisogno di supporto?')) . '</h3>';
    echo '<p>' . esc_html($T(
    'If CAS is already configured but something is not working, open the support request from here: the Doctor Report can be attached automatically. If automatic attachment is not available, download the report and attach it manually.',
    'Se CAS è già configurato ma qualcosa non funziona, apri la richiesta da qui: il Doctor Report può essere allegato automaticamente. Se l’allegato automatico non è disponibile, scarica il report e allegalo manualmente.'
    )) . '</p>';

    $assisted_support_status_class = $assisted_support_enabled
      ? 'is-enabled'
      : 'is-disabled';

    $assisted_support_status_text = $assisted_support_enabled
      ? $T(
          'Assisted Doctor Support is enabled. The redacted report handoff is prepared for the support action and is retrieved by customauthsuite.com only after you open the request.',
          'Il Supporto Assistito Doctor è attivo. L’handoff oscurato del report viene preparato per l’azione di supporto ed è recuperato da customauthsuite.com solo dopo l’apertura della richiesta.'
        )
      : $T(
          'Assisted Doctor Support is off by default. Enable it in “CAS communications and privacy” and save the settings. Local checks and JSON/HTML downloads remain available.',
          'Il Supporto Assistito Doctor è disattivato di default. Abilitalo in “Comunicazioni CAS e privacy” e salva le impostazioni. I controlli locali e i download JSON/HTML restano disponibili.'
        );

    echo '<p class="custausu-doctor-assisted-support-status ' . esc_attr($assisted_support_status_class) . '">'
      . '<strong>' . esc_html($T('Assisted support:', 'Supporto assistito:')) . '</strong> '
      . esc_html($assisted_support_status_text)
      . '</p>';

    echo '<div class="custausu-doctor-life-card__actions">';
    if (!is_array($support_reference_for_ui)) {
      $support_reference_for_ui = [];
    }

    $license_status_ui = !empty($support_reference_for_ui['license_status'])
      ? (string) $support_reference_for_ui['license_status']
      : 'none';

    $license_tail_ui = !empty($support_reference_for_ui['license_tail'])
      ? (string) $support_reference_for_ui['license_tail']
      : '';

    $order_reference_ui = !empty($support_reference_for_ui['order_reference'])
      ? (string) $support_reference_for_ui['order_reference']
      : '';

    $support_reference_ui = !empty($support_reference_for_ui['support_reference'])
      ? (string) $support_reference_for_ui['support_reference']
      : '';

    echo '<div class="custausu-doctor-support-reference-card" aria-label="' . esc_attr($T('Support references', 'Riferimenti supporto')) . '">';
    echo '<strong>' . esc_html($T('Support references', 'Riferimenti supporto')) . '</strong>';
    echo '<ul class="custausu-doctor-support-reference-list">';

    echo '<li><span>' . esc_html($T('License status', 'Stato licenza')) . ':</span> <code>' . esc_html($license_status_ui) . '</code></li>';

    echo '<li><span>' . esc_html($T('License tail', 'Coda licenza')) . ':</span> ';
    echo $license_tail_ui !== ''
      ? '<code>' . esc_html('••••' . $license_tail_ui) . '</code>'
      : '<em>' . esc_html($T('Not available from the local license state', 'Non disponibile dallo stato licenza locale')) . '</em>';
    echo '</li>';

    echo '<li><span>' . esc_html($T('Order reference', 'Riferimento ordine')) . ':</span> ';
    echo $order_reference_ui !== ''
      ? '<code>' . esc_html($order_reference_ui) . '</code>'
      : '<em>' . esc_html($T('Not stored on this site; the Support Desk will match it server-side when possible.', 'Non salvato su questo sito; il Support Desk lo assocerà lato server quando possibile.')) . '</em>';
    echo '</li>';

    echo '<li><span>' . esc_html($T('Support reference', 'Riferimento supporto')) . ':</span> ';
    echo $support_reference_ui !== ''
      ? '<code>' . esc_html($support_reference_ui) . '</code>'
      : '<em>' . esc_html($T('Not stored on this site; the Support Desk will match active support server-side when possible.', 'Non salvato su questo sito; il Support Desk assocerà il supporto attivo lato server quando possibile.')) . '</em>';
    echo '</li>';

    echo '</ul>';
    echo '<p class="description">' . esc_html($T(
      'These references help the Support Desk match your request without exposing full keys or private tokens.',
      'Questi riferimenti aiutano il Support Desk ad associare la richiesta senza esporre chiavi complete o token privati.'
    )) . '</p>';
    echo '</div>';

    if ($assisted_support_enabled && $support_url !== '') {
      echo '<a class="custausu-doctor-support-request-btn" href="' . esc_url($support_url) . '" target="_blank" rel="noopener noreferrer" aria-label="' . esc_attr($T('Open a CAS technical support request with safe prefilled site details', 'Apri una richiesta di supporto tecnico CAS con dati sito sicuri precompilati')) . '">'
        . '<span class="dashicons dashicons-sos" aria-hidden="true"></span>'
        . '<span>' . esc_html($T('Open support request', 'Apri richiesta supporto')) . '</span>'
        . '</a>';
    } else {
      echo '<button type="button" class="custausu-doctor-support-request-btn is-disabled" disabled aria-disabled="true" title="' . esc_attr($T('Enable Assisted Doctor Support and save the CAS settings first.', 'Abilita il Supporto Assistito Doctor e salva prima le impostazioni CAS.')) . '">'
        . '<span class="dashicons dashicons-sos" aria-hidden="true"></span>'
        . '<span>' . esc_html($T('Open support request', 'Apri richiesta supporto')) . '</span>'
        . '</button>';
    }
    echo '<a class="button custausu-doctor-report-action-btn custausu-doctor-report-action-btn--json" href="' . esc_url($export_url) . '">'
    . '<span class="dashicons dashicons-download" aria-hidden="true"></span>'
    . '<span>' . esc_html($T('Download JSON report', 'Scarica report JSON')) . '</span>'
    . '</a>';
    $export_html_url = add_query_arg('format', 'html', $export_url);

    echo '<a class="button button-secondary custausu-doctor-report-action-btn custausu-doctor-report-action-btn--html custausu-doctor-export-btn custausu-doctor-export-btn--html" href="' . esc_url($export_html_url) . '">'
    . '<span class="dashicons dashicons-media-document" aria-hidden="true"></span>'
    . '<span>' . esc_html($T('Download readable HTML report', 'Scarica report HTML leggibile')) . '</span>'
    . '</a>';
    echo '</div>';

    echo wp_kses( custausu_admin_doctor_support_ticket_image_html($T), custausu_admin_allowed_output_html() );

    echo '</div>';
    echo '</div>';

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Doctor change tracking card renderer returns controlled escaped admin HTML.
    echo wp_kses( custausu_admin_doctor_render_change_tracking_card($change_tracking, $T), custausu_admin_allowed_output_html() );

    echo '<div class="custausu-doctor-grid">';

    echo '<div class="custausu-doctor-card custausu-doctor-card--full">';
    echo '<h3>' . esc_html($T('Compatibility scan', 'Scan compatibilità')) . '</h3>';
    echo '<p class="custausu-doctor-card__intro">';
    echo esc_html($T(
    'Grouped by area, so you can open only what matters. The Doctor is here to guide, not to alarm.',
    'Raggruppato per area, così puoi aprire solo ciò che serve. Il Doctor è qui per guidare, non per allarmare.'
    ));
    echo '</p>';

    if (empty($items)) {
    echo '<p class="custausu-doctor-empty">';
    echo esc_html($T(
        'No relevant compatibility warnings detected from the current active plugin/environment scan.',
        'Nessun warning di compatibilità rilevante dallo scan attuale di plugin attivi/ambiente.'
    ));
    echo '</p>';
    } else {
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Doctor grouped cards renderer returns controlled escaped admin HTML.
    echo wp_kses( custausu_admin_doctor_render_group_cards($items, $T, $scan), custausu_admin_allowed_output_html() );
    }

    echo '</div>';

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Inventory renderer escapes every item field.
    echo wp_kses( custausu_admin_doctor_render_plugin_inventory_card(
      $plugin_inventory,
      $T
    ), custausu_admin_allowed_output_html() );

    echo '<div class="custausu-doctor-card custausu-doctor-card--full">';
    echo '<h3>' . esc_html($T('Cache / optimization guidance', 'Guida cache / ottimizzazione')) . '</h3>';
    echo '<p class="custausu-doctor-card__intro">';
    echo esc_html($T(
    'Use these paths as a starting point for cache, CDN, minify and security exclusions. If your hosting has a cache panel, follow its documentation.',
    'Usa questi path come punto di partenza per esclusioni cache, CDN, minify e security. Se il tuo hosting ha un pannello cache, segui la sua documentazione.'
    ));
    echo '</p>';

    echo wp_kses( custausu_admin_doctor_render_cache_guidance_cards($cache_guidance, $T), custausu_admin_allowed_output_html() );

    echo '</div>';

    echo '</div>';

    echo '</div>';
    echo '</details>';

    return (string) ob_get_clean();
  }
}

/* Handle Reset Doctor History */
if (!function_exists('custausu_admin_handle_reset_doctor_history_action')) {
  function custausu_admin_handle_reset_doctor_history_action(): void {
    if (!is_admin() || !current_user_can('manage_options')) {
      wp_die('Forbidden');
    }

    check_admin_referer('custausu_reset_doctor_history');

    $history_key = function_exists('custausu_compatibility_doctor_history_option_name')
      ? custausu_compatibility_doctor_history_option_name()
      : 'custausu_doctor_change_history';

    $snapshot_key = function_exists('custausu_compatibility_doctor_snapshot_option_name')
      ? custausu_compatibility_doctor_snapshot_option_name()
      : 'custausu_doctor_last_snapshot';

    $history = get_option($history_key, []);
    $history = is_array($history) ? array_values($history) : [];

    $history_limit = function_exists('custausu_compatibility_doctor_history_limit')
      ? (int) custausu_compatibility_doctor_history_limit()
      : 120;

    if ($history_limit <= 0) {
      $history_limit = 120;
    }

    $redirect = wp_get_referer();
    if (!$redirect) {
      $redirect = admin_url('admin.php?page=custausu-settings');
    }

    $redirect = strtok($redirect, '#');
    $redirect = remove_query_arg(
      ['_wpnonce', 'action', 'custausu_doctor_memory_reset'],
      $redirect
    );

    /*
     * Safety guard:
     * the Doctor memory can be reset only when the configured limit is reached.
     * This prevents accidental deletion of useful support history.
     */
    if (count($history) < $history_limit) {
      $redirect = add_query_arg('custausu_doctor_memory_reset', 'not_allowed', $redirect);

      wp_safe_redirect($redirect . '#custausu-section-installation-doctor');
      exit;
    }

    delete_option($history_key);
    delete_option($snapshot_key);

    $redirect = add_query_arg('custausu_doctor_memory_reset', '1', $redirect);

    wp_safe_redirect($redirect . '#custausu-section-installation-doctor');
    exit;
  }
}

add_action('admin_post_custausu_export_support_report', 'custausu_admin_handle_export_support_report_action');
add_action('admin_post_custausu_reset_doctor_history', 'custausu_admin_handle_reset_doctor_history_action');
add_action('admin_post_custausu_doctor_plugin_warning_ack', 'custausu_admin_handle_doctor_plugin_warning_ack_action');


