<?php
/**
 * Settings page template
 *
 * Variables provided by Agency_Pulse_Admin_Menu::render_settings_page():
 *
 *   $license_state  array  Output of Agency_Pulse_Admin_Menu_License_Manager::get_state().
 *
 * @package Agency_Pulse_Admin_Menu
 * @since   1.0.0
 */

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

// ── Import result notice (set by handle_import / ajax_backup_pull) ───────────

$import_result = get_transient( 'aamo_import_result_' . get_current_user_id() );
if ( $import_result ) {
	delete_transient( 'aamo_import_result_' . get_current_user_id() );
}

// ── License state display values ──────────────────────────────────────────────

$ao_status      = $license_state['status'];
$ao_active      = Agency_Pulse_Admin_Menu_License_Manager::is_active();
$last_api_error = $license_state['last_api_error'] ?? '';

// ── Dashboard Message data ────────────────────────────────────────────────────

$dm_defaults = array( 'enabled' => false, 'title' => '', 'content' => '' );
$dm          = wp_parse_args(
	get_option( Agency_Pulse_Admin_Menu_Constants::OPTION_DASHBOARD_MESSAGE, array() ),
	$dm_defaults
);

?>
<div class="wrap aamo-wrap">

	<h1 class="aamo-page-title">
		<?php esc_html_e( 'Menu Organizer — Settings', 'agency-pulse-admin-menu' ); ?>
	</h1>

	<?php if ( $import_result ) : ?>
	<div class="notice notice-<?php echo 'success' === $import_result['type'] ? 'success' : 'error'; ?> is-dismissible">
		<p><?php echo esc_html( $import_result['message'] ); ?></p>
	</div>
	<?php endif; ?>

	<?php // ── Dashboard Message panel ──────────────────────────────────────── ?>
	<div class="aamo-settings-panel" id="aamo-dashboard-msg-wrap">

		<h2 class="aamo-settings-panel-title">
			<?php esc_html_e( 'Dashboard Message', 'agency-pulse-admin-menu' ); ?>
		</h2>

		<p class="aamo-settings-description">
			<?php esc_html_e( 'Show a message to all users on the WordPress Dashboard.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<?php if ( ! $ao_active ) : ?>
		<div class="notice notice-warning inline" style="margin:0 0 12px">
			<p><?php printf(
				/* translators: %s: link to license settings */
				esc_html__( 'Dashboard Message requires an active License & Connection. %s', 'agency-pulse-admin-menu' ),
				'<a href="' . esc_url( admin_url( 'admin.php?page=aamo_settings#aamo-license-wrap' ) ) . '">' . esc_html__( 'Activate your license &rarr;', 'agency-pulse-admin-menu' ) . '</a>'
			); ?></p>
		</div>
		<?php endif; ?>

		<div class="aamo-dm-controls<?php echo $ao_active ? '' : ' aamo-panel-locked'; ?>">
		<div class="aamo-dm-toggle-row">
			<label class="aamo-toggle-label">
				<input type="checkbox" id="aamo-dm-enabled" value="1"
					<?php checked( $dm['enabled'] ); ?>>
				<?php esc_html_e( 'Enable Dashboard Widget', 'agency-pulse-admin-menu' ); ?>
			</label>
			<label class="aamo-toggle-label">
				<input type="checkbox" id="aamo-dm-show-first" value="1"
					<?php checked( ! empty( $dm['show_first'] ) ); ?>>
				<?php esc_html_e( 'Always show first (top-left)', 'agency-pulse-admin-menu' ); ?>
			</label>
		</div>

		<div class="aamo-dm-fields">
			<div class="aamo-dm-field-row">
				<label for="aamo-dm-title" class="aamo-dm-label">
					<?php esc_html_e( 'Widget Title:', 'agency-pulse-admin-menu' ); ?>
				</label>
				<input type="text" id="aamo-dm-title" class="regular-text"
					value="<?php echo esc_attr( $dm['title'] ); ?>"
					placeholder="<?php esc_attr_e( 'Admin Notice', 'agency-pulse-admin-menu' ); ?>">
				<span class="aamo-settings-meta">
					<?php esc_html_e( 'Displayed as the widget heading. Leave blank to use "Admin Notice".', 'agency-pulse-admin-menu' ); ?>
				</span>
			</div>

			<div class="aamo-dm-editor-row">
				<label class="aamo-dm-label">
					<?php esc_html_e( 'Message:', 'agency-pulse-admin-menu' ); ?>
				</label>
				<?php
				wp_editor(
					$dm['content'],
					'aamo_message_content',
					array(
						'media_buttons' => false,
						'textarea_rows' => 8,
						'teeny'         => true,
						'quicktags'     => true,
						'textarea_name' => 'aamo_message_content',
					)
				);
				?>
			</div>
		</div><!-- /.aamo-dm-fields -->

		<div class="aamo-settings-action-row aamo-dm-save-row">
			<button type="button" id="aamo-dm-save" class="button button-primary">
				<?php esc_html_e( 'Save Dashboard Message', 'agency-pulse-admin-menu' ); ?>
			</button>
			<span id="aamo-dm-status" class="aamo-status" aria-live="polite"></span>
		</div>

		</div><!-- /.aamo-dm-controls -->

	</div><!-- /#aamo-dashboard-msg-wrap -->

	<?php // ── Cloud Backup panel ────────────────────────────────────────────── ?>
	<div class="aamo-settings-panel" id="aamo-backup-wrap">

		<h2 class="aamo-settings-panel-title">
			<?php esc_html_e( 'Cloud Backup', 'agency-pulse-admin-menu' ); ?>
		</h2>

		<p class="aamo-settings-description">
			<?php esc_html_e( 'Save your entire menu configuration to the Agency Pulse cloud or restore it with one click. Requires an active License & Connection.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<?php if ( ! $ao_active ) : ?>
		<div class="notice notice-warning inline" style="margin:0 0 12px">
			<p><?php printf(
				/* translators: %s: link to license settings */
				esc_html__( 'Cloud backup requires an active License & Connection. %s', 'agency-pulse-admin-menu' ),
				'<a href="' . esc_url( admin_url( 'admin.php?page=aamo_settings#aamo-license-wrap' ) ) . '">' . esc_html__( 'Activate your license &rarr;', 'agency-pulse-admin-menu' ) . '</a>'
			); ?></p>
		</div>
		<?php endif; ?>

		<div class="aamo-settings-actions<?php echo ( $ao_active && empty( $last_api_error ) ) ? '' : ' aamo-panel-locked'; ?>">

			<div class="aamo-settings-action-row">
				<button type="button" id="aamo-backup-push" class="button"
					<?php echo $ao_active ? '' : 'disabled'; ?>>
					<?php esc_html_e( 'Push to Cloud', 'agency-pulse-admin-menu' ); ?>
				</button>
				<span id="aamo-backup-push-status" class="aamo-status" aria-live="polite"></span>
			</div>

			<div class="aamo-settings-action-row">
				<button type="button" id="aamo-backup-pull" class="button"
					<?php echo $ao_active ? '' : 'disabled'; ?>>
					<?php esc_html_e( 'Pull from Cloud', 'agency-pulse-admin-menu' ); ?>
				</button>
				<span id="aamo-backup-pull-status" class="aamo-status" aria-live="polite"></span>
			</div>

		</div>

	</div><!-- /.aamo-settings-panel -->

	<?php // ── Template Library panel ───────────────────────────────────────── ?>
	<div class="aamo-settings-panel" id="aamo-template-wrap">

		<h2 class="aamo-settings-panel-title">
			<?php esc_html_e( 'Template Library', 'agency-pulse-admin-menu' ); ?>
		</h2>

		<p class="aamo-settings-description">
			<?php esc_html_e( 'Save your current configuration as a named template on the Agency Pulse cloud. Apply any stored template to this site instantly, or share templates across all your connected sites.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<?php if ( ! $ao_active ) : ?>
		<div class="notice notice-warning inline" style="margin:0 0 12px">
			<p><?php printf(
				/* translators: %s: link to license settings */
				esc_html__( 'Template Library requires an active License & Connection. %s', 'agency-pulse-admin-menu' ),
				'<a href="' . esc_url( admin_url( 'admin.php?page=aamo_settings#aamo-license-wrap' ) ) . '">' . esc_html__( 'Activate your license &rarr;', 'agency-pulse-admin-menu' ) . '</a>'
			); ?></p>
		</div>
		<?php endif; ?>

		<div<?php echo $ao_active ? '' : ' class="aamo-panel-locked"'; ?>>
		<?php // ── Save section ─────────────────────────────────────────────── ?>
		<div class="aamo-tl-save-section">

			<div class="aamo-settings-action-row">
				<label for="aamo-tl-name" class="aamo-label">
					<?php esc_html_e( 'Template Name:', 'agency-pulse-admin-menu' ); ?>
				</label>
				<input type="text" id="aamo-tl-name" class="regular-text"
					maxlength="191"
					placeholder="<?php esc_attr_e( 'e.g. Agency Default', 'agency-pulse-admin-menu' ); ?>">
			</div>
			<p class="aamo-tl-name-error aamo-settings-note" style="display:none;color:#d63638;margin-top:2px;"></p>

			<div class="aamo-settings-action-row">
				<label for="aamo-tl-desc" class="aamo-label">
					<?php esc_html_e( 'Description:', 'agency-pulse-admin-menu' ); ?>
				</label>
				<input type="text" id="aamo-tl-desc" class="regular-text"
					maxlength="500"
					placeholder="<?php esc_attr_e( 'Optional', 'agency-pulse-admin-menu' ); ?>">
			</div>

			<div class="aamo-settings-action-row">
				<button type="button" id="aamo-tl-save" class="button button-primary">
					<?php esc_html_e( 'Save as Template', 'agency-pulse-admin-menu' ); ?>
				</button>
				<span id="aamo-tl-save-status" class="aamo-status" aria-live="polite"></span>
			</div>

		</div><!-- /.aamo-tl-save-section -->

		<hr class="aamo-access-divider">

		<?php // ── List section ──────────────────────────────────────────────── ?>
		<div class="aamo-tl-list-section">

			<div class="aamo-settings-action-row">
				<button type="button" id="aamo-tl-refresh" class="button">
					<?php esc_html_e( 'Refresh List', 'agency-pulse-admin-menu' ); ?>
				</button>
			</div>

			<div id="aamo-tl-list" class="aamo-tl-list" aria-live="polite">
				<p class="aamo-settings-note aamo-tl-loading">
					<?php esc_html_e( 'Loading templatesâ¦', 'agency-pulse-admin-menu' ); ?>
				</p>
			</div>

		</div><!-- /.aamo-tl-list-section -->

		</div><!-- /.aamo-tl-controls -->

	</div><!-- /#aamo-template-wrap -->

	<?php // ── Reset to Defaults panel ─────────────────────────────────────────── ?>
	<div class="aamo-settings-panel" id="aamo-reset-customization-wrap">

		<h2 class="aamo-settings-panel-title">
			<?php esc_html_e( 'Reset to Defaults', 'agency-pulse-admin-menu' ); ?>
		</h2>

		<p class="aamo-settings-description">
			<?php esc_html_e( 'Reset all admin customization settings to their plugin defaults. This clears the admin bar, footer, and color palette customizations. It does not affect menu configurations unless the checkbox below is checked.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<label class="aamo-reset-menu-label">
			<input type="checkbox" id="aamo-reset-menu-checkbox" value="1">
			<?php esc_html_e( 'Also clear saved menu item arrangements', 'agency-pulse-admin-menu' ); ?>
		</label>
		<p class="aamo-settings-note">
			<?php esc_html_e( 'Config names and role assignments are kept; only the saved menu item order is wiped.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<label class="aamo-reset-menu-label">
			<input type="checkbox" id="aamo-reset-labels-checkbox" value="1">
			<?php esc_html_e( 'Also reset custom menu labels and icons', 'agency-pulse-admin-menu' ); ?>
		</label>
		<p class="aamo-settings-note">
			<?php esc_html_e( 'Menu item titles and icons are restored to their original WordPress values across all configurations.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<label class="aamo-reset-menu-label">
			<input type="checkbox" id="aamo-nuke-menus-checkbox" value="1">
			<?php esc_html_e( 'Wipe all custom menus and role assignments entirely', 'agency-pulse-admin-menu' ); ?>
		</label>
		<p class="aamo-settings-note">
			<?php esc_html_e( 'All configurations and role assignments are deleted. Every user will see the default WordPress admin menu. This supersedes the options above.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<p>
			<button type="button" id="aamo-reset-customization" class="button button-secondary">
				<?php esc_html_e( 'Reset to Defaults', 'agency-pulse-admin-menu' ); ?>
			</button>
			<span id="aamo-reset-customization-status" class="aamo-status" aria-live="polite"></span>
		</p>

		<p class="aamo-settings-note aamo-reset-warning">
			<?php esc_html_e( '⚠ This cannot be undone.', 'agency-pulse-admin-menu' ); ?>
		</p>

	</div><!-- /#aamo-reset-customization-wrap -->


	<?php
	// ── Plugin Access Control panel ──────────────────────────────────────────
	$access_mode      = Agency_Pulse_Admin_Menu_Access_Control::get_mode();
	$can_cap_only     = Agency_Pulse_Admin_Menu_Access_Control::can_enable_cap_only();
	$explicit_holders = Agency_Pulse_Admin_Menu_Access_Control::get_explicit_holders();
	$current_user_id  = get_current_user_id();
	$user_counts      = count_users();
	$total_users      = (int) $user_counts['total_users'];
	$all_users        = $total_users <= 200
		? get_users( array( 'orderby' => 'display_name', 'order' => 'ASC' ) )
		: array();
	?>
	<div class="aamo-settings-panel" id="aamo-access-control-wrap">

		<h2 class="aamo-settings-panel-title">
			<?php esc_html_e( 'Plugin Access Control', 'agency-pulse-admin-menu' ); ?>
		</h2>

		<p class="aamo-settings-description">
			<?php esc_html_e( 'Controls who can see and use the Menu Organizer on this site.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<?php if ( ! $ao_active ) : ?>
		<div class="notice notice-warning inline" style="margin:0 0 12px">
			<p><?php printf(
				/* translators: %s: link to license settings */
				esc_html__( 'Plugin Access Control requires an active License & Connection. %s', 'agency-pulse-admin-menu' ),
				'<a href="' . esc_url( admin_url( 'admin.php?page=aamo_settings#aamo-license-wrap' ) ) . '">' . esc_html__( 'Activate your license &rarr;', 'agency-pulse-admin-menu' ) . '</a>'
			); ?></p>
		</div>
		<?php endif; ?>

		<div class="aamo-ac-controls<?php echo $ao_active ? '' : ' aamo-panel-locked'; ?>">
		<div class="aamo-access-modes">

			<label class="aamo-access-mode-option">
				<input type="radio" name="aamo_access_mode" value="default"
					<?php checked( $access_mode, 'default' ); ?>>
				<span class="aamo-access-mode-label">
					<?php esc_html_e( 'Default', 'agency-pulse-admin-menu' ); ?>
				</span>
				<span class="aamo-access-mode-desc">
					<?php esc_html_e( 'Anyone with the ap_menu_manager capability. Administrators have this by default.', 'agency-pulse-admin-menu' ); ?>
				</span>
			</label>

			<label class="aamo-access-mode-option">
				<input type="radio" name="aamo_access_mode" value="admin_only"
					<?php checked( $access_mode, 'admin_only' ); ?>>
				<span class="aamo-access-mode-label">
					<?php esc_html_e( 'Admin Only', 'agency-pulse-admin-menu' ); ?>
				</span>
				<span class="aamo-access-mode-desc">
					<?php esc_html_e( 'Only users in the Administrator role can see the plugin. Other users with explicit grants cannot access it.', 'agency-pulse-admin-menu' ); ?>
				</span>
			</label>

			<label class="aamo-access-mode-option<?php echo $can_cap_only ? '' : ' aamo-access-mode-disabled'; ?>"
				<?php if ( ! $can_cap_only ) : ?>
				title="<?php esc_attr_e( 'Grant the permission to at least one user before enabling this mode.', 'agency-pulse-admin-menu' ); ?>"
				<?php endif; ?>>
				<input type="radio" name="aamo_access_mode" value="cap_only"
					id="aamo-cap-only-radio"
					<?php checked( $access_mode, 'cap_only' ); ?>
					<?php disabled( ! $can_cap_only ); ?>>
				<span class="aamo-access-mode-label">
					<?php esc_html_e( 'Capability Only', 'agency-pulse-admin-menu' ); ?>
				</span>
				<span class="aamo-access-mode-desc">
					<?php esc_html_e( 'Only users with an explicit individual permission grant. Warning: this removes the capability from the Administrator role. Grant access to at least one user below first.', 'agency-pulse-admin-menu' ); ?>
				</span>
			</label>

		</div><!-- /.aamo-access-modes -->

		<div class="aamo-settings-action-row aamo-access-mode-apply-row">
			<button type="button" id="aamo-apply-mode" class="button button-primary">
				<?php esc_html_e( 'Apply Mode', 'agency-pulse-admin-menu' ); ?>
			</button>
			<span id="aamo-apply-mode-status" class="aamo-status" aria-live="polite"></span>
		</div>

		<hr class="aamo-access-divider">

		<h3 class="aamo-settings-subheading">
			<?php esc_html_e( 'Grant Plugin Access Permission', 'agency-pulse-admin-menu' ); ?>
		</h3>

		<div class="aamo-settings-action-row">
			<?php if ( $total_users <= 200 ) : ?>
			<select id="aamo-grant-user-select" class="aamo-user-select">
				<?php foreach ( $all_users as $u ) : ?>
				<option value="<?php echo esc_attr( $u->ID ); ?>"
					<?php selected( $u->ID, $current_user_id ); ?>>
					<?php
					$label = $u->display_name . ' (' . $u->user_email . ')';
					if ( (int) $u->ID === $current_user_id ) {
						/* translators: appended to user name to indicate the current admin */
						$label .= ' — ' . __( 'you', 'agency-pulse-admin-menu' );
					}
					echo esc_html( $label );
					?>
				</option>
				<?php endforeach; ?>
			</select>
			<?php else : ?>
			<input type="number" id="aamo-grant-user-select" class="small-text"
				placeholder="<?php esc_attr_e( 'User ID', 'agency-pulse-admin-menu' ); ?>"
				value="<?php echo esc_attr( $current_user_id ); ?>"
				min="1">
			<?php endif; ?>
			<button type="button" id="aamo-grant-cap" class="button">
				<?php esc_html_e( 'Grant Permission', 'agency-pulse-admin-menu' ); ?>
			</button>
			<button type="button" id="aamo-revoke-cap" class="button">
				<?php esc_html_e( 'Revoke Permission', 'agency-pulse-admin-menu' ); ?>
			</button>
			<span id="aamo-grant-status" class="aamo-status" aria-live="polite"></span>
		</div>

		<div id="aamo-holders-list">
			<h4 class="aamo-settings-subheading-sm">
				<?php esc_html_e( 'Users with explicit access:', 'agency-pulse-admin-menu' ); ?>
			</h4>
			<?php if ( empty( $explicit_holders ) ) : ?>
			<p class="aamo-settings-note" id="aamo-no-holders">
				<?php esc_html_e( 'No users have been explicitly granted access yet.', 'agency-pulse-admin-menu' ); ?>
			</p>
			<?php else : ?>
			<table class="aamo-holders-table">
				<tbody id="aamo-holders-tbody">
				<?php foreach ( $explicit_holders as $holder ) : ?>
				<tr data-user-id="<?php echo esc_attr( $holder->ID ); ?>">
					<td><?php echo esc_html( $holder->display_name . ' (' . $holder->user_email . ')' ); ?></td>
					<td>
						<button type="button" class="button button-small aamo-revoke-holder"
							data-user-id="<?php echo esc_attr( $holder->ID ); ?>">
							<?php esc_html_e( 'Revoke', 'agency-pulse-admin-menu' ); ?>
						</button>
					</td>
				</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
			<?php endif; ?>
		</div><!-- /#aamo-holders-list -->

		</div><!-- /.aamo-ac-controls -->

	</div><!-- /#aamo-access-control-wrap -->

	<?php // ── Export panel ──────────────────────────────────────────────────── ?>
	<div class="aamo-settings-panel">

		<h2 class="aamo-settings-panel-title">
			<?php esc_html_e( 'Export Configuration', 'agency-pulse-admin-menu' ); ?>
		</h2>

		<p class="aamo-settings-description">
			<?php esc_html_e( 'Download all configurations and role assignments as a JSON file. Use this file to back up your setup or migrate it to another site.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="<?php echo esc_attr( Agency_Pulse_Admin_Menu_Constants::EXPORT_ACTION ); ?>">
			<?php wp_nonce_field( 'aamo_export_nonce' ); ?>
			<button type="submit" class="button">
				<?php esc_html_e( 'Download Export File', 'agency-pulse-admin-menu' ); ?>
			</button>
		</form>

	</div><!-- /.aamo-settings-panel -->

	<?php // ── Import panel ──────────────────────────────────────────────────── ?>
	<div class="aamo-settings-panel">

		<h2 class="aamo-settings-panel-title">
			<?php esc_html_e( 'Import Configuration', 'agency-pulse-admin-menu' ); ?>
		</h2>

		<p class="aamo-settings-description">
			<?php esc_html_e( 'Upload a previously exported JSON file to restore configurations and role assignments.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<div class="aamo-settings-warning">
			<?php esc_html_e( 'Warning: importing will replace all current configurations and role assignments.', 'agency-pulse-admin-menu' ); ?>
		</div>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
			enctype="multipart/form-data">
			<input type="hidden" name="action" value="<?php echo esc_attr( Agency_Pulse_Admin_Menu_Constants::IMPORT_ACTION ); ?>">
			<?php wp_nonce_field( 'aamo_import_nonce' ); ?>
			<div class="aamo-settings-file-row">
				<input type="file" id="aamo-import-file" name="aamo_import_file"
					accept=".json" required class="aamo-file-input">
				<label for="aamo-import-file" class="button">
					<?php esc_html_e( 'Choose File', 'agency-pulse-admin-menu' ); ?>
				</label>
				<span id="aamo-import-file-name" class="aamo-settings-meta aamo-file-name">
					<?php esc_html_e( 'No file chosen', 'agency-pulse-admin-menu' ); ?>
				</span>
				<button type="submit" class="button">
					<?php esc_html_e( 'Import', 'agency-pulse-admin-menu' ); ?>
				</button>
			</div>
		</form>

	</div><!-- /.aamo-settings-panel -->

	<?php // ── License & Connection panel ─────────────────────────────────── ?>
	<div class="aamo-settings-panel" id="aamo-license-wrap">

		<h2 class="aamo-settings-panel-title">
			<?php esc_html_e( 'License & Connection', 'agency-pulse-admin-menu' ); ?>
		</h2>

		<p class="aamo-settings-description">
			<?php esc_html_e( 'Connect this site with your apwp-ao license key to enable cloud backup and other premium features.', 'agency-pulse-admin-menu' ); ?>
		</p>

		<?php // State: inactive (default / no key stored) ?>
		<div class="aamo-license-state" data-status="inactive"
			<?php echo in_array( $ao_status, array( 'inactive', '', 'revoked' ), true ) ? '' : 'style="display:none"'; ?>>

			<?php if ( ! empty( $license_state['last_error'] ) ) : ?>
			<p class="aamo-settings-note aamo-auto-disconnect-note">
				<?php
				printf(
					/* translators: %s: server error message */
					esc_html__( 'This site was automatically disconnected after a persistent connection failure: %s Re-enter your key or click Connect to retry.', 'agency-pulse-admin-menu' ),
					'<strong>' . esc_html( $license_state['last_error'] ) . '</strong> —'
				);
				?>
			</p>
			<?php endif; ?>

			<div class="aamo-settings-action-row">
				<label for="aamo-plugin-key" class="aamo-label">
					<?php esc_html_e( 'Plugin Key:', 'agency-pulse-admin-menu' ); ?>
				</label>
				<input type="text" id="aamo-plugin-key" class="regular-text"
					value="<?php echo esc_attr( $license_state['plugin_key'] ); ?>"
					placeholder="<?php esc_attr_e( 'Enter your apwp-ao license key', 'agency-pulse-admin-menu' ); ?>">
				<button type="button" id="aamo-ao-connect-btn" class="button button-primary">
					<?php esc_html_e( 'Connect This Site', 'agency-pulse-admin-menu' ); ?>
				</button>
				<span id="aamo-connect-status" class="aamo-status" aria-live="polite"></span>
			</div>

		</div>

		<?php // State: pending_email ?>
		<div class="aamo-license-state" data-status="pending_email"
			<?php echo 'pending_email' === $ao_status ? '' : 'style="display:none"'; ?>>

			<p><?php esc_html_e( 'Authorization email sent. Check your inbox and click the confirmation link, then:', 'agency-pulse-admin-menu' ); ?></p>
			<div class="aamo-settings-action-row">
				<button type="button" id="aamo-ao-check-btn" class="button">
					<?php esc_html_e( "I've Confirmed — Check Connection", 'agency-pulse-admin-menu' ); ?>
				</button>
				<span id="aamo-check-status" class="aamo-status" aria-live="polite"></span>
			</div>

		</div>

		<?php // State: active ?>
		<div class="aamo-license-state" data-status="active"
			<?php echo 'active' === $ao_status ? '' : 'style="display:none"'; ?>>

			<p>
				<span class="aamo-badge aamo-badge-green">
					<?php esc_html_e( 'Connected', 'agency-pulse-admin-menu' ); ?>
				</span>
				<?php if ( ! empty( $license_state['slot_id'] ) ) : ?>
				<span class="aamo-slot-id aamo-settings-meta">
					<?php
					printf(
						/* translators: %d: slot number */
						esc_html__( 'Slot #%d', 'agency-pulse-admin-menu' ),
						(int) $license_state['slot_id']
					);
					?>
				</span>
				<?php endif; ?>
				<?php if ( $license_state['expires_at'] > 0 ) : ?>
				<span class="aamo-settings-meta">
					<?php
					printf(
						/* translators: %s: token expiry date and time */
						esc_html__( 'Token expires: %s', 'agency-pulse-admin-menu' ),
						esc_html( wp_date(
							get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
							$license_state['expires_at']
						) )
					);
					?>
				</span>
				<?php endif; ?>
			</p>

			<?php if ( ! empty( $last_api_error ) ) : ?>
			<?php
			$_elapsed_min   = max( 0, (int) floor( ( time() - (int) ( $license_state['api_error_since'] ?? 0 ) ) / 60 ) );
			$_timeout_min   = Agency_Pulse_Admin_Menu_Constants::API_ERROR_DISCONNECT_MINUTES;
			$_remaining_min = max( 0, $_timeout_min - $_elapsed_min );
			?>
			<div class="aamo-api-error-warning">
				<strong><?php esc_html_e( 'Connection Warning', 'agency-pulse-admin-menu' ); ?></strong>
				<?php
				printf(
					/* translators: %s: server error message */
					esc_html__( 'The last server request failed: %s. ', 'agency-pulse-admin-menu' ),
					esc_html( $last_api_error )
				);
				?>
				<span class="aamo-api-error-timer">
				<?php
				printf(
					/* translators: 1: minutes elapsed, 2: total timeout minutes, 3: minutes remaining */
					esc_html__( 'Failing for %1$d of %2$d minutes — auto-disconnect in %3$d minutes.', 'agency-pulse-admin-menu' ),
					$_elapsed_min,
					$_timeout_min,
					$_remaining_min
				);
				?>
				</span>
				<p><?php esc_html_e( 'This may be a temporary connection issue. Wait a few minutes to see if it is resolved before taking any further action. ', 'agency-pulse-admin-menu' ); ?>
				<?php esc_html_e( 'Retry the failed action to clear this warning, or disconnect and reconnect if the problem persists.', 'agency-pulse-admin-menu' ); ?></p>
			</div>
			<?php endif; ?>

			<div class="aamo-settings-action-row">
				<button type="button" id="aamo-ao-disconnect-btn" class="button">
					<?php esc_html_e( 'Disconnect This Site', 'agency-pulse-admin-menu' ); ?>
				</button>
			</div>

		</div>

		<?php // State: slot_full ?>
		<div class="aamo-license-state" data-status="slot_full"
			<?php echo 'slot_full' === $ao_status ? '' : 'style="display:none"'; ?>>

			<p class="aamo-settings-note">
				<?php esc_html_e( 'All domain slots for this license are in use.', 'agency-pulse-admin-menu' ); ?>
				<a href="https://agencypulsewp.com/account/plugin-domains" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Release a slot at agencypulsewp.com/account/plugin-domains &rarr;', 'agency-pulse-admin-menu' ); ?>
				</a>
			</p>
			<div class="aamo-settings-action-row">
				<button type="button" id="aamo-ao-retry-btn" class="button">
					<?php esc_html_e( 'Retry After Releasing a Slot', 'agency-pulse-admin-menu' ); ?>
				</button>
			</div>

		</div>

	</div><!-- /#aamo-license-wrap -->

</div><!-- /.wrap -->

<?php
/*
 * admin_print_footer_scripts does not reliably fire on this page, so the
 * TinyMCE/quicktags initialisation scripts are forced here directly.
 */
do_action( 'admin_print_footer_scripts' );
?>
