<?php

namespace WPSN\Modules\Diagnostics\Admin;

use WPSN\Admin\SettingsRepository;
use WPSN\Core\Branding;
use WPSN\Core\Capabilities;
use WPSN\Core\Container;
use WPSN\Modules\Diagnostics\PlatformOpsAutomation;
use WPSN\Modules\Diagnostics\PlatformOpsCompactSummaryBuilder;
use WPSN\Modules\Diagnostics\PlatformOpsDiffBuilder;
use WPSN\Modules\Diagnostics\PlatformOpsProbeService;
use WPSN\Modules\Diagnostics\PlatformOpsReportRepository;
use WPSN\Modules\Diagnostics\ReleaseSmokeBadgeHtml;

defined('ABSPATH') || exit;

final class PlatformOpsAdmin
{
    public const PAGE_SLUG = 'wpsn-platform-ops';

    private Container $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function register(): void
    {
        add_action('admin_menu', [$this, 'addMenu']);
        add_action('admin_post_wpsn_platform_ops_run', [$this, 'handleRun']);
        add_action('admin_post_wpsn_platform_ops_export', [$this, 'handleExport']);
        add_action('admin_post_wpsn_platform_ops_compare_export', [$this, 'handleCompareExport']);
        add_action('admin_post_wpsn_platform_ops_clear', [$this, 'handleClear']);
        add_action('admin_post_wpsn_platform_ops_save_settings', [$this, 'handleSaveSettings']);
        add_action('admin_post_wpsn_platform_ops_pin', [$this, 'handlePin']);
        add_action('admin_post_wpsn_platform_ops_unpin', [$this, 'handleUnpin']);
    }

    public function addMenu(): void
    {
        add_management_page(
            __('Platform Ops', 'wp-seo-next'),
            __('Platform Ops', 'wp-seo-next'),
            Capabilities::CAP_TOOLS,
            self::PAGE_SLUG,
            [$this, 'render']
        );
    }

