<?php
/**
 * Setup and Health cockpit.
 *
 * @var array<string,mixed> $settings
 * @var bool                $is_connected
 * @var bool                $is_connected_health
 * @var string              $connection_status
 * @var string              $last_checked_at
 * @var string              $site_domain
 * @var string              $org_name
 * @var bool                $wp_ai_visible
 * @var array<string,mixed>|null $coverage
 * @var array<int,array<string,mixed>> $recent_failures
 */
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Included inside Admin::render_settings_page(); these template variables are local to that method.

if (! defined('ABSPATH')) {
    exit;
}
?>
<div class="wrap encypher-settings-page">
    <header class="encypher-page-header">
        <h1 class="encypher-page-title">
            <img
                class="encypher-brand-lockup"
                src="<?php echo esc_url(ENCYPHER_PROVENANCE_PLUGIN_URL . 'assets/images/encypher_full_logo_color.svg'); ?>"
                alt="<?php echo esc_attr__('Encypher', 'encypher-provenance'); ?>"
            />
            <span class="encypher-title-divider" aria-hidden="true">/</span>
            <span><?php esc_html_e('Setup & Health', 'encypher-provenance'); ?></span>
        </h1>
        <p class="description">
            <?php esc_html_e('Connect this site once, then publish normally. Encypher signs eligible content in the background.', 'encypher-provenance'); ?>
        </p>
    </header>

    <?php settings_errors('encypher_provenance_settings'); ?>

    <?php if (! $is_connected) : ?>
        <p class="encypher-connection-status-line">
            <img class="encypher-status-mark" src="<?php echo esc_url(ENCYPHER_PROVENANCE_PLUGIN_URL . 'assets/images/brand/encypher-mark-navy.svg'); ?>" alt="" width="16" height="16" aria-hidden="true" />
            <?php esc_html_e('Status: Not connected.', 'encypher-provenance'); ?>
        </p>

        <div class="encypher-connect-cards">
            <section class="encypher-connect-card encypher-connect-card--recommended" aria-labelledby="encypher-existing-account-title">
                <span class="encypher-card-tag"><?php esc_html_e('Recommended', 'encypher-provenance'); ?></span>
                <h2 id="encypher-existing-account-title"><?php esc_html_e('Connect an existing Encypher account', 'encypher-provenance'); ?></h2>
                <p><?php esc_html_e('Keep this site in your existing organization, team, billing, rights, and reporting.', 'encypher-provenance'); ?></p>
                <?php $this->render_magic_link_connect_field(); ?>
            </section>

            <section class="encypher-connect-card" aria-labelledby="encypher-accountless-title">
                <h2 id="encypher-accountless-title"><?php esc_html_e('Start without an account', 'encypher-provenance'); ?></h2>
                <p><?php esc_html_e('Create an automatic workspace with recommended defaults. You can claim it later without invalidating existing signatures.', 'encypher-provenance'); ?></p>
                <p class="encypher-activate-domain">
                    <?php esc_html_e('Site:', 'encypher-provenance'); ?>
                    <strong id="encypher-activate-domain-display"><?php echo esc_html($site_domain); ?></strong>
                </p>
                <p>
                    <label for="encypher-tos-checkbox">
                        <input type="checkbox" id="encypher-tos-checkbox" />
                        <?php
                        printf(
                            /* translators: 1: opening Terms link, 2: closing link, 3: opening Privacy link, 4: closing link */
                            esc_html__('I agree to the %1$sTerms of Service%2$s and %3$sPrivacy Policy%4$s', 'encypher-provenance'),
                            '<a href="https://encypher.com/terms" target="_blank" rel="noopener noreferrer">',
                            '</a>',
                            '<a href="https://encypher.com/privacy" target="_blank" rel="noopener noreferrer">',
                            '</a>'
                        );
                        ?>
                    </label>
                </p>
                <button type="button" id="encypher-activate-btn" class="button button-secondary" disabled>
                    <?php esc_html_e('Start without an account', 'encypher-provenance'); ?>
                </button>
                <div id="encypher-activate-status" class="encypher-action-status" role="status" aria-live="polite"></div>
                <div id="encypher-activation-result" class="encypher-activation-result" role="status" aria-live="polite"></div>
            </section>
        </div>
    <?php else : ?>
        <?php
        $overall_title = __('Protection is working', 'encypher-provenance');
        $overall_message = $coverage_total > 0
            ? sprintf(
                /* translators: 1: protected percentage, 2: protected content count, 3: eligible public content count. */
                __('%1$d%% of eligible public content is protected (%2$s of %3$s items).', 'encypher-provenance'),
                $coverage_percent,
                number_format_i18n($coverage_protected),
                number_format_i18n($coverage_total)
            )
            : __('The connection is ready. Publish eligible content to start protecting it.', 'encypher-provenance');
        if ('action' === $overall_state) {
            $overall_title = __('Action required', 'encypher-provenance');
            if (! $protection_mode_enabled) {
                $overall_message = __('Protected publishing is off. WordPress may release new or changed content when signing fails.', 'encypher-provenance');
            } elseif (! empty($queue_stall['stalled'])) {
                $overall_message = __('Pending work has no fresh worker heartbeat. Process the queue now, then repair the WordPress cron schedule.', 'encypher-provenance');
            } elseif ('broken' === ($reader_path['status'] ?? 'unknown')) {
                $overall_message = __('Reader checks recorded failed or unavailable verification. Review the reader path before treating protection as healthy.', 'encypher-provenance');
            } elseif ($coverage_attention > 0) {
                $overall_message = sprintf(
                    /* translators: %s: number of eligible public content items needing attention. */
                    __('Eligible public content needing attention: %s.', 'encypher-provenance'),
                    number_format_i18n($coverage_attention)
                );
            } else {
                $overall_message = __('Recent Encypher operations failed. Review the recovery steps below.', 'encypher-provenance');
            }
        } elseif ('check' === $overall_state) {
            $overall_title = __('Check the API connection', 'encypher-provenance');
            $overall_message = __('Protection settings are tracked separately, but the saved API connection has not passed its latest check.', 'encypher-provenance');
        } elseif ('progress' === $overall_state) {
            $overall_title = __('Protection in progress', 'encypher-provenance');
            $overall_message = sprintf(
                /* translators: 1: signing content count, 2: not-yet-signed content count. */
                __('Signing now: %1$s. Not yet signed: %2$s.', 'encypher-provenance'),
                number_format_i18n($coverage_signing),
                number_format_i18n($coverage_unsigned)
            );
        }
        ?>
        <section class="encypher-card encypher-connected-identity encypher-overall-status encypher-overall-status--<?php echo esc_attr($overall_state); ?> encypher-connection-health-card" aria-labelledby="encypher-health-title">
            <div>
                <dl class="encypher-identity-facts" aria-label="<?php esc_attr_e('Connected identity', 'encypher-provenance'); ?>">
                    <div><dt><?php esc_html_e('Workspace', 'encypher-provenance'); ?></dt> <dd><?php echo esc_html($org_name ?: __('Automatic workspace', 'encypher-provenance')); ?></dd></div>
                    <div><dt><?php esc_html_e('Site', 'encypher-provenance'); ?></dt> <dd><?php echo esc_html($site_domain); ?></dd></div>
                    <div><dt><?php esc_html_e('Plan', 'encypher-provenance'); ?></dt> <dd><?php echo esc_html($plan_label); ?></dd></div>
                </dl>
                <h2 id="encypher-health-title"><?php echo esc_html($overall_title); ?></h2>
                <p class="encypher-overall-message"><?php echo esc_html($overall_message); ?></p>
                <dl class="encypher-path-health" aria-label="<?php esc_attr_e('Protection path health', 'encypher-provenance'); ?>">
                    <div>
                        <dt><?php esc_html_e('API connection', 'encypher-provenance'); ?></dt>
                        <dd id="encypher-connection-health-state" role="status" aria-live="polite"><?php echo esc_html($is_connected_health ? __('Healthy', 'encypher-provenance') : __('Check required', 'encypher-provenance')); ?></dd>
                    </div>
                    <div>
                        <dt><?php esc_html_e('Protected publishing', 'encypher-provenance'); ?></dt>
                        <dd><?php echo esc_html($protection_mode_enabled ? __('On - fail closed', 'encypher-provenance') : __('Off - fail open', 'encypher-provenance')); ?></dd>
                    </div>
                    <div>
                        <dt><?php esc_html_e('Reader verification path', 'encypher-provenance'); ?></dt>
                        <dd><?php echo esc_html('broken' === ($reader_path['status'] ?? 'unknown')
                            ? __('Needs attention', 'encypher-provenance')
                            : ('healthy' === ($reader_path['status'] ?? 'unknown')
                                ? __('Healthy', 'encypher-provenance')
                                : __('No checks today', 'encypher-provenance'))); ?></dd>
                    </div>
                </dl>
                <p class="encypher-reader-path-summary description">
                    <?php
                    printf(
                        /* translators: 1: successful reader checks, 2: failed checks, 3: unavailable checks today. */
                        esc_html__('Reader checks today: %1$s successful / %2$s failed / %3$s unavailable.', 'encypher-provenance'),
                        esc_html(number_format_i18n((int) ($reader_path['success'] ?? 0))),
                        esc_html(number_format_i18n((int) ($reader_path['failed'] ?? 0))),
                        esc_html(number_format_i18n((int) ($reader_path['unavailable'] ?? 0)))
                    );
                    ?>
                </p>
                <span id="connection-status" class="encypher-action-status" role="status" aria-live="polite"></span>
                <p id="test-connection-result" class="description" role="status" aria-live="polite">
                    <?php
                    printf(
                        /* translators: %s: formatted date and time or not-yet-available label. */
                        esc_html__('Last API connection check: %s', 'encypher-provenance'),
                        esc_html($last_checked_label)
                    );
                    ?>
                </p>
            </div>
            <div class="encypher-connected-actions">
                <?php if (! empty($queue_stall['pending_count']) || ! empty($queue_stall['failed_count']) || ! empty($queue_stall['stalled'])) : ?>
                    <a href="#encypher-queue-title" class="button button-primary"><?php esc_html_e('Review background work', 'encypher-provenance'); ?></a>
                <?php elseif ($active_failure_count > 0) : ?>
                    <a href="#encypher-recent-failures-title" class="button button-primary"><?php esc_html_e('Review recovery steps', 'encypher-provenance'); ?></a>
                <?php else : ?>
                    <a href="https://dashboard.encypher.com/analytics" target="_blank" rel="noopener noreferrer" class="button button-primary"><?php esc_html_e('View verification trends', 'encypher-provenance'); ?></a>
                <?php endif; ?>
                <button type="button" id="test-connection-btn" class="button"><?php esc_html_e('Check API connection', 'encypher-provenance'); ?></button>
                <a href="https://dashboard.encypher.com" target="_blank" rel="noopener noreferrer" class="button"><?php esc_html_e('Open Encypher dashboard', 'encypher-provenance'); ?></a>
            </div>
        </section>

        <?php if (! empty($queue_stall['pending_count']) || ! empty($queue_stall['failed_count']) || ! empty($queue_stall['stalled'])) : ?>
            <section class="encypher-card encypher-queue-diagnostics <?php echo ! empty($queue_stall['stalled']) ? 'is-stalled' : ''; ?>" aria-labelledby="encypher-queue-title">
                <div>
                    <h2 id="encypher-queue-title"><?php esc_html_e('Background work', 'encypher-provenance'); ?></h2>
                    <p><?php echo esc_html(! empty($queue_stall['stalled'])
                        ? __('Pending work has no fresh worker heartbeat.', 'encypher-provenance')
                        : __('Background work is queued or needs recovery.', 'encypher-provenance')); ?></p>
                    <dl class="encypher-queue-facts">
                        <div><dt><?php esc_html_e('Pending', 'encypher-provenance'); ?></dt><dd><?php echo esc_html(number_format_i18n((int) ($queue_stall['pending_count'] ?? 0))); ?></dd></div>
                        <div><dt><?php esc_html_e('Failed', 'encypher-provenance'); ?></dt><dd><?php echo esc_html(number_format_i18n((int) ($queue_stall['failed_count'] ?? 0))); ?></dd></div>
                        <div><dt><?php esc_html_e('Worker heartbeat', 'encypher-provenance'); ?></dt><dd><?php echo esc_html($queue_heartbeat_label); ?></dd></div>
                        <div><dt><?php esc_html_e('Last attempt', 'encypher-provenance'); ?></dt><dd><?php echo esc_html($queue_last_attempt_label); ?></dd></div>
                        <div><dt><?php esc_html_e('Next attempt', 'encypher-provenance'); ?></dt><dd><?php echo esc_html($queue_next_attempt_label); ?></dd></div>
                    </dl>
                    <?php if (! empty($queue_stall['stalled'])) : ?>
                        <p class="encypher-remediation"><?php esc_html_e('Process one bounded queue batch now. Then enable visitor-triggered WP-Cron, or configure a system scheduler to request wp-cron.php at least every five minutes.', 'encypher-provenance'); ?></p>
                    <?php endif; ?>
                </div>
                <div class="encypher-queue-actions">
                    <button type="button" id="encypher-process-queue-btn" class="button button-primary"><?php esc_html_e('Process queue now', 'encypher-provenance'); ?></button>
                    <?php if ((int) ($queue_stall['failed_count'] ?? 0) > 0 && $active_failure_count > 0) : ?>
                        <a href="#encypher-recent-failures-title" class="button"><?php esc_html_e('Review failed items', 'encypher-provenance'); ?></a>
                    <?php endif; ?>
                    <span id="encypher-process-queue-status" class="encypher-action-status" role="status" aria-live="polite"></span>
                </div>
            </section>
        <?php endif; ?>


        <div class="encypher-health-grid">

            <section class="encypher-card encypher-provenance-coverage-card" aria-labelledby="encypher-coverage-title">
                <h2 id="encypher-coverage-title"><?php esc_html_e('Content coverage', 'encypher-provenance'); ?></h2>
                <p class="description"><?php esc_html_e('Eligible public content on this site', 'encypher-provenance'); ?></p>
                <p class="encypher-coverage-outcome">
                    <strong>
                        <?php
                        printf(
                            /* translators: 1: protected percentage, 2: protected content count, 3: eligible content count. */
                            esc_html__('%1$d%% of eligible content protected', 'encypher-provenance'),
                            esc_html((string) $coverage_percent)
                        );
                        ?>
                    </strong>
                    <?php if ($coverage_total > 0) : ?>
                        <span class="description">
                            <?php
                            printf(
                                /* translators: 1: protected content count, 2: eligible content count. */
                                esc_html__('(%1$s of %2$s)', 'encypher-provenance'),
                                esc_html(number_format_i18n($coverage_protected)),
                                esc_html(number_format_i18n($coverage_total))
                            );
                            ?>
                        </span>
                    <?php endif; ?>
                </p>
                <dl class="encypher-coverage-summary" aria-label="<?php esc_attr_e('Canonical content coverage summary', 'encypher-provenance'); ?>">
                    <?php
                    $coverage_labels = [
                        'verified' => __('Verified', 'encypher-provenance'),
                        'signed' => __('Signed', 'encypher-provenance'),
                        'signing' => __('Signing', 'encypher-provenance'),
                        'not_signed' => __('Not yet signed', 'encypher-provenance'),
                        'edited' => __('Edited', 'encypher-provenance'),
                        'needs_attention' => __('Needs attention', 'encypher-provenance'),
                    ];
                    ?>
                    <?php foreach ($coverage_labels as $display_state => $state_label) : ?>
                        <div class="encypher-coverage-metric encypher-coverage-metric--<?php echo esc_attr($display_state); ?>" data-encypher-display-state="<?php echo esc_attr($display_state); ?>">
                            <dt><?php echo esc_html($state_label); ?></dt>
                            <dd><?php echo esc_html(number_format_i18n((int) ($coverage[$display_state] ?? 0))); ?></dd>
                        </div>
                    <?php endforeach; ?>
                </dl>
                <p class="encypher-draft-count description">
                    <?php
                    printf(
                        /* translators: %s: draft count excluded from eligible public coverage. */
                        esc_html__('Drafts excluded from eligible public content: %s.', 'encypher-provenance'),
                        esc_html(number_format_i18n((int) ($coverage['drafts'] ?? 0)))
                    );
                    ?>
                </p>
                <?php if (! empty($coverage['media']) && is_array($coverage['media'])) : ?>
                    <p class="encypher-coverage-media">
                        <?php
                        printf(
                            /* translators: 1: attachments carrying provenance, 2: attachments not yet scanned, 3: attachments without provenance. */
                            esc_html__('Media: %1$s with provenance / %2$s not yet scanned / %3$s without', 'encypher-provenance'),
                            '<strong>' . esc_html(number_format_i18n((int) ($coverage['media']['carries'] ?? 0))) . '</strong>',
                            '<strong>' . esc_html(number_format_i18n((int) ($coverage['media']['unscanned'] ?? 0))) . '</strong>',
                            '<strong>' . esc_html(number_format_i18n((int) ($coverage['media']['none'] ?? 0))) . '</strong>'
                        );
                        ?>
                        <?php if ((int) ($coverage['media']['none'] ?? 0) > 0 && ! empty($coverage['media']['filter_url'])) : ?>
                            <a class="encypher-coverage-media-link" href="<?php echo esc_url((string) $coverage['media']['filter_url']); ?>">
                                <?php esc_html_e('Review media without provenance', 'encypher-provenance'); ?>
                            </a>
                        <?php endif; ?>
                    </p>
                <?php endif; ?>
                <p class="encypher-coverage-verifications">
                    <?php
                    printf(
                        /* translators: %s: public verification count over the last 30 days. */
                        esc_html__('Public verifications (30 days): %s', 'encypher-provenance'),
                        '<strong>' . esc_html(number_format_i18n((int) $verification_stats['recent'])) . '</strong>'
                    );
                    ?>
                    <span class="description encypher-coverage-verifications-lifetime">
                        <?php
                        printf(
                            /* translators: %s: lifetime public verification count. */
                            esc_html__('(%s all time)', 'encypher-provenance'),
                            esc_html(number_format_i18n((int) $verification_stats['lifetime']))
                        );
                        ?>
                    </span>
                </p>
                <div class="encypher-coverage-sparkline"><?php $this->render_verification_sparkline(); ?></div>
                <?php if ((int) $verification_stats['lifetime'] >= 5 && ! empty($coverage['most_verified']) && is_array($coverage['most_verified'])) : ?>
                    <div class="encypher-coverage-most-verified">
                        <h3 class="encypher-coverage-subhead"><?php esc_html_e('Most verified content', 'encypher-provenance'); ?></h3>
                        <ol class="encypher-most-verified-list">
                            <?php foreach ($coverage['most_verified'] as $verified_item) : ?>
                                <?php if (! is_array($verified_item) || empty($verified_item['id'])) { continue; } ?>
                                <li>
                                    <?php if (! empty($verified_item['edit_url'])) : ?>
                                        <a href="<?php echo esc_url((string) $verified_item['edit_url']); ?>"><?php echo esc_html((string) $verified_item['title']); ?></a>
                                    <?php else : ?>
                                        <span><?php echo esc_html((string) $verified_item['title']); ?></span>
                                    <?php endif; ?>
                                    <span class="encypher-most-verified-count"><?php
                                        printf(
                                            /* translators: %s: public verification count for this post. */
                                            esc_html__('%s verifications', 'encypher-provenance'),
                                            esc_html(number_format_i18n((int) $verified_item['count']))
                                        );
                                    ?></span>
                                </li>
                            <?php endforeach; ?>
                        </ol>
                    </div>
                <?php endif; ?>
                <?php $external_referrers = (int) ($coverage['external_referrers'] ?? 0); ?>
                <?php if ($external_referrers > 0) : ?>
                    <?php $external_top_domains = $this->external_referrer_top_domains(); ?>
                    <p class="encypher-coverage-external-referrers"<?php echo ! empty($external_top_domains) ? ' title="' . esc_attr(implode(', ', $external_top_domains)) . '"' : ''; ?>>
                        <?php
                        printf(
                            /* translators: %s: number of distinct external sites that referred a public verification. */
                            esc_html__('Verified from %s external sites', 'encypher-provenance'),
                            '<strong>' . esc_html(number_format_i18n($external_referrers)) . '</strong>'
                        );
                        ?>
                    </p>
                <?php endif; ?>
                <?php if (! empty($coverage['by_type']) && is_array($coverage['by_type'])) : ?>
                    <?php $has_coverage_actions = $coverage_signing > 0 || $coverage_unsigned > 0 || $coverage_attention > 0; ?>
                    <?php if ($has_coverage_actions) : ?>
                        <details class="encypher-coverage-actions-menu" open>
                            <summary class="button"><?php esc_html_e('Review content', 'encypher-provenance'); ?></summary>
                            <nav class="encypher-coverage-actions" aria-label="<?php esc_attr_e('Content lists by canonical provenance state', 'encypher-provenance'); ?>">
                                <?php foreach ($coverage['by_type'] as $type_coverage) : ?>
                                    <?php if (! is_array($type_coverage) || ! isset($type_coverage['urls'], $type_coverage['label'])) { continue; } ?>
                                    <?php foreach (['not_signed', 'signing', 'edited', 'needs_attention'] as $review_state) : ?>
                                        <?php if ((int) ($type_coverage[$review_state] ?? 0) <= 0 || empty($type_coverage['urls'][$review_state])) { continue; } ?>
                                        <a class="button" data-encypher-display-state="<?php echo esc_attr($review_state); ?>" href="<?php echo esc_url((string) $type_coverage['urls'][$review_state]); ?>">
                                            <?php
                                            printf(
                                                /* translators: 1: canonical status label, 2: eligible public post-type label. */
                                                esc_html__('%1$s: %2$s', 'encypher-provenance'),
                                                esc_html((string) ($coverage_labels[$review_state] ?? $review_state)),
                                                esc_html((string) $type_coverage['label'])
                                            );
                                            ?>
                                        </a>
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                            </nav>
                        </details>
                    <?php endif; ?>
                <?php endif; ?>
                <p class="encypher-coverage-footer">
                    <a href="<?php echo esc_url('https://dashboard.encypher.com/analytics'); ?>" target="_blank" rel="noopener noreferrer">
                        <?php esc_html_e('Full analytics in your Encypher dashboard', 'encypher-provenance'); ?>
                    </a>
                </p>
                <?php if ('healthy' === $overall_state && $coverage_protected > 0 && empty($cdn_cta_dismissed)) : ?>
                    <p class="encypher-coverage-cdn-cta description" id="encypher-cdn-cta">
                        <a href="https://dashboard.encypher.com/cdn-analytics" target="_blank" rel="noopener noreferrer">
                            <?php esc_html_e('See which AI crawlers check your content rights: connect your CDN or edge logs in your Encypher dashboard', 'encypher-provenance'); ?>
                        </a>
                        <button type="button" class="encypher-cdn-cta-dismiss" data-nonce="<?php echo esc_attr($cdn_cta_nonce); ?>" aria-label="<?php esc_attr_e('Dismiss', 'encypher-provenance'); ?>">&times;</button>
                    </p>
                <?php endif; ?>
            </section>

            <?php if (null !== $media_scan && is_array($media_scan)) : ?>
                <?php
                $scan_status = (string) ($media_scan['status'] ?? 'idle');
                $scan_total = max(0, (int) ($media_scan['total'] ?? 0));
                $scan_scanned = max(0, (int) ($media_scan['scanned'] ?? 0));
                $scan_found = max(0, (int) ($media_scan['found'] ?? 0));
                $scan_skipped = max(0, (int) ($media_scan['skipped_offloaded'] ?? 0));
                $scan_processed = max(0, (int) ($media_scan['processed'] ?? ($scan_scanned + $scan_skipped)));
                $scan_denominator = max($scan_total, $scan_processed);
                $scan_empty = 'complete' === $scan_status && 0 === $scan_denominator;
                $scan_btn_label = 'complete' === $scan_status
                    ? __('Rescan media library', 'encypher-provenance')
                    : ('cancelled' === $scan_status
                        ? __('Retry media scan', 'encypher-provenance')
                        : ('running' === $scan_status
                            ? __('Scan in progress', 'encypher-provenance')
                            : __('Scan media library for provenance', 'encypher-provenance')));
                ?>
                <section class="encypher-card encypher-media-scan-card" aria-labelledby="encypher-media-scan-title">
                    <h2 id="encypher-media-scan-title"><?php esc_html_e('Media provenance', 'encypher-provenance'); ?></h2>
                    <p class="description"><?php esc_html_e('Scan your existing media library for embedded C2PA provenance. Detection runs locally at no cost.', 'encypher-provenance'); ?></p>
                    <?php if ($scan_empty) : ?>
                        <p class="encypher-media-scan-empty" role="status"><?php esc_html_e('No media to scan.', 'encypher-provenance'); ?></p>
                    <?php elseif ('idle' !== $scan_status) : ?>
                        <dl class="encypher-media-scan-progress" aria-live="polite">
                            <div><dt><?php esc_html_e('Processed', 'encypher-provenance'); ?></dt><dd><?php echo esc_html(number_format_i18n($scan_processed) . ' / ' . number_format_i18n($scan_denominator)); ?></dd></div>
                            <div><dt><?php esc_html_e('Scanned locally', 'encypher-provenance'); ?></dt><dd><?php echo esc_html(number_format_i18n($scan_scanned)); ?></dd></div>
                            <div><dt><?php esc_html_e('With provenance', 'encypher-provenance'); ?></dt><dd><?php echo esc_html(number_format_i18n($scan_found)); ?></dd></div>
                            <div><dt><?php esc_html_e('Skipped (offloaded)', 'encypher-provenance'); ?></dt><dd><?php echo esc_html(number_format_i18n($scan_skipped)); ?></dd></div>
                        </dl>
                    <?php endif; ?>
                    <?php if ('idle' !== $scan_status) : ?>
                        <p class="encypher-media-scan-last-run">
                            <?php echo esc_html('running' === $scan_status ? __('Last activity:', 'encypher-provenance') : __('Last run:', 'encypher-provenance')); ?>
                            <strong><?php echo esc_html($media_scan_last_run_label); ?></strong>
                        </p>
                    <?php endif; ?>
                    <div class="encypher-media-scan-actions">
                        <button type="button" id="encypher-media-scan-btn" class="button" data-scan-status="<?php echo esc_attr($scan_status); ?>"<?php echo 'running' === $scan_status ? ' disabled' : ''; ?>>
                            <?php echo esc_html($scan_btn_label); ?>
                        </button>
                        <?php if ('running' === $scan_status) : ?>
                            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                                <input type="hidden" name="action" value="encypher_cancel_media_scan" />
                                <?php wp_nonce_field('encypher_cancel_media_scan'); ?>
                                <button type="submit" class="button encypher-media-scan-cancel"><?php esc_html_e('Cancel scan', 'encypher-provenance'); ?></button>
                            </form>
                        <?php endif; ?>
                    </div>
                    <div id="encypher-media-scan-status" class="encypher-action-status" role="status" aria-live="polite"></div>
                </section>
            <?php endif; ?>
        </div>

        <?php if (! empty($recent_failures)) : ?>
            <?php
            $retryable_failure_count = count(array_filter(
                $recent_failures,
                static fn(array $failure): bool => 'retry' === ($failure['action_type'] ?? '')
            ));
            ?>
            <details class="encypher-card encypher-recent-failures-card encypher-responsive-disclosure" aria-labelledby="encypher-recent-failures-title" open>
                <summary class="encypher-recent-failures-heading">
                    <span class="encypher-disclosure-title" id="encypher-recent-failures-title"><?php esc_html_e('Recent failures', 'encypher-provenance'); ?></span>
                    <span class="description">
                        <?php
                        printf(
                            /* translators: %s: number of active grouped failures. */
                            esc_html__('Issues needing attention: %s.', 'encypher-provenance'),
                            esc_html(number_format_i18n($active_failure_count))
                        );
                        ?>
                    </span>
                </summary>
                <?php if ($retryable_failure_count > 1) : ?>
                    <p class="encypher-recent-failures-bulk">
                        <button type="button" id="encypher-retry-all-failures" class="button button-primary"><?php esc_html_e('Retry all eligible failures', 'encypher-provenance'); ?></button>
                        <span id="encypher-retry-all-status" class="encypher-action-status" role="status" aria-live="polite"></span>
                    </p>
                <?php endif; ?>
                <ol class="encypher-recent-failures-list">
                    <?php foreach (array_slice($recent_failures, 0, 5) as $failure) : ?>
                        <?php
                        if (! is_array($failure)) {
                            continue;
                        }
                        $failure_action_type = (string) ($failure['action_type'] ?? 'review');
                        $failure_action_url = (string) ($failure['action_url'] ?? '');
                        ?>
                        <li
                            class="encypher-recent-failure"
                            data-operation="<?php echo esc_attr((string) ($failure['operation'] ?? 'other')); ?>"
                            data-action-type="<?php echo esc_attr($failure_action_type); ?>"
                            data-action-url="<?php echo esc_url($failure_action_url); ?>"
                            data-encypher-display-state="<?php echo esc_attr((string) ($failure['display_state'] ?? 'needs_attention')); ?>"
                            data-encypher-assurance-state="<?php echo esc_attr((string) ($failure['assurance_state'] ?? 'unknown')); ?>"
                        >
                            <div class="encypher-recent-failure-main">
                                <p class="encypher-recent-failure-title">
                                    <strong><?php echo esc_html((string) ($failure['title'] ?? '')); ?></strong>
                                    <span class="encypher-recent-failure-type"><?php echo esc_html((string) ($failure['type'] ?? '')); ?></span>
                                </p>
                                <p class="encypher-recent-failure-detail">
                                    <span class="encypher-recent-failure-operation"><?php echo esc_html((string) ($failure['operation_label'] ?? '')); ?></span>
                                    <span aria-hidden="true">:</span>
                                    <span class="encypher-recent-failure-reason"><?php echo esc_html((string) ($failure['reason'] ?? '')); ?></span>
                                </p>
                                <?php if ((int) ($failure['occurrences'] ?? 1) > 1) : ?>
                                    <p class="encypher-recent-failure-repeat">
                                        <?php
                                        printf(
                                            /* translators: %s: number of repeated occurrences. */
                                            esc_html__('Repeated %s times', 'encypher-provenance'),
                                            esc_html(number_format_i18n((int) $failure['occurrences']))
                                        );
                                        ?>
                                    </p>
                                <?php endif; ?>
                                <details class="encypher-failure-technical">
                                    <summary><?php esc_html_e('Technical details', 'encypher-provenance'); ?></summary>
                                    <code><?php echo esc_html((string) ($failure['technical_reason'] ?? '')); ?></code>
                                </details>
                                <time datetime="<?php echo esc_attr((string) ($failure['timestamp'] ?? '')); ?>"><?php echo esc_html((string) ($failure['timestamp_label'] ?? '')); ?></time>
                            </div>
                            <div class="encypher-recent-failure-action">
                                <?php if (! empty($failure['resolved'])) : ?>
                                    <span class="encypher-recent-failure-resolved"><?php esc_html_e('Resolved', 'encypher-provenance'); ?></span>
                                <?php elseif (empty($failure['target_exists']) && (int) ($failure['post_id'] ?? 0) > 0) : ?>
                                    <span class="encypher-recent-failure-unavailable"><?php esc_html_e('Content no longer available', 'encypher-provenance'); ?></span>
                                <?php elseif ('retry' === $failure_action_type) : ?>
                                    <button
                                        type="button"
                                        class="button button-small encypher-recent-failure-retry"
                                        data-post-id="<?php echo esc_attr((string) ($failure['post_id'] ?? 0)); ?>"
                                        data-action-type="retry"
                                        data-action-url="<?php echo esc_url($failure_action_url); ?>"
                                    ><?php echo esc_html((string) ($failure['action_label'] ?? __('Retry signing', 'encypher-provenance'))); ?></button>
                                <?php elseif ('' !== $failure_action_url) : ?>
                                    <a
                                        class="button button-small"
                                        href="<?php echo esc_url($failure_action_url); ?>"
                                        data-action-type="<?php echo esc_attr($failure_action_type); ?>"
                                        data-action-url="<?php echo esc_url($failure_action_url); ?>"
                                    ><?php echo esc_html((string) ($failure['action_label'] ?? __('Review', 'encypher-provenance'))); ?></a>
                                <?php endif; ?>
                                <span class="encypher-recent-failure-status" role="status" aria-live="polite"></span>
                            </div>
                        </li>
                    <?php endforeach; ?>
                </ol>
            </details>
        <?php endif; ?>

        <?php if ('unclaimed' === $claim_state) : ?>
            <section id="encypher-claim-card" class="encypher-card" aria-labelledby="encypher-claim-title">
                <h2 id="encypher-claim-title"><?php esc_html_e('Claim your workspace', 'encypher-provenance'); ?></h2>
                <p><?php esc_html_e('Claim this automatic workspace without changing or invalidating existing signatures.', 'encypher-provenance'); ?></p>
                <p>
                    <label for="encypher-claim-email"><strong><?php esc_html_e('Owner email', 'encypher-provenance'); ?></strong></label><br />
                    <input type="email" id="encypher-claim-email" class="regular-text" value="<?php echo esc_attr(wp_get_current_user()->user_email); ?>" autocomplete="email" />
                </p>
                <button type="button" id="encypher-claim-btn" class="button button-primary"><?php esc_html_e('Claim workspace', 'encypher-provenance'); ?></button>
                <div id="encypher-claim-status" class="encypher-action-status" role="status" aria-live="polite"></div>
                <p class="encypher-claim-footer">
                    <a href="<?php echo esc_url('https://dashboard.encypher.com/settings/organization'); ?>" target="_blank" rel="noopener noreferrer">
                        <?php esc_html_e('Manage your organization', 'encypher-provenance'); ?>
                    </a>
                </p>
            </section>
        <?php endif; ?>

        <form method="post" action="options.php" class="encypher-card encypher-behavior-settings">
            <details class="encypher-behavior-disclosure encypher-responsive-disclosure" open>
                <summary>
                    <span class="encypher-disclosure-title"><?php esc_html_e('WordPress behavior', 'encypher-provenance'); ?></span>
                    <span class="description"><?php esc_html_e('Signing and reader display settings', 'encypher-provenance'); ?></span>
                </summary>
                <div class="encypher-behavior-body">
                    <p class="description"><?php esc_html_e('These controls affect only how this WordPress site signs and presents content.', 'encypher-provenance'); ?></p>
            <?php settings_fields('encypher_provenance_settings_group'); ?>
            <input type="hidden" name="encypher_provenance_settings[_cockpit_behavior_save]" value="1" />
            <table class="form-table" role="presentation">
                <tbody>
                    <tr>
                        <th scope="row"><?php esc_html_e('Protected publish mode', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_protected_publish_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Protected publishing roles', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_protected_publish_roles_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Protected publishing desks', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_protected_publish_terms_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Sign new content when published', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_auto_mark_on_publish_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Update the signature when content changes', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_auto_mark_on_update_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Eligible public content types', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_post_types_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Include the featured image', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_auto_sign_images_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Media signing method', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_local_hashing_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Full media uploads', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_allow_full_asset_upload_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Non-production signing', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_non_production_signing_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Show the reader badge', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_show_badge_field(); ?></td>
                    </tr>
                    <tr id="encypher-badge-position-row">
                        <th scope="row"><?php esc_html_e('Badge position', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_badge_position_field(); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Provenance info marks on media', 'encypher-provenance'); ?></th>
                        <td><?php $this->render_media_badges_field(); ?></td>
                    </tr>
                    <?php if ($wp_ai_visible) : ?>
                        <tr>
                            <th scope="row"><?php esc_html_e('WordPress/ai signing', 'encypher-provenance'); ?></th>
                            <td><?php $this->render_wordpress_ai_enabled_field(); ?></td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php $branding_entitled = \EncypherProvenance\Admin::allows_whitelabel(); ?>
            <fieldset class="encypher-branding-section">
                <legend><?php esc_html_e('Branding', 'encypher-provenance'); ?></legend>
                <?php if ($branding_entitled) : ?>
                    <table class="form-table" role="presentation">
                        <tbody>
                            <tr>
                                <th scope="row"><?php esc_html_e('Brand logo', 'encypher-provenance'); ?></th>
                                <td><?php $this->render_brand_logo_field(); ?></td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Powered by Encypher', 'encypher-provenance'); ?></th>
                                <td><?php $this->render_powered_by_encypher_field(); ?></td>
                            </tr>
                        </tbody>
                    </table>
                <?php else : ?>
                    <p class="description">
                        <?php esc_html_e('Whitelabel branding is available when Encypher enables it for this account.', 'encypher-provenance'); ?>
                    </p>
                <?php endif; ?>
            </fieldset>
            <?php submit_button(__('Save settings', 'encypher-provenance')); ?>
                </div>
            </details>
        </form>
    <?php endif; ?>

    <details class="encypher-advanced-connection">
        <summary><?php esc_html_e('Advanced connection', 'encypher-provenance'); ?></summary>
        <div class="encypher-advanced-body">
            <?php if ($is_connected) : ?>
                <p class="description">
                    <?php
                    printf(
                        /* translators: %s: API endpoint host. */
                        esc_html__('Connection endpoint: %s. An API key is stored securely in WordPress and is never rendered into this page.', 'encypher-provenance'),
                        esc_html((string) (wp_parse_url((string) ($settings['api_base_url'] ?? ''), PHP_URL_HOST) ?: __('hosted Encypher API', 'encypher-provenance')))
                    );
                    ?>
                </p>
            <?php endif; ?>

            <div class="encypher-advanced-fields">
                <div>
                    <h3><?php esc_html_e('API key', 'encypher-provenance'); ?></h3>
                    <?php $this->render_api_key_field(); ?>
                    <span id="encypher-api-key-status" role="status" aria-live="polite"></span>
                </div>
                <div>
                    <h3><?php esc_html_e('Self-hosted endpoint', 'encypher-provenance'); ?></h3>
                    <?php $this->render_api_base_url_field(); ?>
                </div>
            </div>
            <p>
                <button type="button" id="encypher-advanced-connect-btn" class="button"><?php esc_html_e('Verify and save connection', 'encypher-provenance'); ?></button>
            </p>

            <?php if ($is_connected) : ?>
                <hr />
                <h3><?php esc_html_e('Reconnect account', 'encypher-provenance'); ?></h3>
                <p class="description"><?php esc_html_e('Reconnect through the Encypher dashboard if this site should belong to a different workspace.', 'encypher-provenance'); ?></p>
                <button type="button" id="encypher-oauth-start-btn" class="button"><?php esc_html_e('Reconnect Encypher account', 'encypher-provenance'); ?></button>
                <button type="button" id="encypher-oauth-cancel-btn" class="button" hidden><?php esc_html_e('Cancel', 'encypher-provenance'); ?></button>
                <div id="encypher-oauth-status" class="encypher-action-status" role="status" aria-live="polite"></div>
            <?php endif; ?>
        </div>
    </details>
</div>
