<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/* -------------------------------------------------------------------------
 * Activation router
 * ---------------------------------------------------------------------- */

function misticease_redirect_after_activation(): void {
	if ( is_multisite() && is_network_admin() && get_site_transient( 'misticease_activated_network' ) ) {
		delete_site_transient( 'misticease_activated_network' );
		set_site_transient( 'misticease_redirect_router_needed', '1', 60 );

		wp_safe_redirect( network_admin_url( 'admin.php?page=misticease-activate-router' ) );
		exit;
	}

	if ( ! is_network_admin() && get_transient( 'misticease_activated' ) ) {
		delete_transient( 'misticease_activated' );
		set_transient( 'misticease_redirect_router_needed', '1', 60 );

		wp_safe_redirect( admin_url( 'admin.php?page=misticease-activate-router' ) );
		exit;
	}
}
add_action( 'admin_init', 'misticease_redirect_after_activation', 1 );

function misticease_register_activate_router(): void {
	$cap = ( is_multisite() && is_network_admin() ) ? 'manage_network_options' : 'manage_options';

	add_submenu_page(
		null,
		'MisticEase',
		'MisticEase',
		$cap,
		'misticease-activate-router',
		'misticease_activate_router_cb'
	);
}
add_action( 'admin_menu', 'misticease_register_activate_router', 1 );
add_action( 'network_admin_menu', 'misticease_register_activate_router', 1 );

function misticease_get_activate_router_tab(): string {
	$tab_raw = filter_input( INPUT_GET, 'tab', FILTER_DEFAULT );
	$tab     = is_string( $tab_raw ) ? sanitize_key( $tab_raw ) : 'readme';

	return $tab ?: 'readme';
}

function misticease_redirect_activate_router_request(): void {
	$page_raw = filter_input( INPUT_GET, 'page', FILTER_DEFAULT );
	$page     = is_string( $page_raw ) ? sanitize_key( $page_raw ) : '';

	if ( 'misticease-activate-router' !== $page ) {
		return;
	}

	$get = ( is_multisite() && is_network_admin() ) ? 'get_site_transient' : 'get_transient';
	$del = ( is_multisite() && is_network_admin() ) ? 'delete_site_transient' : 'delete_transient';
	$tab = misticease_get_activate_router_tab();

	if ( $get( 'misticease_redirect_router_needed' ) ) {
		$del( 'misticease_redirect_router_needed' );
	}

	$target = ( is_multisite() && is_network_admin() )
		? network_admin_url( 'admin.php?page=misticease-network&tab=' . rawurlencode( $tab ) )
		: admin_url( 'admin.php?page=misticease-control-panel&tab=' . rawurlencode( $tab ) );

	wp_safe_redirect( $target );
	exit;
}
add_action( 'admin_init', 'misticease_redirect_activate_router_request', 2 );

function misticease_activate_router_cb(): void {
}

/* -------------------------------------------------------------------------
 * Admin (single site)
 * ---------------------------------------------------------------------- */

add_action(
	'admin_init',
	static function (): void {
		register_setting( 'misticease_settings_group', 'misticease_options', 'misticease_sanitize_options' );
	}
);

