<?php

declare( strict_types=1 );

namespace StrykeWP\Core;

use StrykeWP\Modules\ModuleRegistry;

/**
 * Handles all plugin metadata, links, styling, and notices on the
 * WordPress Plugins page (plugins.php).
 *
 * Responsibilities:
 *  - Plugin action links (Settings, Modules)
 *  - Plugin row meta links (Docs, Support, Website, Changelog)
 *  - Plugin icon for update/detail views
 *  - Custom CSS highlighting on the plugins list
 *  - Activation welcome notice (one-time, dismissible)
 *  - Deactivation feedback modal
 *
 * @package StrykeWP\Core
 */
final class PluginMeta {

	private const ACTIVATION_NOTICE_TRANSIENT = 'stryke_wp_activation_notice';
	private const DISMISS_NOTICE_ACTION       = 'stryke_wp_dismiss_activation_notice';

	public function __construct(
		private readonly AssetManager    $assets,
		private readonly ModuleRegistry  $registry,
	) {}

	/**
	 * Registers all WordPress hooks.
	 */
	public function register_hooks(): void {
		// Plugin action links (left side: Settings, Modules).
		add_filter(
			'plugin_action_links_' . STRYKE_WP_BASENAME,
			[ $this, 'add_action_links' ]
		);

		// Plugin row meta (right side: Docs, Support, Website, Changelog).
		add_filter( 'plugin_row_meta', [ $this, 'add_row_meta' ], 10, 2 );

		// Plugin icon for update/details views.
		add_filter( 'plugins_api', [ $this, 'inject_plugin_icon' ], 10, 3 );

		// CSS only on plugins.php.
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_plugins_page_css' ] );

		// Deactivation modal JS/HTML.
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_deactivation_modal' ] );

		// Activation welcome notice.
		add_action( 'admin_notices', [ $this, 'render_activation_notice' ] );

		// AJAX handler to dismiss the activation notice.
		add_action( 'wp_ajax_' . self::DISMISS_NOTICE_ACTION, [ $this, 'ajax_dismiss_activation_notice' ] );
	}

	// =========================================================================
	// 1. Plugin Action Links
	// =========================================================================

