<?php
namespace UM_Elementor\Helpers;

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

/**
 * Ultimate Member core pages — discovery, Elementor status, and admin dashboard data.
 */
class UM_Core_Pages {

	/** @var array<string, array<string, mixed>>|null */
	private static ?array $page_map = null;

	/**
	 * @return array<string, array<string, mixed>>
	 */
	public static function get_page_map(): array {
		if ( null !== self::$page_map ) {
			return self::$page_map;
		}

		self::$page_map = [
			'login' => [
				'label'              => __( 'Login', 'ultimate-member-widgets-for-elementor' ),
				'recommended_widget' => __( 'UM Login & Register Form', 'ultimate-member-widgets-for-elementor' ),
				'widget_types'       => [ 'um-login-register-styler' ],
				'form_mode'          => 'login',
				'show_form_link'     => true,
			],
			'register' => [
				'label'              => __( 'Register', 'ultimate-member-widgets-for-elementor' ),
				'recommended_widget' => __( 'UM Login & Register Form', 'ultimate-member-widgets-for-elementor' ),
				'widget_types'       => [ 'um-login-register-styler' ],
				'form_mode'          => 'register',
				'show_form_link'     => true,
			],
			'user' => [
				'label'              => __( 'User Profile', 'ultimate-member-widgets-for-elementor' ),
				'recommended_widget' => __( 'Profile Page Builder', 'ultimate-member-widgets-for-elementor' ),
				'widget_types'       => [ 'umwfe-pro-profile-builder', 'um-user-avatar', 'um-profile-fields' ],
				'form_mode'          => 'profile',
				'show_form_link'     => true,
				'panel_hint'         => true,
				'requires_pro'       => true,
			],
			'account' => [
				'label'              => __( 'Account', 'ultimate-member-widgets-for-elementor' ),
				'recommended_widget' => __( 'Account Page Styler', 'ultimate-member-widgets-for-elementor' ),
				'widget_types'       => [ 'umwfe-pro-account-styler' ],
				'form_mode'          => null,
				'show_form_link'     => false,
				'panel_hint'         => true,
				'requires_pro'       => true,
			],
			'password-reset' => [
				'label'              => __( 'Password Reset', 'ultimate-member-widgets-for-elementor' ),
				'recommended_widget' => __( 'Password Reset', 'ultimate-member-widgets-for-elementor' ),
				'widget_types'       => [ 'um-password-reset-styler' ],
				'form_mode'          => null,
				'show_form_link'     => false,
			],
			'members' => [
				'label'              => __( 'Members Directory', 'ultimate-member-widgets-for-elementor' ),
				'recommended_widget' => __( 'Member Directory Styler', 'ultimate-member-widgets-for-elementor' ),
				'widget_types'       => [ 'ele-um-user-list', 'umwfe-pro-advanced-filters' ],
				'form_mode'          => 'directory',
				'show_form_link'     => true,
				'requires_pro'       => true,
			],
		];

		return apply_filters( 'umwfe_core_pages_map', self::$page_map );
	}

	public static function is_um_available(): bool {
		return function_exists( 'UM' ) && function_exists( 'um_get_predefined_page_id' );
	}

	/**
	 * Admin URL for Ultimate Member → Settings → Pages (General tab, Pages section).
	 */
	public static function get_um_pages_settings_url(): string {
		return admin_url( 'admin.php?page=um_options' );
	}

	public static function get_setup_settings_url( string $fragment = '' ): string {
		$page = class_exists( 'UMEP_Admin_Settings' ) ? 'umep-elementor-settings' : 'um-elementor-settings';
		$url  = admin_url( 'admin.php?page=' . $page );
		if ( '' !== $fragment ) {
			$url .= '#' . ltrim( $fragment, '#' );
		}
		return $url;
	}

	public static function get_elementor_action_label( bool $is_elementor ): string {
		return $is_elementor
			? __( 'Edit with Elementor', 'ultimate-member-widgets-for-elementor' )
			: __( 'Build with Elementor', 'ultimate-member-widgets-for-elementor' );
	}

	public static function page_requires_pro( string $slug ): bool {
		$config = self::get_page_map()[ $slug ] ?? [];
		return ! empty( $config['requires_pro'] );
	}

	/**
	 * @param array<string, mixed> $row
	 */
	public static function is_pro_locked_row( array $row ): bool {
		if ( defined( 'UMEP_VERSION' ) ) {
			return false;
		}
		return ! empty( $row['requires_pro'] );
	}

	public static function get_pro_upgrade_url( string $source ): string {
		if ( class_exists( '\UM_Elementor\UM_Elementor_Pro_Links' ) ) {
			return \UM_Elementor\UM_Elementor_Pro_Links::upgrade_url( $source );
		}
		return '#';
	}