function misticease_sanitize_options( $input ): array {
	$o  = misticease_opts_get();
	$in = is_array( $input ) ? $input : [];

	$get_scalar = static function ( array $source, string $key ): ?string {
		if ( ! array_key_exists( $key, $source ) || ! is_scalar( $source[ $key ] ) ) {
			return null;
		}
		return (string) $source[ $key ];
	};

	$o['lazy_load']   = ( 'on' === $get_scalar( $in, 'lazy_load' ) ) ? 'on' : 'off';
	$o['image_popup'] = ( 'on' === $get_scalar( $in, 'image_popup' ) ) ? 'on' : 'off';
	$o['floating_ux'] = ( 'on' === $get_scalar( $in, 'floating_ux' ) ) ? 'on' : 'off';

	$thumbnail_max_width = $get_scalar( $in, 'thumbnail_max_width' );
	if ( null !== $thumbnail_max_width ) { $o['thumbnail_max_width'] = max( 200, (int) $thumbnail_max_width ); }

	$popup_max_width = $get_scalar( $in, 'popup_max_width' );
	if ( null !== $popup_max_width ) { $o['popup_max_width'] = max( 200, (int) $popup_max_width ); }

	$enforce_cap    = is_multisite() ? (bool) get_site_option( 'misticease_network_enforce_quota', false ) : false;
	$cache_quota_mb = $get_scalar( $in, 'cache_quota_mb' );
	if ( ! $enforce_cap && null !== $cache_quota_mb ) {
		$o['cache_quota_mb'] = max( 0, (int) $cache_quota_mb );
	}

	$enforce_cdn = is_multisite() ? (bool) get_site_option( 'misticease_network_enforce_cdn', false ) : false;
	if ( ! $enforce_cdn ) {
		$hosts_raw = $in['cdn_hosts'] ?? '';
		$lines     = is_string( $hosts_raw ) ? ( preg_split( '/\r\n|\r|\n/', $hosts_raw ) ?: [] ) : ( is_array( $hosts_raw ) ? $hosts_raw : [] );
		$hosts     = [];
		foreach ( $lines as $h ) {
			if ( ! is_scalar( $h ) ) { continue; }
			$h = strtolower( trim( (string) $h ) );
			if ( '' === $h ) { continue; }
			$h = preg_replace( '#^\w+://#', '', $h );
			$h = preg_replace( '#/.*$#', '', $h );
			if ( preg_match( '/^[a-z0-9.-]+$/', (string) $h ) ) {
				$hosts[] = $h;
			}
		}
		$o['cdn_hosts'] = array_values( array_unique( $hosts ) );
	}

	return $o;
}