	/**
	 * Adds "Einstellungen" and "Module" links next to Activate/Deactivate.
	 *
	 * @param array<string, string> $links Existing action links.
	 * @return array<string, string>
	 */
	public function add_action_links( array $links ): array {
		$custom = [
			'settings' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( admin_url( 'admin.php?page=stryke-wp' ) ),
				esc_html__( 'Einstellungen', 'stryke-wp' )
			),
			'modules' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( admin_url( 'admin.php?page=stryke-wp#modules' ) ),
				esc_html__( 'Module', 'stryke-wp' )
			),
		];

		return array_merge( $custom, $links );
	}

	// =========================================================================
	// 2. Plugin Row Meta
	// =========================================================================

	/**
	 * Adds Docs, Support, Website, Changelog links under the description.
	 *
	 * @param array<int, string> $meta    Existing row meta.
	 * @param string             $file    Plugin basename.
	 * @return array<int, string>
	 */
	public function add_row_meta( array $meta, string $file ): array {
		if ( $file !== STRYKE_WP_BASENAME ) {
			return $meta;
		}

		$extra = [
			'docs' => sprintf(
				'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
				esc_url( 'https://faq.strykehub.de/' ),
				esc_html__( 'FAQ / Dokumentation', 'stryke-wp' )
			),
			'support' => sprintf(
				'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
				esc_url( 'https://support.strykehub.com/' ),
				esc_html__( 'Support', 'stryke-wp' )
			),
			'website' => sprintf(
				'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
				esc_url( 'https://www.strykemarketing.de' ),
				esc_html__( 'STRYKE Marketing', 'stryke-wp' )
			),
			'changelog' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( admin_url( 'admin.php?page=stryke-wp&tab=changelog' ) ),
				esc_html__( 'Changelog', 'stryke-wp' )
			),
		];

		return array_merge( $meta, $extra );
	}

	// =========================================================================
	// 3. Plugin Icon
	// =========================================================================

	/**
	 * Injects the STRYKE logo as plugin icon in update/detail views.
	 *
	 * @param false|object|array<string, mixed> $result The result object or array.
	 * @param string                            $action API action.
	 * @param object                            $args   Request arguments.
	 * @return false|object|array<string, mixed>
	 */
	public function inject_plugin_icon( mixed $result, string $action, object $args ): mixed {
		if ( 'plugin_information' !== $action ) {
			return $result;
		}

		if ( ! isset( $args->slug ) || 'stryke-wp' !== $args->slug ) {
			return $result;
		}

		if ( ! is_object( $result ) ) {
			$result = (object) [];
		}

		$img_url = $this->assets->asset_url( 'img/' );

		/** @var object $result */
		$result->icons = [
			'svg'     => $img_url . 'stryke_icon.svg',
			'1x'      => $img_url . 'icon-128x128.png',
			'2x'      => $img_url . 'icon-256x256.png',
			'default' => $img_url . 'icon-256x256.png',
		];

		$result->banners = [
			'low'  => $img_url . 'banner-772x250.png',
			'high' => $img_url . 'banner-1544x500.png',
		];

		return $result;
	}

	// =========================================================================
	// 4. Plugins Page CSS
	// =========================================================================

	/**
	 * Enqueues custom CSS on the plugins.php page only.
	 *
	 * @param string $hook_suffix Current admin page hook.
	 */
	public function enqueue_plugins_page_css( string $hook_suffix ): void {
		if ( 'plugins.php' !== $hook_suffix ) {
			return;
		}

		wp_enqueue_style(
			'stryke-wp-plugin-meta',
			$this->assets->asset_url( 'css/plugin-meta.css' ),
			[],
			STRYKE_WP_VERSION
		);
	}

	// =========================================================================
	// 5. Deactivation Feedback Modal
	// =========================================================================

	/**
	 * Enqueues the deactivation confirmation modal on plugins.php.
	 *
	 * @param string $hook_suffix Current admin page hook.
	 */
	public function enqueue_deactivation_modal( string $hook_suffix ): void {
		if ( 'plugins.php' !== $hook_suffix ) {
			return;
		}

		add_action( 'admin_footer', [ $this, 'render_deactivation_modal' ] );

		wp_enqueue_script(
			'stryke-wp-deactivation',
			$this->assets->asset_url( 'js/plugin-meta.js' ),
			[],
			STRYKE_WP_VERSION,
			true
		);

		wp_localize_script(
			'stryke-wp-deactivation',
			'strykeWPMeta',
			[
				'basename' => STRYKE_WP_BASENAME,
				'i18n'     => [
					'title'       => __( 'STRYKE WP deaktivieren', 'stryke-wp' ),
					'confirm'     => __( 'Möchtest du STRYKE WP wirklich deaktivieren?', 'stryke-wp' ),
					'deleteData'  => __( 'Alle Plugin-Daten löschen (Tabellen, Optionen, Logs)', 'stryke-wp' ),
					'cancel'      => __( 'Abbrechen', 'stryke-wp' ),
					'deactivate'  => __( 'Deaktivieren', 'stryke-wp' ),
				],
			]
		);
	}

	/**
	 * Renders the deactivation confirmation modal HTML.
	 */
	public function render_deactivation_modal(): void {
		?>
		<div id="stryke-wp-deactivation-modal" class="stryke-wp-modal" style="display:none;">
			<div class="stryke-wp-modal__backdrop"></div>
			<div class="stryke-wp-modal__dialog">
				<div class="stryke-wp-modal__header">
					<h3 id="stryke-wp-modal-title"></h3>
					<button type="button" class="stryke-wp-modal__close" aria-label="<?php esc_attr_e( 'Schließen', 'stryke-wp' ); ?>">&times;</button>
				</div>
				<div class="stryke-wp-modal__body">
					<p id="stryke-wp-modal-message"></p>
					<label class="stryke-wp-modal__checkbox">
						<input type="checkbox" id="stryke-wp-delete-data" value="1">
						<span id="stryke-wp-modal-delete-label"></span>
					</label>
				</div>
				<div class="stryke-wp-modal__footer">
					<button type="button" class="button stryke-wp-modal__cancel" id="stryke-wp-modal-cancel"></button>
					<button type="button" class="button button-primary stryke-wp-modal__confirm" id="stryke-wp-modal-confirm"></button>
				</div>
			</div>
		</div>
		<?php
	}

	// =========================================================================
	// 6. Activation Notice
	// =========================================================================

	/**
	 * Sets the activation notice transient.
	 *
	 * Called from Installer::activate().
	 */
	public static function set_activation_notice(): void {
		set_transient( self::ACTIVATION_NOTICE_TRANSIENT, '1', 3600 );
	}

	/**
	 * Renders a one-time dismissible welcome notice after activation.
	 */
	public function render_activation_notice(): void {
		if ( ! get_transient( self::ACTIVATION_NOTICE_TRANSIENT ) ) {
			return;
		}

		// Also dismiss when user visits the dashboard.
		$screen = get_current_screen();
		if ( $screen && str_contains( $screen->id, 'stryke-wp' ) ) {
			delete_transient( self::ACTIVATION_NOTICE_TRANSIENT );
			return;
		}

		$dashboard_url = admin_url( 'admin.php?page=stryke-wp' );
		?>
		<div class="notice notice-success is-dismissible stryke-wp-activation-notice"
			 data-dismiss-nonce="<?php echo esc_attr( wp_create_nonce( self::DISMISS_NOTICE_ACTION ) ); ?>">
			<p>
				<strong><?php esc_html_e( 'STRYKE WP wurde aktiviert!', 'stryke-wp' ); ?></strong>
				<?php
				printf(
					/* translators: %s: link to the STRYKE WP dashboard */
					wp_kses(
						__( 'Konfiguriere deine Module im %s', 'stryke-wp' ),
						[ 'a' => [ 'href' => [] ] ]
					),
					sprintf(
						'<a href="%s">%s &rarr;</a>',
						esc_url( $dashboard_url ),
						esc_html__( 'STRYKE WP Dashboard', 'stryke-wp' )
					)
				);
				?>
			</p>
		</div>
		<script>
		(function() {
			var notice = document.querySelector('.stryke-wp-activation-notice');
			if (!notice) return;
			notice.addEventListener('click', function(e) {
				if (e.target.classList.contains('notice-dismiss')) {
					var xhr = new XMLHttpRequest();
					xhr.open('POST', ajaxurl);
					xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					xhr.send(
						'action=<?php echo esc_js( self::DISMISS_NOTICE_ACTION ); ?>' +
						'&nonce=' + encodeURIComponent(notice.dataset.dismissNonce)
					);
				}
			});
		})();
		</script>
		<?php
	}

	/**
	 * AJAX handler to dismiss the activation notice.
	 */
	public function ajax_dismiss_activation_notice(): void {
		check_ajax_referer( self::DISMISS_NOTICE_ACTION, 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( null, 403 );
		}

		delete_transient( self::ACTIVATION_NOTICE_TRANSIENT );
		wp_send_json_success();
	}
}