    public function handleRun(): void
    {
        if (!Capabilities::canManageTools()) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'wp-seo-next'));
        }
        check_admin_referer('wpsn_platform_ops_run');

        $keepBaseline = isset($_REQUEST['keep_baseline']) && (string) wp_unslash($_REQUEST['keep_baseline']) === '1';

        $repo = new PlatformOpsReportRepository();
        $previous = $repo->getLast();
        $report = (new PlatformOpsProbeService($this->container))->run([
            'trigger' => 'manual',
            'user_id' => function_exists('get_current_user_id') ? (int) get_current_user_id() : 0,
        ]);
        $repo->save($report);
        if ($keepBaseline) {
            $repo->pin($report);
        }
        do_action('wpsn/platform_ops/run_completed', $report, [
            'trigger' => 'manual',
            'user_id' => function_exists('get_current_user_id') ? (int) get_current_user_id() : 0,
            'previous' => $previous,
            'keep_baseline' => $keepBaseline,
        ]);

        $this->redirect(['wpsn_platform_notice' => $keepBaseline ? 'ran_pinned' : 'ran']);
    }

    public function handleExport(): void
    {
        if (!Capabilities::canManageTools()) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'wp-seo-next'));
        }
        check_admin_referer('wpsn_platform_ops_export');

        $runId = isset($_GET['run_id']) ? sanitize_text_field((string) wp_unslash($_GET['run_id'])) : '';
        $repo = new PlatformOpsReportRepository();
        $report = $runId !== '' ? $repo->get($runId) : $repo->getLast();

        if (empty($report)) {
            $this->redirect(['wpsn_platform_notice' => 'missing']);
        }

        $ts = isset($report['created_at_utc']) ? (string) $report['created_at_utc'] : gmdate('c');
        $ts = preg_replace('/[^0-9T:-]/', '-', $ts);
        $ts = is_string($ts) ? trim($ts, '-') : gmdate('Y-m-d-His');

        nocache_headers();
        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="wpsn-platform-ops-' . $ts . '.json"');
        echo (string) wp_json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        exit;
    }

    public function handleCompareExport(): void
    {
        if (!Capabilities::canManageTools()) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'wp-seo-next'));
        }
        check_admin_referer('wpsn_platform_ops_compare_export');

        $baseId = isset($_GET['baseline_run']) ? sanitize_text_field((string) wp_unslash($_GET['baseline_run'])) : '';
        $candidateId = isset($_GET['candidate_run']) ? sanitize_text_field((string) wp_unslash($_GET['candidate_run'])) : '';
        if ($baseId === '' || $candidateId === '' || $baseId === $candidateId) {
            $this->redirect(['wpsn_platform_notice' => 'compare_missing']);
        }

        $repo = new PlatformOpsReportRepository();
        $baseline = $repo->get($baseId);
        $candidate = $repo->get($candidateId);
        if (empty($baseline) || empty($candidate)) {
            $this->redirect(['wpsn_platform_notice' => 'compare_missing']);
        }

        $diff = (new PlatformOpsDiffBuilder())->compare($baseline, $candidate);
        $baseTs = isset($baseline['created_at_utc']) ? (string) $baseline['created_at_utc'] : 'baseline';
        $candidateTs = isset($candidate['created_at_utc']) ? (string) $candidate['created_at_utc'] : 'candidate';
        $fileTs = preg_replace('/[^0-9T:-]/', '-', $baseTs . '-vs-' . $candidateTs);
        $fileTs = is_string($fileTs) ? trim($fileTs, '-') : gmdate('Y-m-d-His');

        nocache_headers();
        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="wpsn-platform-ops-compare-' . $fileTs . '.json"');
        echo (string) wp_json_encode($diff, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        exit;
    }

    public function handleClear(): void
    {
        if (!Capabilities::canManageTools()) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'wp-seo-next'));
        }
        check_admin_referer('wpsn_platform_ops_clear');

        $repo = new PlatformOpsReportRepository();
        $keptPinned = !empty($repo->getPinned());
        $repo->clear();
        $this->redirect(['wpsn_platform_notice' => $keptPinned ? 'cleared_kept_baseline' : 'cleared']);
    }

    public function handleSaveSettings(): void
    {
        if (!Capabilities::canManageTools()) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'wp-seo-next'));
        }
        check_admin_referer('wpsn_platform_ops_save_settings');

        $schedule = isset($_POST['platform_ops_schedule']) ? sanitize_key((string) wp_unslash($_POST['platform_ops_schedule'])) : 'off';
        if (!in_array($schedule, ['off', 'daily', 'weekly'], true)) {
            $schedule = 'off';
        }

        $hour = isset($_POST['platform_ops_hour_utc']) ? (int) $_POST['platform_ops_hour_utc'] : 6;
        $hour = max(0, min(23, $hour));

        $weekday = isset($_POST['platform_ops_weekday_utc']) ? (int) $_POST['platform_ops_weekday_utc'] : 1;
        $weekday = max(0, min(6, $weekday));

        $flipAlerts = !empty($_POST['platform_ops_notify_on_flip']);

        $repo = new SettingsRepository();
        $all = $repo->getAll();

        $all['platform_ops'] = [
            'automation' => [
                'configured' => true,
                'schedule' => $schedule,
                'hour_utc' => $hour,
                'weekday_utc' => $weekday,
            ],
        ];

        if (!isset($all['notifications']) || !is_array($all['notifications'])) {
            $all['notifications'] = [];
        }
        if (!isset($all['notifications']['sources']) || !is_array($all['notifications']['sources'])) {
            $all['notifications']['sources'] = [];
        }
        $all['notifications']['sources']['platform_ops'] = $flipAlerts;

        $repo->update($all);

        $settings = $this->container->get('settings');
        $settings->flush();

        $automation = new PlatformOpsAutomation($this->container);
        $automation->resetScheduleLocks();
        $automation->ensureCron();

        $this->redirect(['wpsn_platform_notice' => 'settings_saved']);
    }

    public function handlePin(): void
    {
        if (!Capabilities::canManageTools()) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'wp-seo-next'));
        }

        $runId = isset($_GET['run_id']) ? sanitize_text_field((string) wp_unslash($_GET['run_id'])) : '';
        if ($runId === '') {
            $this->redirect(['wpsn_platform_notice' => 'pin_missing']);
        }

        check_admin_referer('wpsn_platform_ops_pin_' . $runId);

        $repo = new PlatformOpsReportRepository();
        $row = $repo->get($runId);
        if (empty($row)) {
            $this->redirect(['wpsn_platform_notice' => 'pin_missing']);
        }

        $repo->pin($row);
        $this->redirect(['wpsn_platform_notice' => 'pinned']);
    }

    public function handleUnpin(): void
    {
        if (!Capabilities::canManageTools()) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'wp-seo-next'));
        }

        check_admin_referer('wpsn_platform_ops_unpin');

        (new PlatformOpsReportRepository())->unpin();
        $this->redirect(['wpsn_platform_notice' => 'unpinned']);
    }

    public function render(): void
    {
        if (!current_user_can(Capabilities::CAP_TOOLS)) {
            wp_die(esc_html__('You do not have permission to access this page.', 'wp-seo-next'));
        }

        $settings = $this->container->get('settings');
        $brand = Branding::brand($settings);
        $title = __('Platform Ops', 'wp-seo-next');
        if ($brand !== '') {
            $title = sprintf(__('%s — Platform Ops', 'wp-seo-next'), $brand);
        }

        $repo = new PlatformOpsReportRepository();
        $last = $repo->getLast();
        $history = $repo->getHistory(10);
        $pinned = $repo->getPinned();
        $pinnedId = !empty($pinned['id']) ? (string) $pinned['id'] : '';
        $compactSummary = (new PlatformOpsCompactSummaryBuilder())->buildFromRuns($last, $history, $pinned);
        $compareRuns = $this->platformCompareRuns($history, $pinned);

        $baseId = isset($_GET['platform_compare_base']) ? sanitize_text_field((string) wp_unslash($_GET['platform_compare_base'])) : '';
        $candidateId = isset($_GET['platform_compare_candidate']) ? sanitize_text_field((string) wp_unslash($_GET['platform_compare_candidate'])) : '';
        if ($baseId === '' && $candidateId === '') {
            if (!empty($compactSummary['has_comparison'])) {
                $summaryBaseline = isset($compactSummary['baseline']['id']) ? (string) $compactSummary['baseline']['id'] : '';
                $summaryCandidate = isset($compactSummary['candidate']['id']) ? (string) $compactSummary['candidate']['id'] : '';
                if ($summaryBaseline !== '' && $summaryCandidate !== '' && $summaryBaseline !== $summaryCandidate) {
                    $baseId = $summaryBaseline;
                    $candidateId = $summaryCandidate;
                }
            }

            $lastId = isset($last['id']) ? (string) $last['id'] : '';
            if ($baseId === '' && $candidateId === '' && $pinnedId !== '' && $lastId !== '' && $lastId !== $pinnedId) {
                $baseId = $pinnedId;
                $candidateId = $lastId;
            } elseif ($baseId === '' && $candidateId === '' && count($compareRuns) >= 2) {
                $candidateId = isset($compareRuns[0]['id']) ? (string) $compareRuns[0]['id'] : '';
                $baseId = isset($compareRuns[1]['id']) ? (string) $compareRuns[1]['id'] : '';
            }
        }

        $compareDiff = [];
        if ($baseId !== '' && $candidateId !== '' && $baseId !== $candidateId) {
            $baseline = $repo->get($baseId);
            $candidate = $repo->get($candidateId);
            if (!empty($baseline) && !empty($candidate)) {
                $compareDiff = (new PlatformOpsDiffBuilder())->compare($baseline, $candidate);
            }
        }

        $runUrl = wp_nonce_url(add_query_arg(['action' => 'wpsn_platform_ops_run'], admin_url('admin-post.php')), 'wpsn_platform_ops_run');
        $runPinUrl = wp_nonce_url(add_query_arg(['action' => 'wpsn_platform_ops_run', 'keep_baseline' => 1], admin_url('admin-post.php')), 'wpsn_platform_ops_run');
        $exportUrl = $this->platformExportUrl('');
        $clearUrl = wp_nonce_url(add_query_arg(['action' => 'wpsn_platform_ops_clear'], admin_url('admin-post.php')), 'wpsn_platform_ops_clear');
        $compareDefaultUrl = $this->platformComparePageUrl($baseId, $candidateId);

        echo '<div class="wrap">';
        echo '<h1>' . esc_html($title) . '</h1>';
        echo '<p class="description">' . esc_html__('Probe optional external platform backends used by licensing, billing, signed updates, SaaS orchestration, AI proxy credits and worker endpoints. This helps separate plugin issues from backend readiness issues.', 'wp-seo-next') . '</p>';
        echo '<style>
            .wpsn-status-pill,.wpsn-compare-pill{display:inline-block;padding:3px 10px;border-radius:999px;font-size:12px;line-height:1.2;background:#f0f0f1;margin-right:6px;vertical-align:middle;}
            .wpsn-status-pill.ok{background:#d1e7dd;}
            .wpsn-status-pill.warn{background:#fff3cd;}
            .wpsn-status-pill.critical{background:#f8d7da;}
            .wpsn-status-pill.skipped,.wpsn-status-pill.info{background:#e2e3e5;}
            .wpsn-compare-pill.improved{background:#d1e7dd;}
            .wpsn-compare-pill.regressed{background:#f8d7da;}
            .wpsn-compare-pill.changed{background:#fff3cd;}
            .wpsn-compare-pill.unchanged{background:#e2e3e5;}
            .wpsn-compare-pill.added,.wpsn-compare-pill.removed{background:#cff4fc;}
            .wpsn-release-badges{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0 0 0;}
            .wpsn-release-badge{display:inline-block;padding:3px 10px;border-radius:999px;background:#f0f0f1;font-size:12px;line-height:1.2;}
            .wpsn-release-badge.ok{background:#d1e7dd;}
            .wpsn-release-badge.warn{background:#fff3cd;}
            .wpsn-release-badge.bad{background:#f8d7da;}
            .wpsn-release-badge.info{background:#cff4fc;}
        </style>';

        if (!empty($_GET['wpsn_platform_notice'])) {
            $notice = sanitize_key((string) wp_unslash($_GET['wpsn_platform_notice']));
            if ($notice === 'ran') {
                echo '<div class="notice notice-success"><p>' . esc_html__('Platform probe finished.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'ran_pinned') {
                echo '<div class="notice notice-success"><p>' . esc_html__('Platform probe finished and the new run was pinned as the healthy baseline.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'cleared') {
                echo '<div class="notice notice-success"><p>' . esc_html__('Platform probe history cleared.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'cleared_kept_baseline') {
                echo '<div class="notice notice-info"><p>' . esc_html__('Platform probe history cleared. The pinned healthy baseline was kept.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'missing') {
                echo '<div class="notice notice-error"><p>' . esc_html__('Requested platform probe report was not found.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'compare_missing') {
                echo '<div class="notice notice-warning"><p>' . esc_html__('Pick two different saved platform probe runs to compare.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'pinned') {
                echo '<div class="notice notice-success"><p>' . esc_html__('Platform baseline pinned.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'pin_missing') {
                echo '<div class="notice notice-warning"><p>' . esc_html__('Saved platform run not found, so it could not be pinned.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'unpinned') {
                echo '<div class="notice notice-info"><p>' . esc_html__('Pinned platform baseline removed.', 'wp-seo-next') . '</p></div>';
            } elseif ($notice === 'settings_saved') {
                echo '<div class="notice notice-success"><p>' . esc_html__('Platform Ops automation settings saved.', 'wp-seo-next') . '</p></div>';
            }
        }

        $automation = new PlatformOpsAutomation($this->container);
        $nextTick = function_exists('wp_next_scheduled') ? wp_next_scheduled(PlatformOpsAutomation::CRON_TICK) : false;
        $automationState = [
            'mode' => $automation->automationMode(),
            'enabled' => $automation->automationEnabled(),
            'configured' => $automation->automationConfigured(),
            'legacy_fallback' => $automation->legacyFallbackActive(),
            'hour_utc' => $automation->runHourUtc(),
            'weekday_utc' => $automation->runWeekdayUtc(),
            'flip_source_enabled' => $automation->flipNotificationSourceEnabled(),
            'notifications_operational' => $automation->notificationsOperational(),
            'next_tick' => is_numeric($nextTick) ? (int) $nextTick : 0,
            'next_due' => $automation->nextDueTimestampUtc(),
            'wp_cron_disabled' => defined('DISABLE_WP_CRON') && DISABLE_WP_CRON,
        ];

        $this->renderCompactOverviewCard(
            $compactSummary,
            $compareDefaultUrl,
            $exportUrl,
            $automationState,
            $runPinUrl
        );
        $this->renderAutomationSettingsCard($automationState);

        echo '<p>';
        echo '<a class="button button-primary" href="' . esc_url($runUrl) . '">' . esc_html__('Run platform probe', 'wp-seo-next') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url($runPinUrl) . '">' . esc_html__('Run now and keep as healthy baseline', 'wp-seo-next') . '</a> ';
        echo '<a class="button" href="' . esc_url($exportUrl) . '">' . esc_html__('Export last JSON', 'wp-seo-next') . '</a> ';
        if ($compareDefaultUrl !== '') {
            echo '<a class="button" href="' . esc_url($compareDefaultUrl) . '">' . esc_html__('Open compare view', 'wp-seo-next') . '</a> ';
        }
        echo '<a class="button" href="' . esc_url(admin_url('admin.php?page=wpsn-license')) . '">' . esc_html__('License & Billing', 'wp-seo-next') . '</a> ';
        echo '<a class="button" href="' . esc_url(admin_url('admin.php?page=wpsn-saas-sync')) . '">' . esc_html__('SaaS Sync', 'wp-seo-next') . '</a> ';
        echo '<a class="button" href="' . esc_url(admin_url('admin.php?page=wpsn-saas-dashboard')) . '">' . esc_html__('SaaS Dashboard', 'wp-seo-next') . '</a> ';
        echo '<a class="button" href="' . esc_url(admin_url('admin.php?page=wpsn-connections')) . '">' . esc_html__('Connections', 'wp-seo-next') . '</a> ';
        if (!empty($history)) {
            echo '<a class="button" style="margin-left:8px;" href="' . esc_url($clearUrl) . '" onclick="return confirm(' . esc_attr(wp_json_encode(__('Clear saved platform probe history? The pinned baseline will stay.', 'wp-seo-next'))) . ');">' . esc_html__('Clear history', 'wp-seo-next') . '</a>';
        }
        echo '</p>';

        if (!empty($pinned)) {
            $pinnedCreated = isset($pinned['created_at_utc']) ? (string) $pinned['created_at_utc'] : '';
            $pinnedCounts = isset($pinned['counts']) && is_array($pinned['counts']) ? $pinned['counts'] : [];
            $pinnedSev = isset($pinned['severity']) ? (string) $pinned['severity'] : 'info';
            $pinnedExportUrl = $this->platformExportUrl((string) ($pinned['id'] ?? ''));
            $lastId = isset($last['id']) ? (string) $last['id'] : '';
            $comparePinnedToLatestUrl = ($pinnedId !== '' && $lastId !== '' && $lastId !== $pinnedId)
                ? $this->platformComparePageUrl($pinnedId, $lastId)
                : '';
            $unpinUrl = $this->platformUnpinUrl();

            echo '<div style="margin:12px 0 10px 0;padding:10px;border:1px solid #bfdbfe;background:#eff6ff;border-radius:4px;">';
            echo '<p style="margin:0 0 6px 0;">' . $this->platformComparePill('unchanged') . ' <strong>' . esc_html__('Pinned healthy baseline (UTC):', 'wp-seo-next') . '</strong> <code>' . esc_html($pinnedCreated) . '</code></p>';
            echo '<p class="description" style="margin:0;">' . esc_html(sprintf(__('Severity %1$s · OK %2$d · Warn %3$d · Critical %4$d · Skipped %5$d', 'wp-seo-next'), strtoupper($pinnedSev), (int) ($pinnedCounts['ok'] ?? 0), (int) ($pinnedCounts['warn'] ?? 0), (int) ($pinnedCounts['critical'] ?? 0), (int) ($pinnedCounts['skipped'] ?? 0))) . '</p>';
            echo '<p class="description" style="margin:6px 0 0 0;">' . esc_html__('Tip: pin a known-good run here, then compare every new platform probe against it to spot backend regressions quickly.', 'wp-seo-next') . '</p>';
            echo '<p style="margin:8px 0 0 0;">';
            if ($pinnedExportUrl !== '') {
                echo '<a class="button button-small" href="' . esc_url($pinnedExportUrl) . '">' . esc_html__('Export pinned JSON', 'wp-seo-next') . '</a> ';
            }
            if ($comparePinnedToLatestUrl !== '') {
                echo '<a class="button button-small" href="' . esc_url($comparePinnedToLatestUrl) . '">' . esc_html__('Compare pinned vs latest', 'wp-seo-next') . '</a> ';
            }
            if ($unpinUrl !== '') {
                echo '<a class="button button-small" href="' . esc_url($unpinUrl) . '">' . esc_html__('Unpin baseline', 'wp-seo-next') . '</a>';
            }
            echo '</p>';
            echo '</div>';
        }

        echo '<h2>' . esc_html__('Latest platform probe', 'wp-seo-next') . '</h2>';
        if (!empty($last)) {
            $counts = isset($last['counts']) && is_array($last['counts']) ? $last['counts'] : [];
            $severity = isset($last['severity']) ? (string) $last['severity'] : 'info';
            $created = isset($last['created_at_utc']) ? (string) $last['created_at_utc'] : '';
            $duration = isset($last['duration_ms']) ? (int) $last['duration_ms'] : 0;
            $localOnly = !empty($last['local_only']);
            $lastId = isset($last['id']) ? (string) $last['id'] : '';
            $pinLatestUrl = ($lastId !== '' && $lastId !== $pinnedId) ? $this->platformPinUrl($lastId) : '';

            echo '<p>';
            echo $this->statusPill($severity);
            echo '<span class="button" style="cursor:default;">' . esc_html(sprintf(__('ok %d', 'wp-seo-next'), (int) ($counts['ok'] ?? 0))) . '</span> ';
            echo '<span class="button" style="cursor:default;">' . esc_html(sprintf(__('warn %d', 'wp-seo-next'), (int) ($counts['warn'] ?? 0))) . '</span> ';
            echo '<span class="button" style="cursor:default;">' . esc_html(sprintf(__('critical %d', 'wp-seo-next'), (int) ($counts['critical'] ?? 0))) . '</span> ';
            echo '<span class="button" style="cursor:default;">' . esc_html(sprintf(__('skipped %d', 'wp-seo-next'), (int) ($counts['skipped'] ?? 0))) . '</span> ';
            if ($created !== '') {
                echo '<span style="margin-left:10px;">' . esc_html(sprintf(__('Created: %s', 'wp-seo-next'), $created)) . '</span>';
            }
            echo '<span style="margin-left:10px;">' . esc_html(sprintf(__('Duration: %d ms', 'wp-seo-next'), $duration)) . '</span>';
            echo '<span style="margin-left:10px;">' . esc_html($localOnly ? __('Local-only: yes', 'wp-seo-next') : __('Local-only: no', 'wp-seo-next')) . '</span>';
            if ($pinnedId !== '' && $lastId === $pinnedId) {
                echo '<span style="margin-left:10px;">' . wp_kses_post($this->platformComparePill('unchanged')) . ' ' . esc_html__('Pinned baseline', 'wp-seo-next') . '</span>';
            }
            echo '</p>';

            if ($pinLatestUrl !== '') {
                echo '<p style="margin:-4px 0 10px 0;"><a class="button button-small" href="' . esc_url($pinLatestUrl) . '">' . esc_html__('Pin latest as healthy baseline', 'wp-seo-next') . '</a></p>';
            }

            $checks = isset($last['checks']) && is_array($last['checks']) ? $last['checks'] : [];
            echo '<table class="widefat striped">';
            echo '<thead><tr>';
            echo '<th>' . esc_html__('Check', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('Result', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('Mode', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('HTTP', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('Summary', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('Key details', 'wp-seo-next') . '</th>';
            echo '</tr></thead><tbody>';

            foreach ($checks as $key => $check) {
                if (!is_array($check)) {
                    continue;
                }
                $label = isset($check['label']) ? (string) $check['label'] : (string) $key;
                $status = isset($check['status']) ? (string) $check['status'] : 'info';
                $mode = isset($check['mode']) ? (string) $check['mode'] : 'live';
                $http = isset($check['http_status']) ? (int) $check['http_status'] : 0;
                $summary = isset($check['summary']) ? (string) $check['summary'] : '';
                $details = isset($check['details']) && is_array($check['details']) ? $check['details'] : [];

                echo '<tr>';
                echo '<td><strong>' . esc_html($label) . '</strong><br /><code>' . esc_html((string) $key) . '</code></td>';
                echo '<td>' . $this->statusPill($status) . '</td>';
                echo '<td>' . esc_html($mode) . '</td>';
                echo '<td>' . esc_html($http > 0 ? (string) $http : '—') . '</td>';
                echo '<td>' . esc_html($summary !== '' ? $summary : '—') . '</td>';
                echo '<td>' . $this->renderDetailsList($details) . '</td>';
                echo '</tr>';
            }

            echo '</tbody></table>';
        } else {
            echo '<p>' . esc_html__('No platform probe has been saved yet.', 'wp-seo-next') . '</p>';
        }

        $this->renderPlatformComparePanel($compareRuns, $baseId, $candidateId, $compareDiff, $pinnedId);

        echo '<h2>' . esc_html__('History', 'wp-seo-next') . '</h2>';
        if (empty($history)) {
            echo '<p>' . esc_html__('No saved platform probe runs yet.', 'wp-seo-next') . '</p>';
        } else {
            $latestId = isset($last['id']) ? (string) $last['id'] : '';
            $previousId = '';
            foreach ($history as $row) {
                if (!is_array($row) || empty($row['id'])) {
                    continue;
                }
                $rowId = (string) $row['id'];
                if ($latestId !== '' && $rowId !== $latestId) {
                    $previousId = $rowId;
                    break;
                }
            }

            echo '<table class="widefat striped">';
            echo '<thead><tr>';
            echo '<th>' . esc_html__('Created', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('Severity', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('Counts', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('Duration', 'wp-seo-next') . '</th>';
            echo '<th>' . esc_html__('Actions', 'wp-seo-next') . '</th>';
            echo '</tr></thead><tbody>';
            foreach ($history as $row) {
                if (!is_array($row)) {
                    continue;
                }
                $runId = isset($row['id']) ? (string) $row['id'] : '';
                if ($runId === '') {
                    continue;
                }
                $created = isset($row['created_at_utc']) ? (string) $row['created_at_utc'] : '';
                $severity = isset($row['severity']) ? (string) $row['severity'] : 'info';
                $counts = isset($row['counts']) && is_array($row['counts']) ? $row['counts'] : [];
                $duration = isset($row['duration_ms']) ? (int) $row['duration_ms'] : 0;
                $itemExport = $this->platformExportUrl($runId);
                $pinUrl = $runId !== $pinnedId ? $this->platformPinUrl($runId) : '';

                $compareTargetId = '';
                if ($pinnedId !== '' && $runId !== $pinnedId) {
                    $compareTargetId = $pinnedId;
                } elseif ($runId === $latestId && $previousId !== '') {
                    $compareTargetId = $previousId;
                } elseif ($latestId !== '' && $runId !== $latestId) {
                    $compareTargetId = $latestId;
                }
                $compareUrl = '';
                if ($pinnedId !== '' && $runId !== $pinnedId) {
                    $compareUrl = $this->platformComparePageUrl($pinnedId, $runId);
                } elseif ($compareTargetId !== '' && $compareTargetId !== $runId) {
                    $compareUrl = $this->platformComparePageUrl($compareTargetId, $runId);
                }

                $countLabel = sprintf(
                    __('ok %1$d · warn %2$d · critical %3$d · skipped %4$d', 'wp-seo-next'),
                    (int) ($counts['ok'] ?? 0),
                    (int) ($counts['warn'] ?? 0),
                    (int) ($counts['critical'] ?? 0),
                    (int) ($counts['skipped'] ?? 0)
                );

                echo '<tr>';
                echo '<td>' . esc_html($created !== '' ? $created : '—');
                if ($runId === $pinnedId) {
                    echo '<br /><span class="description">' . esc_html__('Pinned healthy baseline', 'wp-seo-next') . '</span>';
                }
                echo '</td>';
                echo '<td>' . $this->statusPill($severity) . '</td>';
                echo '<td>' . esc_html($countLabel) . '</td>';
                echo '<td>' . esc_html($duration > 0 ? (string) $duration . ' ms' : '—') . '</td>';
                echo '<td>';
                if ($itemExport !== '') {
                    echo '<a class="button button-small" href="' . esc_url($itemExport) . '">' . esc_html__('JSON', 'wp-seo-next') . '</a> ';
                }
                if ($compareUrl !== '') {
                    echo '<a class="button button-small" href="' . esc_url($compareUrl) . '">' . esc_html__('Compare', 'wp-seo-next') . '</a> ';
                }
                if ($pinUrl !== '') {
                    echo '<a class="button button-small" href="' . esc_url($pinUrl) . '">' . esc_html__('Pin as baseline', 'wp-seo-next') . '</a>';
                } elseif ($runId === $pinnedId) {
                    echo '<span class="description">' . esc_html__('Pinned', 'wp-seo-next') . '</span>';
                }
                echo '</td>';
                echo '</tr>';
            }
            echo '</tbody></table>';
        }

        echo '</div>';
    }

    /**
     * @param array<int,array<string,mixed>> $history
     * @param array<string,mixed> $diff
     */
    private function renderPlatformComparePanel(array $history, string $baseId, string $candidateId, array $diff, string $pinnedId = ''): void
    {
        echo '<div class="wpsn-card" id="wpsn-platform-ops-compare" style="max-width:1200px; margin:16px 0 0 0;">';
        echo '<h2 style="margin:0 0 8px 0;">' . esc_html__('Compare two platform probe runs', 'wp-seo-next') . '</h2>';
        echo '<p class="description" style="margin:0 0 12px 0;">' . esc_html__('Pick any two saved platform runs to see what backend checks regressed, improved, or simply changed between platform snapshots.', 'wp-seo-next') . '</p>';

        echo '<form method="get" action="' . esc_url(admin_url('tools.php')) . '" style="display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;">';
        echo '<input type="hidden" name="page" value="' . esc_attr(self::PAGE_SLUG) . '" />';
        echo '<label><span class="description" style="display:block;margin-bottom:4px;">' . esc_html__('Baseline', 'wp-seo-next') . '</span><select name="platform_compare_base">';
        foreach ($history as $row) {
            if (!is_array($row)) {
                continue;
            }
            $rowId = isset($row['id']) ? (string) $row['id'] : '';
            if ($rowId === '') {
                continue;
            }
            $label = isset($row['created_at_utc']) ? (string) $row['created_at_utc'] : $rowId;
            $severity = isset($row['severity']) ? (string) $row['severity'] : 'info';
            if ($pinnedId !== '' && $rowId === $pinnedId) {
                $label = __('Pinned baseline', 'wp-seo-next') . ' · ' . $label;
            }
            echo '<option value="' . esc_attr($rowId) . '" ' . selected($baseId, $rowId, false) . '>' . esc_html($label . ' · ' . strtoupper($severity)) . '</option>';
        }
        echo '</select></label>';
        echo '<label><span class="description" style="display:block;margin-bottom:4px;">' . esc_html__('Candidate', 'wp-seo-next') . '</span><select name="platform_compare_candidate">';
        foreach ($history as $row) {
            if (!is_array($row)) {
                continue;
            }
            $rowId = isset($row['id']) ? (string) $row['id'] : '';
            if ($rowId === '') {
                continue;
            }
            $label = isset($row['created_at_utc']) ? (string) $row['created_at_utc'] : $rowId;
            $severity = isset($row['severity']) ? (string) $row['severity'] : 'info';
            if ($pinnedId !== '' && $rowId === $pinnedId) {
                $label = __('Pinned baseline', 'wp-seo-next') . ' · ' . $label;
            }
            echo '<option value="' . esc_attr($rowId) . '" ' . selected($candidateId, $rowId, false) . '>' . esc_html($label . ' · ' . strtoupper($severity)) . '</option>';
        }
        echo '</select></label>';
        submit_button(__('Compare runs', 'wp-seo-next'), 'secondary', 'submit', false);
        echo '</form>';

        if (empty($diff)) {
            echo '<p class="description" style="margin:10px 0 0 0;">' . esc_html__('Choose two different saved runs to render a platform diff.', 'wp-seo-next') . '</p>';
            echo '</div>';
            return;
        }

        $summary = isset($diff['summary']) && is_array($diff['summary']) ? $diff['summary'] : [];
        $baseline = isset($diff['baseline']) && is_array($diff['baseline']) ? $diff['baseline'] : [];
        $candidate = isset($diff['candidate']) && is_array($diff['candidate']) ? $diff['candidate'] : [];
        $countDeltas = isset($summary['count_deltas']) && is_array($summary['count_deltas']) ? $summary['count_deltas'] : [];
        $compareExportUrl = $this->platformCompareExportUrl($baseId, $candidateId);

        echo '<div style="margin-top:12px;padding:10px;border:1px solid #dcdcde;border-radius:4px;background:#f8f9fa;">';
        echo '<p style="margin:0 0 6px 0;">' . $this->platformComparePill((string) ($summary['severity_status'] ?? 'changed')) . ' <strong>' . esc_html__('Baseline:', 'wp-seo-next') . '</strong> <code>' . esc_html((string) ($baseline['created_at_utc'] ?? '')) . '</code> → <strong>' . esc_html__('Candidate:', 'wp-seo-next') . '</strong> <code>' . esc_html((string) ($candidate['created_at_utc'] ?? '')) . '</code></p>';
        echo '<p class="description" style="margin:0;">' . esc_html(sprintf(__('Regressions: %1$d · Improvements: %2$d · Changed: %3$d · Unchanged: %4$d', 'wp-seo-next'), (int) ($summary['regressions'] ?? 0), (int) ($summary['improvements'] ?? 0), (int) ($summary['changed'] ?? 0), (int) ($summary['unchanged'] ?? 0))) . '</p>';
        echo '<p class="description" style="margin:6px 0 0 0;">' . esc_html(sprintf(__('Counts Δ → OK %1$+d · Warn %2$+d · Critical %3$+d · Skipped %4$+d', 'wp-seo-next'), (int) ($countDeltas['ok'] ?? 0), (int) ($countDeltas['warn'] ?? 0), (int) ($countDeltas['critical'] ?? 0), (int) ($countDeltas['skipped'] ?? 0))) . '</p>';
        echo '<p class="description" style="margin:6px 0 0 0;">' . esc_html(sprintf(__('Local-only mode: %1$s → %2$s', 'wp-seo-next'), !empty($summary['local_only_baseline']) ? __('yes', 'wp-seo-next') : __('no', 'wp-seo-next'), !empty($summary['local_only_candidate']) ? __('yes', 'wp-seo-next') : __('no', 'wp-seo-next'))) . '</p>';
        if ($compareExportUrl !== '') {
            echo '<p style="margin:8px 0 0 0;"><a class="button button-small" href="' . esc_url($compareExportUrl) . '">' . esc_html__('Export compare JSON', 'wp-seo-next') . '</a></p>';
        }
        echo '</div>';

        $checkRows = isset($diff['checks']) && is_array($diff['checks']) ? $diff['checks'] : [];
        if (!empty($checkRows)) {
            echo '<table class="widefat striped" style="margin-top:12px;">';
            echo '<thead><tr><th style="width:220px;">' . esc_html__('Check', 'wp-seo-next') . '</th><th style="width:260px;">' . esc_html__('Baseline', 'wp-seo-next') . '</th><th style="width:260px;">' . esc_html__('Candidate', 'wp-seo-next') . '</th><th>' . esc_html__('Diff', 'wp-seo-next') . '</th></tr></thead><tbody>';
            foreach ($checkRows as $row) {
                if (!is_array($row)) {
                    continue;
                }
                $rowStatus = isset($row['status']) ? (string) $row['status'] : 'changed';
                $rowLabel = isset($row['label']) ? (string) $row['label'] : (string) ($row['key'] ?? '');
                $baseRow = isset($row['baseline']) && is_array($row['baseline']) ? $row['baseline'] : [];
                $candidateRow = isset($row['candidate']) && is_array($row['candidate']) ? $row['candidate'] : [];
                echo '<tr>';
                echo '<td><strong>' . esc_html($rowLabel) . '</strong><br /><code>' . esc_html((string) ($row['key'] ?? '')) . '</code></td>';
                echo '<td>' . $this->renderCompareCheckCell($baseRow) . '</td>';
                echo '<td>' . $this->renderCompareCheckCell($candidateRow) . '</td>';
                echo '<td>' . $this->platformComparePill($rowStatus) . '</td>';
                echo '</tr>';

                $detailChanges = isset($row['detail_changes']) && is_array($row['detail_changes']) ? $row['detail_changes'] : [];
                if (!empty($detailChanges)) {
                    echo '<tr><td></td><td colspan="3">';
                    echo '<table style="width:100%; border-collapse:collapse;">';
                    foreach ($detailChanges as $detailRow) {
                        if (!is_array($detailRow)) {
                            continue;
                        }
                        echo '<tr>';
                        echo '<td style="padding:4px 10px 4px 0; width:160px;"><strong>' . esc_html((string) ($detailRow['key'] ?? '')) . '</strong></td>';
                        echo '<td style="padding:4px 10px 4px 0; width:280px;">' . esc_html((string) ($detailRow['baseline'] ?? '—')) . '</td>';
                        echo '<td style="padding:4px 0;">' . esc_html((string) ($detailRow['candidate'] ?? '—')) . '</td>';
                        echo '</tr>';
                    }
                    echo '</table>';
                    echo '</td></tr>';
                }
            }
            echo '</tbody></table>';
        }

        echo '</div>';
    }

    /**
     * @param array<string,mixed> $args
     */
    private function redirect(array $args = []): void
    {
        $url = admin_url('tools.php?page=' . self::PAGE_SLUG);
        if (!empty($args)) {
            $url = add_query_arg($args, $url);
        }
        wp_safe_redirect($url);
        exit;
    }

    private function statusPill(string $severity): string
    {
        $severity = sanitize_key($severity);
        if (!in_array($severity, ['ok', 'warn', 'critical', 'skipped', 'info'], true)) {
            $severity = 'info';
        }

        return '<span class="wpsn-status-pill ' . esc_attr($severity) . '">' . esc_html(strtoupper($severity)) . '</span>';
    }

    private function platformComparePill(string $status): string
    {
        $map = [
            'improved' => __('Improved', 'wp-seo-next'),
            'regressed' => __('Regressed', 'wp-seo-next'),
            'changed' => __('Changed', 'wp-seo-next'),
            'unchanged' => __('Unchanged', 'wp-seo-next'),
            'added' => __('Added', 'wp-seo-next'),
            'removed' => __('Removed', 'wp-seo-next'),
        ];
        if (!isset($map[$status])) {
            $status = 'changed';
        }

        return '<span class="wpsn-compare-pill ' . esc_attr($status) . '">' . esc_html($map[$status]) . '</span>';
    }

    /**
     * @param array<string,mixed> $summary
     * @param array<string,mixed> $automationState
     */
    private function renderCompactOverviewCard(array $summary, string $compareUrl, string $exportUrl, array $automationState = [], string $runPinUrl = ''): void
    {
        echo '<div class="wpsn-card" style="max-width:1200px; margin:14px 0 14px 0;">';
        echo '<div style="display:flex;justify-content:space-between;gap:12px;align-items:flex-start;flex-wrap:wrap;">';
        echo '<div>';
        echo '<h2 style="margin:0 0 6px 0;">' . esc_html__('Platform overview', 'wp-seo-next') . '</h2>';
        echo '<p class="description" style="margin:0;max-width:900px;">' . esc_html__('Compact backend health badges from the latest Platform Ops snapshot. Uses the pinned healthy baseline when available, otherwise falls back to the previous saved run.', 'wp-seo-next') . '</p>';
        $badges = !empty($summary['badges']) && is_array($summary['badges']) ? $summary['badges'] : [];
        $badges[] = PlatformOpsAutomation::compactBadgeFromState($automationState);
        if (!empty($badges)) {
            echo ReleaseSmokeBadgeHtml::render($badges);
        }
        if (!empty($summary['summary'])) {
            echo '<p class="description" style="margin:8px 0 0 0;">' . esc_html((string) $summary['summary']) . '</p>';
        }
        if (!empty($summary['meta'])) {
            echo '<p class="description" style="margin:6px 0 0 0;">' . esc_html((string) $summary['meta']) . '</p>';
        }

        $mode = isset($automationState['mode']) ? (string) $automationState['mode'] : 'off';
        $hour = isset($automationState['hour_utc']) ? (int) $automationState['hour_utc'] : 6;
        $weekday = isset($automationState['weekday_utc']) ? (int) $automationState['weekday_utc'] : 1;
        $nextTick = isset($automationState['next_tick']) ? (int) $automationState['next_tick'] : 0;
        $nextDue = isset($automationState['next_due']) ? (int) $automationState['next_due'] : 0;
        $legacyFallback = !empty($automationState['legacy_fallback']);
        $flipSourceEnabled = !empty($automationState['flip_source_enabled']);
        $notificationsOperational = !empty($automationState['notifications_operational']);
        $wpCronDisabled = !empty($automationState['wp_cron_disabled']);

        $autoParts = [];
        if (in_array($mode, ['daily', 'weekly'], true)) {
            $scheduleLabel = $this->platformScheduleLabel($mode, $hour, $weekday);
            if ($legacyFallback) {
                $autoParts[] = sprintf(__('Legacy schedule is active: %s. Save the Automation card below to switch Platform Ops to explicit schedule control.', 'wp-seo-next'), $scheduleLabel);
            } else {
                $autoParts[] = sprintf(__('Automatic probe schedule: %s.', 'wp-seo-next'), $scheduleLabel);
            }
            if ($nextDue > 0) {
                $autoParts[] = sprintf(__('Next due run: %s UTC', 'wp-seo-next'), gmdate('Y-m-d H:i:s', $nextDue));
            }
        } else {
            $autoParts[] = __('Automatic probe schedule is off. Use the Automation card below to enable daily or weekly backend snapshots.', 'wp-seo-next');
        }
        if ($nextTick > 0) {
            $autoParts[] = sprintf(__('Next WP-Cron tick: %s UTC', 'wp-seo-next'), gmdate('Y-m-d H:i:s', $nextTick));
        }
        $autoParts[] = $flipSourceEnabled
            ? __('Flip alerts: on.', 'wp-seo-next')
            : __('Flip alerts: off.', 'wp-seo-next');
        if ($flipSourceEnabled && !$notificationsOperational) {
            $autoParts[] = __('Notifications are globally off, so flip alerts will not deliver until Notifications are enabled.', 'wp-seo-next');
        }
        if ($wpCronDisabled) {
            $autoParts[] = __('WP-Cron is disabled, so scheduled probes require a real cron hitting wp-cron.php.', 'wp-seo-next');
        }
        echo '<p class="description" style="margin:6px 0 0 0;">' . esc_html(implode(' · ', $autoParts)) . '</p>';
        echo '</div>';
        echo '<div class="wpsn-actions">';
        if ($runPinUrl !== '') {
            echo '<a class="button button-primary" href="' . esc_url($runPinUrl) . '">' . esc_html__('Run now + pin baseline', 'wp-seo-next') . '</a> ';
        }
        if ($compareUrl !== '') {
            echo '<a class="button button-secondary" href="' . esc_url($compareUrl) . '">' . esc_html__('Open compare view', 'wp-seo-next') . '</a> ';
        }
        if ($exportUrl !== '') {
            echo '<a class="button button-secondary" href="' . esc_url($exportUrl) . '">' . esc_html__('Latest JSON', 'wp-seo-next') . '</a> ';
        }
        echo '<a class="button button-secondary" href="' . esc_url(admin_url('tools.php?page=wpsn-notifications&tab=settings')) . '">' . esc_html__('Notifications settings', 'wp-seo-next') . '</a>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
    }

    /**
     * @param array<string,mixed> $automationState
     */
    private function renderAutomationSettingsCard(array $automationState): void
    {
        $schedule = isset($automationState['mode']) ? (string) $automationState['mode'] : 'off';
        $hour = isset($automationState['hour_utc']) ? (int) $automationState['hour_utc'] : 6;
        $weekday = isset($automationState['weekday_utc']) ? (int) $automationState['weekday_utc'] : 1;
        $configured = !empty($automationState['configured']);
        $legacyFallback = !empty($automationState['legacy_fallback']);
        $flipSourceEnabled = !empty($automationState['flip_source_enabled']);
        $notificationsOperational = !empty($automationState['notifications_operational']);
        $nextTick = isset($automationState['next_tick']) ? (int) $automationState['next_tick'] : 0;
        $nextDue = isset($automationState['next_due']) ? (int) $automationState['next_due'] : 0;
        $wpCronDisabled = !empty($automationState['wp_cron_disabled']);

        echo '<div class="wpsn-card" style="max-width:1200px; margin:10px 0 14px 0;">';
        echo '<h2 style="margin:0 0 10px 0;">' . esc_html__('Automation', 'wp-seo-next') . '</h2>';
        echo '<p class="description" style="margin:0 0 10px 0;">' . esc_html__('Optional scheduled Platform Ops probes. WP-Cron still ticks hourly, but this page now controls whether snapshots run daily, weekly, or stay off.', 'wp-seo-next') . '</p>';

        if ($legacyFallback) {
            echo '<p class="description" style="margin:0 0 10px 0;"><strong>' . esc_html__('Legacy mode:', 'wp-seo-next') . '</strong> ' . esc_html__('This install is still using the old notification-driven daily schedule. Save the form below once to switch to the new explicit Platform Ops schedule.', 'wp-seo-next') . '</p>';
        } elseif (!$configured && $schedule === 'off') {
            echo '<p class="description" style="margin:0 0 10px 0;">' . esc_html__('No Platform Ops automation has been configured on this page yet.', 'wp-seo-next') . '</p>';
        } else {
            echo '<p class="description" style="margin:0 0 10px 0;">' . esc_html(sprintf(__('Current schedule: %s', 'wp-seo-next'), $this->platformScheduleLabel($schedule, $hour, $weekday))) . '</p>';
        }

        if ($wpCronDisabled) {
            echo '<p class="description" style="margin:0 0 10px 0;"><strong>' . esc_html__('Warning:', 'wp-seo-next') . '</strong> ' . esc_html__('DISABLE_WP_CRON is enabled. Scheduled probes require a real cron hitting wp-cron.php.', 'wp-seo-next') . '</p>';
        }

        $timingParts = [];
        if ($nextDue > 0) {
            $timingParts[] = sprintf(__('Next due run: %s UTC', 'wp-seo-next'), gmdate('Y-m-d H:i:s', $nextDue));
        }
        if ($nextTick > 0) {
            $timingParts[] = sprintf(__('Next WP-Cron tick: %s UTC', 'wp-seo-next'), gmdate('Y-m-d H:i:s', $nextTick));
        }
        if (!empty($timingParts)) {
            echo '<p class="description" style="margin:0 0 10px 0;">' . esc_html(implode(' · ', $timingParts)) . '</p>';
        }

        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
        echo '<input type="hidden" name="action" value="wpsn_platform_ops_save_settings" />';
        wp_nonce_field('wpsn_platform_ops_save_settings');

        echo '<label style="margin-right:12px;">' . esc_html__('Schedule:', 'wp-seo-next') . ' ';
        echo '<select name="platform_ops_schedule">';
        foreach (['off' => __('Off', 'wp-seo-next'), 'daily' => __('Daily', 'wp-seo-next'), 'weekly' => __('Weekly', 'wp-seo-next')] as $key => $label) {
            echo '<option value="' . esc_attr($key) . '" ' . selected($schedule, $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></label>';

        echo '<label style="margin-right:12px;">' . esc_html__('Hour (UTC):', 'wp-seo-next') . ' ';
        echo '<input type="number" min="0" max="23" name="platform_ops_hour_utc" value="' . esc_attr((string) $hour) . '" style="width:80px;" />';
        echo '</label>';

        echo '<label style="margin-right:12px;">' . esc_html__('Weekday (UTC):', 'wp-seo-next') . ' ';
        echo '<select name="platform_ops_weekday_utc">';
        foreach ($this->weekdayOptions() as $key => $label) {
            echo '<option value="' . esc_attr((string) $key) . '" ' . selected($weekday, (int) $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></label>';

        echo '<label style="display:inline-flex;align-items:center;gap:6px;margin-right:12px;">';
        echo '<input type="checkbox" name="platform_ops_notify_on_flip" value="1" ' . checked($flipSourceEnabled, true, false) . ' />';
        echo '<span>' . esc_html__('Create Notifications event when backend health flips from OK to WARN/CRITICAL', 'wp-seo-next') . '</span>';
        echo '</label>';

        submit_button(__('Save automation settings', 'wp-seo-next'), 'secondary', 'submit', false);
        echo ' <a class="button button-secondary" href="' . esc_url(admin_url('tools.php?page=wpsn-notifications&tab=settings')) . '">' . esc_html__('Notifications Center', 'wp-seo-next') . '</a>';
        echo '</form>';

        $notes = [];
        $notes[] = __('Flip alerts use the Notifications center source “Platform backend flips”.', 'wp-seo-next');
        if ($flipSourceEnabled && !$notificationsOperational) {
            $notes[] = __('That source is enabled here, but global Notifications are currently off, so alerts will not be delivered until Notifications are enabled again.', 'wp-seo-next');
        }
        $notes[] = __('Weekly mode uses the selected UTC weekday and hour. Off keeps manual probing available, but no scheduled snapshots are created.', 'wp-seo-next');
        echo '<p class="description" style="margin:10px 0 0 0;">' . esc_html(implode(' · ', $notes)) . '</p>';
        echo '</div>';
    }

    /**
     * @return array<int,string>
     */
    private function weekdayOptions(): array
    {
        return [
            0 => __('Sun', 'wp-seo-next'),
            1 => __('Mon', 'wp-seo-next'),
            2 => __('Tue', 'wp-seo-next'),
            3 => __('Wed', 'wp-seo-next'),
            4 => __('Thu', 'wp-seo-next'),
            5 => __('Fri', 'wp-seo-next'),
            6 => __('Sat', 'wp-seo-next'),
        ];
    }

    private function platformScheduleLabel(string $mode, int $hour, int $weekday): string
    {
        if ($mode === 'daily') {
            return sprintf(__('Daily at %s UTC', 'wp-seo-next'), sprintf('%02d:00', $hour));
        }

        if ($mode === 'weekly') {
            $days = $this->weekdayOptions();
            $dayLabel = isset($days[$weekday]) ? $days[$weekday] : $days[1];
            return sprintf(__('Weekly on %1$s at %2$s UTC', 'wp-seo-next'), $dayLabel, sprintf('%02d:00', $hour));
        }

        return __('Off', 'wp-seo-next');
    }

    /**
     * @param array<string,mixed> $row
     */
    private function renderCompareCheckCell(array $row): string
    {
        if (empty($row)) {
            return '<span class="description">—</span>';
        }

        $severity = isset($row['severity']) ? (string) $row['severity'] : 'info';
        $summary = isset($row['summary']) ? (string) $row['summary'] : '';
        $mode = isset($row['mode']) ? (string) $row['mode'] : '';
        $http = isset($row['http_status']) ? (int) $row['http_status'] : 0;

        $html = $this->statusPill($severity);
        if ($summary !== '') {
            $html .= ' ' . esc_html($summary);
        }

        $meta = [];
        if ($mode !== '') {
            $meta[] = sprintf(__('Mode: %s', 'wp-seo-next'), $mode);
        }
        if ($http > 0) {
            $meta[] = sprintf(__('HTTP: %d', 'wp-seo-next'), $http);
        }
        if (!empty($meta)) {
            $html .= '<div class="description" style="margin-top:4px;">' . esc_html(implode(' · ', $meta)) . '</div>';
        }

        return $html;
    }

    private function platformComparePageUrl(string $baseId, string $candidateId): string
    {
        $baseId = trim($baseId);
        $candidateId = trim($candidateId);
        if ($baseId === '' || $candidateId === '' || $baseId === $candidateId) {
            return '';
        }

        return add_query_arg([
            'page' => self::PAGE_SLUG,
            'platform_compare_base' => $baseId,
            'platform_compare_candidate' => $candidateId,
        ], admin_url('tools.php')) . '#wpsn-platform-ops-compare';
    }

    /**
     * @param array<int,array<string,mixed>> $history
     * @param array<string,mixed> $pinned
     * @return array<int,array<string,mixed>>
     */
    private function platformCompareRuns(array $history, array $pinned = []): array
    {
        $out = [];
        $seen = [];
        $pinnedId = !empty($pinned['id']) ? (string) $pinned['id'] : '';

        if ($pinnedId !== '') {
            $pinned['is_pinned'] = true;
            $out[] = $pinned;
            $seen[$pinnedId] = true;
        }

        foreach ($history as $row) {
            if (!is_array($row) || empty($row['id'])) {
                continue;
            }
            $rowId = (string) $row['id'];
            if (isset($seen[$rowId])) {
                continue;
            }
            if ($pinnedId !== '' && $rowId === $pinnedId) {
                $row['is_pinned'] = true;
            }
            $out[] = $row;
            $seen[$rowId] = true;
        }

        return $out;
    }

    private function platformExportUrl(string $runId): string
    {
        $url = add_query_arg([
            'action' => 'wpsn_platform_ops_export',
        ], admin_url('admin-post.php'));
        if (trim($runId) !== '') {
            $url = add_query_arg(['run_id' => $runId], $url);
        }

        return function_exists('wp_nonce_url')
            ? wp_nonce_url($url, 'wpsn_platform_ops_export')
            : $url;
    }

    private function platformPinUrl(string $runId): string
    {
        $runId = trim($runId);
        if ($runId === '') {
            return '';
        }

        return wp_nonce_url(
            admin_url('admin-post.php?action=wpsn_platform_ops_pin&run_id=' . rawurlencode($runId)),
            'wpsn_platform_ops_pin_' . $runId
        );
    }

    private function platformUnpinUrl(): string
    {
        return wp_nonce_url(
            admin_url('admin-post.php?action=wpsn_platform_ops_unpin'),
            'wpsn_platform_ops_unpin'
        );
    }

    private function platformCompareExportUrl(string $baseId, string $candidateId): string
    {
        $baseId = trim($baseId);
        $candidateId = trim($candidateId);
        if ($baseId === '' || $candidateId === '' || $baseId === $candidateId) {
            return '';
        }

        $url = add_query_arg([
            'action' => 'wpsn_platform_ops_compare_export',
            'baseline_run' => $baseId,
            'candidate_run' => $candidateId,
        ], admin_url('admin-post.php'));

        return function_exists('wp_nonce_url')
            ? wp_nonce_url($url, 'wpsn_platform_ops_compare_export')
            : $url;
    }

    /**
     * @param array<string,mixed> $details
     */
    private function renderDetailsList(array $details): string
    {
        if (empty($details)) {
            return '—';
        }

        $items = [];
        foreach ($details as $key => $value) {
            if (is_array($value)) {
                $value = implode(', ', array_map('strval', array_slice($value, 0, 8)));
            } elseif (is_bool($value)) {
                $value = $value ? 'yes' : 'no';
            } elseif ($value === null || $value === '') {
                continue;
            } else {
                $value = (string) $value;
            }

            if ($value === '') {
                continue;
            }
            $items[] = '<div><strong>' . esc_html((string) $key) . ':</strong> ' . esc_html($value) . '</div>';
            if (count($items) >= 8) {
                break;
            }
        }

        if (empty($items)) {
            return '—';
        }

        return implode('', $items);
    }
}