	public static function get_pro_upgrade_label(): string {
		if ( class_exists( '\UM_Elementor\UM_Elementor_Pro_Links' ) ) {
			return \UM_Elementor\UM_Elementor_Pro_Links::price_label();
		}
		return __( 'Get Pro', 'ultimate-member-widgets-for-elementor' );
	}

	/**
	 * @param array<string, mixed> $row
	 */
	public static function get_elementor_action_label_for_row( array $row ): string {
		$status = (string) ( $row['content_status'] ?? '' );
		if ( 'shortcode_only' === $status ) {
			return __( 'Swap in Elementor', 'ultimate-member-widgets-for-elementor' );
		}
		if ( 'elementor_no_um' === $status ) {
			return __( 'Add UM widget', 'ultimate-member-widgets-for-elementor' );
		}
		return self::get_elementor_action_label( ! empty( $row['is_elementor'] ) );
	}

	/**
	 * @return array{um: bool, elementor: bool, assigned: int, total: int}
	 */
	public static function get_prerequisites_status(): array {
		$rows     = self::is_um_available() ? self::get_dashboard_rows() : [];
		$assigned = 0;
		foreach ( $rows as $row ) {
			if ( (int) ( $row['page_id'] ?? 0 ) > 0 ) {
				++$assigned;
			}
		}

		return [
			'um'        => self::is_um_available(),
			'elementor' => did_action( 'elementor/loaded' ),
			'assigned'  => $assigned,
			'total'     => count( $rows ),
		];
	}

	public static function render_prerequisites_checklist(): void {
		$status = self::get_prerequisites_status();
		?>
		<ul class="umwfe-setup-checklist">
			<li><?php echo $status['um'] ? '✓' : '○'; ?> <?php esc_html_e( 'Ultimate Member is active', 'ultimate-member-widgets-for-elementor' ); ?></li>
			<li><?php echo $status['elementor'] ? '✓' : '○'; ?> <?php esc_html_e( 'Elementor is active', 'ultimate-member-widgets-for-elementor' ); ?></li>
			<li>
				<?php
				if ( $status['total'] > 0 && $status['assigned'] >= $status['total'] ) {
					echo '✓ ';
				} else {
					echo '○ ';
				}
				if ( $status['total'] > 0 ) {
					printf(
						/* translators: 1: assigned pages, 2: total core pages */
						esc_html__( 'Core member pages assigned (%1$d/%2$d)', 'ultimate-member-widgets-for-elementor' ),
						(int) $status['assigned'],
						(int) $status['total']
					);
				} else {
					esc_html_e( 'Core member pages assigned', 'ultimate-member-widgets-for-elementor' );
				}
				?>
			</li>
		</ul>
		<?php
	}

	public static function get_page_id( string $slug ): int {
		if ( ! self::is_um_available() ) {
			return 0;
		}
		return (int) um_get_predefined_page_id( $slug );
	}

	public static function is_on_core_page( string $slug ): bool {
		if ( ! function_exists( 'um_is_core_page' ) ) {
			return false;
		}
		return (bool) um_is_core_page( $slug );
	}

	public static function is_elementor_page( int $page_id ): bool {
		if ( $page_id <= 0 ) {
			return false;
		}
		return 'builder' === get_post_meta( $page_id, '_elementor_edit_mode', true );
	}

	public static function get_elementor_edit_url( int $page_id ): string {
		if ( $page_id <= 0 ) {
			return '';
		}
		return admin_url( 'post.php?post=' . $page_id . '&action=elementor' );
	}

	public static function get_um_forms_admin_url(): string {
		return admin_url( 'edit.php?post_type=um_form' );
	}

	public static function get_edit_form_url( int $form_id ): string {
		if ( $form_id <= 0 ) {
			return self::get_um_forms_admin_url();
		}
		$link = get_edit_post_link( $form_id, 'raw' );
		return $link ? $link : self::get_um_forms_admin_url();
	}