function misticease_save_settings_handler(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have permission.', 'misticease' ) );
	}

	check_admin_referer( 'misticease_save_settings_nonce', 'misticease_save_settings_nonce' );

	$is_ms = is_multisite();

	$net_enforce_cap = $is_ms ? (bool) get_site_option( 'misticease_network_enforce_quota', false ) : false;
	$net_cap_mb      = $is_ms ? (int) get_site_option( 'misticease_network_default_quota_mb', 0 ) : 0;

	$net_enforce_cdn = $is_ms ? (bool) get_site_option( 'misticease_network_enforce_cdn', false ) : false;
	$net_cdn_hosts   = $is_ms ? (array) get_site_option( 'misticease_network_cdn_hosts', [] ) : [];

	if ( isset( $_POST['reset'] ) ) {
		$defaults = misticease_get_default_options();
		$o        = misticease_opts_get();

		$keep = [
			'cache_quota_mb'   => (int) ( $o['cache_quota_mb'] ?? 0 ),
			'cache_version'    => (int) ( $o['cache_version'] ?? 1 ),
			'used_cache_bytes' => (int) ( $o['used_cache_bytes'] ?? 0 ),
		];

		$merged = array_merge( $defaults, $keep );

		if ( $net_enforce_cap ) {
			$merged['cache_quota_mb'] = $net_cap_mb;
		}

		if ( $net_enforce_cdn ) {
			$merged['cdn_hosts'] = array_values( array_filter( array_map( 'strval', $net_cdn_hosts ) ) );
		}

		update_option( 'misticease_options', $merged, 'no' );

		set_transient(
			'misticease_notice',
			[
				'type' => 'success',
				'msg'  => __( 'Settings reset to defaults.', 'misticease' ),
			],
			30
		);

		wp_safe_redirect( admin_url( 'admin.php?page=misticease-control-panel&tab=settings' ) );
		exit;
	}

		$posted_value = static function ( string $key ): string {
			if ( ! isset( $_POST['misticease_save_settings_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['misticease_save_settings_nonce'] ) ), 'misticease_save_settings_nonce' ) ) {
				return '';
			}

			if ( ! isset( $_POST['misticease_options'] ) || ! is_array( $_POST['misticease_options'] ) || ! array_key_exists( $key, $_POST['misticease_options'] ) || ! is_scalar( $_POST['misticease_options'][ $key ] ) ) {
				return '';
			}

			return sanitize_textarea_field( wp_unslash( (string) $_POST['misticease_options'][ $key ] ) );
		};

		$in = [
			'thumbnail_max_width' => sanitize_text_field( $posted_value( 'thumbnail_max_width' ) ),
			'popup_max_width'     => sanitize_text_field( $posted_value( 'popup_max_width' ) ),
			'lazy_load'           => sanitize_text_field( $posted_value( 'lazy_load' ) ),
			'cache_quota_mb'      => sanitize_text_field( $posted_value( 'cache_quota_mb' ) ),
			'image_popup'         => sanitize_text_field( $posted_value( 'image_popup' ) ),
			'floating_ux'         => sanitize_text_field( $posted_value( 'floating_ux' ) ),
			'cdn_hosts'           => sanitize_textarea_field( $posted_value( 'cdn_hosts' ) ),
		];

		$san = misticease_sanitize_options( $in );

	if ( $net_enforce_cap ) {
		$san['cache_quota_mb'] = $net_cap_mb;
	}

	if ( $net_enforce_cdn ) {
		$san['cdn_hosts'] = array_values( array_filter( array_map( 'strval', $net_cdn_hosts ) ) );
	}

	update_option( 'misticease_options', $san, 'no' );

	set_transient(
		'misticease_notice',
		[
			'type' => 'success',
			'msg'  => __( 'Settings saved.', 'misticease' ),
		],
		30
	);

	wp_safe_redirect( admin_url( 'admin.php?page=misticease-control-panel&tab=settings' ) );
	exit;
}
add_action( 'admin_post_misticease_save_settings', 'misticease_save_settings_handler' );


/* -------------------------------------------------------------------------
 * Site settings view
 * ---------------------------------------------------------------------- */

function misticease_settings_content(): void {
	// Keep the site-level usage display accurate when cached thumbnails already exist
	// before a new HD thumbnail download or scheduled cleanup runs. Use the freshly
	// calculated value for this render so persistent object caches cannot show a stale value.
	$used_bytes_live = misticease_sync_used_thumb_cache();

	$notice = get_transient( 'misticease_notice' );
	if ( is_array( $notice ) && ! empty( $notice['msg'] ) ) {
		$type  = $notice['type'] ?? '';
		$class = ( 'success' === $type ) ? 'notice notice-success is-dismissible' : 'notice notice-error is-dismissible';
		echo '<div class="' . esc_attr( $class ) . '"><p>' . esc_html( (string) $notice['msg'] ) . '</p></div>';
		delete_transient( 'misticease_notice' );
	}

	$opts        = misticease_opts_get();
	$used_bytes  = max( 0, (int) $used_bytes_live );
	$usage_mb    = round( $used_bytes / 1048576, 2 );
	$thumb_width = esc_html( (string) ( $opts['thumbnail_max_width'] ?? 640 ) );
	$popup_width = esc_html( (string) ( $opts['popup_max_width'] ?? 854 ) );
	$thumb_cap   = (int) ( $opts['cache_quota_mb'] ?? 0 );
	$lazy_load   = ( isset( $opts['lazy_load'] ) && 'on' === $opts['lazy_load'] ) ? 'on' : 'off';
	$img_popup   = ( isset( $opts['image_popup'] ) && 'on' === $opts['image_popup'] ) ? 'on' : 'off';
	$floating_ux = ( isset( $opts['floating_ux'] ) && 'on' === $opts['floating_ux'] ) ? 'on' : 'off';

	$net_enforce_cap = is_multisite() ? (bool) get_site_option( 'misticease_network_enforce_quota', false ) : false;
	$net_cap_mb      = is_multisite() ? (int) get_site_option( 'misticease_network_default_quota_mb', 0 ) : 0;

	$net_enforce_cdn = is_multisite() ? (bool) get_site_option( 'misticease_network_enforce_cdn', false ) : false;
	$net_cdn_hosts   = is_multisite() ? (array) get_site_option( 'misticease_network_cdn_hosts', [] ) : [];

	$cap_to_show   = $net_enforce_cap ? $net_cap_mb : $thumb_cap;
	$cdn_hosts     = ( isset( $opts['cdn_hosts'] ) && is_array( $opts['cdn_hosts'] ) ) ? $opts['cdn_hosts'] : [];
	$cdn_effective = $net_enforce_cdn ? $net_cdn_hosts : $cdn_hosts;
	$cdn_text      = implode( "\n", array_map( 'strval', $cdn_effective ) );
	?>
	<h2><?php esc_html_e( 'MisticEase settings', 'misticease' ); ?></h2>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:flex;flex-direction:column;gap:1rem;">
		<input type="hidden" name="action" value="misticease_save_settings">
		<?php wp_nonce_field( 'misticease_save_settings_nonce', 'misticease_save_settings_nonce' ); ?>

		<div style="display:grid;grid-template-columns:repeat(2,minmax(200px,1fr));gap:20px;align-items:start;">

			<div>
				<label><strong><?php esc_html_e( 'Thumbnail width (px)', 'misticease' ); ?></strong></label><br>
				<input type="number" name="misticease_options[thumbnail_max_width]" value="<?php echo esc_attr( $thumb_width ); ?>" min="200" style="width:100%;">
				<div class="misticease-help" style="margin-top:6px;">
					<?php esc_html_e( 'Minimum 200 px. No upper limit. Use larger values carefully to avoid layout issues.', 'misticease' ); ?>
				</div>
			</div>

			<div>
				<label><strong><?php esc_html_e( 'Pop-up width (px)', 'misticease' ); ?></strong></label><br>
				<input type="number" name="misticease_options[popup_max_width]" value="<?php echo esc_attr( $popup_width ); ?>" min="200" style="width:100%;">
				<div class="misticease-help" style="margin-top:6px;">
					<?php esc_html_e( 'Minimum 200 px. No upper limit. Use larger values carefully to avoid layout issues.', 'misticease' ); ?>
				</div>
			</div>

			<div>
				<label><strong><?php esc_html_e( 'Thumbnail cache cap (MB)', 'misticease' ); ?></strong></label><br>
				<input type="number" name="misticease_options[cache_quota_mb]" value="<?php echo esc_attr( (string) $cap_to_show ); ?>" min="0" step="10" style="width:100%;" <?php disabled( $net_enforce_cap ); ?>>

				<div class="misticease-help" style="margin-top:6px;">
					<?php if ( $net_enforce_cap ) : ?>
						<div style="margin-top:6px;">
						<strong><?php esc_html_e( 'Currently managed by the network administrator.', 'misticease' ); ?></strong>
						</div>
					<?php endif; ?>
					<?php esc_html_e( '0 = unlimited.', 'misticease' ); ?>
				</div>

				<div style="margin-top:10px;">
					<div>
						<strong>
							<?php
							printf(
								/* translators: %s = size in MB */
								esc_html__( 'Current thumbnail cache usage: %s MB', 'misticease' ),
								esc_html( number_format_i18n( round( $usage_mb, 2 ), 2 ) )
							);
							?>
						</strong>
					</div>

					<div class="misticease-help" style="margin-top:6px;">
						<?php esc_html_e(
							'When a storage limit is configured, cached files are automatically removed starting from the oldest ones as soon as the limit is reached. A scheduled cache cleanup is also performed once every 30 days.',	'misticease'
						); ?>
					</div>
				</div>
			</div>

			<div>
				<label><strong><?php esc_html_e( 'Lazy loading', 'misticease' ); ?></strong></label><br>
				<input type="checkbox" name="misticease_options[lazy_load]" value="on" <?php checked( $lazy_load, 'on' ); ?>>
				<div class="misticease-help" style="margin-top:6px;">
					<?php esc_html_e( 'Delay loading thumbnail images until they enter the viewport to reduce the initial page load.', 'misticease' ); ?>
				</div>
			</div>

			<div>
				<label><strong><?php esc_html_e( 'Enable image pop-ups', 'misticease' ); ?></strong></label><br>
				<input type="checkbox" name="misticease_options[image_popup]" value="on" <?php checked( $img_popup, 'on' ); ?>>
				<div class="misticease-help" style="margin-top:6px;">
					<?php esc_html_e( 'Disable this option if you use another gallery or lightbox plugin for images.', 'misticease' ); ?>
				</div>
			</div>

			<div>
				<label><strong><?php esc_html_e( 'Enable Floating UX mode', 'misticease' ); ?></strong></label><br>
				<input type="checkbox" name="misticease_options[floating_ux]" value="on" <?php checked( $floating_ux, 'on' ); ?>>
				<div class="misticease-help" style="margin-top:6px;">
					<?php esc_html_e( 'Enable Floating UX mode so visitors can move a pop-up into a floating window and keep reading the page while watching or listening. Disable this option to use classic modal pop-ups.', 'misticease' ); ?>
				</div>
			</div>

			<div style="grid-column: 1 / -1;">
				<label><strong><?php esc_html_e( 'CDN image hostnames (one per line)', 'misticease' ); ?></strong></label><br>
				<textarea name="misticease_options[cdn_hosts]" rows="4" style="width:100%;" <?php disabled( $net_enforce_cdn ); ?>><?php echo esc_textarea( $cdn_text ); ?></textarea>

				<div class="misticease-help" style="margin-top:6px;">
					<?php if ( $net_enforce_cdn ) : ?>
						<div style="margin-top:6px;">
							<strong><?php esc_html_e( 'Currently managed by the network administrator.', 'misticease' ); ?></strong>
						</div>
					<?php endif; ?>
					<?php esc_html_e( 'Leave this empty unless image pop-ups do not work on a CDN-delivered site.', 'misticease' ); ?><br>
					<?php esc_html_e( 'If your Media Library images use a different hostname (for example, cdn.example.com), they may be treated as external and not open in the pop-up viewer.', 'misticease' ); ?><br>
					<?php esc_html_e( 'Enter hostnames only (no scheme, no path). Example: cdn.example.com', 'misticease' ); ?><br>
					<?php esc_html_e( 'This is not a security or hotlink protection feature.', 'misticease' ); ?>
				</div>
			</div>
		</div>

		<div style="display:flex;justify-content:space-between;margin-top:0;">
			<button type="submit" name="reset" class="button button-secondary" onclick="return confirm('<?php echo esc_js( __( 'Reset to default values?', 'misticease' ) ); ?>');">
				<?php esc_html_e( 'Reset to defaults', 'misticease' ); ?>
			</button>
			<button type="submit" name="save" class="button button-primary">
				<?php esc_html_e( 'Save changes', 'misticease' ); ?>
			</button>
		</div>
	</form>
	<?php
}



/* -------------------------------------------------------------------------
 * Site readme view
 * ---------------------------------------------------------------------- */

function misticease_render_site_readme_tab(): void {
	$inline_code_allowed_html = array(
		'code' => array(),
	);
	?>
	<div class="misticease-readme">
		<div class="misticease-readme-welcome" style="margin:0 0 18px;padding:16px 18px;border:1px solid #d8e2f0;border-radius:12px;background:linear-gradient(180deg,#f8fbff,#eef6ff);">
			<h2 style="margin:0 0 6px;"><?php esc_html_e( 'Welcome to MisticEase ✨', 'misticease' ); ?></h2>
			<p style="margin:0 0 4px;"><?php esc_html_e( 'Thanks for installing MisticEase.', 'misticease' ); ?></p>
			<p style="margin:0;"><?php esc_html_e( 'MisticEase helps site administrators build media-rich pages by pasting links into the editor and publishing.', 'misticease' ); ?></p>
		</div>

		<h2><?php esc_html_e( 'Basic workflow', 'misticease' ); ?></h2>
		<ol style="padding-left:20px;">
			<li><?php esc_html_e( 'Paste a YouTube, YouTube Shorts, Vimeo, or Dailymotion URL into a paragraph block, table block, or Classic Editor content.', 'misticease' ); ?></li>
			<li><?php esc_html_e( 'Save or publish the page.', 'misticease' ); ?></li>
			<li><?php esc_html_e( 'Open the page on the front end. With the default settings, supported video URLs automatically become clickable thumbnails.', 'misticease' ); ?></li>
			<li><?php esc_html_e( 'For Vimeo videos, a temporary placeholder may appear on the first page load or when no local thumbnail cache is available. This is normal. Open the page once after creating it so MisticEase can retrieve and cache the actual thumbnail.', 'misticease' ); ?></li>
			<li><?php esc_html_e( 'Click a thumbnail or link to open it in a pop-up.', 'misticease' ); ?></li>
		</ol>

		<h2><?php esc_html_e( 'Images', 'misticease' ); ?></h2>
		<p><?php esc_html_e( 'Images from the Media Library that are linked in editor content can open in the pop-up viewer. Link an image in the editor, publish the page, and click it on the front end.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'Text links that point to Media Library images can also open in the pop-up viewer.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'When several linked images are on the same page, visitors can move through them one by one in the pop-up viewer.', 'misticease' ); ?></p>

		<h2><?php esc_html_e( 'Optional display control', 'misticease' ); ?></h2>
		<p><?php esc_html_e( 'In the default workflow, Slash Markup is not required. Paste a supported video URL, save the page, and MisticEase uses the default thumbnail and pop-up settings.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'Use Slash Markup Core when an individual URL needs a title link, thumbnail width, pop-up width, custom label, or image caption.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'Slash Markup is not a shortcode. It works as a URL prefix. The prefix must be next to the URL, with no space, line break, or HTML tag between them.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'Use the same URL syntax and Slash Markup syntax in the Block Editor and the Classic Editor.', 'misticease' ); ?></p>

		<ul style="padding-left:20px;">
			<li>
				<?php
				echo wp_kses(
					sprintf(
						/* translators: %s: Slash Markup token for thumbnail width, for example t300/. */
						__( '%s sets the thumbnail display width to about 300 pixels.', 'misticease' ),
						'<code>t300/</code>'
					),
					$inline_code_allowed_html
				);
				?>
			</li>
			<li>
				<?php
				echo wp_kses(
					sprintf(
						/* translators: %s: Slash Markup token for thumbnail corner radius, for example r30/. */
						__( '%s sets a 30-pixel corner radius on MisticEase video and image thumbnails. It has no effect when MisticEase does not display a thumbnail.', 'misticease' ),
						'<code>r30/</code>'
					),
					$inline_code_allowed_html
				);
				?>
			</li>
			<li>
				<?php
				echo wp_kses(
					sprintf(
						/* translators: %s: Slash Markup token for pop-up width, for example p900/. */
						__( '%s sets the pop-up width to about 900 pixels.', 'misticease' ),
						'<code>p900/</code>'
					),
					$inline_code_allowed_html
				);
				?>
			</li>
			<li>
				<?php
				echo wp_kses(
					sprintf(
						/* translators: %s: Slash Markup token for title-link display. */
						__( '%s shows a title link instead of a thumbnail for supported video URLs.', 'misticease' ),
						'<code>n/</code>'
					),
					$inline_code_allowed_html
				);
				?>
			</li>
			<li>
				<?php
				echo wp_kses(
					sprintf(
						/* translators: 1: Slash Markup token for no-popup image display. 2: Slash Markup token for thumbnail width. */
						__( '%1$s displays a same-site image URL as a normal inline image without opening it in the pop-up gallery. Add %2$s to set its display width.', 'misticease' ),
						'<code>np/</code>',
						'<code>t.../</code>'
					),
					$inline_code_allowed_html
				);
				?>
			</li>
			<li>
				<?php
				echo wp_kses(
					sprintf(
						/* translators: %s: Slash Markup token for image captions or image description text. */
						__( '%s sets an image caption or image description.', 'misticease' ),
						'<code>ttl Text/</code>'
					),
					$inline_code_allowed_html
				);
				?>
			</li>
			<li>
				<?php
				echo wp_kses(
					sprintf(
						/* translators: %s: Slash Markup token for a custom text label. */
						__( '%s sets a custom text label. Place custom labels at the beginning and wrap them with slashes.', 'misticease' ),
						'<code>/Label Text/</code>'
					),
					$inline_code_allowed_html
				);
				?>
			</li>
			<li>
				<?php
				echo wp_kses(
					sprintf(
						/* translators: %s: Slash Markup token used to mark the end of a URL. */
						__( '%s marks the end of a URL when the URL is immediately followed by punctuation or other text.', 'misticease' ),
						'<code>///</code>'
					),
					$inline_code_allowed_html
				);
				?>
			</li>
		</ul>

		<p><?php esc_html_e( 'Examples:', 'misticease' ); ?></p>
		<pre style="white-space:pre-wrap;background:#f6f7f7;border:1px solid #dcdcde;border-radius:6px;padding:10px;overflow:auto;"><code><?php echo esc_html(
't300/https://www.youtube.com/watch?v=VIDEO_ID
r30/t300/https://www.youtube.com/watch?v=VIDEO_ID
p900/https://www.youtube.com/watch?v=VIDEO_ID
n/p900/https://vimeo.com/76979871
np/https://your-site.example/wp-content/uploads/image.jpg
t300/r30/np/https://your-site.example/wp-content/uploads/image.jpg
/Watch this video/p900/https://www.youtube.com/watch?v=VIDEO_ID
/Open image/ttl Image caption/t220/p900/https://your-site.example/wp-content/uploads/image.jpg'
); ?></code></pre>

		<p><?php esc_html_e( 'For videos, captions are usually not needed because MisticEase shows the video title when the pop-up opens. To change the visible text for a video link, use a custom label.', 'misticease' ); ?></p>
		<p>
			<?php
			echo wp_kses(
				sprintf(
					/* translators: 1: Slash Markup token for thumbnail width. 2: wp-content directory name. */
					__( 'MisticEase can apply the %1$s thumbnail display width to a directly pasted image URL only when the image is under the same site’s %2$s path.', 'misticease' ),
					'<code>t.../</code>',
					'<code>wp-content</code>'
				),
				$inline_code_allowed_html
			);
			?>
		</p>
		<p>
			<?php
			echo wp_kses(
				sprintf(
					/* translators: 1: Slash Markup token for no-popup image display. 2: Slash Markup token for thumbnail width. */
					__( 'When %1$s is used on a same-site image URL, MisticEase displays the image as a normal inline image using the default thumbnail width. Add %2$s to set a different width. It will not open in the pop-up and will not be included in the image pop-up gallery.', 'misticease' ),
					'<code>np/</code>',
					'<code>t.../</code>'
				),
				$inline_code_allowed_html
			);
			?>
		</p>
		<p><?php esc_html_e( 'Unsupported video service URLs, including channel pages, playlists, user pages, and search pages, stay as lightweight external links. Use a custom label for these URLs when the default link text is not clear.', 'misticease' ); ?></p>

		<pre style="white-space:pre-wrap;background:#f6f7f7;border:1px solid #dcdcde;border-radius:6px;padding:10px;overflow:auto;"><code><?php echo esc_html(
'/Playlist/https://www.youtube.com/playlist?list=PLAYLIST_ID
/Channel/https://vimeo.com/channels/staffpicks
/Dailymotion Channel/https://www.dailymotion.com/channel/music'
); ?></code></pre>

		<h2><?php esc_html_e( 'Layout tips', 'misticease' ); ?></h2>
		<p><?php esc_html_e( 'The Paragraph block is the quickest way to add a media link. The Columns and Table blocks are useful for arranging several thumbnails in a clean layout.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'Video thumbnails are resized automatically, so columns and tables can build neat media pages without custom code.', 'misticease' ); ?></p>

		<h2><?php esc_html_e( 'Floating UX mode', 'misticease' ); ?></h2>
		<p><?php esc_html_e( 'If Floating UX mode is enabled in MisticEase settings, visitors can drag a pop-up into a floating window and keep reading the page while watching or listening.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'This helps media stay connected to the page instead of interrupting it.', 'misticease' ); ?></p>

		<h2><?php esc_html_e( 'JavaScript requirement', 'misticease' ); ?></h2>
		<p><?php esc_html_e( 'MisticEase requires JavaScript for pop-up viewing.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'Pop-up viewing, floating windows, and gallery navigation do not work when JavaScript is disabled.', 'misticease' ); ?></p>
		<p><?php esc_html_e( 'MisticEase is not designed as a JavaScript-free thumbnail viewer.', 'misticease' ); ?></p>

		<h2><?php esc_html_e( 'CDN hostnames', 'misticease' ); ?></h2>
		<p><?php esc_html_e( 'If media is served from a CDN, add the CDN hostnames in MisticEase settings so those media links can open in the pop-up viewer.', 'misticease' ); ?></p>
	</div>
	<?php
}

/* -------------------------------------------------------------------------
 * Admin assets
 * ---------------------------------------------------------------------- */

function misticease_enqueue_admin_panel_styles(): void {
	$page_raw = filter_input( INPUT_GET, 'page', FILTER_DEFAULT );
	$page     = is_string( $page_raw ) ? sanitize_key( $page_raw ) : '';

	if ( ! in_array( $page, [ 'misticease-control-panel', 'misticease-network' ], true ) ) {
		return;
	}

	[ $css_url, $css_ver ] = misticease_asset( 'inc/app/css/misticease-admin.css' );
	wp_enqueue_style( 'misticease-admin', $css_url, [], $css_ver );
}
add_action( 'admin_enqueue_scripts', 'misticease_enqueue_admin_panel_styles' );


/* -------------------------------------------------------------------------
 * Site control panel
 * ---------------------------------------------------------------------- */

function misticease_add_control_panel_pages(): void {
	$icon_path = plugin_dir_path( misticease_basefile() ) . 'inc/app/img/icon.png';
	$icon      = file_exists( $icon_path ) ? plugins_url( 'inc/app/img/icon.png', misticease_basefile() ) : 'dashicons-format-video';

	add_menu_page(
		__( 'MisticEase control panel', 'misticease' ),
		__( 'MisticEase', 'misticease' ),
		'manage_options',
		'misticease-control-panel',
		'misticease_control_panel_page',
		$icon,
		99
	);
}
add_action( 'admin_menu', 'misticease_add_control_panel_pages' );


function misticease_control_panel_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'misticease' ) );
	}

	$tab_raw     = filter_input( INPUT_GET, 'tab', FILTER_DEFAULT );
	$current_tab = is_string( $tab_raw ) ? sanitize_key( $tab_raw ) : 'settings';
	$allowed     = [ 'settings', 'readme', 'upgrade' ];
	if ( ! in_array( $current_tab, $allowed, true ) ) {
		$current_tab = 'settings';
	}

	$base   = admin_url( 'admin.php?page=misticease-control-panel' );
	$tab_url = static function ( string $tab ) use ( $base ): string {
		return add_query_arg( [ 'tab' => $tab ], $base );
	};

	?>
	<div class="wrap" style="max-width:800px;margin:0 auto;">
		<h1 style="text-align:center;margin-bottom:1.5em;"><?php esc_html_e( 'MisticEase control panel', 'misticease' ); ?></h1>

		<h2 class="nav-tab-wrapper">
			<a href="<?php echo esc_url( $tab_url( 'settings' ) ); ?>" class="nav-tab <?php echo ( 'settings' === $current_tab ? 'nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Settings', 'misticease' ); ?></a>
			<a href="<?php echo esc_url( $tab_url( 'readme' ) ); ?>"   class="nav-tab <?php echo ( 'readme' === $current_tab   ? 'nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Readme', 'misticease' ); ?></a>
			<a href="<?php echo esc_url( $tab_url( 'upgrade' ) ); ?>"
			   class="nav-tab upgrade-tab <?php echo ( 'upgrade' === $current_tab ? 'nav-tab-active' : '' ); ?>">
 			  <?php esc_html_e( 'Upgrade', 'misticease' ); ?>
			</a>
		</h2>

		<div class="misticease-tab-content" style="padding:15px;border:1px solid #ddd;">
		<?php
			switch ( $current_tab ) {
				case 'readme':
					misticease_render_site_readme_tab();
					break;
				case 'upgrade':
					require_once __DIR__ . '/ug/misticease-ug-tab.php';
					if ( function_exists( 'misticease_render_upgrade_tab' ) ) {
						misticease_render_upgrade_tab();
					} else {
						echo '<p>' . esc_html__( 'Upgrade view is unavailable.', 'misticease' ) . '</p>';
					}
					break;
				case 'settings':
				default:
					misticease_settings_content();
					break;
			}
		?>
		</div>
	</div>
  <?php
}