<?php
namespace Tiamr\Admin;

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


final class Admin_Menu {
    public const PAGE_DASHBOARD = 'titanium-advanced-menu-rules';
    public const PAGE_SETTINGS  = 'titanium-advanced-menu-rules-settings';
    public const PAGE_PRO       = 'titanium-advanced-menu-rules-upgrade';
    private const PAGE_LICENSE_ACTIVATION = 'titanium-advanced-menu-rules-license-activation';

    public const OPTION_DELETE_DATA_ON_UNINSTALL = 'tiamr_delete_data_on_uninstall';
    public const OPTION_SHOW_MENU_LOCATION_WARNINGS = 'tiamr_show_menu_location_warnings';
    public const OPTION_BETA_UPDATES = 'tiamr_beta_updates';
    public const OPTION_IMPORT_NOTICE_DISMISSED = 'tiamr_nav_menu_roles_import_notice_dismissed';
    public const OPTION_IMPORT_COMPLETED = 'tiamr_nav_menu_roles_import_completed';

    public function __construct() {
        add_action('admin_menu', [$this, 'register_menu']);
        add_action('admin_head', [$this, 'hide_duplicate_freemius_upgrade_menu']);
        add_action('admin_head', [$this, 'hide_hidden_license_activation_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_init', [$this, 'maybe_redirect_after_activation'], 20);
        add_action('admin_notices', [$this, 'maybe_render_import_available_notice']);
        add_action('admin_notices', [$this, 'maybe_render_nav_menu_roles_active_warning']);
        add_action('admin_notices', [$this, 'maybe_render_menu_location_warning']);
        add_action('admin_post_tiamr_import_nav_menu_roles', [$this, 'handle_nav_menu_roles_import']);
        add_action('admin_post_tiamr_import_user_menus', [$this, 'handle_user_menus_import']);
        add_action('admin_post_tiamr_dismiss_import_notice', [$this, 'handle_dismiss_import_notice']);
        add_action('admin_post_tiamr_existing_license_connect', [$this, 'handle_existing_license_connect']);
        add_action('wp_ajax_tiamr_get_freemius_pricing', [$this, 'ajax_get_freemius_pricing']);
        add_action('wp_ajax_tiamr_save_setting', [$this, 'ajax_save_setting']);
        add_filter('plugin_action_links_' . TIAMR_PLUGIN_BASENAME, [$this, 'add_plugin_action_links']);
    }

    public function register_menu(): void {
        add_menu_page(
            __('Titanium Nav Menu Roles & Visibility Rules', 'titanium-advanced-menu-rules'),
            __('Titanium Menu Rules', 'titanium-advanced-menu-rules'),
            'edit_theme_options',
            self::PAGE_DASHBOARD,
            [$this, 'render_settings_page'],
            'dashicons-menu-alt3',
            59
        );

        add_submenu_page(
            self::PAGE_DASHBOARD,
            __('Settings', 'titanium-advanced-menu-rules'),
            __('Settings', 'titanium-advanced-menu-rules'),
            'edit_theme_options',
            self::PAGE_DASHBOARD,
            [$this, 'render_settings_page']
        );

        add_submenu_page(
            self::PAGE_DASHBOARD,
            __('Activate Pro License', 'titanium-advanced-menu-rules'),
            __('Activate Pro License', 'titanium-advanced-menu-rules'),
            'activate_plugins',
            self::PAGE_LICENSE_ACTIVATION,
            [$this, 'render_license_activation_page']
        );

        if ($this->is_pro_active()) {
            add_submenu_page(
                self::PAGE_DASHBOARD,
                __('License & Plans', 'titanium-advanced-menu-rules'),
                __('License & Plans', 'titanium-advanced-menu-rules'),
                'edit_theme_options',
                self::PAGE_PRO,
                [$this, 'render_pro_page']
            );
        } else {
            add_submenu_page(
                self::PAGE_DASHBOARD,
                __('Upgrade to Pro', 'titanium-advanced-menu-rules'),
                '<span class="amr-upgrade-menu-label">' . esc_html__('Upgrade to Pro', 'titanium-advanced-menu-rules') . '</span>',
                'edit_theme_options',
                self::PAGE_PRO,
                [$this, 'render_pro_page']
            );
        }
    }


    public function hide_duplicate_freemius_upgrade_menu(): void {
        global $submenu;

        if (empty($submenu[self::PAGE_DASHBOARD]) || !is_array($submenu[self::PAGE_DASHBOARD])) {
            return;
        }

        $kept_custom_pricing_page = false;

        foreach ($submenu[self::PAGE_DASHBOARD] as $index => $item) {
            $raw_label = isset($item[0]) ? (string) $item[0] : '';
            $label     = wp_strip_all_tags($raw_label);
            $slug      = isset($item[2]) ? (string) $item[2] : '';

            $is_custom_pricing_slug = (self::PAGE_PRO === $slug);
            $is_our_menu_item       = false !== strpos($raw_label, 'amr-upgrade-menu-label') || false !== strpos($raw_label, 'amr-pricing-menu-label');

            if ($is_custom_pricing_slug && $is_our_menu_item && !$kept_custom_pricing_page) {
                $kept_custom_pricing_page = true;
                continue;
            }

            if ($is_custom_pricing_slug && !$kept_custom_pricing_page) {
                $kept_custom_pricing_page = true;
                continue;
            }

            if (
                $is_custom_pricing_slug ||
                false !== stripos($label, 'upgrade') ||
                false !== stripos($label, 'pricing') ||
                false !== stripos($label, 'plans') ||
                false !== stripos($slug, 'pricing') ||
                false !== stripos($slug, 'upgrade') ||
                false !== stripos($slug, 'checkout')
            ) {
                unset($submenu[self::PAGE_DASHBOARD][$index]);
            }
        }

        $submenu[self::PAGE_DASHBOARD] = array_values($submenu[self::PAGE_DASHBOARD]);
    }


    public function hide_hidden_license_activation_menu(): void {
        global $submenu;

        if (empty($submenu[self::PAGE_DASHBOARD]) || !is_array($submenu[self::PAGE_DASHBOARD])) {
            return;
        }

        foreach ($submenu[self::PAGE_DASHBOARD] as $index => $item) {
            $slug = isset($item[2]) ? (string) $item[2] : '';

            if (self::PAGE_LICENSE_ACTIVATION === $slug) {
                unset($submenu[self::PAGE_DASHBOARD][$index]);
            }
        }

        $submenu[self::PAGE_DASHBOARD] = array_values($submenu[self::PAGE_DASHBOARD]);
    }


    public function handle_existing_license_connect(): void {
        if (!current_user_can('activate_plugins')) {
            wp_die(esc_html__('You do not have permission to activate licenses.', 'titanium-advanced-menu-rules'));
        }

        check_admin_referer('tiamr_existing_license_connect');

        $user_id = get_current_user_id();

        if ($user_id > 0) {
            update_user_meta($user_id, '_tiamr_existing_license_flow', '1');
        }

        if (!headers_sent()) {
            setcookie('tiamr_existing_license_flow', '1', time() + (10 * MINUTE_IN_SECONDS), COOKIEPATH ?: '/', COOKIE_DOMAIN, is_ssl(), true);
        }

        wp_safe_redirect($this->get_freemius_license_connect_url());
        exit;
    }

    public function register_settings(): void {
        register_setting(
            'tiamr_settings',
            self::OPTION_DELETE_DATA_ON_UNINSTALL,
            [
                'type'              => 'boolean',
                'sanitize_callback' => [$this, 'sanitize_checkbox'],
                'default'           => false,
            ]
        );

        register_setting(
            'tiamr_settings',
            self::OPTION_SHOW_MENU_LOCATION_WARNINGS,
            [
                'type'              => 'boolean',
                'sanitize_callback' => [$this, 'sanitize_checkbox'],
                'default'           => true,
            ]
        );

        register_setting(
            'tiamr_settings',
            self::OPTION_BETA_UPDATES,
            [
                'type'              => 'boolean',
                'sanitize_callback' => [$this, 'sanitize_checkbox'],
                'default'           => false,
            ]
        );
    }

    /**
     * @param mixed $value
     */
    public function sanitize_checkbox($value): int {
        return !empty($value) ? 1 : 0;
    }


    public function ajax_save_setting(): void {
        if (!current_user_can('edit_theme_options')) {
            wp_send_json_error(['message' => __('You do not have permission to change this setting.', 'titanium-advanced-menu-rules')], 403);
        }

        check_ajax_referer('tiamr_save_setting', 'nonce');

        $option = isset($_POST['option']) ? sanitize_key(wp_unslash($_POST['option'])) : '';
        $value  = isset($_POST['value']) ? sanitize_text_field(wp_unslash($_POST['value'])) : '';

        $allowed = [
            self::OPTION_SHOW_MENU_LOCATION_WARNINGS => 'boolean',
            self::OPTION_DELETE_DATA_ON_UNINSTALL   => 'boolean',
            self::OPTION_BETA_UPDATES             => 'boolean',
        ];

        $allowed = (array) apply_filters('tiamr/admin/ajax_save_settings_allowed', $allowed);

        if (!isset($allowed[$option])) {
            wp_send_json_error(['message' => __('Unknown setting.', 'titanium-advanced-menu-rules')], 400);
        }

        $type = (string) $allowed[$option];

        if ('boolean' === $type) {
            $new_value = '1' === $value ? 1 : 0;
        } elseif ('integer' === $type) {
            $new_value = absint($value);
        } else {
            $new_value = sanitize_key($value);
        }

        $new_value = apply_filters('tiamr/admin/ajax_save_setting_value', $new_value, $option, $type);

        update_option($option, $new_value, false);

        wp_send_json_success([
            'option' => $option,
            'value'  => $new_value,
        ]);
    }

    private function get_nav_menu_roles_importer(): Nav_Menu_Roles_Importer {
        return new Nav_Menu_Roles_Importer();
    }

    private function get_user_menus_importer(): User_Menus_Importer {
        return new User_Menus_Importer();
    }

    public function handle_nav_menu_roles_import(): void {
        if (!current_user_can('edit_theme_options')) {
            wp_die(esc_html__('You do not have permission to import menu rules.', 'titanium-advanced-menu-rules'));
        }

        check_admin_referer('tiamr_import_nav_menu_roles');

        $replace_existing = !empty($_POST['tiamr_replace_existing']);
        $result           = $this->get_nav_menu_roles_importer()->import($replace_existing, $replace_existing);

        $redirect_url = add_query_arg(
            [
                'page'                    => self::PAGE_DASHBOARD,
                'tiamr_nmr_import'          => '1',
                'tiamr_nmr_found'           => absint($result['found']),
                'tiamr_nmr_imported'        => absint($result['imported']),
                'tiamr_nmr_skipped_existing'=> absint($result['skipped_existing']),
                'tiamr_nmr_skipped_unsupported' => absint($result['skipped_unsupported']),
                'tiamr_nmr_replaced_pro'    => absint($result['replaced_pro']),
                'tiamr_nmr_kept_pro'        => absint($result['kept_pro']),
            ],
            admin_url('admin.php')
        );

        update_option(self::OPTION_IMPORT_NOTICE_DISMISSED, 1, false);
        delete_option('tiamr_do_activation_redirect');

        if (!empty($result['imported'])) {
            update_option(self::OPTION_IMPORT_COMPLETED, 1, false);
        }

        wp_safe_redirect($redirect_url);
        exit;
    }

    public function handle_user_menus_import(): void {
        if (!current_user_can('edit_theme_options')) {
            wp_die(esc_html__('You do not have permission to import menu rules.', 'titanium-advanced-menu-rules'));
        }

        check_admin_referer('tiamr_import_user_menus');

        $replace_existing = !empty($_POST['tiamr_replace_existing']);
        $result           = $this->get_user_menus_importer()->import($replace_existing, $replace_existing);

        $redirect_url = add_query_arg(
            [
                'page'                    => self::PAGE_DASHBOARD,
                'tiamr_user_menus_import'   => '1',
                'tiamr_user_menus_found'    => absint($result['found']),
                'tiamr_user_menus_imported' => absint($result['imported']),
                'tiamr_user_menus_skipped_existing'    => absint($result['skipped_existing']),
                'tiamr_user_menus_skipped_unsupported' => absint($result['skipped_unsupported']),
                'tiamr_user_menus_replaced_pro'        => absint($result['replaced_pro']),
                'tiamr_user_menus_kept_pro'            => absint($result['kept_pro']),
            ],
            admin_url('admin.php')
        );

        update_option(self::OPTION_IMPORT_NOTICE_DISMISSED, 1, false);
        delete_option('tiamr_do_activation_redirect');

        if (!empty($result['imported'])) {
            update_option(self::OPTION_IMPORT_COMPLETED, 1, false);
        }

        wp_safe_redirect($redirect_url);
        exit;
    }


    public function handle_dismiss_import_notice(): void {
        if (!current_user_can('edit_theme_options')) {
            wp_die(esc_html__('You do not have permission to dismiss this notice.', 'titanium-advanced-menu-rules'));
        }

        check_admin_referer('tiamr_dismiss_import_notice');
        update_option(self::OPTION_IMPORT_NOTICE_DISMISSED, 1, false);
        delete_option('tiamr_do_activation_redirect');

        $redirect = add_query_arg('tiamr_import_skipped', '1', admin_url('admin.php?page=' . self::PAGE_DASHBOARD));

        wp_safe_redirect($redirect);
        exit;
    }

    private function render_nav_menu_roles_import_notice(): void {
        if (!empty($_GET['tiamr_user_menus_import'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $imported            = isset($_GET['tiamr_user_menus_imported']) ? absint($_GET['tiamr_user_menus_imported']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $skipped_existing    = isset($_GET['tiamr_user_menus_skipped_existing']) ? absint($_GET['tiamr_user_menus_skipped_existing']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $skipped_unsupported = isset($_GET['tiamr_user_menus_skipped_unsupported']) ? absint($_GET['tiamr_user_menus_skipped_unsupported']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $replaced_pro        = isset($_GET['tiamr_user_menus_replaced_pro']) ? absint($_GET['tiamr_user_menus_replaced_pro']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $kept_pro            = isset($_GET['tiamr_user_menus_kept_pro']) ? absint($_GET['tiamr_user_menus_kept_pro']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            ?>
            <div class="notice notice-success is-dismissible">
                <p>
                    <?php
                    printf(
                        /* translators: 1: imported count, 2: skipped existing count, 3: skipped unsupported count, 4: replaced Pro count, 5: kept Pro count */
                        esc_html__('User Menus import finished. Imported: %1$d. Skipped existing Titanium Nav Menu Roles & Visibility Rules items: %2$d. Skipped empty or unsupported items: %3$d. Replaced Pro rules: %4$d. Kept existing Pro rules: %5$d.', 'titanium-advanced-menu-rules'),
                        esc_html((string) $imported),
                        esc_html((string) $skipped_existing),
                        esc_html((string) $skipped_unsupported),
                        esc_html((string) $replaced_pro),
                        esc_html((string) $kept_pro)
                    );
                    ?>
                </p>
            </div>
            <?php
            return;
        }

        if (empty($_GET['tiamr_nmr_import'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return;
        }

        $imported            = isset($_GET['tiamr_nmr_imported']) ? absint($_GET['tiamr_nmr_imported']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $skipped_existing    = isset($_GET['tiamr_nmr_skipped_existing']) ? absint($_GET['tiamr_nmr_skipped_existing']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $skipped_unsupported = isset($_GET['tiamr_nmr_skipped_unsupported']) ? absint($_GET['tiamr_nmr_skipped_unsupported']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $replaced_pro        = isset($_GET['tiamr_nmr_replaced_pro']) ? absint($_GET['tiamr_nmr_replaced_pro']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $kept_pro            = isset($_GET['tiamr_nmr_kept_pro']) ? absint($_GET['tiamr_nmr_kept_pro']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        ?>
        <div class="notice notice-success is-dismissible">
            <p>
                <?php
                printf(
                    /* translators: 1: imported count, 2: skipped existing count, 3: skipped unsupported count, 4: replaced Pro count, 5: kept Pro count */
                    esc_html__('Nav Menu Roles import finished. Imported: %1$d. Skipped existing Titanium Nav Menu Roles & Visibility Rules items: %2$d. Skipped empty or unsupported items: %3$d. Replaced Pro rules: %4$d. Kept existing Pro rules: %5$d.', 'titanium-advanced-menu-rules'),
                    esc_html((string) $imported),
                    esc_html((string) $skipped_existing),
                    esc_html((string) $skipped_unsupported),
                    esc_html((string) $replaced_pro),
                    esc_html((string) $kept_pro)
                );
                ?>
            </p>
        </div>
        <?php
    }

    public function maybe_redirect_after_activation(): void {
        if (!get_option('tiamr_do_activation_redirect', false)) {
            return;
        }

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

        if (wp_doing_ajax() || wp_doing_cron() || is_network_admin()) {
            return;
        }

        $current_page = isset($_GET['page']) ? sanitize_key((string) wp_unslash($_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $current_tab  = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        // If the user is already on the import page, clear the one-time redirect flag.
        // This prevents an activation redirect loop and keeps Plugins/Settings reachable.
        if (self::PAGE_DASHBOARD === $current_page && 'import' === $current_tab) {
            delete_option('tiamr_do_activation_redirect');
            return;
        }

        if (!$this->has_active_importable_source()) {
            delete_option('tiamr_do_activation_redirect');
            return;
        }

        // One-shot redirect only. Clear before redirecting so a failed/blank load cannot trap the admin.
        delete_option('tiamr_do_activation_redirect');

        wp_safe_redirect(admin_url('admin.php?page=' . self::PAGE_DASHBOARD . '&tab=import&tiamr_import_detected=1'));
        exit;
    }

    private function has_active_importable_source(): bool {
        $sources = $this->get_active_import_sources(true);

        return !empty($sources);
    }

    /**
     * @return array<int,array{name:string,slug:string,stats:array}>
     */
    private function get_active_import_sources(bool $importable_only = false): array {
        $sources = [];

        if ($this->is_nav_menu_roles_active()) {
            $stats = $this->get_nav_menu_roles_importer()->get_stats();

            if (!$importable_only || !empty($stats['importable'])) {
                $sources[] = [
                    'name'  => __('Nav Menu Roles', 'titanium-advanced-menu-rules'),
                    'slug'  => 'nav-menu-roles',
                    'stats' => $stats,
                ];
            }
        }

        if ($this->is_user_menus_active()) {
            $stats = $this->get_user_menus_importer()->get_stats();

            if (!$importable_only || !empty($stats['importable'])) {
                $sources[] = [
                    'name'  => __('User Menus', 'titanium-advanced-menu-rules'),
                    'slug'  => 'user-menus',
                    'stats' => $stats,
                ];
            }
        }

        return $sources;
    }

    private function is_nav_menu_roles_active(): bool {
        return function_exists('nav_menu_roles') || class_exists('Nav_Menu_Roles');
    }

    private function is_user_menus_active(): bool {
        return function_exists('jp_user_menus') || class_exists('JP_User_Menus');
    }




    private function get_pricing_id_for_licenses(string $licenses, string $fallback = ''): string {
        $map = [
            '1'         => '69061',
            '3'         => '69062',
            '5'         => '69063',
            '10'        => '69064',
            '20'        => '69065',
            'unlimited' => '69066',
        ];

        return $map[$licenses] ?? $fallback;
    }

    /**
     * Build Freemius checkout URLs with RFC3986 encoding.
     * This keeps license keys containing #, ?, &, etc. from breaking later query args like coupon/pricing_id.
     */
    private function build_hosted_freemius_url(array $args): string {
        $clean_args = [];

        foreach ($args as $key => $value) {
            if (null === $value || false === $value || '' === $value) {
                continue;
            }

            $clean_args[(string) $key] = (string) $value;
        }

        return 'https://checkout.freemius.com/product/32028/plan/52536/?' . http_build_query($clean_args, '', '&', PHP_QUERY_RFC3986);
    }

    private function normalize_checkout_coupon_code(string $coupon_code): string {
        $coupon_code = trim($coupon_code);

        if ('' === $coupon_code) {
            return '';
        }

        if (0 === strcasecmp($coupon_code, 'FirstYear50')) {
            return 'FirstYear50';
        }

        return $coupon_code;
    }

    private function get_hosted_checkout_url(string $pricing_id, string $coupon_code = ''): string {
        $coupon_code = $this->normalize_checkout_coupon_code($coupon_code);

        if ('' === $pricing_id) {
            return '';
        }

        $args = [
            'pricing_id'    => $pricing_id,
            'billing_cycle' => 'annual',
            'currency'      => 'gbp',
        ];

        if ('' !== $coupon_code) {
            $args['coupon']      = $coupon_code;
            $args['coupon_code'] = $coupon_code;
            $args['hide_coupon'] = '1';
        }

        return $this->build_hosted_freemius_url($args);
    }

    private function get_checkout_url(string $licenses = '1', string $pricing_id = '', string $coupon_code = ''): string {
        $coupon_code = $this->normalize_checkout_coupon_code($coupon_code);

        $hosted_checkout_url = $this->get_hosted_checkout_url($pricing_id, $coupon_code);

        if ('' !== $hosted_checkout_url) {
            return $hosted_checkout_url;
        }

        $fallback_url = 'https://adminplugins.com/advanced-menu-rules/';

        if (function_exists('tiamr_fs')) {
            $fs = tiamr_fs();

            if (is_object($fs) && method_exists($fs, 'checkout_url')) {
                $extra = [
                    'plan_id'  => '52536',
                    'currency' => 'gbp',
                ];

                if ('' !== $coupon_code) {
                    $extra['coupon']      = $coupon_code;
                    $extra['coupon_code'] = $coupon_code;
                    $extra['hide_coupon'] = true;
                }

                if ('unlimited' !== $licenses) {
                    $license_count = absint($licenses);

                    if ($license_count > 0) {
                        $extra['licenses'] = $license_count;
                    }
                }

                $checkout_url = $fs->checkout_url(
                    'annual',
                    false,
                    $extra
                );

                if (is_string($checkout_url) && '' !== $checkout_url && false === strpos($checkout_url, 'page=titanium-advanced-menu-rules')) {
                    return $checkout_url;
                }
            }
        }

        return (string) apply_filters('tiamr/pro_url', $fallback_url);
    }

    private function get_upgrade_url(): string {
        return $this->get_checkout_url('1');
    }



    private function get_current_license_key(): string {
        if (!function_exists('tiamr_fs')) {
            return '';
        }

        $fs = tiamr_fs();

        if (!is_object($fs) || !method_exists($fs, '_get_license')) {
            return '';
        }

        $license = $fs->_get_license();

        if (!is_object($license) || empty($license->secret_key)) {
            return '';
        }

        return (string) $license->secret_key;
    }

    private function get_hosted_upgrade_url(string $pricing_id, string $coupon_code = ''): string {
        $coupon_code = $this->normalize_checkout_coupon_code($coupon_code);

        $license_key = $this->get_current_license_key();

        if ('' === $license_key || '' === $pricing_id) {
            return $this->get_plan_change_url();
        }

        $args = [
            'license_key'   => $license_key,
            'pricing_id'    => $pricing_id,
            'billing_cycle' => 'annual',
            'currency'      => 'gbp',
        ];

        if ('' !== $coupon_code) {
            $args['coupon']      = $coupon_code;
            $args['coupon_code'] = $coupon_code;
            $args['hide_coupon'] = '1';
        }

        return $this->build_hosted_freemius_url($args);
    }

    private function get_plan_change_url(): string {
        if (function_exists('tiamr_fs')) {
            $fs = tiamr_fs();

            if (is_object($fs) && method_exists($fs, 'get_upgrade_url')) {
                $url = $fs->get_upgrade_url('annual', false);

                if (is_string($url) && '' !== $url) {
                    return add_query_arg('currency', 'gbp', $url);
                }
            }

            if (is_object($fs) && method_exists($fs, 'pricing_url')) {
                $url = $fs->pricing_url('annual', false);

                if (is_string($url) && '' !== $url) {
                    return add_query_arg('currency', 'gbp', $url);
                }
            }
        }

        return $this->get_checkout_url('1');
    }


    private function get_freemius_account_url_if_connected(): string {
        if (!function_exists('tiamr_fs')) {
            return '';
        }

        $fs = tiamr_fs();

        if (!is_object($fs) || !method_exists($fs, 'get_account_url')) {
            return '';
        }

        if (method_exists($fs, 'is_registered') && !$fs->is_registered()) {
            return '';
        }

        $account_url = $fs->get_account_url();

        return is_string($account_url) ? $account_url : '';
    }

    private function get_license_activation_url(): string {
        $account_url = $this->get_freemius_account_url_if_connected();

        if ('' !== $account_url) {
            return $account_url;
        }

        return wp_nonce_url(
            admin_url('admin.php?page=' . self::PAGE_LICENSE_ACTIVATION),
            'tiamr_license_activation_page'
        );
    }

    private function get_freemius_license_connect_url(): string {
        if (function_exists('tiamr_fs')) {
            $fs = tiamr_fs();

            if (is_object($fs) && method_exists($fs, 'get_activation_url')) {
                $params = [
                    'fs_action'       => 'reset_pending_activation_mode',
                    'require_license' => 'true',
                ];

                if (method_exists($fs, 'get_unique_affix')) {
                    $params['fs_unique_affix'] = $fs->get_unique_affix();
                }

                $activation_url = $fs->get_activation_url($params);

                if (is_string($activation_url) && '' !== $activation_url) {
                    return $activation_url;
                }
            }
        }

        return admin_url('admin.php?page=titanium-advanced-menu-rules');
    }

    private function get_existing_license_connect_url(): string {
        return wp_nonce_url(
            admin_url('admin-post.php?action=tiamr_existing_license_connect'),
            'tiamr_existing_license_connect'
        );
    }




    private function is_pro_active(): bool {
        return defined('TIAMR_PRO_FEATURES_ACTIVE') && TIAMR_PRO_FEATURES_ACTIVE;
    }

    private function is_advanced_menu_rules_screen(): bool {
        $pagenow = isset($GLOBALS['pagenow']) ? (string) $GLOBALS['pagenow'] : '';

        if ('admin.php' !== $pagenow) {
            return false;
        }

        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        return in_array(
            $page,
            [
                self::PAGE_DASHBOARD,
                self::PAGE_SETTINGS,
                self::PAGE_PRO,
                self::PAGE_LICENSE_ACTIVATION,
            ],
            true
        );
    }




    private function beta_updates_enabled(): bool {
        if (function_exists('tiamr_fs')) {
            $fs = tiamr_fs();

            if (is_object($fs) && method_exists($fs, 'get_site')) {
                $site = $fs->get_site();

                if (is_object($site) && isset($site->is_beta)) {
                    return (bool) $site->is_beta;
                }
            }
        }

        return (bool) get_option(self::OPTION_BETA_UPDATES, false);
    }

    private function show_menu_location_warnings(): bool {
        return (bool) get_option(self::OPTION_SHOW_MENU_LOCATION_WARNINGS, true);
    }

    public function maybe_render_menu_location_warning(): void {
        if (!$this->show_menu_location_warnings()) {
            return;
        }

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

        $pagenow = isset($GLOBALS['pagenow']) ? (string) $GLOBALS['pagenow'] : '';

        if ('nav-menus.php' !== $pagenow) {
            return;
        }

        $menu_id = $this->get_current_nav_menu_id();

        if ($this->should_show_menu_location_warning_for_menu($menu_id)) {
            ?>
            <div class="notice notice-warning amr-menu-location-warning">
                <p>
                    <strong><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules warning:', 'titanium-advanced-menu-rules'); ?></strong>
                    <?php esc_html_e('This menu contains visibility rules, but it is not assigned to any menu location. Your theme may display another fallback menu on the frontend, so these rules may not affect the menu visitors see.', 'titanium-advanced-menu-rules'); ?>
                </p>
            </div>
            <?php
            return;
        }

        $this->render_mobile_menu_location_note($menu_id);
    }

    private function get_current_nav_menu_id(): int {
        if (isset($GLOBALS['nav_menu_selected_id'])) {
            $global_menu_id = absint($GLOBALS['nav_menu_selected_id']);

            if ($global_menu_id > 0) {
                return $global_menu_id;
            }
        }

        $menu_id = 0;

        if (isset($_REQUEST['menu'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $menu_id = absint(wp_unslash($_REQUEST['menu'])); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        }

        if ($menu_id > 0) {
            return $menu_id;
        }

        if (function_exists('nav_menu_get_selected_menu')) {
            $selected_menu = nav_menu_get_selected_menu();

            if ($selected_menu instanceof \WP_Term) {
                return absint($selected_menu->term_id);
            }
        }

        return 0;
    }

    private function menu_has_advanced_rules(int $menu_id): bool {
        $items = wp_get_nav_menu_items($menu_id, ['post_status' => 'any']);

        if (empty($items) || !is_array($items)) {
            return false;
        }

        foreach ($items as $item) {
            if (!$item instanceof \WP_Post) {
                continue;
            }

            if ($this->menu_item_has_advanced_rules((int) $item->ID)) {
                return true;
            }
        }

        return false;
    }

    private function menu_item_has_advanced_rules(int $item_id): bool {
        $free_action = (string) get_post_meta($item_id, '_tiamr_action', true);

        if (in_array($free_action, ['show', 'hide'], true)) {
            return true;
        }

        $legacy_condition = (string) get_post_meta($item_id, '_tiamr_condition', true);

        if ('' !== $legacy_condition && 'no_rule' !== $legacy_condition) {
            return true;
        }

        $pro_enabled = get_post_meta($item_id, '_tiamr_pro_enabled', true);
        $pro_action  = (string) get_post_meta($item_id, '_tiamr_pro_action', true);
        $pro_groups  = (string) get_post_meta($item_id, '_tiamr_pro_condition_groups', true);

        return !empty($pro_enabled) && in_array($pro_action, ['show', 'hide'], true) && '' !== $pro_groups && '[]' !== $pro_groups;
    }

    private function is_menu_assigned_to_location(int $menu_id): bool {
        $locations = get_nav_menu_locations();

        if (empty($locations) || !is_array($locations)) {
            return false;
        }

        return in_array($menu_id, array_map('absint', $locations), true);
    }

    private function active_theme_has_classic_menu_locations(): bool {
        $locations = get_registered_nav_menus();

        return !empty($locations) || current_theme_supports('menus');
    }

    private function render_no_classic_menu_locations_notice(): void {
        if (!$this->show_menu_location_warnings()) {
            return;
        }

        if ($this->active_theme_has_classic_menu_locations()) {
            return;
        }

        ?>
        <div class="notice notice-warning inline amr-settings-theme-warning">
            <p>
                <strong><?php esc_html_e('No classic menu locations found for the active theme.', 'titanium-advanced-menu-rules'); ?></strong>
                <?php esc_html_e('This usually means the theme uses the WordPress Site Editor and Navigation blocks instead of Appearance → Menus. Rules added to classic menu items may not affect the visible frontend navigation unless that menu is actually used by the theme.', 'titanium-advanced-menu-rules'); ?>
            </p>
        </div>
        <?php
    }


    private function should_show_menu_location_warning_for_menu(int $menu_id): bool {
        if ($menu_id <= 0) {
            return false;
        }

        if (!$this->menu_has_advanced_rules($menu_id)) {
            return false;
        }

        return !$this->is_menu_assigned_to_location($menu_id);
    }

    private function get_unassigned_rule_menus(): array {
        $menus = wp_get_nav_menus();
        $unassigned = [];

        if (empty($menus) || !is_array($menus)) {
            return $unassigned;
        }

        foreach ($menus as $menu) {
            if (!$menu instanceof \WP_Term) {
                continue;
            }

            $menu_id = absint($menu->term_id);

            if ($this->should_show_menu_location_warning_for_menu($menu_id)) {
                $unassigned[] = [
                    'id'   => $menu_id,
                    'name' => $menu->name,
                    'url'  => admin_url('nav-menus.php?action=edit&menu=' . $menu_id),
                ];
            }
        }

        return $unassigned;
    }


    private function get_mobile_like_menu_locations(): array {
        $locations = get_registered_nav_menus();
        $mobile_locations = [];

        if (empty($locations) || !is_array($locations)) {
            return $mobile_locations;
        }

        foreach ($locations as $slug => $label) {
            $haystack = strtolower((string) $slug . ' ' . (string) $label);

            if (
                false !== strpos($haystack, 'mobile') ||
                false !== strpos($haystack, 'offcanvas') ||
                false !== strpos($haystack, 'off-canvas') ||
                false !== strpos($haystack, 'drawer') ||
                false !== strpos($haystack, 'tablet') ||
                false !== strpos($haystack, 'responsive')
            ) {
                $mobile_locations[(string) $slug] = (string) $label;
            }
        }

        return $mobile_locations;
    }

    private function get_desktop_like_menu_locations(): array {
        $locations = get_registered_nav_menus();
        $desktop_locations = [];

        if (empty($locations) || !is_array($locations)) {
            return $desktop_locations;
        }

        foreach ($locations as $slug => $label) {
            $haystack = strtolower((string) $slug . ' ' . (string) $label);

            if (
                false !== strpos($haystack, 'header') ||
                false !== strpos($haystack, 'primary') ||
                false !== strpos($haystack, 'main') ||
                false !== strpos($haystack, 'top') ||
                false !== strpos($haystack, 'desktop')
            ) {
                $desktop_locations[(string) $slug] = (string) $label;
            }
        }

        return $desktop_locations;
    }


    private function get_footer_like_menu_locations(): array {
        $locations = get_registered_nav_menus();
        $footer_locations = [];

        if (empty($locations) || !is_array($locations)) {
            return $footer_locations;
        }

        foreach ($locations as $slug => $label) {
            $haystack = strtolower((string) $slug . ' ' . (string) $label);

            if (
                false !== strpos($haystack, 'footer') ||
                false !== strpos($haystack, 'bottom') ||
                false !== strpos($haystack, 'legal') ||
                false !== strpos($haystack, 'copyright')
            ) {
                $footer_locations[(string) $slug] = (string) $label;
            }
        }

        return $footer_locations;
    }

    private function get_menu_assigned_location_slugs(int $menu_id): array {
        $locations = get_nav_menu_locations();
        $assigned = [];

        if (empty($locations) || !is_array($locations)) {
            return $assigned;
        }

        foreach ($locations as $slug => $assigned_menu_id) {
            if (absint($assigned_menu_id) === $menu_id) {
                $assigned[] = (string) $slug;
            }
        }

        return $assigned;
    }

    private function should_show_mobile_menu_location_note(int $menu_id): bool {
        if ($menu_id <= 0) {
            return false;
        }

        if (!$this->menu_has_advanced_rules($menu_id)) {
            return false;
        }

        if (!$this->is_menu_assigned_to_location($menu_id)) {
            return false;
        }

        return !empty($this->get_missing_related_menu_locations($menu_id));
    }

    private function get_missing_related_menu_locations(int $menu_id): array {
        $assigned_slugs = $this->get_menu_assigned_location_slugs($menu_id);
        $missing = [];

        if (empty($assigned_slugs)) {
            return $missing;
        }

        $mobile_locations = $this->get_mobile_like_menu_locations();
        $desktop_locations = $this->get_desktop_like_menu_locations();
        $footer_locations = $this->get_footer_like_menu_locations();

        $assigned_mobile = !empty(array_intersect(array_keys($mobile_locations), $assigned_slugs));
        $assigned_desktop = !empty(array_intersect(array_keys($desktop_locations), $assigned_slugs));
        $assigned_footer = !empty(array_intersect(array_keys($footer_locations), $assigned_slugs));

        /*
         * Footer-only menus are valid, but they usually do not control the main
         * header/mobile navigation. Show a light diagnostic note so users do not
         * expect header rules to work from a footer-only assignment.
         */
        if ($assigned_footer && !$assigned_mobile && !$assigned_desktop) {
            $missing['main_navigation'] = array_merge($desktop_locations, $mobile_locations);
            return $missing;
        }

        /*
         * Footer + Mobile is common and should not imply that a desktop Header
         * location must also use this same menu.
         */
        if ($assigned_footer && $assigned_mobile && !$assigned_desktop) {
            return $missing;
        }

        if ($assigned_desktop && !empty($mobile_locations) && !$assigned_mobile) {
            $missing['mobile'] = $mobile_locations;
        }

        if ($assigned_mobile && !empty($desktop_locations) && !$assigned_desktop) {
            $missing['desktop'] = $desktop_locations;
        }

        return $missing;
    }

    private function render_mobile_menu_location_note(int $menu_id): void {
        if (!$this->show_menu_location_warnings()) {
            return;
        }

        $missing_locations = $this->get_missing_related_menu_locations($menu_id);

        if (empty($missing_locations)) {
            return;
        }

        $location_names = [];

        foreach ($missing_locations as $locations) {
            foreach ($locations as $label) {
                $location_names[] = (string) $label;
            }
        }

        $location_names = array_values(array_unique($location_names));
        $is_footer_only = isset($missing_locations['main_navigation']);
        ?>
        <div class="notice notice-info amr-menu-location-warning amr-menu-location-warning--info">
            <p>
                <strong><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules menu location note:', 'titanium-advanced-menu-rules'); ?></strong>
                <?php if ($is_footer_only) : ?>
                    <?php esc_html_e('This menu has visibility rules, but it is assigned only to a footer-style location. That is fine for footer navigation, but it will not affect header or mobile navigation if your theme displays a different menu there.', 'titanium-advanced-menu-rules'); ?>
                <?php else : ?>
                    <?php esc_html_e('This menu has visibility rules and is assigned to at least one location, but the active theme also has other main/mobile menu locations that are not using this menu. If those locations display a different menu, add the same rules there too or assign this menu to those locations.', 'titanium-advanced-menu-rules'); ?>
                <?php endif; ?>
            </p>
            <?php if (!empty($location_names)) : ?>
                <p class="description">
                    <?php echo esc_html(sprintf(
                        /* translators: %s: comma-separated menu location names. */
                        __('Other related locations found: %s', 'titanium-advanced-menu-rules'),
                        implode(', ', $location_names)
                    )); ?>
                </p>
            <?php endif; ?>
        </div>
        <?php
    }


    private function get_assigned_rule_menus_with_location_notes(): array {
        $menus = wp_get_nav_menus();
        $items = [];

        if (empty($menus) || !is_array($menus)) {
            return $items;
        }

        foreach ($menus as $menu) {
            if (!$menu instanceof \WP_Term) {
                continue;
            }

            $menu_id = absint($menu->term_id);

            if ($menu_id <= 0 || !$this->menu_has_advanced_rules($menu_id)) {
                continue;
            }

            if (!$this->is_menu_assigned_to_location($menu_id)) {
                continue;
            }

            $missing_locations = $this->get_missing_related_menu_locations($menu_id);

            if (empty($missing_locations)) {
                continue;
            }

            $location_names = [];

            foreach ($missing_locations as $locations) {
                foreach ($locations as $label) {
                    $location_names[] = (string) $label;
                }
            }

            $items[] = [
                'id'             => $menu_id,
                'name'           => $menu->name,
                'url'            => admin_url('nav-menus.php?action=edit&menu=' . $menu_id),
                'is_footer_only' => isset($missing_locations['main_navigation']),
                'locations'      => array_values(array_unique($location_names)),
            ];
        }

        return $items;
    }

    private function render_assigned_rule_menus_with_location_notes_notice(): void {
        if (!$this->show_menu_location_warnings()) {
            return;
        }

        if (!$this->active_theme_has_classic_menu_locations()) {
            return;
        }

        $menus = $this->get_assigned_rule_menus_with_location_notes();

        if (empty($menus)) {
            return;
        }

        ?>
        <div class="notice notice-info inline amr-settings-theme-warning amr-settings-theme-warning--info">
            <p>
                <strong><?php esc_html_e('Some menus with visibility rules may need attention.', 'titanium-advanced-menu-rules'); ?></strong>
                <?php esc_html_e('These menus are assigned to at least one location, but another related header/mobile location may use a different menu, or the menu is assigned only to a footer-style location.', 'titanium-advanced-menu-rules'); ?>
            </p>
            <ul class="amr-settings-warning-list">
                <?php foreach ($menus as $menu) : ?>
                    <li>
                        <a href="<?php echo esc_url($menu['url']); ?>">
                            <?php echo esc_html($menu['name']); ?>
                        </a>
                        <?php if ($menu['is_footer_only']) : ?>
                            <span><?php esc_html_e('— footer-only assignment', 'titanium-advanced-menu-rules'); ?></span>
                        <?php elseif (!empty($menu['locations'])) : ?>
                            <span>
                                <?php echo esc_html(sprintf(
                                    /* translators: %s: comma-separated menu location names. */
                                    __('— related locations: %s', 'titanium-advanced-menu-rules'),
                                    implode(', ', $menu['locations'])
                                )); ?>
                            </span>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php
    }

    private function render_unassigned_rule_menus_notice(): void {
        if (!$this->show_menu_location_warnings()) {
            return;
        }

        if (!$this->active_theme_has_classic_menu_locations()) {
            return;
        }

        $menus = $this->get_unassigned_rule_menus();

        if (empty($menus)) {
            return;
        }

        ?>
        <div class="notice notice-warning inline amr-settings-theme-warning">
            <p>
                <strong><?php esc_html_e('Menus with visibility rules are not assigned to any menu location.', 'titanium-advanced-menu-rules'); ?></strong>
                <?php esc_html_e('These rules may not affect the frontend if your theme displays another fallback menu.', 'titanium-advanced-menu-rules'); ?>
            </p>
            <ul class="amr-settings-warning-list">
                <?php foreach ($menus as $menu) : ?>
                    <li>
                        <a href="<?php echo esc_url($menu['url']); ?>">
                            <?php echo esc_html($menu['name']); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php
    }

    public function maybe_render_nav_menu_roles_active_warning(): void {
        if (!current_user_can('edit_theme_options')) {
            return;
        }

        if (!get_option(self::OPTION_IMPORT_COMPLETED, false)) {
            return;
        }

        if (!$this->is_advanced_menu_rules_screen()) {
            return;
        }

        $source_name = '';

        if ($this->is_nav_menu_roles_active()) {
            $source_name = __('Nav Menu Roles', 'titanium-advanced-menu-rules');
        } elseif ($this->is_user_menus_active()) {
            $source_name = __('User Menus', 'titanium-advanced-menu-rules');
        }

        if ('' === $source_name) {
            return;
        }
        ?>
        <div class="notice notice-error amr-nmr-active-warning">
            <h2>
                <?php
                printf(
                    /* translators: %s: source plugin name */
                    esc_html__('%s is still active', 'titanium-advanced-menu-rules'),
                    esc_html($source_name)
                );
                ?>
            </h2>
            <p>
                <?php
                printf(
                    /* translators: %s: source plugin name */
                    esc_html__('After importing your old menu rules, deactivate %s to avoid duplicate or conflicting menu filtering.', 'titanium-advanced-menu-rules'),
                    esc_html($source_name)
                );
                ?>
            </p>
            <p>
                <a class="button button-primary" href="<?php echo esc_url(admin_url('plugins.php')); ?>">
                    <?php esc_html_e('Open Plugins', 'titanium-advanced-menu-rules'); ?>
                </a>
                <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=' . self::PAGE_SETTINGS . '&tab=import')); ?>">
                    <?php esc_html_e('Open Import', 'titanium-advanced-menu-rules'); ?>
                </a>
            </p>
        </div>
        <?php
    }

    public function maybe_render_import_available_notice(): void {
        if (!current_user_can('edit_theme_options')) {
            return;
        }

        if (get_option(self::OPTION_IMPORT_NOTICE_DISMISSED, false)) {
            return;
        }

        $current_page = '';

        if (isset($_GET['page'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin notice display only.
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin notice display only; value is unslashed and sanitized.
            $current_page = sanitize_key(wp_unslash($_GET['page']));
        }

        if (self::PAGE_SETTINGS === $current_page) {
            return;
        }

        $nav_menu_roles_stats = $this->get_nav_menu_roles_importer()->get_stats();
        $user_menus_stats     = $this->get_user_menus_importer()->get_stats();

        $found = 0;
        $importable = 0;
        $existing = 0;
        $unsupported = 0;

        if ($this->is_nav_menu_roles_active()) {
            $found       += absint($nav_menu_roles_stats['found']);
            $importable  += absint($nav_menu_roles_stats['importable']);
            $existing    += absint($nav_menu_roles_stats['existing']);
            $unsupported += absint($nav_menu_roles_stats['unsupported']);
        }

        if ($this->is_user_menus_active()) {
            $found       += absint($user_menus_stats['found']);
            $importable  += absint($user_menus_stats['importable']);
            $existing    += absint($user_menus_stats['existing']);
            $unsupported += absint($user_menus_stats['unsupported']);
        }

        if ($found < 1) {
            return;
        }

        $import_url = admin_url('admin.php?page=' . self::PAGE_SETTINGS . '&tab=import&tiamr_import_detected=1');
        $dismiss_url = wp_nonce_url(
            admin_url('admin-post.php?action=tiamr_dismiss_import_notice'),
            'tiamr_dismiss_import_notice'
        );
        ?>
        <div class="notice notice-info amr-import-notice">
            <h2><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules found importable menu visibility settings.', 'titanium-advanced-menu-rules'); ?></h2>
            <p>
                <?php esc_html_e('Compatible menu visibility data was found on this site. You can review it and import compatible menu-item rules into Titanium Nav Menu Roles & Visibility Rules.', 'titanium-advanced-menu-rules'); ?>
            </p>
            <p>
                <strong>
                    <?php
                    printf(
                        /* translators: 1: found count, 2: importable count, 3: existing count, 4: unsupported count */
                        esc_html__('Found: %1$d menu items. Importable: %2$d. Already using Titanium Nav Menu Roles & Visibility Rules: %3$d. Empty or unsupported: %4$d.', 'titanium-advanced-menu-rules'),
                        absint($found),
                        absint($importable),
                        absint($existing),
                        absint($unsupported)
                    );
                    ?>
                </strong>
            </p>
            <p>
                <a class="button button-primary" href="<?php echo esc_url($import_url); ?>">
                    <?php esc_html_e('Review Import', 'titanium-advanced-menu-rules'); ?>
                </a>
                <a class="button" href="<?php echo esc_url($dismiss_url); ?>">
                    <?php esc_html_e('Not now', 'titanium-advanced-menu-rules'); ?>
                </a>
            </p>
        </div>
        <?php
    }

    public function add_plugin_action_links(array $links): array {
        $settings_link = sprintf(
            '<a href="%s">%s</a>',
            esc_url(admin_url('admin.php?page=' . self::PAGE_DASHBOARD)),
            esc_html__('Settings', 'titanium-advanced-menu-rules')
        );

        if ($this->is_pro_active()) {
            array_unshift($links, $settings_link);
            return $links;
        }

        $pro_link = sprintf(
            '<a href="%s" style="color:#00a32a;font-weight:700;">%s</a>',
            esc_url(admin_url('admin.php?page=' . self::PAGE_PRO)),
            esc_html__('Upgrade to Pro', 'titanium-advanced-menu-rules')
        );

        array_unshift($links, $settings_link, $pro_link);

        return $links;
    }

    public function render_dashboard_page(): void {
        if (!current_user_can('edit_theme_options')) {
            return;
        }

        if ($this->is_pro_active()) {
            $this->render_pro_active_dashboard();
            return;
        }
        ?>
        <div class="wrap amr-admin-page amr-modern-dashboard">
            <h1><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules', 'titanium-advanced-menu-rules'); ?></h1>

            <?php $this->render_nav_menu_roles_import_notice(); ?>

            <div class="amr-modern-hero amr-modern-hero--free">
                <div class="amr-modern-hero-content">
                    <span class="amr-dashboard-kicker"><?php esc_html_e('Free version active', 'titanium-advanced-menu-rules'); ?></span>
                    <h2><?php esc_html_e('Server-side menu visibility without hidden links left behind.', 'titanium-advanced-menu-rules'); ?></h2>
                    <p><?php esc_html_e('Control classic WordPress menu items by login state, WordPress role, page, and post rules. Hidden items are removed before the menu HTML is printed.', 'titanium-advanced-menu-rules'); ?></p>
                    <div class="amr-dashboard-actions">
                        <?php if (current_theme_supports('menus') || !empty(get_registered_nav_menus())) : ?>
                            <a class="button button-primary button-hero" href="<?php echo esc_url(admin_url('nav-menus.php')); ?>">
                                <?php esc_html_e('Edit Menu Rules', 'titanium-advanced-menu-rules'); ?>
                            </a>
                        <?php endif; ?>

                        <?php if (!$this->is_pro_active()) : ?>
                            <a class="button button-hero amr-upgrade-button" href="<?php echo esc_url(admin_url('admin.php?page=' . self::PAGE_PRO)); ?>">
                                <?php esc_html_e('View Pro pricing', 'titanium-advanced-menu-rules'); ?>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="amr-modern-hero-panel">
                    <strong><?php esc_html_e('FREE', 'titanium-advanced-menu-rules'); ?></strong>
                    <span><?php esc_html_e('Server-side filtering', 'titanium-advanced-menu-rules'); ?></span>
                </div>
            </div>

            <div class="amr-modern-grid">
                <div class="amr-modern-card">
                    <span class="amr-modern-icon">01</span>
                    <h3><?php esc_html_e('Audience rules', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Target everyone, logged-in users, logged-out users, or specific WordPress roles.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-modern-card">
                    <span class="amr-modern-icon">02</span>
                    <h3><?php esc_html_e('Location rules', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Limit menu items to selected pages or posts, or exclude them from selected content.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-modern-card">
                    <span class="amr-modern-icon">03</span>
                    <h3><?php esc_html_e('Clean HTML output', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Menu items are removed server-side instead of being left in the page and hidden with CSS.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
            </div>

            <div class="amr-upgrade-showcase">
                <div>
                    <span class="amr-dashboard-kicker amr-dashboard-kicker--pro"><?php esc_html_e('Pro features', 'titanium-advanced-menu-rules'); ?></span>
                    <h2><?php esc_html_e('Need more advanced menu logic?', 'titanium-advanced-menu-rules'); ?></h2>
                    <p><?php esc_html_e('Upgrade when menu items need multiple condition groups, membership-level checks, combined role logic, or optional linked page protection.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <a class="button button-primary button-hero amr-upgrade-button amr-upgrade-button--large" href="<?php echo esc_url(admin_url('admin.php?page=' . self::PAGE_PRO)); ?>">
                    <?php esc_html_e('View Pro Features', 'titanium-advanced-menu-rules'); ?>
                </a>
            </div>

            <div class="amr-pro-preview-grid">
                <div class="amr-pro-preview-card">
                    <span>01</span>
                    <h3><?php esc_html_e('Condition groups', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Use AND logic inside groups and OR logic between groups for flexible menu visibility.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-pro-preview-card">
                    <span>02</span>
                    <h3><?php esc_html_e('PMPro level rules', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Show or hide menu items by active Paid Memberships Pro membership levels.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-pro-preview-card">
                    <span>03</span>
                    <h3><?php esc_html_e('Role + membership logic', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Combine WordPress roles, membership levels, login status, pages, and posts in the same rule.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-pro-preview-card">
                    <span>04</span>
                    <h3><?php esc_html_e('Linked page protection', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Optionally protect linked WordPress pages/posts from direct URL access using the same menu rules.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
            </div>

            <div class="amr-modern-note">
                <h2><?php esc_html_e('Important note', 'titanium-advanced-menu-rules'); ?></h2>
                <p><?php esc_html_e('Free controls menu visibility only. Titanium Nav Menu Roles & Visibility Rules can optionally protect linked WordPress pages/posts from direct URL access.', 'titanium-advanced-menu-rules'); ?></p>
            </div>
        </div>
        <?php
    }

    private function render_pro_active_dashboard(): void {
        ?>
        <div class="wrap amr-admin-page amr-pro-active-page">
            <h1><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules', 'titanium-advanced-menu-rules'); ?></h1>

            <?php $this->render_nav_menu_roles_import_notice(); ?>

            <div class="amr-pro-active-hero">
                <div class="amr-pro-active-hero-content">
                    <span class="amr-dashboard-kicker"><?php esc_html_e('Pro is active', 'titanium-advanced-menu-rules'); ?></span>
                    <h2><?php esc_html_e('Advanced menu visibility is running.', 'titanium-advanced-menu-rules'); ?></h2>
                    <p><?php esc_html_e('Use Pro condition groups to combine WordPress roles, PMPro membership levels, login status, pages, and posts for individual menu items.', 'titanium-advanced-menu-rules'); ?></p>
                    <p class="amr-dashboard-actions">
                        <a class="button button-primary button-hero" href="<?php echo esc_url(admin_url('nav-menus.php')); ?>">
                            <?php esc_html_e('Edit Menu Rules', 'titanium-advanced-menu-rules'); ?>
                        </a>
                        <a class="button button-hero" href="<?php echo esc_url(admin_url('admin.php?page=titanium-advanced-menu-rules-settings')); ?>">
                            <?php esc_html_e('Pro Settings', 'titanium-advanced-menu-rules'); ?>
                        </a>
                    </p>
                </div>
                <div class="amr-pro-active-status">
                    <strong><?php esc_html_e('PRO', 'titanium-advanced-menu-rules'); ?></strong>
                    <span><?php esc_html_e('Active', 'titanium-advanced-menu-rules'); ?></span>
                </div>
            </div>

            <div class="amr-pro-active-grid">
                <div class="amr-pro-active-feature">
                    <span>01</span>
                    <h3><?php esc_html_e('Condition groups', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Create multiple Show and Hide conditions with AND logic inside groups and OR logic between groups.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-pro-active-feature">
                    <span>02</span>
                    <h3><?php esc_html_e('PMPro level rules', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Show or hide menu items for specific Paid Memberships Pro levels, with role checks in the same rule.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-pro-active-feature">
                    <span>03</span>
                    <h3><?php esc_html_e('Role + membership logic', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Combine WordPress roles, membership levels, login status, pages, and posts without rebuilding your menu.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-pro-active-feature">
                    <span>04</span>
                    <h3><?php esc_html_e('Linked page protection', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Optionally block direct URL access to linked WordPress pages/posts when the visitor cannot see the protected menu item.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <div class="amr-pro-active-feature">
                    <span>05</span>
                    <h3><?php esc_html_e('Server-side output', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('Hidden menu items are removed before menu HTML is printed, instead of only being hidden with CSS.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
            </div>
        </div>
        <?php
    }

    private function get_settings_tab(): string {
        $tab = isset($_GET['tab']) ? sanitize_key((string) $_GET['tab']) : 'settings'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $allowed_tabs = ['settings', 'import', 'more-plugins'];

        return in_array($tab, $allowed_tabs, true) ? $tab : 'settings';
    }

    private function render_settings_tabs(string $active_tab): void {
        $settings_url     = admin_url('admin.php?page=' . self::PAGE_DASHBOARD . '&tab=settings');
        $import_url       = admin_url('admin.php?page=' . self::PAGE_DASHBOARD . '&tab=import');
        $more_plugins_url = admin_url('admin.php?page=' . self::PAGE_DASHBOARD . '&tab=more-plugins');
        ?>
        <nav class="nav-tab-wrapper amr-settings-tabs" aria-label="<?php esc_attr_e('Titanium Nav Menu Roles & Visibility Rules settings sections', 'titanium-advanced-menu-rules'); ?>">
            <a class="nav-tab <?php echo 'settings' === $active_tab ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url($settings_url); ?>">
                <?php esc_html_e('Settings', 'titanium-advanced-menu-rules'); ?>
            </a>
            <a class="nav-tab <?php echo 'import' === $active_tab ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url($import_url); ?>">
                <?php esc_html_e('Import', 'titanium-advanced-menu-rules'); ?>
            </a>
            <a class="nav-tab <?php echo 'more-plugins' === $active_tab ? 'nav-tab-active' : ''; ?>" href="<?php echo esc_url($more_plugins_url); ?>">
                <?php esc_html_e('More Plugins', 'titanium-advanced-menu-rules'); ?>
            </a>
        </nav>
        <?php
    }

    public function render_settings_page(): void {
        if (!current_user_can('edit_theme_options')) {
            return;
        }

        $active_tab = $this->get_settings_tab();
        ?>
        <div class="wrap amr-admin-page">
            <h1 class="amr-wp-notice-anchor"><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules Settings', 'titanium-advanced-menu-rules'); ?></h1>

            <?php
            $this->render_nav_menu_roles_import_notice();
            $this->render_no_classic_menu_locations_notice();
            $this->render_unassigned_rule_menus_notice();
            $this->render_assigned_rule_menus_with_location_notes_notice();
            ?>

            <div class="amr-product-hero amr-product-hero--settings">
                <div class="amr-product-hero__content">
                    <span class="amr-product-hero__brand" aria-hidden="true">TITANIUM</span>
                    <div class="amr-product-hero__title" role="heading" aria-level="1"><?php esc_html_e('Nav Menu Roles & Visibility Rules', 'titanium-advanced-menu-rules'); ?></div>
                    <div class="amr-product-hero__version"><?php
                        /* translators: %s: plugin version number. */
                        printf(esc_html__('Version %s', 'titanium-advanced-menu-rules'), esc_html(TIAMR_VERSION));
                        ?></div>
                </div>
            </div>

            <?php
            $this->render_settings_tabs($active_tab);

            if ('import' === $active_tab) {
                $this->render_import_tab();
            } elseif ('more-plugins' === $active_tab) {
                (new More_Plugins_Page())->render();
            } else {
                $this->render_general_settings_tab();
            }
            ?>
        </div>
        <?php
    }

    private function render_general_settings_tab(): void {
        $delete_data   = (bool) get_option(self::OPTION_DELETE_DATA_ON_UNINSTALL, false);
        $show_warnings = $this->show_menu_location_warnings();
        ?>
        <div class="amr-settings-autosave" data-amr-autosave-settings>
            <div class="amr-admin-card amr-admin-card--wide">
                <h2><?php esc_html_e('Menu diagnostics', 'titanium-advanced-menu-rules'); ?></h2>

                <label class="amr-modern-toggle amr-modern-toggle--settings">
                    <input
                        type="checkbox"
                        data-amr-autosave-toggle
                        data-option="<?php echo esc_attr(self::OPTION_SHOW_MENU_LOCATION_WARNINGS); ?>"
                        value="1"
                        <?php checked($show_warnings); ?>
                    />
                    <span class="amr-modern-toggle__visual" aria-hidden="true"></span>
                    <span class="amr-modern-toggle__text">
                        <strong><?php esc_html_e('Show menu location warnings', 'titanium-advanced-menu-rules'); ?></strong>
                        <em><?php esc_html_e('Warn when a menu with visibility rules is not assigned to the expected theme location.', 'titanium-advanced-menu-rules'); ?></em>
                    </span>
                    <span class="amr-autosave-status" aria-live="polite"></span>
                </label>
            </div>

            <div class="amr-admin-card amr-admin-card--wide">
                <h2><?php esc_html_e('Beta updates', 'titanium-advanced-menu-rules'); ?></h2>

                <label class="amr-modern-toggle amr-modern-toggle--settings">
                    <input
                        type="checkbox"
                        data-amr-autosave-toggle
                        data-amr-beta-toggle
                        data-option="<?php echo esc_attr(self::OPTION_BETA_UPDATES); ?>"
                        value="1"
                        <?php checked($this->beta_updates_enabled()); ?>
                    />
                    <span class="amr-modern-toggle__visual" aria-hidden="true"></span>
                    <span class="amr-modern-toggle__text">
                        <strong><?php esc_html_e('Join the beta updates program', 'titanium-advanced-menu-rules'); ?></strong>
                        <em><?php esc_html_e('Receive beta update offers when beta builds are available. Use beta versions carefully on production sites.', 'titanium-advanced-menu-rules'); ?></em>
                    </span>
                    <span class="amr-autosave-status" aria-live="polite"></span>
                </label>
            </div>

            <div class="amr-admin-card amr-admin-card--wide">
                <h2><?php esc_html_e('Uninstall behaviour', 'titanium-advanced-menu-rules'); ?></h2>

                <label class="amr-modern-toggle amr-modern-toggle--settings">
                    <input
                        type="checkbox"
                        data-amr-autosave-toggle
                        data-option="<?php echo esc_attr(self::OPTION_DELETE_DATA_ON_UNINSTALL); ?>"
                        value="1"
                        <?php checked($delete_data); ?>
                    />
                    <span class="amr-modern-toggle__visual" aria-hidden="true"></span>
                    <span class="amr-modern-toggle__text">
                        <strong><?php esc_html_e('Delete plugin data on uninstall', 'titanium-advanced-menu-rules'); ?></strong>
                        <em><?php esc_html_e('Only deletes saved plugin data if the plugin is uninstalled.', 'titanium-advanced-menu-rules'); ?></em>
                    </span>
                    <span class="amr-autosave-status" aria-live="polite"></span>
                </label>
            </div>

            <?php do_action('tiamr/admin/settings_form_after_uninstall'); ?>

            <?php if (!$this->is_pro_active()) : ?>
                <?php $this->render_disabled_page_protection_preview(); ?>
            <?php endif; ?>
        </div>
        <?php
    }

    private function render_disabled_page_protection_preview(): void {
        ?>
        <div class="amr-protection-preview-card amr-protection-preview-card--locked amr-protection-preview-card--full">
            <div class="amr-protection-preview-card__content">
                <span class="amr-dashboard-kicker amr-dashboard-kicker--pro"><?php esc_html_e('Pro feature', 'titanium-advanced-menu-rules'); ?></span>
                <h2><?php esc_html_e('Linked Page Protection', 'titanium-advanced-menu-rules'); ?></h2>
                <p><?php esc_html_e('Pro can optionally protect linked WordPress pages and posts from direct URL access using the same menu item visibility rules.', 'titanium-advanced-menu-rules'); ?></p>

                <label class="amr-modern-toggle amr-modern-toggle--disabled">
                    <input type="checkbox" disabled="disabled" />
                    <span class="amr-modern-toggle__visual" aria-hidden="true"></span>
                    <span class="amr-modern-toggle__text">
                        <strong><?php esc_html_e('Protect linked content globally', 'titanium-advanced-menu-rules'); ?></strong>
                        <em><?php esc_html_e('Available in Titanium Nav Menu Roles & Visibility Rules.', 'titanium-advanced-menu-rules'); ?></em>
                    </span>
                </label>

                <label class="amr-modern-toggle amr-modern-toggle--disabled">
                    <input type="checkbox" disabled="disabled" />
                    <span class="amr-modern-toggle__visual" aria-hidden="true"></span>
                    <span class="amr-modern-toggle__text">
                        <strong><?php esc_html_e("Don't protect linked content for Administrators", 'titanium-advanced-menu-rules'); ?></strong>
                        <em><?php esc_html_e('Available in Titanium Nav Menu Roles & Visibility Rules Pro.', 'titanium-advanced-menu-rules'); ?></em>
                    </span>
                </label>

                <div class="amr-disabled-choice-section">
                    <div class="amr-disabled-choice-section-header">
                        <span class="amr-disabled-choice-section-icon">↔</span>
                        <div>
                            <h4><?php esc_html_e('Compatibility & safe bypasses', 'titanium-advanced-menu-rules'); ?></h4>
                            <p><?php esc_html_e('Pro can skip membership plugin system pages, run after other redirects, and ignore custom excluded paths.', 'titanium-advanced-menu-rules'); ?></p>
                        </div>
                    </div>

                    <label class="amr-modern-toggle amr-modern-toggle--disabled">
                        <input type="checkbox" disabled="disabled" />
                        <span class="amr-modern-toggle__visual" aria-hidden="true"></span>
                        <span class="amr-modern-toggle__text">
                            <strong><?php esc_html_e('Do not run on membership plugin system pages', 'titanium-advanced-menu-rules'); ?></strong>
                            <em><?php esc_html_e('Supports Paid Memberships Pro, MemberPress, WooCommerce Memberships, Restrict Content Pro, and Paid Member Subscriptions.', 'titanium-advanced-menu-rules'); ?></em>
                        </span>
                    </label>

                    <label class="amr-modern-toggle amr-modern-toggle--disabled">
                        <input type="checkbox" disabled="disabled" />
                        <span class="amr-modern-toggle__visual" aria-hidden="true"></span>
                        <span class="amr-modern-toggle__text">
                            <strong><?php esc_html_e('Let other redirects run first', 'titanium-advanced-menu-rules'); ?></strong>
                            <em><?php esc_html_e('Lets membership plugins, security plugins, and custom redirect snippets handle their own redirects before Linked Page Protection.', 'titanium-advanced-menu-rules'); ?></em>
                        </span>
                    </label>

                    <label>
                        <strong><?php esc_html_e('Excluded paths', 'titanium-advanced-menu-rules'); ?></strong>
                        <textarea class="amr-disabled-textarea-preview" disabled="disabled" readonly="readonly">/account/&#10;/signin/&#10;/register/&#10;/membership-account/</textarea>
                    </label>
                </div>

                <div class="amr-disabled-pro-flow" aria-hidden="true">
                    <div class="amr-disabled-choice-section">
                        <div class="amr-disabled-choice-section-header">
                            <span class="amr-disabled-choice-section-icon">→</span>
                            <div>
                                <h4><?php esc_html_e('Choose denied access action', 'titanium-advanced-menu-rules'); ?></h4>
                                <p><?php esc_html_e('Select what should happen when protected content is opened directly.', 'titanium-advanced-menu-rules'); ?></p>
                            </div>
                        </div>
                        <div class="amr-disabled-choice-options amr-disabled-choice-options--three">
                            <span class="amr-disabled-choice-option"><span class="amr-disabled-choice-check"></span><span><strong><?php esc_html_e('Show 404 page', 'titanium-advanced-menu-rules'); ?></strong><em><?php esc_html_e('Hide protected content behind a 404 response.', 'titanium-advanced-menu-rules'); ?></em></span></span>
                            <span class="amr-disabled-choice-option"><span class="amr-disabled-choice-check"></span><span><strong><?php esc_html_e('Redirect to homepage', 'titanium-advanced-menu-rules'); ?></strong><em><?php esc_html_e('Send denied visitors to the site homepage.', 'titanium-advanced-menu-rules'); ?></em></span></span>
                            <span class="amr-disabled-choice-option"><span class="amr-disabled-choice-check"></span><span><strong><?php esc_html_e('Redirect to selected page', 'titanium-advanced-menu-rules'); ?></strong><em><?php esc_html_e('Send denied visitors to a page you choose.', 'titanium-advanced-menu-rules'); ?></em></span></span>
                        </div>
                    </div>

                    <div class="amr-disabled-choice-section">
                        <div class="amr-disabled-choice-section-header">
                            <span class="amr-disabled-choice-section-icon">404</span>
                            <div>
                                <h4><?php esc_html_e('404 page source', 'titanium-advanced-menu-rules'); ?></h4>
                                <p><?php esc_html_e('Choose the plugin built-in 404 page or the site/theme 404 page.', 'titanium-advanced-menu-rules'); ?></p>
                            </div>
                        </div>
                        <div class="amr-disabled-choice-options amr-disabled-choice-options--two">
                            <span class="amr-disabled-choice-option"><span class="amr-disabled-choice-check"></span><span><strong><?php esc_html_e('Use plugin built-in 404 page', 'titanium-advanced-menu-rules'); ?></strong><em><?php esc_html_e('Best if your theme only shows a basic “page not found” screen.', 'titanium-advanced-menu-rules'); ?></em></span></span>
                            <span class="amr-disabled-choice-option"><span class="amr-disabled-choice-check"></span><span><strong><?php esc_html_e('Use site/theme 404 page', 'titanium-advanced-menu-rules'); ?></strong><em><?php esc_html_e('Best if your site already has a custom 404 page.', 'titanium-advanced-menu-rules'); ?></em></span></span>
                        </div>
                    </div>

                    <div class="amr-disabled-choice-section">
                        <div class="amr-disabled-choice-section-header">
                            <span class="amr-disabled-choice-section-icon">↪</span>
                            <div>
                                <h4><?php esc_html_e('Selected page redirect', 'titanium-advanced-menu-rules'); ?></h4>
                                <p><?php esc_html_e('Select a page to use when Redirect to selected page is chosen.', 'titanium-advanced-menu-rules'); ?></p>
                            </div>
                        </div>
                        <div class="amr-disabled-select-preview"><?php esc_html_e('Select a page', 'titanium-advanced-menu-rules'); ?></div>
                    </div>
                </div>

                <a class="button button-primary amr-upgrade-button" href="<?php echo esc_url(admin_url('admin.php?page=' . self::PAGE_PRO)); ?>">
                    <?php esc_html_e('Upgrade to Pro', 'titanium-advanced-menu-rules'); ?>
                </a>
            </div>
        </div>
        <?php
    }

    private function render_import_tab(): void {
        $nav_menu_roles_active = $this->is_nav_menu_roles_active();
        $user_menus_active     = $this->is_user_menus_active();
        ?>
        <div class="amr-admin-card amr-admin-card--wide amr-import-card">
            <h2><?php esc_html_e('Import menu visibility rules', 'titanium-advanced-menu-rules'); ?></h2>
            <p>
                <?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules can import compatible settings from supported menu visibility plugins. Imported rules are matched by the original WordPress menu item ID, so duplicate menu item names are not a problem.', 'titanium-advanced-menu-rules'); ?>
            </p>

            <?php if (!$nav_menu_roles_active && !$user_menus_active) : ?>
                <div class="amr-empty-import amr-empty-import--active-source">
                    <h3><?php esc_html_e('No active supported plugin found', 'titanium-advanced-menu-rules'); ?></h3>
                    <p><?php esc_html_e('There is no active supported menu visibility plugin to import from right now.', 'titanium-advanced-menu-rules'); ?></p>
                    <p class="description">
                        <?php esc_html_e('Currently supported importers: Nav Menu Roles and User Menus. Activate the old plugin first if you still need to import its menu settings.', 'titanium-advanced-menu-rules'); ?>
                    </p>
                </div>
            <?php else : ?>
                <?php if (!empty($_GET['tiamr_import_detected'])) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
                    <?php $this->render_activation_import_review_box($this->get_active_import_sources(true)); ?>
                <?php endif; ?>

                <?php
                if ($nav_menu_roles_active) {
                    $this->render_nav_menu_roles_import_source();
                }

                if ($user_menus_active) {
                    $this->render_user_menus_import_source();
                }
                ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * @param array<int,array{name:string,slug:string,stats:array}> $sources
     */
    private function render_activation_import_review_box(array $sources): void {
        if (empty($sources)) {
            return;
        }

        $source_names = wp_list_pluck($sources, 'name');
        $source_label = implode(', ', array_map('wp_strip_all_tags', $source_names));
        ?>
        <div class="amr-import-hero amr-import-hero--activation">
            <span class="amr-import-hero-badge"><?php esc_html_e('Active plugin settings found', 'titanium-advanced-menu-rules'); ?></span>
            <h2><?php esc_html_e('We found settings from an active plugin', 'titanium-advanced-menu-rules'); ?></h2>
            <p>
                <?php
                printf(
                    /* translators: %s: source plugin name(s) */
                    esc_html__('Titanium Nav Menu Roles & Visibility Rules found menu visibility settings from %s, which is currently active on this website.', 'titanium-advanced-menu-rules'),
                    esc_html($source_label)
                );
                ?>
            </p>
            <p><?php esc_html_e('You can import these settings now and continue managing your menu visibility rules with Titanium Nav Menu Roles & Visibility Rules.', 'titanium-advanced-menu-rules'); ?></p>
            <p><?php esc_html_e('Please keep the source plugin active until the import has finished. After importing, review your menu items to make sure everything was imported correctly. Once you have confirmed the imported rules are working as expected, you can deactivate the old plugin. Before deleting it, we strongly recommend checking that all important menu items are configured correctly.', 'titanium-advanced-menu-rules'); ?></p>
            <p><?php esc_html_e('In some cases, a few menu items may need to be reviewed or adjusted manually after import.', 'titanium-advanced-menu-rules'); ?></p>

            <div class="amr-import-hero-actions">
                <a class="button button-primary" href="#amr-import-sources"><?php esc_html_e('Review import options', 'titanium-advanced-menu-rules'); ?></a>
                <?php $this->render_skip_import_button($source_label); ?>
            </div>
        </div>
        <div id="amr-import-sources"></div>
        <?php
    }

    private function render_skip_import_button(string $source_label): void {
        ?>
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="amr-skip-import-form" data-source-name="<?php echo esc_attr($source_label); ?>">
            <?php wp_nonce_field('tiamr_dismiss_import_notice'); ?>
            <input type="hidden" name="action" value="tiamr_dismiss_import_notice" />
            <input type="hidden" name="tiamr_skip_import" value="1" />
            <button type="submit" class="button amr-skip-import-button"><?php esc_html_e('Skip import', 'titanium-advanced-menu-rules'); ?></button>
        </form>
        <?php
    }

    private function render_nav_menu_roles_import_source(): void {
        $importer         = $this->get_nav_menu_roles_importer();
        $importer_stats   = $importer->get_stats();
        $has_data         = $importer_stats['found'] > 0;
        $can_import       = $importer_stats['importable'] > 0;
        $import_completed = (bool) get_option(self::OPTION_IMPORT_COMPLETED, false);
        ?>

        <?php if (!$has_data) : ?>
            <div class="amr-empty-import">
                <h3><?php esc_html_e('Nav Menu Roles is active, but no compatible menu settings were found', 'titanium-advanced-menu-rules'); ?></h3>
                <p><?php esc_html_e('No Nav Menu Roles menu-item settings are available to import on this site.', 'titanium-advanced-menu-rules'); ?></p>
            </div>
        <?php else : ?>
            <div class="amr-import-source-card">
                <div class="amr-import-source-header">
                    <div>
                        <span class="amr-import-source-label"><?php esc_html_e('Detected plugin data', 'titanium-advanced-menu-rules'); ?></span>
                        <h3><?php esc_html_e('Nav Menu Roles', 'titanium-advanced-menu-rules'); ?></h3>
                    </div>
                </div>

                <?php $this->render_import_stats($importer_stats, __('Nav Menu Roles items found', 'titanium-advanced-menu-rules')); ?>

                <p class="description">
                    <?php esc_html_e('Keep Nav Menu Roles active until the import has completed. After importing, review your menu items before deactivating or deleting the old plugin.', 'titanium-advanced-menu-rules'); ?>
                </p>

                <?php if ($can_import) : ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="amr-import-form">
                        <?php wp_nonce_field('tiamr_import_nav_menu_roles'); ?>
                        <input type="hidden" name="action" value="tiamr_import_nav_menu_roles" />

                        <?php $this->render_import_replace_warning($importer_stats, __('Nav Menu Roles', 'titanium-advanced-menu-rules')); ?>

                        <?php
                        submit_button(
                            __('Import settings now', 'titanium-advanced-menu-rules'),
                            'primary',
                            'submit',
                            false
                        );
                        ?>
                    </form>
                <?php else : ?>
                    <div class="amr-empty-import">
                        <h3><?php esc_html_e('No compatible rules can be imported', 'titanium-advanced-menu-rules'); ?></h3>
                        <p><?php esc_html_e('Nav Menu Roles data was found, but the saved values are empty or not supported by the Titanium Nav Menu Roles & Visibility Rules Free importer.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($import_completed) : ?>
            <div class="notice notice-error amr-inline-error-card amr-import-after-card">
                <h2><?php esc_html_e('Import completed. Deactivate Nav Menu Roles now.', 'titanium-advanced-menu-rules'); ?></h2>
                <p><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules has imported the menu visibility settings. Please review your menu items and confirm the imported rules work as expected before deactivating Nav Menu Roles. Before deleting the old plugin, make sure all important menu items are configured correctly.', 'titanium-advanced-menu-rules'); ?></p>
                <p>
                    <a class="button button-primary" href="<?php echo esc_url(admin_url('plugins.php')); ?>">
                        <?php esc_html_e('Open Plugins', 'titanium-advanced-menu-rules'); ?>
                    </a>
                </p>
            </div>
        <?php endif; ?>
        <?php
    }

    private function render_user_menus_import_source(): void {
        $importer       = $this->get_user_menus_importer();
        $importer_stats = $importer->get_stats();
        $has_data       = $importer_stats['found'] > 0;
        $can_import     = $importer_stats['importable'] > 0;
        ?>

        <?php if (!$has_data) : ?>
            <div class="amr-empty-import">
                <h3><?php esc_html_e('User Menus is active, but no compatible menu settings were found', 'titanium-advanced-menu-rules'); ?></h3>
                <p><?php esc_html_e('No User Menus menu-item settings are available to import on this site.', 'titanium-advanced-menu-rules'); ?></p>
            </div>
        <?php else : ?>
            <div class="amr-import-source-card">
                <div class="amr-import-source-header">
                    <div>
                        <span class="amr-import-source-label"><?php esc_html_e('Detected plugin data', 'titanium-advanced-menu-rules'); ?></span>
                        <h3><?php esc_html_e('User Menus', 'titanium-advanced-menu-rules'); ?></h3>
                    </div>
                </div>

                <?php $this->render_import_stats($importer_stats, __('User Menus items found', 'titanium-advanced-menu-rules')); ?>

                <p class="description">
                    <?php esc_html_e('Keep User Menus active until the import has completed. After importing, review your menu items before deactivating or deleting the old plugin.', 'titanium-advanced-menu-rules'); ?>
                </p>

                <?php if ($can_import) : ?>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="amr-import-form">
                        <?php wp_nonce_field('tiamr_import_user_menus'); ?>
                        <input type="hidden" name="action" value="tiamr_import_user_menus" />

                        <?php $this->render_import_replace_warning($importer_stats, __('User Menus', 'titanium-advanced-menu-rules')); ?>

                        <?php
                        submit_button(
                            __('Import settings now', 'titanium-advanced-menu-rules'),
                            'primary',
                            'submit',
                            false
                        );
                        ?>
                    </form>
                <?php else : ?>
                    <div class="amr-empty-import">
                        <h3><?php esc_html_e('No compatible rules can be imported', 'titanium-advanced-menu-rules'); ?></h3>
                        <p><?php esc_html_e('User Menus data was found, but the saved values are empty or not supported by the Titanium Nav Menu Roles & Visibility Rules Free importer.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        <?php
    }

    private function render_import_stats(array $importer_stats, string $found_label): void {
        ?>
        <div class="amr-import-stats">
            <div class="amr-import-stat">
                <strong><?php echo esc_html((string) absint($importer_stats['found'])); ?></strong>
                <span><?php echo esc_html($found_label); ?></span>
            </div>
            <div class="amr-import-stat">
                <strong><?php echo esc_html((string) absint($importer_stats['importable'])); ?></strong>
                <span><?php esc_html_e('importable rules', 'titanium-advanced-menu-rules'); ?></span>
            </div>
            <div class="amr-import-stat">
                <strong><?php echo esc_html((string) absint($importer_stats['existing'])); ?></strong>
                <span><?php esc_html_e('already using Titanium Nav Menu Roles & Visibility Rules', 'titanium-advanced-menu-rules'); ?></span>
            </div>
            <div class="amr-import-stat amr-import-stat--warning">
                <strong><?php echo esc_html((string) absint($importer_stats['pro_existing'])); ?></strong>
                <span><?php esc_html_e('existing Pro rules found', 'titanium-advanced-menu-rules'); ?></span>
            </div>
            <div class="amr-import-stat">
                <strong><?php echo esc_html((string) absint($importer_stats['unsupported'])); ?></strong>
                <span><?php esc_html_e('empty or unsupported', 'titanium-advanced-menu-rules'); ?></span>
            </div>
        </div>
        <?php
    }

    private function render_import_replace_warning(array $importer_stats, string $source_name): void {
        if (empty($importer_stats['existing']) && empty($importer_stats['pro_existing'])) {
            return;
        }
        ?>
        <div class="amr-pro-import-warning">
            <h3><?php esc_html_e('Existing Titanium Nav Menu Roles & Visibility Rules settings were found', 'titanium-advanced-menu-rules'); ?></h3>
            <p>
                <?php
                printf(
                    /* translators: %s: source plugin name */
                    esc_html__('Some matching menu items already have Titanium Nav Menu Roles & Visibility Rules settings. Tick the checkbox below if you want the imported %s rules to replace those existing Free and Pro settings.', 'titanium-advanced-menu-rules'),
                    esc_html($source_name)
                );
                ?>
            </p>
            <label class="amr-admin-checkbox">
                <input type="checkbox" name="tiamr_replace_existing" value="1" />
                <span>
                    <?php
                    printf(
                        /* translators: %s: source plugin name */
                        esc_html__('Replace existing Free and Pro settings with the imported %s rules.', 'titanium-advanced-menu-rules'),
                        esc_html($source_name)
                    );
                    ?>
                </span>
            </label>
        </div>
        <?php
    }




    public function render_license_activation_page(): void {
        if (!current_user_can('activate_plugins')) {
            return;
        }

        check_admin_referer('tiamr_license_activation_page');

        $connected_account_url = $this->get_freemius_account_url_if_connected();

        if ('' !== $connected_account_url) {
            wp_safe_redirect($connected_account_url);
            exit;
        }

        $connect_url = $this->get_existing_license_connect_url();
        ?>
        <div class="wrap amr-admin-page amr-pro-page amr-pro-page--premium">
            <div class="amr-license-flow-hero">
                <div class="amr-license-flow-panel">
                    <span class="amr-section-eyebrow"><?php esc_html_e('Existing Pro license', 'titanium-advanced-menu-rules'); ?></span>
                    <h1><?php esc_html_e('Activate your Pro license', 'titanium-advanced-menu-rules'); ?></h1>
                    <p class="amr-license-flow-lead">
                        <?php esc_html_e('To activate a license you already purchased, Freemius needs to connect this website first. After the connection, the Account page should show the available license activation. If Freemius asks for email confirmation, complete that confirmation first.', 'titanium-advanced-menu-rules'); ?>
                    </p>

                    <div class="amr-license-flow-steps">
                        <div>
                            <strong><?php esc_html_e('1', 'titanium-advanced-menu-rules'); ?></strong>
                            <span><?php esc_html_e('Connect this website', 'titanium-advanced-menu-rules'); ?></span>
                        </div>
                        <div>
                            <strong><?php esc_html_e('2', 'titanium-advanced-menu-rules'); ?></strong>
                            <span><?php esc_html_e('Allow Freemius connection', 'titanium-advanced-menu-rules'); ?></span>
                        </div>
                        <div>
                            <strong><?php esc_html_e('3', 'titanium-advanced-menu-rules'); ?></strong>
                            <span><?php esc_html_e('Activate license from Account', 'titanium-advanced-menu-rules'); ?></span>
                        </div>
                    </div>

                    <div class="amr-license-flow-actions">
                        <a class="amr-upgrade-primary" href="<?php echo esc_url($connect_url); ?>">
                            <?php esc_html_e('Continue to Freemius', 'titanium-advanced-menu-rules'); ?>
                        </a>
                        <a class="amr-upgrade-secondary" href="<?php echo esc_url(admin_url('admin.php?page=' . self::PAGE_PRO)); ?>">
                            <?php esc_html_e('Back to Pricing', 'titanium-advanced-menu-rules'); ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }



    private function get_current_license_marker(): array {
        $marker = [
            'licenses' => '',
        ];

        if (!$this->is_pro_active()) {
            return $marker;
        }

        if (!function_exists('tiamr_fs')) {
            return $marker;
        }

        $fs = tiamr_fs();

        if (!is_object($fs) || !method_exists($fs, '_get_license')) {
            return $marker;
        }

        $license = $fs->_get_license();

        if (!is_object($license)) {
            return $marker;
        }

        if (method_exists($license, 'is_unlimited') && $license->is_unlimited()) {
            $marker['licenses'] = 'unlimited';
        } elseif (isset($license->quota)) {
            $quota = absint($license->quota);
            $marker['licenses'] = $quota > 0 ? (string) $quota : '';
        }

        return $marker;
    }

    public function ajax_get_freemius_pricing(): void {
        if (!current_user_can('edit_theme_options')) {
            wp_send_json_error([
                'message' => __('You do not have permission to view pricing.', 'titanium-advanced-menu-rules'),
            ], 403);
        }

        check_ajax_referer('tiamr_pricing_nonce', 'nonce');

        $no_cache = isset($_POST['no_cache']) && '1' === sanitize_text_field(wp_unslash($_POST['no_cache'])); // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $pricing  = $this->get_freemius_pricing_result($no_cache);
        $plans    = isset($pricing['plans']) && is_array($pricing['plans']) ? $pricing['plans'] : [];

        if (empty($plans)) {
            wp_send_json_error([
                'message' => __('Unable to load prices. Secure checkout will show the current price.', 'titanium-advanced-menu-rules'),
            ]);
        }

        wp_send_json_success([
            'plans'        => $plans,
            'pricesLoaded' => !empty($pricing['prices_loaded']),
            'proActive'    => $this->is_pro_active(),
        ]);
    }

    private function get_freemius_pricing_cards(bool $no_cache = false): array {
        $pricing = $this->get_freemius_pricing_result($no_cache);

        return isset($pricing['plans']) && is_array($pricing['plans']) ? $pricing['plans'] : [];
    }

    private function get_freemius_pricing_result(bool $no_cache = false): array {
        $public_data = $this->get_public_pricing_data($no_cache);

        if (!empty($public_data)) {
            $public_cards = $this->build_pricing_cards_from_public_response($public_data);

            if (!empty($public_cards)) {
                return [
                    'plans'         => $public_cards,
                    'prices_loaded' => true,
                ];
            }
        }

        return [
            'plans'         => $this->get_pricing_cards_without_prices(),
            'prices_loaded' => false,
        ];
    }

    private function get_public_pricing_endpoint_url(): string {
        return 'https://adminplugins.com/wp-json/amr-freemius/v1/pricing';
    }

    private function get_public_pricing_cache_key(): string {
        return 'tiamr_public_pricing_v4';
    }

    private function get_cached_public_pricing_data(): array {
        $cached = get_transient($this->get_public_pricing_cache_key());

        if (!is_array($cached) || empty($cached['pricing']) || !is_array($cached['pricing'])) {
            return [];
        }

        return $cached;
    }

    private function get_cached_pricing_cards(): array {
        $cached_data = $this->get_cached_public_pricing_data();

        if (empty($cached_data)) {
            return [];
        }

        $cards = $this->build_pricing_cards_from_public_response($cached_data);

        return !empty($cards) ? $cards : [];
    }

    private function get_public_pricing_data(bool $no_cache = false): array {
        $cache_key       = $this->get_public_pricing_cache_key();
        $error_cache_key = $cache_key . '_error';

        if ($no_cache) {
            delete_transient($cache_key);
            delete_transient($error_cache_key);
        }

        $cached = $no_cache ? false : get_transient($cache_key);

        if (is_array($cached) && !empty($cached['pricing']) && is_array($cached['pricing'])) {
            return $cached;
        }

        if (!$no_cache && get_transient($error_cache_key)) {
            return [];
        }

        $endpoint_url = $this->get_public_pricing_endpoint_url();

        if ($no_cache) {
            $endpoint_url = add_query_arg('no_cache', '1', $endpoint_url);
        }

        $response = wp_remote_get(
            $endpoint_url,
            [
                'timeout'     => 5,
                'redirection' => 3,
                'headers'     => [
                    'Accept'     => 'application/json',
                    'User-Agent' => 'Titanium-AMR-Plugin-Pricing/1.0',
                ],
            ]
        );

        if (is_wp_error($response)) {
            set_transient($error_cache_key, '1', 5 * MINUTE_IN_SECONDS);
            return [];
        }

        $status = (int) wp_remote_retrieve_response_code($response);

        if ($status < 200 || $status >= 300) {
            set_transient($error_cache_key, '1', 5 * MINUTE_IN_SECONDS);
            return [];
        }

        $data = json_decode(wp_remote_retrieve_body($response), true);

        if (!is_array($data) || empty($data['pricing']) || !is_array($data['pricing'])) {
            set_transient($error_cache_key, '1', 5 * MINUTE_IN_SECONDS);
            return [];
        }

        delete_transient($error_cache_key);
        set_transient($cache_key, $data, DAY_IN_SECONDS);

        return $data;
    }

    private function build_pricing_cards_from_public_response(array $data): array {
        $pricing = isset($data['pricing']) && is_array($data['pricing']) ? $data['pricing'] : [];
        $coupon  = isset($data['coupon']) && is_array($data['coupon']) ? $data['coupon'] : null;
        $cards   = [];

        foreach ($this->get_pricing_license_map() as $licenses => $pricing_id) {
            if (empty($pricing[$pricing_id]) || !is_array($pricing[$pricing_id])) {
                continue;
            }

            $item   = $pricing[$pricing_id];
            $amount = $item['annual_price'] ?? '';

            if ('' === $amount || !is_numeric($amount)) {
                continue;
            }

            $currency    = strtolower((string) ($item['currency'] ?? $data['currency'] ?? 'gbp'));
            $annual      = (float) $amount;
            $discounted  = $this->apply_coupon_discount($annual, $coupon);
            $has_coupon  = $this->has_public_coupon_discount($coupon) && $discounted < $annual;
            $coupon_code = $has_coupon ? $this->normalize_checkout_coupon_code(sanitize_text_field((string) ($coupon['code'] ?? ''))) : '';

            $cards[] = [
                'label'         => $this->format_license_label((string) $licenses),
                'license_label' => $this->format_license_pill((string) $licenses),
                'licenses'      => (string) $licenses,
                'price'         => $this->format_price($discounted, '' !== $currency ? $currency : 'gbp'),
                'regular_price' => $has_coupon ? $this->format_price($annual, '' !== $currency ? $currency : 'gbp') : '',
                'has_discount'  => $has_coupon,
                'term'          => $has_coupon ? 'first year' : '/ year',
                'discount_note' => $has_coupon ? $this->format_public_coupon_note($annual, $coupon, '' !== $currency ? $currency : 'gbp') : '',
                'coupon_code'   => $coupon_code,
                'pricing_id'    => (string) $pricing_id,
                'checkout'      => $this->is_pro_active()
                    ? $this->get_hosted_upgrade_url((string) $pricing_id, $coupon_code)
                    : $this->get_checkout_url((string) $licenses, (string) $pricing_id, $coupon_code),
            ];
        }

        return $cards;
    }

    private function get_pricing_license_map(): array {
        return [
            '1'         => '69061',
            '3'         => '69062',
            '5'         => '69063',
            '10'        => '69064',
            '20'        => '69065',
            'unlimited' => '69066',
        ];
    }

    private function get_pricing_cards_without_prices(): array {
        $cards = [];

        foreach ($this->get_pricing_license_map() as $licenses => $pricing_id) {
            $cards[] = [
                'label'         => $this->format_license_label((string) $licenses),
                'license_label' => $this->format_license_pill((string) $licenses),
                'licenses'      => (string) $licenses,
                'price'         => '',
                'regular_price' => '',
                'has_discount'  => false,
                'term'          => '',
                'discount_note' => '',
                'coupon_code'   => '',
                'pricing_id'    => (string) $pricing_id,
                'checkout'      => $this->is_pro_active()
                    ? $this->get_hosted_upgrade_url((string) $pricing_id)
                    : $this->get_checkout_url((string) $licenses, (string) $pricing_id),
            ];
        }

        return $cards;
    }

    private function pricing_license_rank(string $licenses): int {
        $licenses = strtolower(trim($licenses));

        if ('unlimited' === $licenses) {
            return 999999;
        }

        $value = absint($licenses);

        if ($value < 1) {
            return 0;
        }

        if ($value >= 20) {
            return 20;
        }

        if ($value >= 10) {
            return 10;
        }

        if ($value >= 5) {
            return 5;
        }

        if ($value >= 3) {
            return 3;
        }

        return 1;
    }

    private function render_pricing_placeholder_card(array $plan, string $button_text, array $current_license_marker): void {
        $plan_licenses    = isset($plan['licenses']) ? (string) $plan['licenses'] : '';
        $current_licenses = $this->is_pro_active() && isset($current_license_marker['licenses']) ? (string) $current_license_marker['licenses'] : '';
        $current_rank     = $this->pricing_license_rank($current_licenses);
        $plan_rank        = $this->pricing_license_rank($plan_licenses);
        $is_active        = $this->is_pro_active() && $current_rank > 0 && $plan_rank > 0 && $current_rank === $plan_rank;
        $is_lower_plan    = $this->is_pro_active() && $current_rank > 0 && $plan_rank > 0 && $plan_rank < $current_rank;
        $label            = isset($plan['label']) ? (string) $plan['label'] : '';
        $license_label    = isset($plan['license_label']) ? (string) $plan['license_label'] : $label . ' license';
        $checkout         = isset($plan['checkout']) ? (string) $plan['checkout'] : '#';
        $price            = isset($plan['price']) ? (string) $plan['price'] : '';
        $regular_price    = isset($plan['regular_price']) ? (string) $plan['regular_price'] : '';
        $term             = isset($plan['term']) && '' !== (string) $plan['term'] ? (string) $plan['term'] : __('/ year', 'titanium-advanced-menu-rules');
        $discount_note    = isset($plan['discount_note']) ? (string) $plan['discount_note'] : '';
        $has_price        = '' !== $price;
        $has_discount     = $has_price && !empty($plan['has_discount']);
        $price_status     = isset($plan['price_status']) ? (string) $plan['price_status'] : '';
        $is_error         = 'error' === $price_status;
        $is_loading       = !$has_price && !$is_error;
        $card_classes     = 'amr-pricing-card-premium';

        if ($is_loading) {
            $card_classes .= ' amr-pricing-card-premium--loading';
        }

        if ($is_active) {
            $card_classes .= ' amr-pricing-card-premium--active';
        }

        if ($is_lower_plan) {
            $card_classes .= ' amr-pricing-card-premium--disabled';
        }
        ?>
        <div class="<?php echo esc_attr($card_classes); ?>">
            <div class="amr-pricing-shine"></div>
            <div class="amr-pricing-card-head">
                <span class="amr-plan-pro-badge">PRO</span>
                <span class="amr-plan-cycle">ANNUAL</span>
            </div>
            <h3><?php echo esc_html($label); ?></h3>
            <?php if ($has_discount && '' !== $regular_price) : ?>
                <div class="amr-pricing-price-old">
                    <?php esc_html_e('Regular price:', 'titanium-advanced-menu-rules'); ?> <del><?php echo esc_html($regular_price); ?></del>
                </div>
            <?php endif; ?>
            <?php if ($has_price) : ?>
                <div class="amr-pricing-price-premium<?php echo $has_discount ? ' amr-pricing-price-premium--sale' : ''; ?>">
                    <strong><?php echo esc_html($price); ?></strong>
                    <span><?php echo esc_html($term); ?></span>
                </div>
            <?php elseif ($is_error) : ?>
                <div class="amr-pricing-price-unavailable amr-pricing-price-unavailable--error">
                    <?php esc_html_e('Unable to load prices. Secure checkout will show the current price.', 'titanium-advanced-menu-rules'); ?>
                </div>
            <?php else : ?>
                <div class="amr-pricing-price-premium amr-pricing-price-premium--loading">
                    <span class="amr-pricing-inline-status">
                        <span class="amr-pricing-spinner amr-pricing-spinner--small" aria-hidden="true"></span>
                        <strong><?php esc_html_e('Loading prices...', 'titanium-advanced-menu-rules'); ?></strong>
                    </span>
                </div>
            <?php endif; ?>
            <?php if ($has_discount && '' !== $discount_note) : ?>
                <div class="amr-pricing-discount-badge"><strong><?php echo esc_html($discount_note); ?></strong></div>
            <?php endif; ?>
            <span class="amr-plan-license-pill"><?php echo esc_html($license_label); ?></span>
            <div class="amr-plan-includes">
                <span><?php esc_html_e('All Pro features', 'titanium-advanced-menu-rules'); ?></span>
                <span><?php esc_html_e('Updates and support', 'titanium-advanced-menu-rules'); ?></span>
                <span><?php esc_html_e('License managed by Freemius', 'titanium-advanced-menu-rules'); ?></span>
            </div>
            <?php if ($is_active) : ?>
                <button class="amr-upgrade-card-button amr-upgrade-card-button--active" type="button" disabled><?php esc_html_e('ACTIVE', 'titanium-advanced-menu-rules'); ?></button>
            <?php elseif ($is_lower_plan) : ?>
                <button class="amr-upgrade-card-button amr-upgrade-card-button--disabled" type="button" disabled><?php echo esc_html($button_text); ?></button>
            <?php else : ?>
                <a class="amr-upgrade-card-button" href="<?php echo esc_url($checkout); ?>"><?php echo esc_html($button_text); ?></a>
            <?php endif; ?>
        </div>
        <?php
    }

    private function has_public_coupon_discount(?array $coupon): bool {
        if (null === $coupon || empty($coupon['is_active'])) {
            return false;
        }

        $discount = isset($coupon['discount']) ? (float) $coupon['discount'] : 0.0;
        $type     = $this->normalise_public_coupon_type((string) ($coupon['discount_type'] ?? ''));

        return $discount > 0 && in_array($type, ['percentage', 'fixed'], true);
    }

    private function normalise_public_coupon_type(string $type): string {
        $type = strtolower(trim($type));

        if (in_array($type, ['percentage', 'percent', '%'], true)) {
            return 'percentage';
        }

        if (in_array($type, ['fixed', 'money', 'amount', 'currency'], true)) {
            return 'fixed';
        }

        return $type;
    }

    private function apply_coupon_discount(float $price, ?array $coupon): float {
        if (!$this->has_public_coupon_discount($coupon)) {
            return $price;
        }

        $discount = (float) ($coupon['discount'] ?? 0);
        $type     = $this->normalise_public_coupon_type((string) ($coupon['discount_type'] ?? ''));

        if ('percentage' === $type) {
            return max(0.0, $price - ($price * $discount / 100));
        }

        return max(0.0, $price - $discount);
    }

    private function format_public_coupon_note(float $annual, ?array $coupon, string $currency): string {
        if (!$this->has_public_coupon_discount($coupon)) {
            return '';
        }

        $discount = (float) ($coupon['discount'] ?? 0);
        $type     = $this->normalise_public_coupon_type((string) ($coupon['discount_type'] ?? ''));

        if ('percentage' === $type) {
            $discount_text = (0.0 === fmod($discount, 1.0)) ? number_format($discount, 0) . '%' : number_format($discount, 2) . '%';
        } else {
            $discount_text = $this->format_price($discount, $currency);
        }

        return sprintf('%s first-year discount applied. Renews at %s/year.', $discount_text, $this->format_price($annual, $currency));
    }

    private function get_freemius_pricing_cards_from_sdk(): array {
        if (!function_exists('tiamr_fs')) {
            return [];
        }

        $fs = tiamr_fs();

        if (!is_object($fs) || !method_exists($fs, 'get_api_plugin_scope') || !method_exists($fs, 'add_show_pending')) {
            return [];
        }

        $api = $fs->get_api_plugin_scope();

        if (!is_object($api) || !method_exists($api, 'get')) {
            return [];
        }

        $path = $fs->add_show_pending('pricing.json?' . http_build_query([
            'is_enriched' => 'true',
            'currency'    => 'gbp',
        ]));

        $response = $api->get($path);

        if (is_object($response) && isset($response->error)) {
            return [];
        }

        return $this->build_pricing_cards_from_freemius_response($response);
    }

    /**
     * @param mixed $response
     */
    private function build_pricing_cards_from_freemius_response($response): array {
        $plans = $this->pricing_value($response, 'plans');

        if (!is_array($plans)) {
            return [];
        }

        $pro_plan = null;

        foreach ($plans as $plan) {
            $plan_id   = (string) $this->pricing_value($plan, 'id');
            $plan_name = strtolower((string) $this->pricing_value($plan, 'name'));

            if ('52536' === $plan_id || 'pro' === $plan_name) {
                $pro_plan = $plan;
                break;
            }
        }

        if (null === $pro_plan) {
            foreach ($plans as $plan) {
                $pricing = $this->pricing_value($plan, 'pricing');

                if (is_array($pricing) && !empty($pricing)) {
                    $pro_plan = $plan;
                    break;
                }
            }
        }

        if (null === $pro_plan) {
            return [];
        }

        $pricing_rows = $this->pricing_value($pro_plan, 'pricing');

        if (!is_array($pricing_rows)) {
            return [];
        }

        $cards = [];

        foreach ($pricing_rows as $pricing) {
            $billing_cycle = strtolower((string) $this->pricing_value($pricing, 'billing_cycle'));
            $currency      = strtolower((string) $this->pricing_value($pricing, 'currency'));
            $licenses      = $this->normalize_freemius_licenses($this->pricing_value($pricing, 'licenses'));
            $pricing_id    = (string) $this->pricing_value($pricing, 'id');
            $checkout_pricing_id = $this->get_pricing_id_for_licenses($licenses, $pricing_id);

            if ('' !== $currency && 'gbp' !== $currency) {
                continue;
            }

            if ('' !== $billing_cycle && !in_array($billing_cycle, ['annual', 'yearly', 'year'], true)) {
                continue;
            }

            $amount = $this->pricing_value($pricing, 'annual_price');

            if (null === $amount || '' === $amount) {
                $amount = $this->pricing_value($pricing, 'annual');
            }

            if (null === $amount || '' === $amount) {
                $amount = $this->pricing_value($pricing, 'price');
            }

            if (null === $amount || '' === $amount || !is_numeric($amount)) {
                continue;
            }

            $cards[] = [
                'label'    => $this->format_license_label($licenses),
                'licenses' => $licenses,
                'price'      => $this->format_price((float) $amount, '' !== $currency ? $currency : 'gbp'),
                'pricing_id' => $checkout_pricing_id,
                'checkout'   => $this->is_pro_active() ? $this->get_hosted_upgrade_url($checkout_pricing_id) : $this->get_checkout_url($licenses, $checkout_pricing_id),
            ];
        }

        usort($cards, function (array $a, array $b): int {
            return $this->license_sort_weight($a['licenses']) <=> $this->license_sort_weight($b['licenses']);
        });

        return $cards;
    }

    /**
     * @param mixed $value
     */
    private function pricing_value($value, string $key) {
        if (is_array($value) && array_key_exists($key, $value)) {
            return $value[$key];
        }

        if (is_object($value) && isset($value->{$key})) {
            return $value->{$key};
        }

        return null;
    }

    /**
     * @param mixed $licenses
     */
    private function normalize_freemius_licenses($licenses): string {
        if (null === $licenses || '' === $licenses) {
            return 'unlimited';
        }

        $licenses_string = strtolower((string) $licenses);

        if (in_array($licenses_string, ['unlimited', 'inf', 'infinite', '0'], true)) {
            return 'unlimited';
        }

        return (string) max(1, absint($licenses_string));
    }

    private function format_license_label(string $licenses): string {
        if ('unlimited' === $licenses) {
            return __('Unlimited Sites', 'titanium-advanced-menu-rules');
        }

        if ('1' === $licenses) {
            return __('Single Site', 'titanium-advanced-menu-rules');
        }

        return sprintf(
            /* translators: %s: number of websites included in the license. */
            __('%s Sites', 'titanium-advanced-menu-rules'),
            number_format_i18n((int) $licenses)
        );
    }

    private function format_license_pill(string $licenses): string {
        if ('unlimited' === $licenses) {
            return __('Unlimited site license', 'titanium-advanced-menu-rules');
        }

        if ('1' === $licenses) {
            return __('Single site license', 'titanium-advanced-menu-rules');
        }

        return sprintf(
            /* translators: %s: number of licensed sites. */
            __('%s site license', 'titanium-advanced-menu-rules'),
            $licenses
        );
    }

    private function license_sort_weight(string $licenses): int {
        if ('unlimited' === $licenses) {
            return PHP_INT_MAX;
        }

        return (int) $licenses;
    }

    private function format_price(float $amount, string $currency): string {
        $symbol = [
            'gbp' => '£',
            'usd' => '$',
            'eur' => '€',
        ][strtolower($currency)] ?? strtoupper($currency) . ' ';

        return $symbol . number_format_i18n($amount, 2);
    }


    private function get_feature_request_url(): string {
        if (function_exists('tiamr_fs')) {
            $fs = tiamr_fs();

            if (is_object($fs) && method_exists($fs, 'contact_url')) {
                $url = $fs->contact_url(
                    'feature_request',
                    '',
                    __('Feature request', 'titanium-advanced-menu-rules')
                );

                if (is_string($url) && '' !== $url) {
                    return $url;
                }
            }
        }

        return admin_url('admin.php?page=titanium-advanced-menu-rules');
    }

    public function render_pro_page(): void {
        if (!current_user_can('edit_theme_options')) {
            return;
        }

        $pro_active = $this->is_pro_active();
        $license_activation_url = $this->get_license_activation_url();
        $pricing_button_text = __('UPGRADE NOW', 'titanium-advanced-menu-rules');
        $pricing_heading = $pro_active ? __('License plans', 'titanium-advanced-menu-rules') : __('Choose your Pro license', 'titanium-advanced-menu-rules');
        $pricing_intro = $pro_active
            ? __('Your current Pro license stays active. Use this page only if you need more websites later.', 'titanium-advanced-menu-rules')
            : __('Every license unlocks the same Pro features. Pick only the number of websites you need.', 'titanium-advanced-menu-rules');
        $current_license_marker = $this->get_current_license_marker();
        $cached_pricing_cards = $this->get_cached_pricing_cards();
        $pricing_cards = !empty($cached_pricing_cards) ? $cached_pricing_cards : $this->get_pricing_cards_without_prices();
        $prices_loaded_on_render = !empty($cached_pricing_cards);
        $feature_request_url = $this->get_feature_request_url();
        ?>
        <div class="wrap amr-admin-page amr-pro-page amr-pro-page--premium">
            <h1 class="amr-wp-notice-anchor"><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules', 'titanium-advanced-menu-rules'); ?></h1>

            <div class="amr-product-hero amr-product-hero--pricing">
                <div class="amr-product-hero__content">
                    <span class="amr-product-hero__brand" aria-hidden="true">TITANIUM</span>
                    <div class="amr-product-hero__title" role="heading" aria-level="1"><?php esc_html_e('Nav Menu Roles & Visibility Rules', 'titanium-advanced-menu-rules'); ?></div>
                    <div class="amr-product-hero__version"><?php
                        /* translators: %s: plugin version number. */
                        printf(esc_html__('Version %s', 'titanium-advanced-menu-rules'), esc_html(TIAMR_VERSION));
                        ?></div>
                </div>
            </div>

            <?php if ($pro_active) : ?>
                <div class="amr-license-status-panel">
                    <span><?php esc_html_e('Titanium Nav Menu Roles & Visibility Rules is active on this site.', 'titanium-advanced-menu-rules'); ?></span>
                    <strong><?php esc_html_e('No action needed unless you want to change the number of websites on your license.', 'titanium-advanced-menu-rules'); ?></strong>
                </div>
            <?php endif; ?>

            <div class="amr-pro-section amr-pricing-section">
                <div class="amr-pro-section-header amr-section-header-centered">
                    <span class="amr-section-eyebrow"><?php esc_html_e('Simple annual pricing', 'titanium-advanced-menu-rules'); ?></span>
                    <h2><?php echo esc_html($pricing_heading); ?></h2>
                    <p><?php echo esc_html($pricing_intro); ?></p>
                </div>

                <div
                    class="amr-pricing-grid amr-pricing-grid--premium amr-pricing-grid--dynamic"
                    id="amr-dynamic-pricing"
                    data-nonce="<?php echo esc_attr(wp_create_nonce('tiamr_pricing_nonce')); ?>"
                    data-error="<?php echo esc_attr__('Unable to load prices. Secure checkout will show the current price.', 'titanium-advanced-menu-rules'); ?>"
                    data-button="<?php echo esc_attr($pricing_button_text); ?>"
                    data-current-licenses="<?php echo esc_attr($current_license_marker['licenses']); ?>"
                    data-pro-active="<?php echo $pro_active ? '1' : '0'; ?>"
                    data-prices-loaded="<?php echo $prices_loaded_on_render ? '1' : '0'; ?>"
                >
                    <?php foreach ($pricing_cards as $pricing_card) : ?>
                        <?php $this->render_pricing_placeholder_card($pricing_card, $pricing_button_text, $current_license_marker); ?>
                    <?php endforeach; ?>
                </div>
            </div>

            <?php if (!$pro_active) : ?>
            <div class="amr-license-panel">
                <div>
                    <span class="amr-section-eyebrow"><?php esc_html_e('Already purchased?', 'titanium-advanced-menu-rules'); ?></span>
                    <h2><?php esc_html_e('Connect and activate your existing license', 'titanium-advanced-menu-rules'); ?></h2>
                    <p><?php esc_html_e('Connect this website with Freemius so it can match your purchase, then open the Account page and activate the available Pro license.', 'titanium-advanced-menu-rules'); ?></p>
                </div>
                <a class="amr-upgrade-secondary amr-upgrade-secondary--bright" href="<?php echo esc_url($license_activation_url); ?>">
                    <?php esc_html_e('Connect & activate license', 'titanium-advanced-menu-rules'); ?>
                </a>
            </div>

            <?php endif; ?>

            <div class="amr-pro-section amr-pro-feature-showcase">
                <div class="amr-pro-section-header amr-section-header-centered">
                    <span class="amr-section-eyebrow"><?php esc_html_e('Pro toolkit', 'titanium-advanced-menu-rules'); ?></span>
                    <h2><?php esc_html_e('Built for serious menu control', 'titanium-advanced-menu-rules'); ?></h2>
                    <p><?php esc_html_e('Pro adds access protection, Paid Memberships Pro rules, migration tools, and advanced denied access handling.', 'titanium-advanced-menu-rules'); ?></p>
                </div>

                <div class="amr-pro-preview-grid amr-pro-preview-grid--premium amr-pro-showcase-grid">
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">01</span>
                        <strong><?php esc_html_e('Condition groups', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Combine rules with AND / OR logic for advanced visibility setups without custom snippets.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">02</span>
                        <strong><?php esc_html_e('Paid Memberships Pro rules', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Show or hide menu items by Paid Memberships Pro membership level.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">03</span>
                        <strong><?php esc_html_e('Access Protection', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Protect linked pages and posts from direct URL access using the same menu visibility rules.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">04</span>
                        <strong><?php esc_html_e('Denied access actions', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Choose whether blocked visitors see a 404 page, the homepage, or a selected redirect page.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">05</span>
                        <strong><?php esc_html_e('Per-menu overrides', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Override the global denied access action for individual protected menu items.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">06</span>
                        <strong><?php esc_html_e('Selectable 404 handling', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Choose the plugin built-in 404 page or your site/theme 404 page, with fallback protection when needed.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">07</span>
                        <strong><?php esc_html_e('Menu diagnostics', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Warn when menus with rules are not assigned to the expected theme locations.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">08</span>
                        <strong><?php esc_html_e('Header, mobile, and footer awareness', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Understand whether rules affect desktop, mobile, or footer menu locations.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">09</span>
                        <strong><?php esc_html_e('Import tools', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Import supported rules from Nav Menu Roles and User Menus to speed up migration.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                    <div class="amr-pro-feature-card amr-pro-feature-card--visual">
                        <span class="amr-feature-icon" aria-hidden="true">10</span>
                        <strong><?php esc_html_e('Beta update channel', 'titanium-advanced-menu-rules'); ?></strong>
                        <p><?php esc_html_e('Pro users can opt into beta update offers when beta builds are available through Freemius.', 'titanium-advanced-menu-rules'); ?></p>
                    </div>
                </div>

                <a class="amr-feature-request-panel amr-feature-request-panel--link" href="<?php echo esc_url($feature_request_url); ?>">
                    <div class="amr-feature-request-orb" aria-hidden="true"></div>
                    <div>
                        <span class="amr-section-eyebrow"><?php esc_html_e('Have a useful idea?', 'titanium-advanced-menu-rules'); ?></span>
                        <h3><?php esc_html_e('Feature requests are welcome', 'titanium-advanced-menu-rules'); ?></h3>
                        <p><?php esc_html_e('If your website needs a rule or workflow that would help other users too, send the idea in. Good feature requests can help shape future updates.', 'titanium-advanced-menu-rules'); ?></p>
                        <span class="amr-feature-request-cta"><?php esc_html_e('Open Contact Us', 'titanium-advanced-menu-rules'); ?></span>
                    </div>
                </a>
            </div>

            <div class="amr-pro-section amr-comparison-section">
                <div class="amr-pro-section-header amr-section-header-centered">
                    <span class="amr-section-eyebrow"><?php esc_html_e('Compare plans', 'titanium-advanced-menu-rules'); ?></span>
                </div>

                <div class="amr-plan-compare-wrap">
                <table class="widefat amr-pro-table amr-pro-table-premium amr-plan-compare-table">
                    <thead>
                        <tr>
                            <th class="amr-plan-compare-empty" aria-hidden="true"></th>
                            <th class="amr-plan-compare-heading amr-plan-compare-heading--free"><?php esc_html_e('Free', 'titanium-advanced-menu-rules'); ?></th>
                            <th class="amr-plan-compare-heading amr-plan-compare-heading--pro"><?php esc_html_e('Pro', 'titanium-advanced-menu-rules'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><?php esc_html_e('Server-side menu item hiding', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Show / Hide menu items', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Logged-in and logged-out visitor rules', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('WordPress role is / role is not rules', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Page and post location rules', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Maintenance and compatibility updates', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Menu diagnostics and location warnings', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Header / mobile / footer menu awareness', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Combined condition groups with AND / OR logic', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td class="amr-plan-compare-feature">
                                <span class="amr-plan-feature-title"><?php esc_html_e('Membership plugin conditions', 'titanium-advanced-menu-rules'); ?></span>
                                <span class="amr-plan-feature-plugins"><?php esc_html_e('Paid Memberships Pro, MemberPress, WooCommerce Memberships,', 'titanium-advanced-menu-rules'); ?><br><?php esc_html_e('Restrict Content / Restrict Content Pro, and Paid Member Subscriptions', 'titanium-advanced-menu-rules'); ?></span>
                            </td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Direct URL linked content protection', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td class="amr-plan-compare-feature">
                                <span class="amr-plan-feature-title"><?php esc_html_e('Linked Page Protection compatibility controls', 'titanium-advanced-menu-rules'); ?></span>
                                <span class="amr-plan-feature-plugins"><?php esc_html_e('Membership system page bypass, delayed redirect priority, and custom excluded paths', 'titanium-advanced-menu-rules'); ?></span>
                            </td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Global denied access action', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Per-menu denied access action override', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Selectable 404 handling with built-in fallback', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Beta update opt-in', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                        <tr>
                            <td><?php esc_html_e('Priority Pro email support', 'titanium-advanced-menu-rules'); ?></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--no" aria-label="<?php esc_attr_e('Not included', 'titanium-advanced-menu-rules'); ?>">×</span></td>
                            <td class="amr-plan-compare-cell"><span class="amr-plan-icon amr-plan-icon--yes" aria-label="<?php esc_attr_e('Included', 'titanium-advanced-menu-rules'); ?>">✓</span></td>
                        </tr>
                    </tbody>
                </table>
                </div>
            </div>

        </div>
        <?php
    }


}
