<?php
/**
 * AdminUI — renders the Link Assassin admin page.
 *
 * Three tabs:
 *   - Scan: dry-run preview
 *   - Execute: batched delete with progress bar (JS-driven)
 *   - Restore: list of backups with one-click restore
 *
 * @package Platform\Helm\Modules\LinkAssassin
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\LinkAssassin;

use Platform\Helm\Core\Assets;
use Platform\Helm\Core\Ui;

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

final class AdminUI {

	public const PAGE_SLUG = 'platform-helm-link-assassin';

	public function __construct(
		private Assets $assets,
		private BackupManager $backups
	) {}

	public function register_hooks(): void {
		add_action( 'admin_menu', [ $this, 'register_menu' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'maybe_enqueue' ] );
	}

	public function register_menu(): void {
		if ( ! \Platform\Helm\Core\Authorization::is_master_admin() ) {
			return;
		}
		add_management_page(
			__( 'Link Assassin', 'platform-helm' ),
			__( 'Link Assassin', 'platform-helm' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render' ]
		);
	}

	public function maybe_enqueue( string $hook_suffix ): void {
		if ( false === strpos( $hook_suffix, self::PAGE_SLUG ) ) {
			return;
		}
		$this->assets->enqueue_link_assassin( [
			'ajaxUrl'      => admin_url( 'admin-ajax.php' ),
			'nonce'        => wp_create_nonce( AjaxController::NONCE_ACTION ),
			'batchSize'    => LinkAssassinModule::BATCH_SIZE,
			'i18n'         => [
				'scanFirst'      => __( 'Run the scan first to preview matches.', 'platform-helm' ),
				'noUrls'         => __( 'Please paste at least one URL.', 'platform-helm' ),
				'confirmExecute' => __( 'This will modify your database. Per-post backups are saved automatically. Continue?', 'platform-helm' ),
				'starting'       => __( 'Starting…', 'platform-helm' ),
				'scanning'       => __( 'Scanning…', 'platform-helm' ),
				'processing'     => __( 'Processing posts %1$d–%2$d of %3$d…', 'platform-helm' ),
				'doneTitle'      => __( 'Done', 'platform-helm' ),
				'doneSummary'    => __( 'Modified %1$d posts, removed %2$d links. %3$d errors.', 'platform-helm' ),
				'networkError'   => __( 'Network error. Please retry.', 'platform-helm' ),
				'restoreConfirm' => __( 'Restore this post to its pre-Assassin state and delete the backup?', 'platform-helm' ),
				'deleteConfirm'  => __( 'Delete this backup without restoring? This cannot be undone.', 'platform-helm' ),
			],
		] );
	}

	public function render(): void {
		\Platform\Helm\Core\Authorization::require_master_admin();

		$active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( (string) $_GET['tab'] ) ) : 'scan';
		$tabs       = [
			'scan'    => __( '1. Scan', 'platform-helm' ),
			'execute' => __( '2. Execute', 'platform-helm' ),
			'restore' => __( '3. Restore', 'platform-helm' ),
		];
		if ( ! isset( $tabs[ $active_tab ] ) ) {
			$active_tab = 'scan';
		}

		Ui::open_page(
			__( 'Link Assassin', 'platform-helm' ),
			__( 'Bulk-remove dead outbound links from posts and Elementor data. Batched, reversible, DOM-safe.', 'platform-helm' )
		);

		echo '<div class="tabs">';
		foreach ( $tabs as $tab => $label ) {
			$url = add_query_arg( [ 'page' => self::PAGE_SLUG, 'tab' => $tab ], admin_url( 'tools.php' ) );
			printf(
				'<a href="%s" class="tab%s">%s</a>',
				esc_url( $url ),
				$active_tab === $tab ? ' active' : '',
				esc_html( $label )
			);
		}
		echo '</div>';

		$titles = [
			'scan'    => [ __( 'Scan for broken URLs', 'platform-helm' ), 'ti-search' ],
			'execute' => [ __( 'Execute removal', 'platform-helm' ), 'ti-skull' ],
			'restore' => [ __( 'Backups', 'platform-helm' ), 'ti-history' ],
		];
		Ui::card_open( $titles[ $active_tab ][0], '', $titles[ $active_tab ][1] );
		match ( $active_tab ) {
			'scan'    => $this->render_scan_tab(),
			'execute' => $this->render_execute_tab(),
			'restore' => $this->render_restore_tab(),
		};
		Ui::card_close();
		Ui::close_page();
	}

	private function render_scan_tab(): void {
		echo '<p class="text-secondary" style="margin-bottom:12px">' . esc_html__( 'Paste broken URLs (one per line). The scan is read-only.', 'platform-helm' ) . '</p>';
		echo '<textarea id="platform-helm-la-urls" class="field-input" rows="8" style="font-family:var(--font-mono)" placeholder="https://example.com/dead-page&#10;https://example.com/another-404"></textarea>';
		echo '<div style="margin-top:12px"><button type="button" id="platform-helm-la-scan-btn" class="btn btn-primary"><i class="ti ti-search" aria-hidden="true"></i> ' . esc_html__( 'Run scan', 'platform-helm' ) . '</button></div>';
		echo '<div id="platform-helm-la-scan-results" style="margin-top:16px"></div>';
	}

	private function render_execute_tab(): void {
		echo '<p class="text-secondary" style="margin-bottom:12px">' . esc_html__( 'Posts are processed 25 at a time. Each modified post is backed up first.', 'platform-helm' ) . '</p>';
		echo '<textarea id="platform-helm-la-urls" class="field-input" rows="8" style="font-family:var(--font-mono)" placeholder="https://example.com/dead-page"></textarea>';
		echo '<div style="margin-top:12px"><button type="button" id="platform-helm-la-execute-btn" class="btn btn-danger-ghost"><i class="ti ti-trash" aria-hidden="true"></i> ' . esc_html__( 'Execute removal', 'platform-helm' ) . '</button></div>';
		echo '<div id="platform-helm-la-progress-wrap" class="progress-card" style="display:none;margin-top:16px"><div class="progress-track"><div class="progress-fill" id="platform-helm-la-progress-bar" style="width:0"></div></div><p class="progress-meta" id="platform-helm-la-progress-text"></p></div>';
		echo '<div id="platform-helm-la-execute-results" style="margin-top:16px"></div>';
	}

	private function render_restore_tab(): void {
		$backups = $this->backups->list_backups();
		echo '<p class="text-secondary" style="margin-bottom:12px">' . esc_html(
			sprintf( /* translators: %d: backup count */ _n( '%d backup on record — newest first.', '%d backups on record — newest first.', count( $backups ), 'platform-helm' ), count( $backups ) )
		) . '</p>';

		if ( empty( $backups ) ) {
			echo '<p class="text-faint">' . esc_html__( 'No backups yet. Run Execute first.', 'platform-helm' ) . '</p>';
			return;
		}

		echo '<div class="table-wrap"><table id="platform-helm-la-backups"><thead><tr>';
		echo '<th>' . esc_html__( 'Post', 'platform-helm' ) . '</th>';
		echo '<th>' . esc_html__( 'Type', 'platform-helm' ) . '</th>';
		echo '<th>' . esc_html__( 'Backup created', 'platform-helm' ) . '</th>';
		echo '<th class="right">' . esc_html__( 'Actions', 'platform-helm' ) . '</th>';
		echo '</tr></thead><tbody>';

		foreach ( $backups as $b ) {
			$edit = get_edit_post_link( (int) $b['post_id'] );
			echo '<tr data-post-id="' . esc_attr( (string) $b['post_id'] ) . '" data-meta-key="' . esc_attr( $b['meta_key'] ) . '">';
			echo '<td><p class="url-cell">' . ( $edit ? '<a href="' . esc_url( $edit ) . '">' . esc_html( $b['post_title'] ?: __( '(no title)', 'platform-helm' ) ) . '</a>' : esc_html( $b['post_title'] ?: __( '(no title)', 'platform-helm' ) ) ) . '</p><p class="meta-line">ID: ' . esc_html( (string) $b['post_id'] ) . '</p></td>';
			echo '<td><span class="badge badge-neutral">' . esc_html( $b['post_type'] ) . '</span></td>';
			echo '<td><span style="color:var(--text-muted)">' . esc_html(
				$b['timestamp'] ? wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $b['timestamp'] ) : __( 'unknown', 'platform-helm' )
			) . '</span></td>';
			echo '<td class="right"><button type="button" class="btn btn-ghost btn-sm platform-helm-la-restore-btn"><i class="ti ti-rotate-clockwise" aria-hidden="true"></i> ' . esc_html__( 'Restore', 'platform-helm' ) . '</button> <button type="button" class="btn btn-danger-ghost btn-sm platform-helm-la-delete-btn">' . esc_html__( 'Delete', 'platform-helm' ) . '</button></td>';
			echo '</tr>';
		}
		echo '</tbody></table></div>';
	}
}