	public static function get_default_form_id( string $mode ): int {
		if ( ! self::is_um_available() ) {
			return 0;
		}

		if ( 'profile' === $mode ) {
			global $wpdb;
			if ( ! isset( $wpdb ) ) {
				return 0;
			}
			$id = $wpdb->get_var(
				"SELECT pm.post_id
				FROM {$wpdb->postmeta} pm
				LEFT JOIN {$wpdb->postmeta} pm2
				  ON pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default'
				WHERE pm.meta_key   = '_um_mode'
				  AND pm.meta_value = 'profile'
				  AND pm2.meta_value = '1'
				LIMIT 1"
			);
			return $id ? (int) $id : 0;
		}

		if ( 'directory' === $mode ) {
			$dirs = get_option( 'um_core_directories', [] );
			if ( is_array( $dirs ) && ! empty( $dirs['members'] ) ) {
				return (int) $dirs['members'];
			}
			return 0;
		}

		if ( ! in_array( $mode, [ 'login', 'register' ], true ) ) {
			return 0;
		}

		global $wpdb;
		if ( ! isset( $wpdb ) ) {
			return 0;
		}

		$id = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT pm.post_id
				FROM {$wpdb->postmeta} pm
				LEFT JOIN {$wpdb->postmeta} pm2
				  ON pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default'
				WHERE pm.meta_key   = '_um_mode'
				  AND pm.meta_value = %s
				  AND pm2.meta_value = '1'
				LIMIT 1",
				$mode
			)
		);

		return $id ? (int) $id : 0;
	}

	/**
	 * @param array<string> $widget_types
	 */
	public static function page_has_um_widget( int $page_id, array $widget_types ): bool {
		$elements = self::get_elementor_elements( $page_id );
		if ( empty( $elements ) ) {
			return false;
		}
		return self::elementor_tree_has_widget( $elements, $widget_types );
	}

	/**
	 * @return array<int, array<string, mixed>>
	 */
	private static function get_elementor_elements( int $page_id ): array {
		if ( $page_id <= 0 ) {
			return [];
		}
		$raw = get_post_meta( $page_id, '_elementor_data', true );
		if ( empty( $raw ) ) {
			return [];
		}
		if ( is_string( $raw ) ) {
			$data = json_decode( $raw, true );
		} else {
			$data = $raw;
		}
		return is_array( $data ) ? $data : [];
	}

	/**
	 * @param array<int, array<string, mixed>> $elements
	 * @param array<string>                    $widget_types
	 */
	private static function elementor_tree_has_widget( array $elements, array $widget_types ): bool {
		foreach ( $elements as $element ) {
			if ( ! is_array( $element ) ) {
				continue;
			}
			if ( isset( $element['widgetType'] ) && in_array( (string) $element['widgetType'], $widget_types, true ) ) {
				return true;
			}
			if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
				if ( self::elementor_tree_has_widget( $element['elements'], $widget_types ) ) {
					return true;
				}
			}
		}
		return false;
	}

	public static function page_uses_raw_um_shortcode( int $page_id ): bool {
		$post = get_post( $page_id );
		if ( $post && self::content_has_um_shortcode( (string) $post->post_content ) ) {
			return true;
		}
		return self::elementor_tree_has_um_shortcode( self::get_elementor_elements( $page_id ) );
	}

	private static function content_has_um_shortcode( string $content ): bool {
		if ( '' === $content ) {
			return false;
		}
		return (bool) preg_match( '/\[ultimatemember(?:_account|_password)?\b/', $content );
	}

	/**
	 * @param array<int, array<string, mixed>> $elements
	 */
	private static function elementor_tree_has_um_shortcode( array $elements ): bool {
		foreach ( $elements as $element ) {
			if ( ! is_array( $element ) ) {
				continue;
			}
			if ( isset( $element['widgetType'] ) ) {
				$type = (string) $element['widgetType'];
				if ( 'shortcode' === $type ) {
					$shortcode = $element['settings']['shortcode'] ?? '';
					if ( is_string( $shortcode ) && self::content_has_um_shortcode( $shortcode ) ) {
						return true;
					}
				}
				if ( in_array( $type, [ 'text-editor', 'html' ], true ) ) {
					$content = 'text-editor' === $type
						? (string) ( $element['settings']['editor'] ?? '' )
						: (string) ( $element['settings']['html'] ?? '' );
					if ( self::content_has_um_shortcode( $content ) ) {
						return true;
					}
				}
			}
			if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
				if ( self::elementor_tree_has_um_shortcode( $element['elements'] ) ) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * @return 'not_set'|'missing'|'shortcode_only'|'um_widget'|'elementor_no_um'|'classic'
	 */
	public static function get_content_status( int $page_id, array $widget_types ): string {
		if ( $page_id <= 0 ) {
			return 'not_set';
		}
		$post = get_post( $page_id );
		if ( ! $post ) {
			return 'missing';
		}
		if ( self::page_has_um_widget( $page_id, $widget_types ) ) {
			return 'um_widget';
		}
		if ( self::page_uses_raw_um_shortcode( $page_id ) ) {
			return self::is_elementor_page( $page_id ) ? 'shortcode_only' : 'classic';
		}
		if ( self::is_elementor_page( $page_id ) ) {
			return 'elementor_no_um';
		}
		return 'classic';
	}

	public static function get_content_status_label( string $status ): string {
		$labels = [
			'not_set'         => __( 'Not assigned', 'ultimate-member-widgets-for-elementor' ),
			'missing'         => __( 'Page missing', 'ultimate-member-widgets-for-elementor' ),
			'shortcode_only'  => __( 'UM shortcode on page — swap for UM Elementor widget', 'ultimate-member-widgets-for-elementor' ),
			'um_widget'       => __( 'UM Elementor widget', 'ultimate-member-widgets-for-elementor' ),
			'elementor_no_um' => __( 'Elementor (no UM output yet)', 'ultimate-member-widgets-for-elementor' ),
			'classic'         => __( 'Classic / no Elementor', 'ultimate-member-widgets-for-elementor' ),
		];
		return $labels[ $status ] ?? $status;
	}

	public static function get_content_status_short_label( string $status ): string {
		$labels = [
			'not_set'         => __( 'Not assigned', 'ultimate-member-widgets-for-elementor' ),
			'missing'         => __( 'Missing', 'ultimate-member-widgets-for-elementor' ),
			'shortcode_only'  => __( 'UM shortcode', 'ultimate-member-widgets-for-elementor' ),
			'um_widget'       => __( 'Ready', 'ultimate-member-widgets-for-elementor' ),
			'elementor_no_um' => __( 'Needs widget', 'ultimate-member-widgets-for-elementor' ),
			'classic'         => __( 'Classic', 'ultimate-member-widgets-for-elementor' ),
		];
		return $labels[ $status ] ?? self::get_content_status_label( $status );
	}

	/**
	 * @return array<int, array<string, mixed>>
	 */
	public static function get_dashboard_rows(): array {
		if ( ! self::is_um_available() ) {
			return [];
		}

		$rows = [];
		foreach ( self::get_page_map() as $slug => $config ) {
			$page_id = self::get_page_id( $slug );
			$status  = self::get_content_status( $page_id, (array) ( $config['widget_types'] ?? [] ) );

			$form_id = 0;
			if ( ! empty( $config['form_mode'] ) ) {
				$form_id = self::get_default_form_id( (string) $config['form_mode'] );
			}

			$rows[] = [
				'slug'                 => $slug,
				'label'                => (string) $config['label'],
				'page_id'              => $page_id,
				'url'                  => $page_id > 0 ? get_permalink( $page_id ) : '',
				'is_elementor'         => self::is_elementor_page( $page_id ),
				'content_status'       => $status,
				'content_status_label' => self::get_content_status_label( $status ),
				'recommended_widget'   => (string) $config['recommended_widget'],
				'requires_pro'         => ! empty( $config['requires_pro'] ),
				'elementor_edit_url'   => self::get_elementor_edit_url( $page_id ),
				'form_edit_url'        => ! empty( $config['show_form_link'] ) ? self::get_edit_form_url( $form_id ) : '',
				'um_pages_url'         => self::get_um_pages_settings_url(),
			];
		}

		return $rows;
	}

	/**
	 * @return array<string, mixed>|null
	 */
	public static function get_dashboard_row_by_page_id( int $page_id ): ?array {
		if ( $page_id < 1 ) {
			return null;
		}

		foreach ( self::get_dashboard_rows() as $row ) {
			if ( (int) ( $row['page_id'] ?? 0 ) === $page_id ) {
				return $row;
			}
		}

		return null;
	}

	/**
	 * Contextual toast shown once in the Elementor editor for UM core pages.
	 *
	 * @return array{message: string, dismiss_id: string, dismiss_label: string}|null
	 */
	public static function get_editor_setup_hint_data( int $page_id ): ?array {
		$row = self::get_dashboard_row_by_page_id( $page_id );
		if ( ! $row || self::is_pro_locked_row( $row ) ) {
			return null;
		}

		$status = (string) ( $row['content_status'] ?? '' );
		if ( in_array( $status, [ 'um_widget', 'not_set', 'missing', '' ], true ) ) {
			return null;
		}

		$widget = (string) ( $row['recommended_widget'] ?? '' );
		$message = '';

		switch ( $status ) {
			case 'shortcode_only':
				$message = sprintf(
					/* translators: %s: recommended Elementor widget name */
					__( 'Delete the [ultimatemember] shortcode block, then add "%s" from UM Member Pages.', 'ultimate-member-widgets-for-elementor' ),
					$widget
				);
				break;
			case 'elementor_no_um':
				$message = sprintf(
					/* translators: %s: recommended Elementor widget name */
					__( 'Add "%s" from the UM Member Pages widget panel.', 'ultimate-member-widgets-for-elementor' ),
					$widget
				);
				break;
			case 'classic':
				$message = sprintf(
					/* translators: %s: recommended Elementor widget name */
					__( 'Add "%s" from UM Member Pages (replace any UM shortcode if present).', 'ultimate-member-widgets-for-elementor' ),
					$widget
				);
				break;
		}

		if ( '' === $message ) {
			return null;
		}

		return [
			'message'        => $message,
			'dismiss_id'     => 'umep_editor_setup_' . $page_id,
			'dismiss_label'  => __( 'Got it', 'ultimate-member-widgets-for-elementor' ),
		];
	}

	/**
	 * Canvas bar copy when a UM shortcode block is rendered in the Elementor editor.
	 *
	 * @return array{title: string, message: string}|null
	 */
	public static function get_shortcode_canvas_notice_data( int $page_id ): ?array {
		if ( $page_id < 1 ) {
			return null;
		}

		$row = self::get_dashboard_row_by_page_id( $page_id );
		if ( $row ) {
			$status = (string) ( $row['content_status'] ?? '' );
			$widget = (string) ( $row['recommended_widget'] ?? '' );
			if ( '' !== $widget && in_array( $status, [ 'shortcode_only', 'classic', 'elementor_no_um' ], true ) ) {
				if ( self::page_uses_raw_um_shortcode( $page_id ) ) {
					return self::build_shortcode_canvas_notice( $widget );
				}
			}
		}

		if ( ! self::is_um_available() ) {
			return null;
		}

		foreach ( self::get_page_map() as $slug => $config ) {
			if ( self::get_page_id( $slug ) !== $page_id ) {
				continue;
			}
			if ( ! self::page_uses_raw_um_shortcode( $page_id ) ) {
				return null;
			}
			if ( self::page_has_um_widget( $page_id, (array) ( $config['widget_types'] ?? [] ) ) ) {
				return null;
			}
			$widget = (string) ( $config['recommended_widget'] ?? '' );
			if ( '' === $widget ) {
				return null;
			}
			return self::build_shortcode_canvas_notice( $widget );
		}

		return null;
	}

	/**
	 * @return array{title: string, message: string}
	 */
	private static function build_shortcode_canvas_notice( string $widget ): array {
		return [
			'title'   => __( 'UM shortcode — replace with Elementor widget', 'ultimate-member-widgets-for-elementor' ),
			'message' => sprintf(
				/* translators: %s: recommended Elementor widget name */
				__( 'Delete this block, then add "%s" from UM Member Pages.', 'ultimate-member-widgets-for-elementor' ),
				$widget
			),
		];
	}

	/**
	 * @param array<int, array<string, mixed>> $rows
	 * @return array{ready: int, total: int}
	 */
	public static function get_dashboard_progress( array $rows ): array {
		$ready = 0;
		$total = 0;
		foreach ( $rows as $row ) {
			if ( self::is_pro_locked_row( $row ) ) {
				continue;
			}
			++$total;
			if ( ! empty( $row['content_status'] ) && 'um_widget' === $row['content_status'] ) {
				++$ready;
			}
		}

		return [
			'ready' => $ready,
			'total' => $total,
		];
	}

	/**
	 * Dashicon for a core page slug (admin UI).
	 */
	public static function get_page_icon( string $slug ): string {
		$icons = [
			'login'          => 'dashicons-lock',
			'register'       => 'dashicons-admin-users',
			'user'           => 'dashicons-id',
			'account'        => 'dashicons-admin-settings',
			'password-reset' => 'dashicons-privacy',
			'members'        => 'dashicons-groups',
		];

		return $icons[ $slug ] ?? 'dashicons-admin-page';
	}

	/**
	 * One-line hint for card layout (kept short).
	 *
	 * @param array<string, mixed> $row
	 */
	public static function get_row_action_short_hint( array $row ): string {
		if ( self::is_pro_locked_row( $row ) ) {
			return __( 'Pro unlocks Elementor widgets for this page', 'ultimate-member-widgets-for-elementor' );
		}

		$status = (string) ( $row['content_status'] ?? '' );
		$widget = (string) ( $row['recommended_widget'] ?? '' );

		switch ( $status ) {
			case 'not_set':
			case 'missing':
				return __( 'Assign page in UM settings', 'ultimate-member-widgets-for-elementor' );
			case 'shortcode_only':
				return sprintf(
					/* translators: %s: recommended Elementor widget name */
					__( 'Remove shortcode → add “%s”', 'ultimate-member-widgets-for-elementor' ),
					$widget
				);
			case 'elementor_no_um':
				return sprintf(
					/* translators: %s: recommended Elementor widget name */
					__( 'Add “%s” widget', 'ultimate-member-widgets-for-elementor' ),
					$widget
				);
			case 'classic':
				return sprintf(
					/* translators: %s: recommended Elementor widget name */
					__( 'Open Elementor → add “%s”', 'ultimate-member-widgets-for-elementor' ),
					$widget
				);
			case 'um_widget':
				return __( 'Widget active', 'ultimate-member-widgets-for-elementor' );
			default:
				return '';
		}
	}

	/**
	 * @param array<string, mixed> $row
	 */
	public static function get_row_action_hint( array $row ): string {
		$status    = (string) ( $row['content_status'] ?? '' );
		$widget    = (string) ( $row['recommended_widget'] ?? '' );
		$page_id   = (int) ( $row['page_id'] ?? 0 );
		$elementor = ! empty( $row['is_elementor'] );

		switch ( $status ) {
			case 'not_set':
			case 'missing':
				return __( 'Assign in UM → Settings → Pages, then open in Elementor.', 'ultimate-member-widgets-for-elementor' );
			case 'shortcode_only':
				$hint = sprintf(
					/* translators: %s: recommended Elementor widget name */
					__( 'In Elementor: delete the [ultimatemember] shortcode, then add “%s” from the UM Member Pages widget panel.', 'ultimate-member-widgets-for-elementor' ),
					$widget
				);
				if ( 'login' === (string) ( $row['slug'] ?? '' ) ) {
					$hint .= ' ' . __( 'That widget can also customize the logged-in welcome.', 'ultimate-member-widgets-for-elementor' );
				}
				if ( 'user' === (string) ( $row['slug'] ?? '' ) ) {
					$hint .= ' ' . __( 'Optional: use Hide UM header after the widget is in place.', 'ultimate-member-widgets-for-elementor' );
				}
				return $hint;
			case 'elementor_no_um':
				return sprintf(
					/* translators: %s: recommended Elementor widget name */
					__( 'Elementor layout exists but no UM widget yet. Add “%s” from UM Member Pages.', 'ultimate-member-widgets-for-elementor' ),
					$widget
				);
			case 'um_widget':
				return __( 'Preview on the front end.', 'ultimate-member-widgets-for-elementor' );
			case 'classic':
				if ( $page_id > 0 && ! $elementor ) {
					return sprintf(
						/* translators: %s: recommended Elementor widget name */
						__( 'Open in Elementor and add “%s” from UM Member Pages (replace any UM shortcode if present).', 'ultimate-member-widgets-for-elementor' ),
						$widget
					);
				}
				return __( 'Open in Elementor.', 'ultimate-member-widgets-for-elementor' );
			default:
				return '';
		}
	}

	public static function render_dashboard_progress( array $rows ): void {
		$progress = self::get_dashboard_progress( $rows );
		if ( $progress['total'] < 1 ) {
			return;
		}

		$percent = (int) round( ( $progress['ready'] / max( 1, $progress['total'] ) ) * 100 );
		?>
		<div class="umwfe-core-pages-progress-bar" role="progressbar" aria-valuenow="<?php echo esc_attr( (string) $percent ); ?>" aria-valuemin="0" aria-valuemax="100">
			<span style="width: <?php echo esc_attr( (string) $percent ); ?>%;"></span>
		</div>
		<?php
	}

	/**
	 * @param array<int, array<string, mixed>> $rows
	 */
	public static function render_setup_summary( array $rows ): void {
		$progress   = self::get_dashboard_progress( $rows );
		$prereq     = self::get_prerequisites_status();
		$needs_work = $progress['ready'] < $progress['total'];
		$percent    = $progress['total'] > 0
			? (int) round( ( $progress['ready'] / max( 1, $progress['total'] ) ) * 100 )
			: 0;
		?>
		<div class="umwfe-setup-hero">
			<div class="umwfe-setup-hero-top">
				<?php if ( $progress['total'] > 0 ) : ?>
					<div class="umwfe-setup-progress-ring" role="img" aria-label="<?php echo esc_attr( sprintf(
						/* translators: 1: ready count, 2: total count */
						__( '%1$d of %2$d pages ready', 'ultimate-member-widgets-for-elementor' ),
						(int) $progress['ready'],
						(int) $progress['total']
					) ); ?>">
						<svg viewBox="0 0 36 36" aria-hidden="true">
							<path class="umwfe-ring-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
							<path class="umwfe-ring-fill" stroke-dasharray="<?php echo esc_attr( (string) $percent ); ?>, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
						</svg>
						<span class="umwfe-ring-label">
							<strong><?php echo esc_html( (string) $progress['ready'] ); ?></strong>
							<small>/ <?php echo esc_html( (string) $progress['total'] ); ?></small>
						</span>
					</div>
				<?php endif; ?>
				<div class="umwfe-setup-hero-copy">
					<p class="umwfe-setup-tagline">
						<?php
						if ( $needs_work || $progress['total'] < 1 ) {
							esc_html_e( 'Replace UM shortcodes with Elementor widgets on each member page.', 'ultimate-member-widgets-for-elementor' );
						} else {
							esc_html_e( 'All member pages use UM Elementor widgets.', 'ultimate-member-widgets-for-elementor' );
						}
						?>
					</p>
					<div class="umwfe-setup-quicklinks">
						<a href="<?php echo esc_url( self::get_um_pages_settings_url() ); ?>"><?php esc_html_e( 'UM Pages', 'ultimate-member-widgets-for-elementor' ); ?></a>
						<span aria-hidden="true">·</span>
						<a href="<?php echo esc_url( self::get_um_forms_admin_url() ); ?>"><?php esc_html_e( 'UM Forms', 'ultimate-member-widgets-for-elementor' ); ?></a>
					</div>
				</div>
			</div>

			<ul class="umwfe-setup-pills" aria-label="<?php esc_attr_e( 'How it works', 'ultimate-member-widgets-for-elementor' ); ?>">
				<li><span class="dashicons dashicons-forms" aria-hidden="true"></span> <?php esc_html_e( 'Logic in UM Forms', 'ultimate-member-widgets-for-elementor' ); ?></li>
				<li><span class="dashicons dashicons-layout" aria-hidden="true"></span> <?php esc_html_e( 'Layout in Elementor', 'ultimate-member-widgets-for-elementor' ); ?></li>
				<li><span class="dashicons dashicons-yes-alt" aria-hidden="true"></span> <?php esc_html_e( 'Ready = widget on page', 'ultimate-member-widgets-for-elementor' ); ?></li>
			</ul>

			<?php if ( ! $prereq['um'] || ! $prereq['elementor'] || $prereq['assigned'] < $prereq['total'] ) : ?>
				<ul class="umwfe-setup-warnings">
					<?php if ( ! $prereq['um'] ) : ?>
						<li><?php esc_html_e( 'Activate Ultimate Member.', 'ultimate-member-widgets-for-elementor' ); ?></li>
					<?php endif; ?>
					<?php if ( ! $prereq['elementor'] ) : ?>
						<li><?php esc_html_e( 'Activate Elementor.', 'ultimate-member-widgets-for-elementor' ); ?></li>
					<?php endif; ?>
					<?php if ( $prereq['um'] && $prereq['assigned'] < $prereq['total'] ) : ?>
						<li>
							<?php
							printf(
								wp_kses(
									/* translators: 1: assigned count, 2: total count, 3: UM pages settings URL */
									__( '%1$d/%2$d pages assigned — <a href="%3$s">UM Settings → Pages</a>', 'ultimate-member-widgets-for-elementor' ),
									[ 'a' => [ 'href' => [] ] ]
								),
								(int) $prereq['assigned'],
								(int) $prereq['total'],
								esc_url( self::get_um_pages_settings_url() )
							);
							?>
						</li>
					<?php endif; ?>
				</ul>
			<?php endif; ?>
		</div>
		<?php
	}

	public static function render_status_legend(): void {
		// Kept for backward compatibility; legend removed from setup UI.
	}

	public static function render_dashboard_table(): void {
		if ( ! self::is_um_available() ) {
			echo '<div class="notice notice-warning inline"><p>';
			esc_html_e( 'Ultimate Member must be active to list core membership pages.', 'ultimate-member-widgets-for-elementor' );
			echo '</p></div>';
			return;
		}

		$rows = self::get_dashboard_rows();
		self::render_setup_summary( $rows );
		?>
		<div class="umwfe-page-cards" role="list">
			<?php if ( empty( $rows ) ) : ?>
				<p class="umwfe-page-cards-empty"><?php esc_html_e( 'No Ultimate Member pages found.', 'ultimate-member-widgets-for-elementor' ); ?></p>
			<?php else : ?>
				<?php foreach ( $rows as $row ) : ?>
					<?php
					$status       = (string) ( $row['content_status'] ?? '' );
					$is_pro       = self::is_pro_locked_row( $row );
					$is_ready     = ! $is_pro && 'um_widget' === $status;
					$status_class = $is_pro
						? 'umwfe-badge umwfe-badge-pro'
						: 'umwfe-badge umwfe-badge-' . sanitize_html_class( $status );
					$card_class   = $is_pro
						? 'umwfe-page-card umwfe-page-card-pro'
						: ( $is_ready ? 'umwfe-page-card umwfe-page-card-ready' : 'umwfe-page-card umwfe-page-card-action' );
					$icon         = self::get_page_icon( (string) ( $row['slug'] ?? '' ) );
					$hint         = self::get_row_action_short_hint( $row );
					$slug         = (string) ( $row['slug'] ?? '' );
					?>
					<article class="<?php echo esc_attr( $card_class ); ?>" role="listitem">
						<header class="umwfe-page-card-head">
							<span class="umwfe-page-card-icon <?php echo esc_attr( $icon ); ?>" aria-hidden="true"></span>
							<div class="umwfe-page-card-title">
								<h2><?php echo esc_html( $row['label'] ); ?></h2>
								<?php if ( ! empty( $row['url'] ) ) : ?>
									<a class="umwfe-page-card-url" href="<?php echo esc_url( $row['url'] ); ?>" target="_blank" rel="noopener noreferrer">
										<?php echo esc_html( wp_parse_url( $row['url'], PHP_URL_PATH ) ?: $row['url'] ); ?>
									</a>
								<?php else : ?>
									<a class="umwfe-page-card-url" href="<?php echo esc_url( $row['um_pages_url'] ); ?>">
										<?php esc_html_e( 'Assign in UM', 'ultimate-member-widgets-for-elementor' ); ?>
									</a>
								<?php endif; ?>
							</div>
							<span class="<?php echo esc_attr( $status_class ); ?>" title="<?php echo esc_attr( $is_pro ? __( 'Pro feature', 'ultimate-member-widgets-for-elementor' ) : (string) $row['content_status_label'] ); ?>">
								<?php
								if ( $is_pro ) {
									esc_html_e( 'Pro', 'ultimate-member-widgets-for-elementor' );
								} else {
									echo esc_html( self::get_content_status_short_label( $status ) );
								}
								?>
							</span>
						</header>

						<?php if ( $is_pro && ! empty( $row['recommended_widget'] ) ) : ?>
							<p class="umwfe-page-card-widget">
								<span class="dashicons dashicons-lock" aria-hidden="true"></span>
								<?php echo esc_html( (string) $row['recommended_widget'] ); ?>
							</p>
						<?php elseif ( ! $is_ready && ! empty( $row['recommended_widget'] ) ) : ?>
							<p class="umwfe-page-card-widget">
								<span class="dashicons dashicons-screenoptions" aria-hidden="true"></span>
								<?php echo esc_html( (string) $row['recommended_widget'] ); ?>
							</p>
						<?php endif; ?>

						<?php if ( '' !== $hint && ( $is_pro || ! $is_ready ) ) : ?>
							<p class="umwfe-page-card-hint"><?php echo esc_html( $hint ); ?></p>
						<?php endif; ?>

						<footer class="umwfe-page-card-actions">
							<?php if ( $is_pro ) : ?>
								<a class="button button-primary button-small" href="<?php echo esc_url( self::get_pro_upgrade_url( 'setup-page-' . $slug ) ); ?>">
									<?php echo esc_html( self::get_pro_upgrade_label() ); ?>
								</a>
							<?php elseif ( $row['page_id'] > 0 && $row['elementor_edit_url'] ) : ?>
								<a class="button button-primary button-small" href="<?php echo esc_url( $row['elementor_edit_url'] ); ?>">
									<?php echo esc_html( self::get_elementor_action_label_for_row( $row ) ); ?>
								</a>
							<?php endif; ?>
							<?php if ( ! empty( $row['form_edit_url'] ) ) : ?>
								<a class="button button-small" href="<?php echo esc_url( $row['form_edit_url'] ); ?>">
									<?php esc_html_e( 'UM form', 'ultimate-member-widgets-for-elementor' ); ?>
								</a>
							<?php endif; ?>
							<?php if ( $is_ready && ! empty( $row['url'] ) ) : ?>
								<a class="button button-small" href="<?php echo esc_url( $row['url'] ); ?>" target="_blank" rel="noopener noreferrer">
									<?php esc_html_e( 'View', 'ultimate-member-widgets-for-elementor' ); ?>
								</a>
							<?php endif; ?>
						</footer>
					</article>
				<?php endforeach; ?>
			<?php endif; ?>
		</div>
		<?php
	}

	public static function get_edit_form_notice_html(): string {
		$forms_url = esc_url( self::get_um_forms_admin_url() );
		return sprintf(
			/* translators: %s: link to UM Forms admin screen */
			__( '<strong>Fields &amp; validation</strong> are managed in Ultimate Member, not in Elementor. <a href="%s" target="_blank" rel="noopener noreferrer">Open Forms →</a>', 'ultimate-member-widgets-for-elementor' ),
			$forms_url
		);
	}

	public static function get_core_page_panel_hint_html( string $slug, string $widget_title ): string {
		$page_id = self::get_page_id( $slug );
		if ( $page_id <= 0 ) {
			return '';
		}

		$config     = self::get_page_map()[ $slug ] ?? null;
		$page_label = is_array( $config ) ? (string) $config['label'] : $slug;
		$edit_url   = esc_url( self::get_elementor_edit_url( $page_id ) );

		return sprintf(
			/* translators: 1: widget title, 2: UM page label, 3: open-in-elementor URL */
			__( '<strong>%1$s</strong> works best on your UM %2$s page. <a href="%3$s">Open that page in Elementor →</a>', 'ultimate-member-widgets-for-elementor' ),
			esc_html( $widget_title ),
			esc_html( $page_label ),
			$edit_url
		);
	}
}
