<?php

namespace CelerSearch\Admin;

defined( 'ABSPATH' ) || exit;

use CelerSearch\Interfaces\IRegistrable;

/**
 * First-run welcome notice.
 *
 * Renders a standard WordPress admin notice at the top of the CelerSearch
 * admin screen with the four-step setup guide, until the user dismisses it.
 * Dismissal uses the celersearch_welcome_dismiss AJAX endpoint (registered
 * in Admin\Ajax) and persists via the celersearch_welcome_dismissed option.
 *
 * Notice (rather than a separate /welcome SPA view) is the right shape here
 * because: (a) WordPress users already know how to read & dismiss admin
 * notices, (b) it doesn't hijack SPA routing, (c) it can show on first
 * navigation without needing an activation transient + redirect dance.
 */
class WelcomeNotice implements IRegistrable {

	const PAGE_SLUG = 'celersearch';

	public function register(): void {
		add_action( 'admin_notices', [ $this, 'render' ] );
	}

	public function render(): void {
		// Show on every admin screen EXCEPT the CelerSearch one — once the user
		// is already on the plugin's screen they're engaged, so the notice
		// would just be noise there. Its value is in nudging users elsewhere
		// in wp-admin to come complete the setup.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Just checking admin page context
		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		if ( self::PAGE_SLUG === $page ) {
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// (bool) cast handles the empty-string-is-false WordPress option
		// convention. Default true so absent option (existing installs that
		// pre-date this feature) never see the notice.
		$dismissed = (bool) get_option( 'celersearch_welcome_dismissed', true );
		if ( $dismissed ) {
			return;
		}

		$nonce       = wp_create_nonce( 'celersearch' );
		$ajax_url    = esc_url_raw( admin_url( 'admin-ajax.php' ) );
		$services_url = esc_url( admin_url( 'admin.php?page=' . self::PAGE_SLUG ) ) . '#/services?action=new';
		$indices_url  = esc_url( admin_url( 'admin.php?page=' . self::PAGE_SLUG ) ) . '#/?action=new';
		$settings_url = esc_url( admin_url( 'admin.php?page=' . self::PAGE_SLUG ) ) . '#/settings';

		$self_host_url = 'https://www.meilisearch.com/docs/learn/self_hosted/getting_started_with_self_hosted_meilisearch';
		$managed_url   = 'https://celersearch.com/';
		?>
		<div class="notice notice-info is-dismissible cs-welcome-notice" data-cs-welcome>
			<h2 class="cs-welcome-notice__title"><?php esc_html_e( 'Welcome to CelerSearch', 'celersearch' ); ?></h2>
			<p class="cs-welcome-notice__intro">
				<?php esc_html_e( 'CelerSearch needs a Meilisearch engine to power your site search. Run it yourself on your favorite VPS, or let us manage one for you — pick whichever fits your team.', 'celersearch' ); ?>
			</p>

			<div class="cs-welcome-notice__cards">
				<div class="cs-welcome-notice__card">
					<h3><?php esc_html_e( 'Self-host', 'celersearch' ); ?></h3>
					<p><?php esc_html_e( 'Run Meilisearch on your own VPS. Free, you own the data, you handle updates and backups.', 'celersearch' ); ?></p>
					<a href="<?php echo esc_url( $self_host_url ); ?>" target="_blank" rel="noopener noreferrer" class="button">
						<?php esc_html_e( 'View self-host guide', 'celersearch' ); ?>
						<span aria-hidden="true" class="dashicons dashicons-external" style="font-size:14px;line-height:1.4;"></span>
					</a>
				</div>
				<div class="cs-welcome-notice__card cs-welcome-notice__card--accent">
					<h3><?php esc_html_e( 'Managed by CelerSearch', 'celersearch' ); ?></h3>
					<p><?php esc_html_e( 'Provisioned in seconds, daily backups, SSL, no ops to worry about. Plans start at $10/mo.', 'celersearch' ); ?></p>
					<a href="<?php echo esc_url( $managed_url ); ?>" target="_blank" rel="noopener noreferrer" class="button button-primary">
						<?php esc_html_e( 'Get a managed instance', 'celersearch' ); ?>
						<span aria-hidden="true" class="dashicons dashicons-external" style="font-size:14px;line-height:1.4;"></span>
					</a>
				</div>
			</div>

			<p class="cs-welcome-notice__next">
				<span class="cs-welcome-notice__next-label"><?php esc_html_e( 'Once your engine is ready:', 'celersearch' ); ?></span>
				<a href="<?php echo $services_url; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- composed from esc_url() above ?>" class="button button-primary"><?php esc_html_e( 'Add service', 'celersearch' ); ?></a>
				<a href="<?php echo $indices_url; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- composed from esc_url() above ?>" class="button"><?php esc_html_e( 'Create index', 'celersearch' ); ?></a>
				<a href="<?php echo $settings_url; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- composed from esc_url() above ?>" class="button"><?php esc_html_e( 'Configure search', 'celersearch' ); ?></a>
			</p>
		</div>

		<style>
			.cs-welcome-notice { padding: 16px 36px 16px 16px; }
			.cs-welcome-notice__title { margin: 0 0 6px; font-size: 1.2em; }
			.cs-welcome-notice__intro { margin: 0 0 14px; max-width: 720px; color: #50575e; }
			.cs-welcome-notice__cards {
				display: grid;
				grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
				gap: 12px;
				margin-bottom: 14px;
			}
			.cs-welcome-notice__card {
				border: 1px solid #dcdcde;
				background: #fff;
				border-radius: 4px;
				padding: 12px 14px;
				display: flex;
				flex-direction: column;
			}
			.cs-welcome-notice__card--accent {
				border-color: #c5d9ed;
				background: #f0f6fc;
			}
			.cs-welcome-notice__card h3 { margin: 0 0 4px; font-size: 14px; }
			.cs-welcome-notice__card p { margin: 0 0 10px; font-size: 13px; color: #50575e; flex: 1; }
			.cs-welcome-notice__card .button { align-self: flex-start; }
			.cs-welcome-notice__next { margin: 0; display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
			.cs-welcome-notice__next-label { color: #50575e; font-size: 13px; margin-right: 4px; }
		</style>

		<script>
		(function () {
			// Hook the standard WP "X" dismiss button so the dismissal persists
			// across page loads instead of just hiding the notice for this view.
			document.addEventListener('click', function (event) {
				var btn = event.target.closest('.cs-welcome-notice .notice-dismiss');
				if (!btn) return;

				var body = new FormData();
				body.append('action', 'celersearch_welcome_dismiss');
				body.append('_wpnonce', <?php echo wp_json_encode( $nonce ); ?>);
				fetch(<?php echo wp_json_encode( $ajax_url ); ?>, {
					method: 'POST',
					credentials: 'same-origin',
					body: body
				}).catch(function () { /* non-fatal — notice is already hidden visually */ });
			});
		})();
		</script>
		<?php
	}
}
