<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Templates use local variables supplied by the render context.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

        wp_enqueue_media();
        $settings_brand_name = $this->get_admin_brand_name();
        $site_profile_catalog = method_exists($this, 'get_site_profile_catalog') ? (array) $this->get_site_profile_catalog() : [];
        $starter_blueprints = method_exists($this, 'get_starter_blueprint_catalog') ? (array) $this->get_starter_blueprint_catalog() : [];
        if (empty($site_profile_catalog)) {
            $site_profile_catalog = [
                'events' => ['label' => __('Events (default)', 'nexdirectory')],
            ];
        }
        if (method_exists($this, 'normalize_site_profile_key')) {
            $site_profile_value = (string) $this->normalize_site_profile_key((string) get_option('nexdirectory_site_profile', 'events'));
        } else {
            $site_profile_value = sanitize_key((string) get_option('nexdirectory_site_profile', 'events'));
        }
        if ($site_profile_value === '' || !isset($site_profile_catalog[$site_profile_value])) {
            $site_profile_value = 'events';
        }
        $active_starter_blueprint = sanitize_key((string) get_option('nexdirectory_active_starter_blueprint', ''));
        if (
            $active_starter_blueprint === ''
            || !isset($starter_blueprints[$active_starter_blueprint])
            || sanitize_key((string) ($starter_blueprints[$active_starter_blueprint]['site_profile'] ?? '')) !== $site_profile_value
        ) {
            $active_starter_blueprint = '';
            foreach ($starter_blueprints as $candidate_blueprint_key => $candidate_blueprint) {
                if (sanitize_key((string) ($candidate_blueprint['site_profile'] ?? '')) === $site_profile_value) {
                    $active_starter_blueprint = sanitize_key((string) $candidate_blueprint_key);
                    break;
                }
            }
        }
        $this->sync_route_options_to_existing_pages($site_profile_value);
        $platform_mode_value = $this->sanitize_platform_mode_option((string) get_option('nexdirectory_platform_mode', 'user_generated'));
        $site_profile_ui = method_exists($this, 'get_site_profile_ui_labels') ? (array) $this->get_site_profile_ui_labels($site_profile_value) : [];
        $settings_events_page_url = $this->get_platform_page_url(
            'nexdirectory_page_events_url',
            $this->get_profile_route_slugs('events', $site_profile_value),
            $this->get_profile_route_default_url('events', $site_profile_value)
        );
        $settings_map_page_url = $this->get_platform_page_url(
            'nexdirectory_page_events_map_url',
            $this->get_profile_route_slugs('map', $site_profile_value),
            $this->get_profile_route_default_url('map', $site_profile_value)
        );
        $settings_calendar_page_url = $this->get_platform_page_url(
            'nexdirectory_page_events_calendar_url',
            $this->get_profile_route_slugs('calendar', $site_profile_value),
            $this->get_profile_route_default_url('calendar', $site_profile_value)
        );
        $settings_submit_page_url = $this->get_platform_page_url(
            'nexdirectory_page_submit_event_url',
            $this->get_profile_route_slugs('submit', $site_profile_value),
            $this->get_profile_route_default_url('submit', $site_profile_value)
        );
        $settings_my_items_page_url = $this->get_platform_page_url(
            'nexdirectory_page_my_events_url',
            $this->get_profile_route_slugs('my_items', $site_profile_value),
            $this->get_profile_route_default_url('my_items', $site_profile_value)
        );
        $settings_saved_page_url = $this->get_platform_page_url(
            'nexdirectory_page_my_tickets_url',
            $this->get_profile_route_slugs('attending', $site_profile_value),
            $this->get_profile_route_default_url('attending', $site_profile_value)
        );
        $settings_whos_attending_page_url = $this->get_platform_page_url(
            'nexdirectory_page_whos_attending_url',
            $this->get_profile_route_slugs('attendees', $site_profile_value),
            $this->get_profile_route_default_url('attendees', $site_profile_value)
        );
        $settings_whats_new_page_url = $this->get_platform_page_url(
            'nexdirectory_page_whats_new_url',
            ['whats-new'],
            home_url('/whats-new/')
        );
        $settings_account_page_url = $this->get_platform_page_url(
            'nexdirectory_page_account_url',
            $this->get_profile_route_slugs('account', $site_profile_value),
            $this->get_profile_route_default_url('account', $site_profile_value)
        );
        $settings_auth_page_url = $this->get_platform_page_url(
            'nexdirectory_page_login_signup_url',
            $this->get_profile_route_slugs('auth', $site_profile_value),
            $this->get_profile_route_default_url('auth', $site_profile_value)
        );
        $settings_claim_page_url = $this->get_platform_page_url(
            'nexdirectory_claim_listing_page_url',
            $this->get_profile_route_slugs('claim', $site_profile_value),
            $this->get_profile_route_default_url('claim', $site_profile_value)
        );
        $settings_singular_label = sanitize_text_field((string) ($site_profile_ui['singular'] ?? __('Listing', 'nexdirectory')));
        $settings_plural_label = sanitize_text_field((string) ($site_profile_ui['plural'] ?? __('Listings', 'nexdirectory')));
        $settings_owner_singular = sanitize_text_field((string) ($site_profile_ui['owner_singular'] ?? __('Owner', 'nexdirectory')));
        $settings_type_label = sanitize_text_field((string) ($site_profile_ui['taxonomy_type_singular'] ?? __('Type', 'nexdirectory')));
        $settings_mode_label = sanitize_text_field((string) ($site_profile_ui['taxonomy_mode_singular'] ?? __('Mode', 'nexdirectory')));
        $settings_attending_title = sanitize_text_field((string) ($site_profile_ui['attending_title'] ?? __('Saved Listings', 'nexdirectory')));
        $settings_singular_lower = function_exists('mb_strtolower') ? mb_strtolower($settings_singular_label, 'UTF-8') : strtolower($settings_singular_label);
        $settings_plural_lower = function_exists('mb_strtolower') ? mb_strtolower($settings_plural_label, 'UTF-8') : strtolower($settings_plural_label);
        $settings_owner_singular_lower = function_exists('mb_strtolower') ? mb_strtolower($settings_owner_singular, 'UTF-8') : strtolower($settings_owner_singular);
        $settings_page_title = sprintf(
            /* translators: %s: Placeholder value. */
            __('%s Settings', 'nexdirectory'),
            $settings_brand_name
        );
        $font_presets = [
            'Inter, system-ui, -apple-system, sans-serif' => __('Inter', 'nexdirectory'),
            'Roboto, system-ui, -apple-system, sans-serif' => __('Roboto', 'nexdirectory'),
            '"Open Sans", system-ui, -apple-system, sans-serif' => __('Open Sans', 'nexdirectory'),
            '"Montserrat", system-ui, -apple-system, sans-serif' => __('Montserrat', 'nexdirectory'),
            '"Lato", system-ui, -apple-system, sans-serif' => __('Lato', 'nexdirectory'),
        ];
        $display_font_presets = [
            'Oswald, Inter, sans-serif' => __('Oswald', 'nexdirectory'),
            'Inter, system-ui, -apple-system, sans-serif' => __('Inter', 'nexdirectory'),
            '"Montserrat", system-ui, -apple-system, sans-serif' => __('Montserrat', 'nexdirectory'),
            '"Bebas Neue", Oswald, sans-serif' => __('Bebas Neue', 'nexdirectory'),
            '"Anton", Oswald, sans-serif' => __('Anton', 'nexdirectory'),
        ];
        $font_size_presets = ['16px', '17px', '18px', '19px', '20px'];
        $h2_size_presets = ['1.5rem', '1.625rem', '1.75rem', '1.875rem', '2rem'];
        $h3_size_presets = ['1.2rem', '1.3rem', '1.35rem', '1.45rem', '1.5rem'];
        $font_weight_presets = ['300', '400', '500', '600', '700', '800'];
        $spacing_unit_presets = ['12px', '14px', '16px', '18px', '20px'];
        $spacing_scale_presets = ['0.85', '1', '1.15', '1.3', '1.5'];
        $radius_presets = ['8px', '10px', '12px', '14px', '16px', '20px', '24px'];

        $body_font_value = (string) get_option('nexdirectory_style_font_family', 'Inter, system-ui, -apple-system, sans-serif');
        $display_font_value = (string) get_option('nexdirectory_style_display_font_family', 'Oswald, Inter, sans-serif');
        $base_font_size_value = (string) get_option('nexdirectory_style_font_size_base', '18px');
        $h2_size_value = (string) get_option('nexdirectory_style_h2_size', '1.75rem');
        $h3_size_value = (string) get_option('nexdirectory_style_h3_size', '1.35rem');
        $body_weight_value = (string) get_option('nexdirectory_style_font_weight_body', '400');
        $heading_weight_value = (string) get_option('nexdirectory_style_font_weight_heading', '700');
        $spacing_unit_value = (string) get_option('nexdirectory_style_spacing_unit', '16px');
        $spacing_scale_value = (string) get_option('nexdirectory_style_spacing_scale', '1');
        $radius_md_value = (string) get_option('nexdirectory_style_radius_md', '12px');
        $radius_lg_value = (string) get_option('nexdirectory_style_radius_lg', '24px');
        $style_box_style_value = $this->sanitize_style_box_style_option((string) get_option('nexdirectory_style_box_style', 'default'));
        $style_button_style_value = $this->sanitize_style_button_style_option((string) get_option('nexdirectory_style_button_style', 'solid'));
        $style_button_radius_mode_value = $this->sanitize_style_button_radius_mode_option((string) get_option('nexdirectory_style_button_radius_mode', 'inherit'));
        $style_density_mode_value = $this->sanitize_style_density_mode_option((string) get_option('nexdirectory_style_density_mode', 'comfortable'));
        $style_border_mode_value = $this->sanitize_style_border_mode_option((string) get_option('nexdirectory_style_border_mode', 'subtle'));
        $style_shadow_mode_value = $this->sanitize_style_shadow_mode_option((string) get_option('nexdirectory_style_shadow_mode', 'soft'));
        $style_content_width_value = $this->sanitize_style_content_width_option((string) get_option('nexdirectory_style_content_width', 'standard'));
        $style_input_style_value = $this->sanitize_style_input_style_option((string) get_option('nexdirectory_style_input_style', 'outline'));
        $map_layout_value = sanitize_key((string) get_option('nexdirectory_map_layout_default', 'three-column'));
        if ($map_layout_value === 'below') {
            $map_layout_value = 'below-list';
        } elseif ($map_layout_value === 'sidebar') {
            $map_layout_value = 'three-column';
        }
        if (!in_array($map_layout_value, ['three-column', 'below-list', 'below-grid', 'below-grid-large', 'grid-no-map', 'grid-no-map-large'], true)) {
            $map_layout_value = 'three-column';
        }
        $map_view_template_value = sanitize_key((string) get_option('nexdirectory_map_view_template', 'default'));
        if (!in_array($map_view_template_value, ['default', 'triple'], true)) {
            $map_view_template_value = 'default';
        }
        $map_focus_region_value = $this->sanitize_map_focus_region_option((string) get_option('nexdirectory_map_focus_region', 'global'));
        $map_focus_region_options = (array) $this->get_map_focus_region_options();
        $page_side_padding_value = $this->sanitize_page_side_padding_option((string) get_option('nexdirectory_page_side_padding', '10%'));
        $page_side_padding_mobile_raw = (string) get_option('nexdirectory_page_side_padding_mobile', '2%');
        $page_side_padding_mobile_value = $this->sanitize_page_side_padding_mobile_option($page_side_padding_mobile_raw);
        $nav_side_padding_desktop_raw = (string) get_option('nexdirectory_nav_side_padding_desktop', '0%');
        $nav_side_padding_desktop_value = $this->sanitize_nav_side_padding_desktop_option($nav_side_padding_desktop_raw);
        $map_mobile_filter_mode = sanitize_key((string) get_option('nexdirectory_map_mobile_filter_mode', 'drawer'));
        if (!in_array($map_mobile_filter_mode, ['drawer', 'inline'], true)) {
            $map_mobile_filter_mode = 'drawer';
        }
        $map_provider_value = sanitize_key((string) get_option('nexdirectory_map_provider', 'openstreetmap'));
        if (!in_array($map_provider_value, ['openstreetmap', 'mapbox', 'google'], true)) {
            $map_provider_value = 'openstreetmap';
        }
        $map_style_value = sanitize_key((string) get_option('nexdirectory_map_style', 'osm-standard'));
        if (!in_array($map_style_value, ['osm-standard', 'osm-hot', 'carto-light', 'carto-dark', 'topo', 'mapbox-streets', 'mapbox-outdoors', 'mapbox-satellite', 'google-roadmap', 'google-satellite', 'custom'], true)) {
            $map_style_value = 'osm-standard';
        }
        $mapbox_style_value = $this->sanitize_mapbox_style_id_option((string) get_option('nexdirectory_mapbox_style_id', 'mapbox/streets-v12'));
        $mapbox_style_options = (array) $this->get_mapbox_style_id_options();
        $thumb_fallback_raw = (string) get_option('nexdirectory_style_fallback_thumb_url', '');
        $thumb_fallback_urls = preg_split('/\r\n|\r|\n|,/', $thumb_fallback_raw);
        if (!is_array($thumb_fallback_urls)) {
            $thumb_fallback_urls = [];
        }
        $thumb_fallback_urls = array_values(array_filter(array_map('esc_url', array_map('trim', $thumb_fallback_urls))));
        $hero_fallback_url = esc_url((string) get_option('nexdirectory_style_fallback_hero_url', ''));
        $favicon_url = esc_url((string) get_option('nexdirectory_style_favicon_url', ''));
        $home_meta_title_value = $this->sanitize_home_meta_title_option((string) get_option('nexdirectory_home_meta_title', ''));
        $home_meta_description_value = $this->sanitize_home_meta_description_option((string) get_option('nexdirectory_home_meta_description', ''));
        $home_meta_title_count = function_exists('mb_strlen') ? (int) mb_strlen($home_meta_title_value) : strlen($home_meta_title_value);
        $home_meta_description_count = function_exists('mb_strlen') ? (int) mb_strlen($home_meta_description_value) : strlen($home_meta_description_value);
        $home_meta_preview_title = $home_meta_title_value !== '' ? $home_meta_title_value : sanitize_text_field((string) $this->get_white_label_brand_name());
        $home_meta_preview_description = $home_meta_description_value !== '' ? $home_meta_description_value : sanitize_text_field((string) get_bloginfo('description'));
        $home_meta_preview_url = home_url('/');
        $recaptcha_version_value = sanitize_key((string) get_option('nexdirectory_recaptcha_version', 'v3'));
        if (!in_array($recaptcha_version_value, ['v3', 'v2'], true)) {
            $recaptcha_version_value = 'v3';
        }
        $email_template_defaults = $this->get_default_event_email_templates();

        $body_font_preset = isset($font_presets[$body_font_value]) ? $body_font_value : 'custom';
        $display_font_preset = isset($display_font_presets[$display_font_value]) ? $display_font_value : 'custom';
        $base_font_size_preset = in_array($base_font_size_value, $font_size_presets, true) ? $base_font_size_value : 'custom';
        $h2_size_preset = in_array($h2_size_value, $h2_size_presets, true) ? $h2_size_value : 'custom';
        $h3_size_preset = in_array($h3_size_value, $h3_size_presets, true) ? $h3_size_value : 'custom';
        $body_weight_preset = in_array($body_weight_value, $font_weight_presets, true) ? $body_weight_value : 'custom';
        $heading_weight_preset = in_array($heading_weight_value, $font_weight_presets, true) ? $heading_weight_value : 'custom';
        $spacing_unit_preset = in_array($spacing_unit_value, $spacing_unit_presets, true) ? $spacing_unit_value : 'custom';
        $spacing_scale_preset = in_array($spacing_scale_value, $spacing_scale_presets, true) ? $spacing_scale_value : 'custom';
        $radius_md_preset = in_array($radius_md_value, $radius_presets, true) ? $radius_md_value : 'custom';
        $radius_lg_preset = in_array($radius_lg_value, $radius_presets, true) ? $radius_lg_value : 'custom';
        $pending_badge_toggle_value = get_option('nexdirectory_notify_admin_pending_badge', null);
        if ($pending_badge_toggle_value === null || $pending_badge_toggle_value === false || $pending_badge_toggle_value === '') {
            $pending_badge_toggle_value = get_option('nexdirectory_enable_pending_admin_notifications', '1');
        }
        $pending_email_toggle_value = get_option('nexdirectory_notify_admin_pending_email', null);
        if ($pending_email_toggle_value === null || $pending_email_toggle_value === false || $pending_email_toggle_value === '') {
            $pending_email_toggle_value = get_option('nexdirectory_enable_pending_admin_notifications', '1');
        }
        $extension_app_pass = $this->get_extension_app_pass();
        $extension_import_status = sanitize_key((string) get_option('nexdirectory_extension_import_status', 'draft'));
        if (!in_array($extension_import_status, ['draft', 'publish'], true)) {
            $extension_import_status = 'draft';
        }
        $extension_import_media_policy = sanitize_key((string) get_option('nexdirectory_extension_import_media_policy', ''));
        if (!in_array($extension_import_media_policy, ['none', 'images', 'images_video', 'video'], true)) {
            $extension_import_media_policy = 'none';
        }
        $extension_ai_importer_enabled = function_exists('nexdirectory_is_pro_feature_enabled')
            && nexdirectory_is_pro_feature_enabled('ai_importer');
        $extension_import_content_default = $extension_ai_importer_enabled ? 'rewrite' : 'verbatim';
        $extension_import_content_mode = sanitize_key((string) get_option('nexdirectory_extension_import_content_mode', $extension_import_content_default));
        if (!in_array($extension_import_content_mode, ['rewrite', 'verbatim'], true)) {
            $extension_import_content_mode = $extension_import_content_default;
        }
        if (!$extension_ai_importer_enabled) {
            $extension_import_content_mode = 'verbatim';
        }
        $extension_ai_importer_url = method_exists($this, 'get_free_pro_comparison_url')
            ? $this->get_free_pro_comparison_url('ai-importer')
            : admin_url('admin.php?page=nexdirectory-free-vs-pro');
        $extension_notify_owner_default = (string) get_option('nexdirectory_extension_notify_potential_owner_default', '0') === '1';
        $extension_import_author_id = absint((int) get_option('nexdirectory_extension_import_author_id', 0));
        $extension_import_author_options = get_users([
            'orderby' => 'display_name',
            'order' => 'ASC',
            'number' => 200,
            'fields' => ['ID', 'display_name', 'user_email'],
            'role__in' => ['administrator', 'editor', 'author', 'event_submitter'],
        ]);
        $sticky_nav_behavior = sanitize_key((string) get_option('nexdirectory_frontend_sticky_nav_behavior', 'sticky'));
        if (!in_array($sticky_nav_behavior, ['sticky', 'static', 'smart'], true)) {
            $sticky_nav_behavior = 'sticky';
        }
        $sticky_nav_logo_url = esc_url((string) get_option('nexdirectory_frontend_sticky_nav_logo_url', ''));
        $sticky_nav_logo_link_url = esc_url((string) get_option('nexdirectory_frontend_sticky_nav_logo_link_url', home_url('/')));
        if ($sticky_nav_logo_link_url === '') {
            $sticky_nav_logo_link_url = esc_url(home_url('/'));
        }
        $sticky_nav_custom_links_value = (string) get_option('nexdirectory_frontend_sticky_nav_custom_links', '');
        $sticky_nav_use_wp_menus = (string) get_option('nexdirectory_frontend_sticky_nav_use_wp_menus', '0') === '1';
        $sticky_nav_wp_menu_guest = absint((int) get_option('nexdirectory_frontend_sticky_nav_wp_menu_guest', 0));
        $sticky_nav_wp_menu_member = absint((int) get_option('nexdirectory_frontend_sticky_nav_wp_menu_member', 0));
        $sticky_nav_wp_menu_admin = absint((int) get_option('nexdirectory_frontend_sticky_nav_wp_menu_admin', 0));
        $sticky_nav_wp_menu_roles = get_option('nexdirectory_frontend_sticky_nav_wp_menu_roles', []);
        if (!is_array($sticky_nav_wp_menu_roles)) {
            $sticky_nav_wp_menu_roles = [];
        }
        $sticky_nav_wp_menu_roles = array_filter(array_map('absint', $sticky_nav_wp_menu_roles), static function ($menu_id) {
            return $menu_id > 0;
        });
        $sticky_nav_role_options = function_exists('get_editable_roles') ? (array) get_editable_roles() : [];
        $sticky_nav_wp_menus = wp_get_nav_menus(['orderby' => 'name', 'order' => 'ASC']);
        if (!is_array($sticky_nav_wp_menus)) {
            $sticky_nav_wp_menus = [];
        }
        $footer_enabled = (string) get_option('nexdirectory_enable_frontend_footer', '1') === '1';
        $footer_show_logo = (string) get_option('nexdirectory_frontend_footer_show_logo', '1') === '1';
        $footer_logo_url = esc_url((string) get_option('nexdirectory_frontend_footer_logo_url', ''));
        $footer_logo_link_url = esc_url((string) get_option('nexdirectory_frontend_footer_logo_link_url', home_url('/')));
        if ($footer_logo_link_url === '') {
            $footer_logo_link_url = esc_url(home_url('/'));
        }
        $footer_use_wp_menus = (string) get_option('nexdirectory_frontend_footer_use_wp_menus', '0') === '1';
        $footer_menu_count = (int) get_option('nexdirectory_frontend_footer_menu_count', 3);
        if (method_exists($this, 'sanitize_footer_menu_count_option')) {
            $footer_menu_count = (int) $this->sanitize_footer_menu_count_option($footer_menu_count);
        } else {
            $footer_menu_count = max(1, min(5, $footer_menu_count));
        }
        $footer_wp_menu_ids = get_option('nexdirectory_frontend_footer_wp_menus', []);
        if (!is_array($footer_wp_menu_ids)) {
            $footer_wp_menu_ids = [];
        }
        $footer_wp_menu_ids = array_values(array_unique(array_filter(array_map('absint', $footer_wp_menu_ids), static function ($menu_id) {
            return $menu_id > 0;
        })));
        $footer_wp_menu_ids = array_slice($footer_wp_menu_ids, 0, 5);
        $footer_show_privacy_link = (string) get_option('nexdirectory_frontend_footer_show_privacy_link', '1') === '1';
        $footer_bottom_text = (string) get_option('nexdirectory_frontend_footer_bottom_text', '');
        $shortcodes = [
            ['code' => '[nexdirectory_listings_archive]', 'usage' => __('Filterable listings archive grid page.', 'nexdirectory')],
            ['code' => '[nexdirectory_listings_map]', 'usage' => __('Interactive map page with filters and results list.', 'nexdirectory')],
            ['code' => '[nexdirectory_listings_calendar]', 'usage' => __('Monthly calendar/timeline view for listings.', 'nexdirectory')],
            ['code' => '[nexdirectory_events_query_grid]', 'usage' => __('Elementor-friendly query grid with custom taxonomy/category filtering.', 'nexdirectory')],
            ['code' => '[nexdirectory_events_bento_grid]', 'usage' => __('Bento-style query grid with hover effects and 6 layout templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_events_ajax_search]', 'usage' => __('Dynamic AJAX search widget with custom query controls and filters.', 'nexdirectory')],
            ['code' => '[nexdirectory_submit]', 'usage' => __('Frontend submit/edit listing form for logged-in users.', 'nexdirectory')],
            ['code' => '[nexdirectory_my_listings]', 'usage' => __('User dashboard for submitted listings and quick edits.', 'nexdirectory')],
            ['code' => '[nexdirectory_saved_listings]', 'usage' => __('Dashboard for saved/attending listings.', 'nexdirectory')],
            ['code' => '[nexdirectory_account]', 'usage' => __('Account management and recommendations.', 'nexdirectory')],
            ['code' => '[nexdirectory_auth]', 'usage' => __('Custom login/sign-up experience.', 'nexdirectory')],
            ['code' => '[nexdirectory_auth_links]', 'usage' => __('Reusable Login/Signup buttons with signed-in account dropdown menu.', 'nexdirectory')],
            ['code' => '[nexdirectory_user_management]', 'usage' => __('Admin user management and listing moderation actions.', 'nexdirectory')],
            ['code' => '[nexdirectory_moderation_queue]', 'usage' => __('Admin moderation queue for pending listings and reports.', 'nexdirectory')],
            ['code' => '[nexdirectory_organizers]', 'usage' => __('Public organizer directory.', 'nexdirectory')],
            ['code' => '[nexdirectory_claim_listing]', 'usage' => __('Frontend listing claim form for imported/admin-created listings.', 'nexdirectory')],
        ];
        $shortcode_aliases = [
            ['code' => '[nexdirectory_events_archive]', 'usage' => __('Legacy alias of [nexdirectory_listings_archive].', 'nexdirectory')],
            ['code' => '[nexdirectory_events_map]', 'usage' => __('Legacy alias of [nexdirectory_listings_map].', 'nexdirectory')],
            ['code' => '[nexdirectory_events_calendar]', 'usage' => __('Legacy alias of [nexdirectory_listings_calendar].', 'nexdirectory')],
            ['code' => '[nexdirectory_submit_event]', 'usage' => __('Legacy alias of [nexdirectory_submit].', 'nexdirectory')],
            ['code' => '[nexdirectory_my_events]', 'usage' => __('Legacy alias of [nexdirectory_my_listings].', 'nexdirectory')],
            ['code' => '[nexdirectory_my_tickets]', 'usage' => __('Legacy alias of [nexdirectory_saved_listings].', 'nexdirectory')],
        ];
        $runtime_logs = $this->get_runtime_logs(120);
        $settings_email_health = $this->get_settings_email_health();
        $settings_map_health = $this->get_settings_map_health();
        $settings_captcha_health = $this->get_settings_captcha_health();
        $settings_routing_health = $this->get_settings_routing_health($site_profile_value);
        $settings_allowance_class = 'is-pro-active';
        $settings_allowance_title = __('Unlimited submissions included', 'nexdirectory');
        $settings_allowance_text = __('The WordPress.org version includes unlimited core publishing.', 'nexdirectory');
        $settings_allowance_tooltip = __('Nex Directory Free core publishing is unlimited.', 'nexdirectory');
        $settings_pro_addon_active = function_exists('nexdirectory_is_pro_addon_active')
            && nexdirectory_is_pro_addon_active();
        $settings_primary_label = $settings_pro_addon_active
            ? __('Manage Pro', 'nexdirectory')
            : __('Compare Free & Pro', 'nexdirectory');
        $settings_primary_url = $settings_pro_addon_active
            ? admin_url('admin.php?page=nexdirectory-pro')
            : $this->get_free_pro_comparison_url();
        ?>
        <div class="wrap nexdirectory-admin-premium nexdirectory-settings-premium">
            <?php $this->render_admin_premium_shell_styles(); ?>
            <section class="nexdirectory-admin-hero">
                <div class="nexdirectory-settings-hero-main">
                    <span class="nexdirectory-admin-hero-kicker"><?php esc_html_e('Admin Control Center', 'nexdirectory'); ?></span>
                    <h1><?php echo esc_html($settings_page_title); ?></h1>
                    <?php /* translators: %s: Placeholder value. */ ?>
                    <p><?php echo esc_html(sprintf(__('Configure routing, design, moderation, notifications, and publishing tools for your %s experience.', 'nexdirectory'), $settings_plural_lower)); ?></p>
                    <div class="nexdirectory-settings-hero-meta">
                        <span class="nexdirectory-settings-hero-pill"><span class="dashicons dashicons-layout" aria-hidden="true"></span><?php esc_html_e('Template-Based Settings', 'nexdirectory'); ?></span>
                        <span class="nexdirectory-settings-hero-pill"><span class="dashicons dashicons-saved" aria-hidden="true"></span><?php esc_html_e('Review Before Saving', 'nexdirectory'); ?></span>
                    </div>
                </div>
                <div class="nexdirectory-settings-hero-tools">
                    <div class="nexdirectory-settings-search-wrap nexdirectory-settings-search-wrap-top">
                        <span class="dashicons dashicons-search" aria-hidden="true"></span>
                        <input type="search" id="nexdirectory-settings-search-top" placeholder="<?php esc_attr_e('Search all settings...', 'nexdirectory'); ?>" aria-label="<?php esc_attr_e('Search settings fields', 'nexdirectory'); ?>">
                        <button type="button" class="nexdirectory-settings-search-clear" id="nexdirectory-settings-search-top-clear" data-target-input="nexdirectory-settings-search-top" aria-label="<?php esc_attr_e('Clear settings search', 'nexdirectory'); ?>">&times;</button>
                    </div>
                    <p class="description"><?php esc_html_e('Press "/" from anywhere on this page to jump to search.', 'nexdirectory'); ?></p>
                </div>
            </section>
                <section class="nexdirectory-settings-demo-alert <?php echo esc_attr($settings_allowance_class); ?>" aria-label="<?php esc_attr_e('Publishing status', 'nexdirectory'); ?>" title="<?php echo esc_attr($settings_allowance_tooltip); ?>">
                    <div class="nexdirectory-settings-demo-alert-copy">
                        <h3><?php echo esc_html($settings_allowance_title); ?></h3>
                        <p><?php echo esc_html($settings_allowance_text); ?></p>
                        <span class="nexdirectory-settings-demo-alert-meta"><?php echo esc_html($settings_allowance_tooltip); ?></span>
                    </div>
                    <div class="nexdirectory-settings-demo-alert-actions">
                        <a class="button" href="<?php echo esc_url($settings_primary_url); ?>"><?php echo esc_html($settings_primary_label); ?></a>
                    </div>
                </section>
            <?php settings_errors(); ?>
            <section class="nexdirectory-admin-panel">
            <?php $this->enqueue_local_style_asset('templates-admin-settings-page-php-style-1', 'assets/generated/templates-admin-settings-page-php-style-1.css'); ?>
            <form method="post" action="options.php">
                <?php settings_fields('nexdirectory_settings_group'); ?>
                <nav class="nav-tab-wrapper nexdirectory-settings-tabs" id="nexdirectory-settings-tabs">
                    <a href="#nexdirectory-tab-general" class="nav-tab nav-tab-active" data-tab="general"><span class="dashicons dashicons-admin-generic" aria-hidden="true"></span><?php esc_html_e('General', 'nexdirectory'); ?></a>
                    <a href="#nexdirectory-tab-design-maps" class="nav-tab" data-tab="design-maps"><span class="dashicons dashicons-art" aria-hidden="true"></span><?php esc_html_e('Design & Maps', 'nexdirectory'); ?></a>
                    <a href="#nexdirectory-tab-submissions" class="nav-tab" data-tab="submissions"><span class="dashicons dashicons-clipboard" aria-hidden="true"></span><?php esc_html_e('Submissions', 'nexdirectory'); ?></a>
                    <a href="#nexdirectory-tab-notifications" class="nav-tab" data-tab="notifications"><span class="dashicons dashicons-bell" aria-hidden="true"></span><?php esc_html_e('Notifications', 'nexdirectory'); ?></a>
                    <a href="#nexdirectory-tab-advanced" class="nav-tab" data-tab="advanced"><span class="dashicons dashicons-admin-tools" aria-hidden="true"></span><?php esc_html_e('Advanced', 'nexdirectory'); ?></a>
                </nav>
                <div class="nexdirectory-settings-shell">
                    <aside class="nexdirectory-settings-sidebar">
                        <h3 class="nexdirectory-settings-sidebar-title"><?php esc_html_e('Navigate Settings', 'nexdirectory'); ?></h3>
                        <p class="nexdirectory-settings-search-meta" id="nexdirectory-settings-search-meta"><?php esc_html_e('Search all sections and tabs.', 'nexdirectory'); ?></p>
                        <nav class="nexdirectory-settings-subtabs" id="nexdirectory-settings-subtabs" aria-label="<?php esc_attr_e('Settings sections', 'nexdirectory'); ?>">
                            <a href="#nexdirectory-tab-general--setup" class="nexdirectory-settings-subtab is-active" data-parent-tab="general" data-subtab="setup"><?php esc_html_e('Setup', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-general--routing" class="nexdirectory-settings-subtab" data-parent-tab="general" data-subtab="routing"><?php esc_html_e('Routing', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-general--navbar" class="nexdirectory-settings-subtab" data-parent-tab="general" data-subtab="navbar"><?php esc_html_e('Navbar', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-general--footer" class="nexdirectory-settings-subtab" data-parent-tab="general" data-subtab="footer"><?php esc_html_e('Footer', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-general--shortcodes" class="nexdirectory-settings-subtab" data-parent-tab="general" data-subtab="shortcodes"><?php esc_html_e('Shortcodes', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-design-maps--branding" class="nexdirectory-settings-subtab" data-parent-tab="design-maps" data-subtab="branding"><?php esc_html_e('Branding & UI', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-design-maps--heros" class="nexdirectory-settings-subtab" data-parent-tab="design-maps" data-subtab="heros"><?php esc_html_e('Heroes', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-design-maps--layouts" class="nexdirectory-settings-subtab" data-parent-tab="design-maps" data-subtab="layouts"><?php esc_html_e('Layouts', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-design-maps--maps" class="nexdirectory-settings-subtab" data-parent-tab="design-maps" data-subtab="maps"><?php esc_html_e('Maps Configuration', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-submissions--rules" class="nexdirectory-settings-subtab" data-parent-tab="submissions" data-subtab="rules"><?php esc_html_e('Rules & Moderation', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-submissions--permissions" class="nexdirectory-settings-subtab" data-parent-tab="submissions" data-subtab="permissions"><?php esc_html_e('Roles & Access', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-submissions--submission-form" class="nexdirectory-settings-subtab" data-parent-tab="submissions" data-subtab="submission-form"><?php esc_html_e('Form Setup & Limits', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-notifications--email" class="nexdirectory-settings-subtab" data-parent-tab="notifications" data-subtab="email"><?php esc_html_e('Email', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-notifications--alerts" class="nexdirectory-settings-subtab" data-parent-tab="notifications" data-subtab="alerts"><?php esc_html_e('Alerts', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-advanced--seo" class="nexdirectory-settings-subtab" data-parent-tab="advanced" data-subtab="seo"><?php esc_html_e('SEO', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-advanced--extension" class="nexdirectory-settings-subtab" data-parent-tab="advanced" data-subtab="extension"><?php esc_html_e('Chrome Extension', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-advanced--email" class="nexdirectory-settings-subtab" data-parent-tab="advanced" data-subtab="email"><?php esc_html_e('SMTP Email', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-advanced--apis" class="nexdirectory-settings-subtab" data-parent-tab="advanced" data-subtab="apis"><?php esc_html_e('APIs', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-advanced--display" class="nexdirectory-settings-subtab" data-parent-tab="advanced" data-subtab="display"><?php esc_html_e('Display', 'nexdirectory'); ?></a>
                            <a href="#nexdirectory-tab-advanced--logs" class="nexdirectory-settings-subtab" data-parent-tab="advanced" data-subtab="logs"><?php esc_html_e('Logs', 'nexdirectory'); ?></a>
                        </nav>
                    </aside>
                    <div class="nexdirectory-settings-content" id="nexdirectory-settings-content">
                        <div class="nexdirectory-settings-content-header">
                            <h2 id="nexdirectory-settings-active-section-title"><?php esc_html_e('Setup', 'nexdirectory'); ?></h2>
                            <p id="nexdirectory-settings-active-section-description"><?php esc_html_e('Manage configuration and preferences for this section.', 'nexdirectory'); ?></p>
                        </div>
                        <div class="nexdirectory-settings-search-empty" id="nexdirectory-settings-search-empty" hidden><?php esc_html_e('No fields matched your search across settings.', 'nexdirectory'); ?></div>
                <?php require __DIR__ . '/sections/tab-general.php'; ?>
                <?php require __DIR__ . '/sections/tab-design-maps.php'; ?>
                <?php require __DIR__ . '/sections/tab-submissions.php'; ?>
                <?php require __DIR__ . '/sections/tab-notifications.php'; ?>
                <?php require __DIR__ . '/sections/tab-advanced.php'; ?>
                    </div>
                </div>

                <div class="nexdirectory-settings-sticky-save">
                    <div class="nexdirectory-settings-sticky-status">
                        <span class="nexdirectory-settings-status-dot" id="nexdirectory-settings-status-dot" aria-hidden="true"></span>
                        <p id="nexdirectory-settings-autosave-status-sticky" class="nexdirectory-settings-autosave-status"><?php esc_html_e('No unsaved changes.', 'nexdirectory'); ?></p>
                    </div>
                    <div class="nexdirectory-settings-sticky-actions">
                        <button type="button" class="button" id="nexdirectory-settings-reset-button-sticky"><?php esc_html_e('Reset View', 'nexdirectory'); ?></button>
                        <button type="submit" class="button button-primary" id="nexdirectory-settings-save-button"><?php esc_html_e('Save Settings', 'nexdirectory'); ?></button>
                    </div>
                </div>
            </form>
            </section>
            <form id="nexdirectory-clear-logs-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="nexdirectory_clear_logs">
                <?php wp_nonce_field('nexdirectory_clear_logs', 'nexdirectory_clear_logs_nonce'); ?>
            </form>
            <form id="nexdirectory-send-test-email-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="nexdirectory_send_test_email">
                <?php wp_nonce_field('nexdirectory_send_test_email', 'nexdirectory_send_test_email_nonce'); ?>
            </form>
            <form id="nexdirectory-notification-lab-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <?php wp_nonce_field('nexdirectory_notification_lab', 'nexdirectory_notification_lab_nonce'); ?>
            </form>
            <form id="nexdirectory-test-map-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="nexdirectory_test_map_connection">
                <?php wp_nonce_field('nexdirectory_test_map_connection', 'nexdirectory_test_map_connection_nonce'); ?>
            </form>
            <form id="nexdirectory-test-captcha-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="nexdirectory_test_captcha_connection">
                <?php wp_nonce_field('nexdirectory_test_captcha_connection', 'nexdirectory_test_captcha_connection_nonce'); ?>
            </form>
            <form id="nexdirectory-test-routing-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="nexdirectory_test_routing_connection">
                <?php wp_nonce_field('nexdirectory_test_routing_connection', 'nexdirectory_test_routing_connection_nonce'); ?>
            </form>
            <form id="nexdirectory-reset-smooth-scroll-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="nexdirectory_reset_smooth_scroll_defaults">
                <?php wp_nonce_field('nexdirectory_reset_smooth_scroll_defaults', 'nexdirectory_reset_smooth_scroll_defaults_nonce'); ?>
            </form>
            <form id="nexdirectory-generate-pages-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="nexdirectory_generate_pages">
                <?php wp_nonce_field('nexdirectory_generate_pages', 'nexdirectory_generate_pages_nonce'); ?>
            </form>
            <?php foreach ($starter_blueprints as $blueprint_key => $blueprint) : ?>
                <?php
                $blueprint_key = sanitize_key((string) $blueprint_key);
                if ($blueprint_key === '') {
                    continue;
                }
                ?>
                <form id="nexdirectory-blueprint-form-<?php echo esc_attr($blueprint_key); ?>" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <input type="hidden" name="action" value="nexdirectory_apply_starter_blueprint">
                    <input type="hidden" name="nexdirectory_starter_blueprint" value="<?php echo esc_attr($blueprint_key); ?>">
                    <input type="hidden" name="nexdirectory_blueprint_include_content" value="1">
                    <input type="hidden" name="nexdirectory_blueprint_confirmed" value="0">
                    <input type="hidden" name="nexdirectory_redirect_to" value="<?php echo esc_url(admin_url('admin.php?page=nexdirectory-settings&tab=general&subtab=setup')); ?>">
                    <?php wp_nonce_field('nexdirectory_apply_starter_blueprint', 'nexdirectory_starter_blueprint_nonce'); ?>
                </form>
            <?php endforeach; ?>
            <form id="nexdirectory-regenerate-app-pass-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="nexdirectory_regenerate_extension_app_pass">
                <?php wp_nonce_field('nexdirectory_regenerate_extension_app_pass', 'nexdirectory_regenerate_extension_app_pass_nonce'); ?>
            </form>
            <div class="nexdirectory-help-dialog-backdrop" id="nexdirectory-blueprint-confirm-backdrop" data-nexdirectory-blueprint-cancel="1"></div>
            <div class="nexdirectory-help-dialog" id="nexdirectory-blueprint-confirm-dialog" role="dialog" aria-modal="true" aria-hidden="true" aria-labelledby="nexdirectory-blueprint-confirm-title" aria-describedby="nexdirectory-blueprint-confirm-message">
                <div class="nexdirectory-help-dialog-header">
                    <h3 id="nexdirectory-blueprint-confirm-title"><?php esc_html_e('Apply starter blueprint?', 'nexdirectory'); ?></h3>
                    <button type="button" class="nexdirectory-help-dialog-close" data-nexdirectory-blueprint-cancel="1" aria-label="<?php esc_attr_e('Close blueprint confirmation', 'nexdirectory'); ?>">&times;</button>
                </div>
                <div class="nexdirectory-help-dialog-body">
                    <p id="nexdirectory-blueprint-confirm-message"><?php esc_html_e('Confirm the selected starter setup changes.', 'nexdirectory'); ?></p>
                    <p><strong><?php esc_html_e('Safety:', 'nexdirectory'); ?></strong> <?php esc_html_e('Existing listings and page content are not deleted or replaced. Reapplying skips starter samples that already exist.', 'nexdirectory'); ?></p>
                </div>
                <div class="nexdirectory-settings-actions" style="display:flex;justify-content:flex-end;gap:8px;margin-top:16px;">
                    <button type="button" class="button" data-nexdirectory-blueprint-cancel="1"><?php esc_html_e('Cancel', 'nexdirectory'); ?></button>
                    <button type="button" class="button button-primary" id="nexdirectory-blueprint-confirm-submit"><?php esc_html_e('Apply Blueprint', 'nexdirectory'); ?></button>
                </div>
            </div>
            <div class="nexdirectory-help-dialog-backdrop" id="nexdirectory-settings-help-backdrop" data-nexdirectory-help-close="1"></div>
            <div class="nexdirectory-help-dialog" id="nexdirectory-settings-help-dialog" role="dialog" aria-modal="true" aria-hidden="true" aria-labelledby="nexdirectory-settings-help-title">
                <div class="nexdirectory-help-dialog-header">
                    <h3 id="nexdirectory-settings-help-title"><?php esc_html_e('Settings Help', 'nexdirectory'); ?></h3>
                    <button type="button" class="nexdirectory-help-dialog-close" data-nexdirectory-help-close="1" aria-label="<?php esc_attr_e('Close help dialog', 'nexdirectory'); ?>">&times;</button>
                </div>
                <div class="nexdirectory-help-dialog-body" id="nexdirectory-settings-help-body">
                    <p><?php esc_html_e('Click the help icons beside each field to see guidance.', 'nexdirectory'); ?></p>
                </div>
            </div>
            <?php ob_start(); ?>
                (function () {
                    var tabsRoot = document.getElementById('nexdirectory-settings-tabs');
                    if (!tabsRoot) {
                        return;
                    }
                    var tabs = tabsRoot.querySelectorAll('[data-tab]');
                    var subtabsRoot = document.getElementById('nexdirectory-settings-subtabs');
                    var subtabs = subtabsRoot ? subtabsRoot.querySelectorAll('[data-parent-tab][data-subtab]') : [];
                    var panels = document.querySelectorAll('.nexdirectory-settings-panel[data-tab][data-subtab]');
                    var settingsForm = document.querySelector('form[action="options.php"]');
                    var blueprintConfirmDialog = document.getElementById('nexdirectory-blueprint-confirm-dialog');
                    var blueprintConfirmBackdrop = document.getElementById('nexdirectory-blueprint-confirm-backdrop');
                    var blueprintConfirmTitle = document.getElementById('nexdirectory-blueprint-confirm-title');
                    var blueprintConfirmMessage = document.getElementById('nexdirectory-blueprint-confirm-message');
                    var blueprintConfirmSubmit = document.getElementById('nexdirectory-blueprint-confirm-submit');
                    var pendingBlueprintForm = null;
                    var pendingBlueprintTrigger = null;
                    var dirtyState = false;
                    var activeTabStorageKey = 'nexdirectorySettingsActiveTab';
                    var activeSubtabStorageKey = 'nexdirectorySettingsActiveSubtab';
                    var settingsSearchPrimaryInput = document.getElementById('nexdirectory-settings-search');
                    var settingsSearchTopInput = document.getElementById('nexdirectory-settings-search-top');
                    var settingsSearchInputs = [settingsSearchPrimaryInput, settingsSearchTopInput].filter(function (inputEl) {
                        return !!inputEl;
                    });
                    var settingsSearchPrimaryClear = document.getElementById('nexdirectory-settings-search-clear');
                    var settingsSearchTopClear = document.getElementById('nexdirectory-settings-search-top-clear');
                    var settingsSearchClearButtons = [settingsSearchPrimaryClear, settingsSearchTopClear].filter(function (buttonEl) {
                        return !!buttonEl;
                    });
                    var settingsSearchMeta = document.getElementById('nexdirectory-settings-search-meta');
                    var settingsSearchEmpty = document.getElementById('nexdirectory-settings-search-empty');
                    var settingsSaveButton = document.getElementById('nexdirectory-settings-save-button');
                    var resetViewButtonSticky = document.getElementById('nexdirectory-settings-reset-button-sticky');
                    var autosaveStatusNodes = [
                        document.getElementById('nexdirectory-settings-autosave-status-sticky')
                    ].filter(function (nodeEl) {
                        return !!nodeEl;
                    });
                    var autosaveStatusDot = document.getElementById('nexdirectory-settings-status-dot');
                    var activeSectionTitleNode = document.getElementById('nexdirectory-settings-active-section-title');
                    var activeSectionDescriptionNode = document.getElementById('nexdirectory-settings-active-section-description');
                    var autosaveStatusTimer = null;
                    var searchCrossTabJumpInProgress = false;
                    var closeBlueprintConfirmation = function (resetConfirmation) {
                        var confirmedInput = pendingBlueprintForm
                            ? pendingBlueprintForm.querySelector('input[name="nexdirectory_blueprint_confirmed"]')
                            : null;
                        if (resetConfirmation !== false && confirmedInput) {
                            confirmedInput.value = '0';
                        }
                        if (blueprintConfirmDialog) {
                            blueprintConfirmDialog.classList.remove('is-open');
                            blueprintConfirmDialog.setAttribute('aria-hidden', 'true');
                        }
                        if (blueprintConfirmBackdrop) {
                            blueprintConfirmBackdrop.classList.remove('is-open');
                        }
                        if (pendingBlueprintTrigger && typeof pendingBlueprintTrigger.focus === 'function') {
                            pendingBlueprintTrigger.focus();
                        }
                        pendingBlueprintForm = null;
                        pendingBlueprintTrigger = null;
                    };
                    var openBlueprintConfirmation = function (trigger) {
                        var formId = trigger ? String(trigger.getAttribute('data-blueprint-form-id') || '').trim() : '';
                        var targetForm = formId ? document.getElementById(formId) : null;
                        var confirmedInput = targetForm
                            ? targetForm.querySelector('input[name="nexdirectory_blueprint_confirmed"]')
                            : null;
                        if (!targetForm || !confirmedInput || !blueprintConfirmDialog || !blueprintConfirmBackdrop) {
                            return;
                        }
                        confirmedInput.value = '0';
                        pendingBlueprintForm = targetForm;
                        pendingBlueprintTrigger = trigger;
                        if (blueprintConfirmTitle) {
                            blueprintConfirmTitle.textContent = String(trigger.getAttribute('data-blueprint-confirm-title') || '<?php echo esc_js(__('Apply starter blueprint?', 'nexdirectory')); ?>');
                        }
                        if (blueprintConfirmMessage) {
                            blueprintConfirmMessage.textContent = String(trigger.getAttribute('data-blueprint-confirm-message') || '<?php echo esc_js(__('Confirm the selected starter setup changes.', 'nexdirectory')); ?>');
                        }
                        if (blueprintConfirmSubmit) {
                            blueprintConfirmSubmit.textContent = String(trigger.getAttribute('data-blueprint-confirm-label') || '<?php echo esc_js(__('Apply Blueprint', 'nexdirectory')); ?>');
                            blueprintConfirmSubmit.disabled = false;
                        }
                        blueprintConfirmDialog.classList.add('is-open');
                        blueprintConfirmBackdrop.classList.add('is-open');
                        blueprintConfirmDialog.setAttribute('aria-hidden', 'false');
                        if (blueprintConfirmSubmit) {
                            blueprintConfirmSubmit.focus();
                        }
                    };
                    var getSettingsSearchQuery = function () {
                        if (!settingsSearchInputs.length) {
                            return '';
                        }
                        var raw = String(settingsSearchInputs[0].value || '').trim();
                        return raw.toLowerCase();
                    };
                    var syncSettingsSearchInputs = function (value, originInput) {
                        settingsSearchInputs.forEach(function (inputEl) {
                            if (!inputEl || inputEl === originInput) {
                                return;
                            }
                            inputEl.value = String(value || '');
                        });
                    };
                    var clearSettingsSearch = function (focusInput) {
                        settingsSearchInputs.forEach(function (inputEl) {
                            if (inputEl) {
                                inputEl.value = '';
                            }
                        });
                        if (focusInput && typeof focusInput.focus === 'function') {
                            focusInput.focus();
                        }
                    };
                    var pendingBadgeToggle = document.querySelector('input[name="nexdirectory_notify_admin_pending_badge"][type="checkbox"]');
                    var pendingEmailToggle = document.querySelector('input[name="nexdirectory_notify_admin_pending_email"][type="checkbox"]');
                    var legacyPendingToggleInput = document.getElementById('nexdirectory_enable_pending_admin_notifications');
                    var syncLegacyPendingToggle = function () {
                        if (!legacyPendingToggleInput) {
                            return;
                        }
                        var enabled = false;
                        if (pendingBadgeToggle && pendingBadgeToggle.checked) {
                            enabled = true;
                        }
                        if (pendingEmailToggle && pendingEmailToggle.checked) {
                            enabled = true;
                        }
                        legacyPendingToggleInput.value = enabled ? '1' : '0';
                    };
                    if (pendingBadgeToggle) {
                        pendingBadgeToggle.addEventListener('change', syncLegacyPendingToggle);
                    }
                    if (pendingEmailToggle) {
                        pendingEmailToggle.addEventListener('change', syncLegacyPendingToggle);
                    }
                    syncLegacyPendingToggle();
                    document.addEventListener('click', function (event) {
                        var submitter = event.target ? event.target.closest('button[form]') : null;
                        if (!submitter) {
                            return;
                        }
                        var formId = String(submitter.getAttribute('form') || '').trim();
                        if (!formId) {
                            return;
                        }
                        var externalForm = document.getElementById(formId);
                        if (!externalForm) {
                            return;
                        }
                        var parentForm = submitter.closest('form');
                        if (parentForm && parentForm === externalForm) {
                            return;
                        }
                        if (submitter.disabled) {
                            return;
                        }
                        event.preventDefault();
                        if (typeof externalForm.requestSubmit === 'function') {
                            externalForm.requestSubmit(submitter);
                            return;
                        }
                        var submitterName = String(submitter.getAttribute('name') || '').trim();
                        var submitterValue = String(submitter.getAttribute('value') || '');
                        if (submitterName) {
                            var submitterInput = document.createElement('input');
                            submitterInput.type = 'hidden';
                            submitterInput.name = submitterName;
                            submitterInput.value = submitterValue;
                            externalForm.appendChild(submitterInput);
                        }
                        externalForm.submit();
                    });
                    var getActivePanel = function () {
                        return document.querySelector('.nexdirectory-settings-panel.is-active');
                    };
                    var getSubtabLabel = function (parentKey, subtabKey) {
                        var label = '';
                        subtabs.forEach(function (subtab) {
                            var tabParent = String(subtab.getAttribute('data-parent-tab') || '').trim();
                            var tabChild = String(subtab.getAttribute('data-subtab') || '').trim();
                            if (tabParent === String(parentKey || '').trim() && tabChild === String(subtabKey || '').trim()) {
                                label = String(subtab.textContent || '').trim();
                            }
                        });
                        return label;
                    };
                    var getTabLabel = function (tabKey) {
                        var label = '';
                        tabs.forEach(function (tab) {
                            if (label) {
                                return;
                            }
                            if (String(tab.getAttribute('data-tab') || '').trim() !== String(tabKey || '').trim()) {
                                return;
                            }
                            label = String(tab.textContent || '').replace(/\s+/g, ' ').trim();
                        });
                        return label;
                    };
                    var updateActiveSectionHeader = function (parentKey, subtabKey) {
                        if (!activeSectionTitleNode && !activeSectionDescriptionNode) {
                            return;
                        }
                        var subtabLabel = getSubtabLabel(parentKey, subtabKey);
                        var tabLabel = getTabLabel(parentKey);
                        if (activeSectionTitleNode) {
                            activeSectionTitleNode.textContent = subtabLabel || '<?php echo esc_js(__('Settings', 'nexdirectory')); ?>';
                        }
                        if (activeSectionDescriptionNode) {
                            if (subtabLabel && tabLabel) {
                                activeSectionDescriptionNode.textContent = '<?php echo esc_js(__('Manage configuration and preferences for', 'nexdirectory')); ?> ' + tabLabel + ' / ' + subtabLabel + '.';
                            } else {
                                activeSectionDescriptionNode.textContent = '<?php echo esc_js(__('Manage configuration and preferences for this section.', 'nexdirectory')); ?>';
                            }
                        }
                    };
                    var isControlDisabled = function (el) {
                        if (!el) {
                            return false;
                        }
                        return String(el.getAttribute('data-disabled') || '').trim() === '1';
                    };
                    var getFieldSearchText = function (fieldEl) {
                        if (!fieldEl) {
                            return '';
                        }
                        var cache = String(fieldEl.getAttribute('data-nexdirectory-search-text') || '').trim();
                        if (cache !== '') {
                            return cache;
                        }
                        var textParts = [];
                        var titleNodes = fieldEl.querySelectorAll('label, h2, h3, h4, legend, summary, strong');
                        titleNodes.forEach(function (node) {
                            var text = String(node.textContent || '').replace(/\s+/g, ' ').trim();
                            if (text) {
                                textParts.push(text);
                            }
                        });
                        var descriptionNodes = fieldEl.querySelectorAll('.description');
                        descriptionNodes.forEach(function (node) {
                            var text = String(node.textContent || '').replace(/\s+/g, ' ').trim();
                            if (text) {
                                textParts.push(text);
                            }
                        });
                        var valueNodes = fieldEl.querySelectorAll('input, textarea, select, option, button, code');
                        valueNodes.forEach(function (node) {
                            var text = String(node.textContent || '').replace(/\s+/g, ' ').trim();
                            if (text) {
                                textParts.push(text);
                            }
                            var attrs = ['name', 'id', 'placeholder', 'value', 'data-subtab', 'data-parent-tab'];
                            attrs.forEach(function (attrKey) {
                                var attrValue = String(node.getAttribute(attrKey) || '').replace(/\s+/g, ' ').trim();
                                if (attrValue) {
                                    textParts.push(attrValue);
                                }
                            });
                        });
                        var fallbackFieldText = String(fieldEl.textContent || '').replace(/\s+/g, ' ').trim();
                        if (fallbackFieldText) {
                            textParts.push(fallbackFieldText);
                        }
                        var serialized = textParts.join(' ').toLowerCase();
                        fieldEl.setAttribute('data-nexdirectory-search-text', serialized);
                        return serialized;
                    };
                    var applySettingsSearch = function (parentKey, subtabKey, allowCrossTabJump) {
                        var canCrossTabJump = !!allowCrossTabJump;
                        var panel = getActivePanel();
                        var query = getSettingsSearchQuery();
                        var globalMatchCount = 0;
                        var globalSectionsWithMatches = [];
                        var firstMatchingPanel = null;
                        panels.forEach(function (panelEl) {
                            if (!panelEl) {
                                return;
                            }
                            var panelParent = String(panelEl.getAttribute('data-tab') || '').trim();
                            var panelSubtab = String(panelEl.getAttribute('data-subtab') || '').trim();
                            if (!panelParent || !panelSubtab) {
                                return;
                            }
                            var matchingSubtab = null;
                            subtabs.forEach(function (subtabEl) {
                                if (matchingSubtab) {
                                    return;
                                }
                                var subParent = String(subtabEl.getAttribute('data-parent-tab') || '').trim();
                                var subChild = String(subtabEl.getAttribute('data-subtab') || '').trim();
                                if (subParent === panelParent && subChild === panelSubtab) {
                                    matchingSubtab = subtabEl;
                                }
                            });
                            if (matchingSubtab && isControlDisabled(matchingSubtab)) {
                                return;
                            }
                            var panelFields = panelEl.querySelectorAll('.nexdirectory-settings-field');
                            var panelMatches = 0;
                            panelFields.forEach(function (fieldEl) {
                                var matched = true;
                                if (query !== '') {
                                    matched = getFieldSearchText(fieldEl).indexOf(query) > -1;
                                }
                                fieldEl.classList.toggle('nexdirectory-search-hidden', !matched);
                                if (matched) {
                                    panelMatches += 1;
                                }
                            });
                            if (query !== '' && panelMatches > 0) {
                                globalMatchCount += panelMatches;
                                globalSectionsWithMatches.push(panelParent + '::' + panelSubtab);
                                if (!firstMatchingPanel) {
                                    firstMatchingPanel = {
                                        parent: panelParent,
                                        subtab: panelSubtab
                                    };
                                }
                            }
                        });
                        if (!panel) {
                            if (settingsSearchMeta) {
                                settingsSearchMeta.textContent = '<?php echo esc_js(__('No settings section is active.', 'nexdirectory')); ?>';
                            }
                            if (settingsSearchEmpty) {
                                settingsSearchEmpty.hidden = true;
                            }
                            return;
                        }
                        if (query !== '' && canCrossTabJump && firstMatchingPanel && !searchCrossTabJumpInProgress) {
                            var activeParent = String(panel.getAttribute('data-tab') || '').trim();
                            var activeSubtab = String(panel.getAttribute('data-subtab') || '').trim();
                            if (activeParent !== firstMatchingPanel.parent || activeSubtab !== firstMatchingPanel.subtab) {
                                searchCrossTabJumpInProgress = true;
                                activate(firstMatchingPanel.parent, firstMatchingPanel.subtab);
                                searchCrossTabJumpInProgress = false;
                                return;
                            }
                        }
                        panel = getActivePanel();
                        if (settingsSearchMeta) {
                            var sectionLabel = getSubtabLabel(parentKey, subtabKey);
                            if (query === '') {
                                settingsSearchMeta.textContent = sectionLabel
                                    ? '<?php echo esc_js(__('Viewing section:', 'nexdirectory')); ?> ' + sectionLabel
                                    : '<?php echo esc_js(__('Search all sections and tabs.', 'nexdirectory')); ?>';
                            } else {
                                var sectionCount = Array.from(new Set(globalSectionsWithMatches)).length;
                                if (globalMatchCount > 0) {
                                    settingsSearchMeta.textContent = globalMatchCount + ' <?php echo esc_js(__('fields match across', 'nexdirectory')); ?> ' + sectionCount + ' <?php echo esc_js(__('sections.', 'nexdirectory')); ?>';
                                } else {
                                    settingsSearchMeta.textContent = '<?php echo esc_js(__('No settings fields matched your search.', 'nexdirectory')); ?>';
                                }
                            }
                        }
                        if (settingsSearchEmpty) {
                            settingsSearchEmpty.hidden = !(query !== '' && globalMatchCount === 0);
                        }
                    };
                    var findFirstSubtab = function (parentKey) {
                        var found = '';
                        subtabs.forEach(function (subtab) {
                            if (found !== '') {
                                return;
                            }
                            if (isControlDisabled(subtab)) {
                                return;
                            }
                            if (String(subtab.getAttribute('data-parent-tab') || '') === String(parentKey || '')) {
                                found = String(subtab.getAttribute('data-subtab') || '').trim();
                            }
                        });
                        return found;
                    };
                    var activate = function (parentKey, subtabKey) {
                        if (!parentKey) {
                            parentKey = 'general';
                        }
                        var parentMatched = false;
                        tabs.forEach(function (tab) {
                            if (tab.getAttribute('data-tab') === parentKey && !isControlDisabled(tab)) {
                                parentMatched = true;
                            }
                        });
                        if (!parentMatched) {
                            parentKey = 'general';
                        }
                        if (!subtabKey) {
                            subtabKey = findFirstSubtab(parentKey);
                        }
                        var subtabMatched = false;
                        subtabs.forEach(function (subtab) {
                            if (String(subtab.getAttribute('data-parent-tab') || '') === parentKey && String(subtab.getAttribute('data-subtab') || '') === subtabKey) {
                                subtabMatched = true;
                            }
                        });
                        if (!subtabMatched) {
                            subtabKey = findFirstSubtab(parentKey);
                        }
                        tabs.forEach(function (tab) {
                            var active = tab.getAttribute('data-tab') === parentKey;
                            tab.classList.toggle('nav-tab-active', active);
                        });
                        subtabs.forEach(function (subtab) {
                            var tabParent = String(subtab.getAttribute('data-parent-tab') || '').trim();
                            var tabChild = String(subtab.getAttribute('data-subtab') || '').trim();
                            var visible = tabParent === parentKey;
                            subtab.hidden = !visible;
                            subtab.classList.toggle('is-active', visible && tabChild === subtabKey);
                        });
                        panels.forEach(function (panel) {
                            var active = panel.getAttribute('data-tab') === parentKey && panel.getAttribute('data-subtab') === subtabKey;
                            panel.classList.toggle('is-active', active);
                        });
                        updateActiveSectionHeader(parentKey, subtabKey);
                        applySettingsSearch(parentKey, subtabKey, false);
                        try {
                            window.localStorage.setItem(activeTabStorageKey, parentKey);
                            window.localStorage.setItem(activeSubtabStorageKey, subtabKey);
                        } catch (storageError) {
                            // no-op
                        }
                        try {
                            if (window.history && typeof window.history.replaceState === 'function') {
                                var baseUrl = String(window.location.href || '').split('#')[0];
                                var hash = '#nexdirectory-tab-' + parentKey;
                                if (subtabKey) {
                                    hash += '--' + subtabKey;
                                }
                                window.history.replaceState({}, '', baseUrl + hash);
                            }
                        } catch (historyError) {
                            // no-op
                        }
                    };
                    var setSettingsStatus = function (message, tone, persist) {
                        if (!autosaveStatusNodes.length) {
                            return;
                        }
                        autosaveStatusNodes.forEach(function (statusNode) {
                            statusNode.textContent = String(message || '').trim();
                            if (tone) {
                                statusNode.setAttribute('data-tone', String(tone));
                            } else {
                                statusNode.removeAttribute('data-tone');
                            }
                        });
                        if (autosaveStatusDot) {
                            if (tone) {
                                autosaveStatusDot.setAttribute('data-tone', String(tone));
                            } else {
                                autosaveStatusDot.removeAttribute('data-tone');
                            }
                        }
                        if (autosaveStatusTimer) {
                            window.clearTimeout(autosaveStatusTimer);
                            autosaveStatusTimer = null;
                        }
                        if (!persist && String(message || '').trim() !== '') {
                            autosaveStatusTimer = window.setTimeout(function () {
                                setSettingsStatus('<?php echo esc_js(__('No unsaved changes.', 'nexdirectory')); ?>', '', true);
                            }, 2800);
                        }
                    };
                    var markDirty = function () {
                        dirtyState = true;
                        if (settingsSaveButton) {
                            settingsSaveButton.disabled = false;
                        }
                        setSettingsStatus('<?php echo esc_js(__('Unsaved changes. Review and save when ready.', 'nexdirectory')); ?>', 'pending', true);
                    };
                    var clearDirty = function () {
                        dirtyState = false;
                    };
                    if (settingsForm) {
                        settingsForm.querySelectorAll('input[name], select[name], textarea[name]').forEach(function (inputEl) {
                            if (inputEl.form !== settingsForm) {
                                return;
                            }
                            inputEl.addEventListener('input', markDirty);
                            inputEl.addEventListener('change', markDirty);
                        });
                        settingsForm.addEventListener('submit', function () {
                            syncLegacyPendingToggle();
                            setSettingsStatus('<?php echo esc_js(__('Saving settings...', 'nexdirectory')); ?>', 'pending', true);
                            if (settingsSaveButton) {
                                settingsSaveButton.disabled = true;
                            }
                            clearDirty();
                        });
                        if (settingsSaveButton) {
                            settingsSaveButton.disabled = true;
                        }
                        window.addEventListener('beforeunload', function (event) {
                            if (!dirtyState) {
                                return;
                            }
                            event.preventDefault();
                            event.returnValue = '';
                        });
                    }
                    var resetSettingsView = function () {
                        var shouldReset = window.confirm('<?php echo esc_js(__('Reset the settings view and reload this page?', 'nexdirectory')); ?>');
                        if (!shouldReset) {
                            return;
                        }
                        try {
                            window.localStorage.removeItem(activeTabStorageKey);
                            window.localStorage.removeItem(activeSubtabStorageKey);
                        } catch (storageError) {
                            // no-op
                        }
                        var cleanUrl = String(window.location.href || '').split('#')[0];
                        window.location.href = cleanUrl;
                    };
                    if (resetViewButtonSticky) {
                        resetViewButtonSticky.addEventListener('click', resetSettingsView);
                    }
                    tabs.forEach(function (tab) {
                        tab.addEventListener('click', function (event) {
                            event.preventDefault();
                            if (isControlDisabled(tab)) {
                                return;
                            }
                            var key = tab.getAttribute('data-tab') || '';
                            if (key) {
                                activate(key, findFirstSubtab(key));
                            }
                        });
                    });
                    subtabs.forEach(function (subtab) {
                        subtab.addEventListener('click', function (event) {
                            event.preventDefault();
                            if (isControlDisabled(subtab)) {
                                return;
                            }
                            var parentKey = String(subtab.getAttribute('data-parent-tab') || '').trim();
                            var childKey = String(subtab.getAttribute('data-subtab') || '').trim();
                            if (parentKey && childKey) {
                                activate(parentKey, childKey);
                            }
                        });
                    });
                    var hashTab = '';
                    var hashSubtab = '';
                    var hashValue = String(window.location.hash || '').trim();
                    if (hashValue.indexOf('#nexdirectory-tab-') === 0) {
                        var hashToken = hashValue.replace('#nexdirectory-tab-', '');
                        if (hashToken.indexOf('--') > -1) {
                            var hashParts = hashToken.split('--');
                            hashTab = String(hashParts.shift() || '').trim();
                            hashSubtab = String(hashParts.shift() || '').trim();
                        } else {
                            hashTab = String(hashToken || '').trim();
                        }
                    }
                    if ((hashTab === '' || hashSubtab === '') && /^#nexdirectory-tab-[a-z0-9-]+$/i.test(hashValue)) {
                        var panelFromHash = document.getElementById(hashValue.replace('#', ''));
                        if (panelFromHash && panelFromHash.hasAttribute('data-tab') && panelFromHash.hasAttribute('data-subtab')) {
                            hashTab = String(panelFromHash.getAttribute('data-tab') || hashTab).trim();
                            hashSubtab = String(panelFromHash.getAttribute('data-subtab') || hashSubtab).trim();
                        }
                    }
                    var storedTab = '';
                    var storedSubtab = '';
                    try {
                        storedTab = String(window.localStorage.getItem(activeTabStorageKey) || '').trim();
                        storedSubtab = String(window.localStorage.getItem(activeSubtabStorageKey) || '').trim();
                    } catch (storageError) {
                        storedTab = '';
                        storedSubtab = '';
                    }
                    var initialTab = hashTab || storedTab || 'general';
                    var initialSubtab = hashSubtab || storedSubtab || '';
                    activate(initialTab, initialSubtab);
                    settingsSearchInputs.forEach(function (searchInput) {
                        searchInput.addEventListener('input', function () {
                            syncSettingsSearchInputs(searchInput.value, searchInput);
                            var activePanel = getActivePanel();
                            var tabKey = activePanel ? String(activePanel.getAttribute('data-tab') || '').trim() : initialTab;
                            var subtabKey = activePanel ? String(activePanel.getAttribute('data-subtab') || '').trim() : initialSubtab;
                            applySettingsSearch(tabKey, subtabKey, true);
                        });
                        searchInput.addEventListener('keydown', function (event) {
                            if (event.key === 'Escape') {
                                clearSettingsSearch(searchInput);
                                var activePanel = getActivePanel();
                                var tabKey = activePanel ? String(activePanel.getAttribute('data-tab') || '').trim() : initialTab;
                                var subtabKey = activePanel ? String(activePanel.getAttribute('data-subtab') || '').trim() : initialSubtab;
                                applySettingsSearch(tabKey, subtabKey, true);
                            }
                        });
                    });
                    settingsSearchClearButtons.forEach(function (clearButton) {
                        clearButton.addEventListener('click', function () {
                            var targetInputId = String(clearButton.getAttribute('data-target-input') || '').trim();
                            var focusTarget = targetInputId ? document.getElementById(targetInputId) : settingsSearchTopInput || settingsSearchPrimaryInput;
                            if (!focusTarget) {
                                focusTarget = settingsSearchTopInput || settingsSearchPrimaryInput;
                            }
                            clearSettingsSearch(focusTarget);
                            var activePanel = getActivePanel();
                            var tabKey = activePanel ? String(activePanel.getAttribute('data-tab') || '').trim() : initialTab;
                            var subtabKey = activePanel ? String(activePanel.getAttribute('data-subtab') || '').trim() : initialSubtab;
                            applySettingsSearch(tabKey, subtabKey, true);
                        });
                    });
                    document.addEventListener('keydown', function (event) {
                        var primarySearchInput = settingsSearchTopInput || settingsSearchPrimaryInput;
                        if (!primarySearchInput) {
                            return;
                        }
                        if (event.key !== '/') {
                            return;
                        }
                        var activeTag = document.activeElement ? String(document.activeElement.tagName || '').toLowerCase() : '';
                        if (activeTag === 'input' || activeTag === 'textarea' || activeTag === 'select') {
                            return;
                        }
                        event.preventDefault();
                        primarySearchInput.focus();
                    });

                    var autosaveToggle = document.getElementById('nexdirectory_enable_submit_autosave');
                    var autosaveField = document.getElementById('nexdirectory-autosave-interval-field');
                    var syncAutosaveField = function () {
                        if (!autosaveToggle || !autosaveField) {
                            return;
                        }
                        var enabled = !!autosaveToggle.checked;
                        autosaveField.style.display = enabled ? '' : 'none';
                    };
                    if (autosaveToggle && autosaveField) {
                        autosaveToggle.addEventListener('change', syncAutosaveField);
                        syncAutosaveField();
                    }

                    var themeOverrideMasterToggle = document.getElementById('nexdirectory_theme_override_all_plugin_pages');
                    var themeOverrideGranular = document.getElementById('nexdirectory-theme-override-granular');
                    var syncThemeOverrideFields = function () {
                        if (!themeOverrideMasterToggle || !themeOverrideGranular) {
                            return;
                        }
                        var showGranular = !themeOverrideMasterToggle.checked;
                        themeOverrideGranular.style.display = showGranular ? '' : 'none';
                    };
                    if (themeOverrideMasterToggle && themeOverrideGranular) {
                        themeOverrideMasterToggle.addEventListener('change', syncThemeOverrideFields);
                        syncThemeOverrideFields();
                    }

                    var presetSelects = document.querySelectorAll('[data-nexdirectory-preset-target]');
                    presetSelects.forEach(function (selectEl) {
                        var targetSelector = selectEl.getAttribute('data-nexdirectory-preset-target') || '';
                        if (!targetSelector) {
                            return;
                        }
                        var targetInput = document.querySelector(targetSelector);
                        if (!targetInput) {
                            return;
                        }
                        selectEl.addEventListener('change', function () {
                            var value = String(selectEl.value || '').trim();
                            if (value && value !== 'custom') {
                                targetInput.value = value;
                                markDirty();
                            }
                        });
                    });

                    var initHomepageSeoPreview = function () {
                        var titleInput = document.getElementById('nexdirectory_home_meta_title');
                        var descriptionInput = document.getElementById('nexdirectory_home_meta_description');
                        var titleCount = document.getElementById('nexdirectory-home-meta-title-count');
                        var descriptionCount = document.getElementById('nexdirectory-home-meta-description-count');
                        var titleStatus = document.getElementById('nexdirectory-home-meta-title-status');
                        var descriptionStatus = document.getElementById('nexdirectory-home-meta-description-status');
                        var serpTitle = document.getElementById('nexdirectory-home-serp-title');
                        var serpDescription = document.getElementById('nexdirectory-home-serp-description');
                        if (!titleInput || !descriptionInput || !titleCount || !descriptionCount || !titleStatus || !descriptionStatus || !serpTitle || !serpDescription) {
                            return;
                        }

                        var fallbackSerpTitle = String(serpTitle.textContent || '').trim();
                        var fallbackSerpDescription = String(serpDescription.textContent || '').trim();

                        var countChars = function (value) {
                            return Array.from(String(value || '')).length;
                        };
                        var buildTitleStatus = function (count) {
                            if (count === 0) {
                                return '<?php echo esc_js(__('Set an SEO title for homepage search results.', 'nexdirectory')); ?>';
                            }
                            if (count < 50) {
                                return '<?php echo esc_js(__('Too short. Aim for 50–60 characters.', 'nexdirectory')); ?>';
                            }
                            if (count <= 60) {
                                return '<?php echo esc_js(__('Good length for search display.', 'nexdirectory')); ?>';
                            }
                            return '<?php echo esc_js(__('Too long. Keep it under 60 characters.', 'nexdirectory')); ?>';
                        };
                        var buildDescriptionStatus = function (count) {
                            if (count === 0) {
                                return '<?php echo esc_js(__('Write a concise summary for homepage search snippets.', 'nexdirectory')); ?>';
                            }
                            if (count < 120) {
                                return '<?php echo esc_js(__('Too short. Aim for 120–158 characters.', 'nexdirectory')); ?>';
                            }
                            if (count <= 158) {
                                return '<?php echo esc_js(__('Good length for search display.', 'nexdirectory')); ?>';
                            }
                            return '<?php echo esc_js(__('Too long. Keep it under 158 characters.', 'nexdirectory')); ?>';
                        };
                        var sync = function () {
                            var titleValue = String(titleInput.value || '').trim();
                            var descriptionValue = String(descriptionInput.value || '').trim();
                            var titleLength = countChars(titleValue);
                            var descriptionLength = countChars(descriptionValue);

                            titleCount.textContent = String(titleLength);
                            descriptionCount.textContent = String(descriptionLength);
                            titleStatus.textContent = buildTitleStatus(titleLength);
                            descriptionStatus.textContent = buildDescriptionStatus(descriptionLength);

                            serpTitle.textContent = titleValue || fallbackSerpTitle;
                            serpDescription.textContent = descriptionValue || fallbackSerpDescription;
                        };

                        titleInput.addEventListener('input', sync);
                        descriptionInput.addEventListener('input', sync);
                        titleInput.addEventListener('change', sync);
                        descriptionInput.addEventListener('change', sync);
                        sync();
                    };
                    initHomepageSeoPreview();

                    var buildVisualSelectors = function () {
                        var selects = document.querySelectorAll('select[data-nexdirectory-visual-select]');
                        selects.forEach(function (selectEl) {
                            if (!selectEl || selectEl.nextElementSibling && selectEl.nextElementSibling.classList.contains('nexdirectory-settings-visual-options')) {
                                return;
                            }
                            var wrapper = document.createElement('div');
                            wrapper.className = 'nexdirectory-settings-visual-options';
                            var syncActiveOption = function () {
                                var currentValue = String(selectEl.value || '');
                                wrapper.querySelectorAll('.nexdirectory-settings-visual-option').forEach(function (opt) {
                                    var value = String(opt.getAttribute('data-nexdirectory-value') || '');
                                    opt.classList.toggle('is-active', value === currentValue);
                                });
                            };
                            Array.prototype.forEach.call(selectEl.options || [], function (option) {
                                if (!option || option.disabled) {
                                    return;
                                }
                                var button = document.createElement('button');
                                button.type = 'button';
                                button.className = 'nexdirectory-settings-visual-option';
                                button.setAttribute('data-nexdirectory-value', String(option.value || ''));
                                var title = document.createElement('strong');
                                title.textContent = String(option.textContent || '').trim();
                                button.appendChild(title);
                                var hint = document.createElement('span');
                                hint.textContent = '<?php echo esc_js(__('Click to apply this layout', 'nexdirectory')); ?>';
                                button.appendChild(hint);
                                if (String(selectEl.value || '') === String(option.value || '')) {
                                    button.classList.add('is-active');
                                }
                                button.addEventListener('click', function () {
                                    selectEl.value = String(option.value || '');
                                    selectEl.dispatchEvent(new Event('change', { bubbles: true }));
                                    syncActiveOption();
                                    markDirty();
                                });
                                wrapper.appendChild(button);
                            });
                            selectEl.insertAdjacentElement('afterend', wrapper);
                            selectEl.addEventListener('change', syncActiveOption);
                            syncActiveOption();
                        });
                    };
                    buildVisualSelectors();

                    var initDesignChoiceGrids = function () {
                        var grids = document.querySelectorAll('[data-nexdirectory-choice-grid][data-nexdirectory-select]');
                        grids.forEach(function (grid) {
                            var selectSelector = String(grid.getAttribute('data-nexdirectory-select') || '').trim();
                            if (!selectSelector) {
                                return;
                            }
                            var selectEl = document.querySelector(selectSelector);
                            if (!selectEl) {
                                return;
                            }
                            var sync = function () {
                                var currentValue = String(selectEl.value || '');
                                grid.querySelectorAll('.nexdirectory-design-choice').forEach(function (choice) {
                                    var choiceValue = String(choice.getAttribute('data-nexdirectory-choice-value') || '');
                                    choice.classList.toggle('is-active', choiceValue === currentValue);
                                });
                            };
                            grid.querySelectorAll('.nexdirectory-design-choice').forEach(function (choice) {
                                choice.addEventListener('click', function () {
                                    var nextValue = String(choice.getAttribute('data-nexdirectory-choice-value') || '');
                                    if (!nextValue || !Array.prototype.some.call(selectEl.options || [], function (option) { return String(option.value || '') === nextValue; })) {
                                        return;
                                    }
                                    selectEl.value = nextValue;
                                    selectEl.dispatchEvent(new Event('change', { bubbles: true }));
                                    sync();
                                    markDirty();
                                });
                            });
                            selectEl.addEventListener('change', sync);
                            sync();
                        });
                    };
                    initDesignChoiceGrids();

                    var initDesignPresets = function () {
                        var presetSelect = document.querySelector('[data-nexdirectory-design-preset-select]');
                        var presetApply = document.querySelector('[data-nexdirectory-design-preset-apply]');
                        var presetStatus = document.querySelector('[data-nexdirectory-design-preset-status]');
                        if (!presetSelect || !presetApply) {
                            return;
                        }
                        var presets = {
                            'launchpad-modern': {
                                label: 'Launchpad Modern',
                                values: {
                                    nexdirectory_event_hero_layout: 'cinematic',
                                    nexdirectory_event_page_layout: 'modern',
                                    nexdirectory_event_gallery_type: 'default',
                                    nexdirectory_style_box_style: 'default',
                                    nexdirectory_style_button_style: 'solid',
                                    nexdirectory_style_button_radius_mode: 'inherit',
                                    nexdirectory_style_input_style: 'outline',
                                    nexdirectory_style_density_mode: 'comfortable',
                                    nexdirectory_style_border_mode: 'subtle',
                                    nexdirectory_style_shadow_mode: 'soft',
                                    nexdirectory_style_content_width: 'standard',
                                    nexdirectory_page_side_padding: '10%',
                                    nexdirectory_page_side_padding_mobile: '2%'
                                }
                            },
                            'minimal-focus': {
                                label: 'Minimal Focus',
                                values: {
                                    nexdirectory_event_hero_layout: 'minimal',
                                    nexdirectory_event_page_layout: 'single-column',
                                    nexdirectory_event_gallery_type: 'default',
                                    nexdirectory_style_box_style: 'default',
                                    nexdirectory_style_button_style: 'outline',
                                    nexdirectory_style_button_radius_mode: 'sharp',
                                    nexdirectory_style_input_style: 'underlined',
                                    nexdirectory_style_density_mode: 'loose',
                                    nexdirectory_style_border_mode: 'minimal',
                                    nexdirectory_style_shadow_mode: 'none',
                                    nexdirectory_style_content_width: 'narrow',
                                    nexdirectory_page_side_padding: '8%',
                                    nexdirectory_page_side_padding_mobile: '4%'
                                }
                            },
                            'editorial-story': {
                                label: 'Editorial Story',
                                values: {
                                    nexdirectory_event_hero_layout: 'split',
                                    nexdirectory_event_page_layout: 'editorial',
                                    nexdirectory_event_gallery_type: 'default',
                                    nexdirectory_style_box_style: 'gradient',
                                    nexdirectory_style_button_style: 'soft',
                                    nexdirectory_style_button_radius_mode: 'inherit',
                                    nexdirectory_style_input_style: 'filled',
                                    nexdirectory_style_density_mode: 'comfortable',
                                    nexdirectory_style_border_mode: 'subtle',
                                    nexdirectory_style_shadow_mode: 'medium',
                                    nexdirectory_style_content_width: 'standard',
                                    nexdirectory_page_side_padding: '10%',
                                    nexdirectory_page_side_padding_mobile: '3%'
                                }
                            },
                            'executive-spotlight': {
                                label: 'Executive Spotlight',
                                values: {
                                    nexdirectory_event_hero_layout: 'spotlight',
                                    nexdirectory_event_page_layout: 'left-sidebar',
                                    nexdirectory_event_gallery_type: 'default',
                                    nexdirectory_style_box_style: 'bold',
                                    nexdirectory_style_button_style: 'dark',
                                    nexdirectory_style_button_radius_mode: 'sharp',
                                    nexdirectory_style_input_style: 'outline',
                                    nexdirectory_style_density_mode: 'comfortable',
                                    nexdirectory_style_border_mode: 'strong',
                                    nexdirectory_style_shadow_mode: 'medium',
                                    nexdirectory_style_content_width: 'wide',
                                    nexdirectory_page_side_padding: '8%',
                                    nexdirectory_page_side_padding_mobile: '2%'
                                }
                            },
                            'immersive-showcase': {
                                label: 'Immersive Showcase',
                                values: {
                                    nexdirectory_event_hero_layout: 'immersive',
                                    nexdirectory_event_page_layout: 'full3',
                                    nexdirectory_event_gallery_type: 'carousel',
                                    nexdirectory_style_box_style: 'gradient',
                                    nexdirectory_style_button_style: 'solid',
                                    nexdirectory_style_button_radius_mode: 'pill',
                                    nexdirectory_style_input_style: 'filled',
                                    nexdirectory_style_density_mode: 'loose',
                                    nexdirectory_style_border_mode: 'minimal',
                                    nexdirectory_style_shadow_mode: 'dramatic',
                                    nexdirectory_style_content_width: 'wide',
                                    nexdirectory_page_side_padding: '6%',
                                    nexdirectory_page_side_padding_mobile: '2%'
                                }
                            },
                            'compact-control': {
                                label: 'Compact Control',
                                values: {
                                    nexdirectory_event_hero_layout: 'compact',
                                    nexdirectory_event_page_layout: 'zig-zag',
                                    nexdirectory_event_gallery_type: 'default',
                                    nexdirectory_style_box_style: 'default',
                                    nexdirectory_style_button_style: 'outline',
                                    nexdirectory_style_button_radius_mode: 'sharp',
                                    nexdirectory_style_input_style: 'outline',
                                    nexdirectory_style_density_mode: 'compact',
                                    nexdirectory_style_border_mode: 'strong',
                                    nexdirectory_style_shadow_mode: 'soft',
                                    nexdirectory_style_content_width: 'standard',
                                    nexdirectory_page_side_padding: '7%',
                                    nexdirectory_page_side_padding_mobile: '2%'
                                }
                            },
                            'zen-clean': {
                                label: 'Zen Clean',
                                values: {
                                    nexdirectory_event_hero_layout: 'minimal',
                                    nexdirectory_event_page_layout: 'zen',
                                    nexdirectory_event_gallery_type: 'default',
                                    nexdirectory_style_box_style: 'default',
                                    nexdirectory_style_button_style: 'soft',
                                    nexdirectory_style_button_radius_mode: 'inherit',
                                    nexdirectory_style_input_style: 'underlined',
                                    nexdirectory_style_density_mode: 'loose',
                                    nexdirectory_style_border_mode: 'minimal',
                                    nexdirectory_style_shadow_mode: 'none',
                                    nexdirectory_style_content_width: 'narrow',
                                    nexdirectory_page_side_padding: '9%',
                                    nexdirectory_page_side_padding_mobile: '4%'
                                }
                            },
                            'bold-campaign': {
                                label: 'Bold Campaign',
                                values: {
                                    nexdirectory_event_hero_layout: 'cinematic',
                                    nexdirectory_event_page_layout: 'fifty-fifty',
                                    nexdirectory_event_gallery_type: 'carousel',
                                    nexdirectory_style_box_style: 'bold',
                                    nexdirectory_style_button_style: 'solid',
                                    nexdirectory_style_button_radius_mode: 'pill',
                                    nexdirectory_style_input_style: 'filled',
                                    nexdirectory_style_density_mode: 'compact',
                                    nexdirectory_style_border_mode: 'strong',
                                    nexdirectory_style_shadow_mode: 'dramatic',
                                    nexdirectory_style_content_width: 'full',
                                    nexdirectory_page_side_padding: '4%',
                                    nexdirectory_page_side_padding_mobile: '2%'
                                }
                            },
                            'gallery-plus': {
                                label: 'Gallery Plus',
                                values: {
                                    nexdirectory_event_hero_layout: 'split',
                                    nexdirectory_event_page_layout: 'full3',
                                    nexdirectory_event_gallery_type: 'wall',
                                    nexdirectory_style_box_style: 'gradient',
                                    nexdirectory_style_button_style: 'dark',
                                    nexdirectory_style_button_radius_mode: 'inherit',
                                    nexdirectory_style_input_style: 'filled',
                                    nexdirectory_style_density_mode: 'comfortable',
                                    nexdirectory_style_border_mode: 'subtle',
                                    nexdirectory_style_shadow_mode: 'medium',
                                    nexdirectory_style_content_width: 'wide',
                                    nexdirectory_page_side_padding: '6%',
                                    nexdirectory_page_side_padding_mobile: '2%'
                                }
                            },
                            'professional-default': {
                                label: 'Professional Default',
                                values: {
                                    nexdirectory_event_hero_layout: 'cinematic',
                                    nexdirectory_event_page_layout: 'modern',
                                    nexdirectory_event_gallery_type: 'default',
                                    nexdirectory_style_box_style: 'default',
                                    nexdirectory_style_button_style: 'solid',
                                    nexdirectory_style_button_radius_mode: 'inherit',
                                    nexdirectory_style_input_style: 'outline',
                                    nexdirectory_style_density_mode: 'comfortable',
                                    nexdirectory_style_border_mode: 'subtle',
                                    nexdirectory_style_shadow_mode: 'soft',
                                    nexdirectory_style_content_width: 'standard',
                                    nexdirectory_page_side_padding: '10%',
                                    nexdirectory_page_side_padding_mobile: '2%'
                                }
                            }
                        };
                        var applyPreset = function (presetKey) {
                            var config = presets[String(presetKey || '')] || null;
                            if (!config || !config.values) {
                                return false;
                            }
                            Object.keys(config.values).forEach(function (fieldId) {
                                var field = document.getElementById(fieldId);
                                if (!field) {
                                    return;
                                }
                                var nextValue = String(config.values[fieldId]);
                                if (String(field.value || '') === nextValue) {
                                    return;
                                }
                                field.value = nextValue;
                                field.dispatchEvent(new Event('input', { bubbles: true }));
                                field.dispatchEvent(new Event('change', { bubbles: true }));
                            });
                            markDirty();
                            if (presetStatus) {
                                presetStatus.textContent = config.label + ' <?php echo esc_js(__('preset applied. Save settings to publish it.', 'nexdirectory')); ?>';
                            }
                            return true;
                        };
                        presetApply.addEventListener('click', function () {
                            var selectedKey = String(presetSelect.value || '');
                            if (!applyPreset(selectedKey) && presetStatus) {
                                presetStatus.textContent = '<?php echo esc_js(__('Choose a preset first.', 'nexdirectory')); ?>';
                            }
                        });
                    };
                    initDesignPresets();

                    var mapProviderSelect = document.getElementById('nexdirectory_map_provider');
                    var mapStyleSelect = document.getElementById('nexdirectory_map_style');
                    var syncMapStyleOptions = function () {
                        if (!mapProviderSelect || !mapStyleSelect) {
                            return;
                        }
                        var provider = String(mapProviderSelect.value || '').toLowerCase();
                        var selectedStillVisible = false;
                        Array.prototype.forEach.call(mapStyleSelect.options || [], function (option) {
                            var scope = String(option.getAttribute('data-provider') || 'all').toLowerCase();
                            var visible = (scope === 'all' || scope === provider);
                            option.hidden = !visible;
                            option.disabled = !visible;
                            if (visible && option.value === mapStyleSelect.value) {
                                selectedStillVisible = true;
                            }
                        });
                        if (!selectedStillVisible) {
                            var firstVisible = Array.prototype.find.call(mapStyleSelect.options || [], function (option) {
                                return !option.hidden && !option.disabled;
                            });
                            if (firstVisible) {
                                mapStyleSelect.value = String(firstVisible.value || '');
                            }
                        }
                    };
                    if (mapProviderSelect && mapStyleSelect) {
                        mapProviderSelect.addEventListener('change', syncMapStyleOptions);
                        syncMapStyleOptions();
                    }

                    var preloaderEnabledToggle = document.getElementById('nexdirectory_preloader_enabled');
                    var preloaderSourceSelect = document.getElementById('nexdirectory_preloader_source');
                    var preloaderSvgField = document.querySelector('[data-nexdirectory-preloader-field="svg"]');
                    var preloaderImageField = document.querySelector('[data-nexdirectory-preloader-field="image"]');
                    var preloaderResetButton = document.getElementById('nexdirectory-preloader-reset-defaults');
                    var preloaderSvgTextarea = document.getElementById('nexdirectory_preloader_svg_markup');
                    var preloaderImageInput = document.getElementById('nexdirectory_preloader_image_url');
                    var preloaderBgInput = document.getElementById('nexdirectory_preloader_background_color');
                    var preloaderWidthInput = document.getElementById('nexdirectory_preloader_logo_max_width');
                    var preloaderMinInput = document.getElementById('nexdirectory_preloader_min_duration_ms');
                    var preloaderFadeInput = document.getElementById('nexdirectory_preloader_fade_duration_ms');
                    var preloaderInitialToggle = document.querySelector('input[type="checkbox"][name="nexdirectory_preloader_show_on_initial"]');
                    var preloaderSpaToggle = document.querySelector('input[type="checkbox"][name="nexdirectory_preloader_show_on_spa"]');
                    var preloaderOnlyHomeToggle = document.querySelector('input[type="checkbox"][name="nexdirectory_preloader_show_only_home"]');
                    var preloaderShowOnceToggle = document.querySelector('input[type="checkbox"][name="nexdirectory_preloader_show_once"]');
                    var preloaderMobileToggle = document.querySelector('input[type="checkbox"][name="nexdirectory_preloader_disable_mobile"]');
                    var preloaderMotionToggle = document.querySelector('input[type="checkbox"][name="nexdirectory_preloader_respect_motion"]');
                    var preloaderDefaultSvg = <?php echo wp_json_encode((string) (method_exists($this, 'get_default_preloader_svg_markup') ? $this->get_default_preloader_svg_markup() : '')); ?>;
                    var preloaderPreviewShell = document.getElementById('nexdirectory-preloader-preview-shell');
                    var preloaderPreviewStage = document.getElementById('nexdirectory-preloader-preview-stage');
                    var preloaderPreviewStatus = document.getElementById('nexdirectory-preloader-preview-status');
                    var preloaderPreviewTiming = document.getElementById('nexdirectory-preloader-preview-timing');
                    var preloaderPreviewPlay = document.getElementById('nexdirectory-preloader-preview-play');
                    var preloaderPreviewStop = document.getElementById('nexdirectory-preloader-preview-stop');
                    var preloaderPreviewTimer = null;
                    var preloaderPreviewFadeTimer = null;
                    var parseNumericWithin = function (value, min, max, fallback) {
                        var parsed = parseFloat(String(value || '').trim());
                        if (!Number.isFinite(parsed)) {
                            return fallback;
                        }
                        if (parsed < min) {
                            return min;
                        }
                        if (parsed > max) {
                            return max;
                        }
                        return parsed;
                    };

                    var preloaderPreviewStopPlayback = function () {
                        if (preloaderPreviewTimer) {
                            window.clearTimeout(preloaderPreviewTimer);
                            preloaderPreviewTimer = null;
                        }
                        if (preloaderPreviewFadeTimer) {
                            window.clearTimeout(preloaderPreviewFadeTimer);
                            preloaderPreviewFadeTimer = null;
                        }
                        if (preloaderPreviewShell) {
                            preloaderPreviewShell.classList.remove('is-fading');
                        }
                        if (preloaderPreviewStatus) {
                            preloaderPreviewStatus.textContent = '<?php echo esc_js(__('Ready', 'nexdirectory')); ?>';
                        }
                    };

                    var syncPreloaderPreview = function () {
                        if (!preloaderPreviewShell || !preloaderPreviewStage) {
                            return;
                        }
                        var source = preloaderSourceSelect ? String(preloaderSourceSelect.value || 'svg').toLowerCase() : 'svg';
                        var bgColor = preloaderBgInput ? String(preloaderBgInput.value || '').trim() : '#FFFFFF';
                        var artWidth = preloaderWidthInput ? parseNumericWithin(preloaderWidthInput.value, 120, 900, 420) : 420;
                        var minMs = preloaderMinInput ? parseNumericWithin(preloaderMinInput.value, 0, 8000, 400) : 400;
                        var fadeMs = preloaderFadeInput ? parseNumericWithin(preloaderFadeInput.value, 80, 2000, 420) : 420;
                        var imageUrl = preloaderImageInput ? String(preloaderImageInput.value || '').trim() : '';
                        var svgMarkup = preloaderSvgTextarea ? String(preloaderSvgTextarea.value || '').trim() : '';
                        var enabled = preloaderEnabledToggle ? !!preloaderEnabledToggle.checked : true;

                        preloaderPreviewShell.style.setProperty('--nexdirectory-preloader-preview-bg', bgColor || '#FFFFFF');
                        preloaderPreviewShell.style.setProperty('--nexdirectory-preloader-preview-width', String(Math.round(artWidth)) + 'px');
                        preloaderPreviewShell.style.setProperty('--nexdirectory-preloader-preview-fade', String(Math.round(fadeMs)) + 'ms');

                        if (!enabled) {
                            preloaderPreviewStage.innerHTML = '<div class="nexdirectory-preloader-preview-empty"><?php echo esc_js(__('Pre-loader is disabled.', 'nexdirectory')); ?></div>';
                        } else if (source === 'image') {
                            if (imageUrl) {
                                preloaderPreviewStage.innerHTML = '';
                                var image = document.createElement('img');
                                image.src = imageUrl;
                                image.alt = '<?php echo esc_js(__('Pre-loader image preview', 'nexdirectory')); ?>';
                                image.decoding = 'async';
                                preloaderPreviewStage.appendChild(image);
                            } else {
                                preloaderPreviewStage.innerHTML = '<div class="nexdirectory-preloader-preview-empty"><?php echo esc_js(__('Choose an image to preview.', 'nexdirectory')); ?></div>';
                            }
                        } else if (svgMarkup) {
                            preloaderPreviewStage.innerHTML = svgMarkup;
                        } else {
                            preloaderPreviewStage.innerHTML = '<div class="nexdirectory-preloader-preview-empty"><?php echo esc_js(__('Paste SVG markup to preview.', 'nexdirectory')); ?></div>';
                        }

                        if (preloaderPreviewTiming) {
                            preloaderPreviewTiming.textContent = '<?php echo esc_js(__('Min', 'nexdirectory')); ?> ' + Math.round(minMs) + 'ms · <?php echo esc_js(__('Fade', 'nexdirectory')); ?> ' + Math.round(fadeMs) + 'ms';
                        }
                    };

                    var playPreloaderPreview = function () {
                        if (!preloaderPreviewShell) {
                            return;
                        }
                        preloaderPreviewStopPlayback();
                        syncPreloaderPreview();
                        if (preloaderPreviewStatus) {
                            preloaderPreviewStatus.textContent = '<?php echo esc_js(__('Playing...', 'nexdirectory')); ?>';
                        }

                        var minMs = preloaderMinInput ? parseNumericWithin(preloaderMinInput.value, 0, 8000, 400) : 400;
                        var fadeMs = preloaderFadeInput ? parseNumericWithin(preloaderFadeInput.value, 80, 2000, 420) : 420;
                        preloaderPreviewTimer = window.setTimeout(function () {
                            preloaderPreviewShell.classList.add('is-fading');
                            if (preloaderPreviewStatus) {
                                preloaderPreviewStatus.textContent = '<?php echo esc_js(__('Fading...', 'nexdirectory')); ?>';
                            }
                            preloaderPreviewFadeTimer = window.setTimeout(function () {
                                preloaderPreviewShell.classList.remove('is-fading');
                                preloaderPreviewFadeTimer = null;
                                if (preloaderPreviewStatus) {
                                    preloaderPreviewStatus.textContent = '<?php echo esc_js(__('Preview complete', 'nexdirectory')); ?>';
                                }
                            }, Math.round(fadeMs));
                            preloaderPreviewTimer = null;
                        }, Math.round(minMs));
                    };

                    var syncPreloaderFields = function () {
                        if (!preloaderSourceSelect) {
                            return;
                        }
                        var enabled = preloaderEnabledToggle ? preloaderEnabledToggle.checked : true;
                        var source = String(preloaderSourceSelect.value || 'svg').toLowerCase();
                        if (preloaderSvgField) {
                            preloaderSvgField.style.display = (enabled && source === 'svg') ? '' : 'none';
                        }
                        if (preloaderImageField) {
                            preloaderImageField.style.display = (enabled && source === 'image') ? '' : 'none';
                        }
                        syncPreloaderPreview();
                    };

                    if (preloaderEnabledToggle) {
                        preloaderEnabledToggle.addEventListener('change', syncPreloaderFields);
                    }
                    if (preloaderSourceSelect) {
                        preloaderSourceSelect.addEventListener('change', syncPreloaderFields);
                    }
                    syncPreloaderFields();

                    if (preloaderResetButton) {
                        preloaderResetButton.addEventListener('click', function () {
                            if (preloaderSourceSelect) {
                                preloaderSourceSelect.value = 'svg';
                            }
                            if (preloaderSvgTextarea) {
                                preloaderSvgTextarea.value = String(preloaderDefaultSvg || '').trim();
                            }
                            if (preloaderImageInput) {
                                preloaderImageInput.value = '';
                            }
                            if (preloaderBgInput) {
                                preloaderBgInput.value = '#FFFFFF';
                            }
                            if (preloaderWidthInput) {
                                preloaderWidthInput.value = '420';
                            }
                            if (preloaderMinInput) {
                                preloaderMinInput.value = '400';
                            }
                            if (preloaderFadeInput) {
                                preloaderFadeInput.value = '420';
                            }
                            if (preloaderEnabledToggle) {
                                preloaderEnabledToggle.checked = true;
                            }
                            if (preloaderInitialToggle) {
                                preloaderInitialToggle.checked = true;
                            }
                            if (preloaderSpaToggle) {
                                preloaderSpaToggle.checked = true;
                            }
                            if (preloaderOnlyHomeToggle) {
                                preloaderOnlyHomeToggle.checked = false;
                            }
                            if (preloaderShowOnceToggle) {
                                preloaderShowOnceToggle.checked = false;
                            }
                            if (preloaderMobileToggle) {
                                preloaderMobileToggle.checked = false;
                            }
                            if (preloaderMotionToggle) {
                                preloaderMotionToggle.checked = true;
                            }

                            var imagePreview = document.getElementById('nexdirectory-preloader-image-preview');
                            if (imagePreview) {
                                imagePreview.innerHTML = '';
                            }
                            syncPreloaderFields();
                            preloaderPreviewStopPlayback();
                            markDirty();
                        });
                    }

                    if (preloaderPreviewPlay) {
                        preloaderPreviewPlay.addEventListener('click', playPreloaderPreview);
                    }
                    if (preloaderPreviewStop) {
                        preloaderPreviewStop.addEventListener('click', function () {
                            preloaderPreviewStopPlayback();
                            syncPreloaderPreview();
                        });
                    }
                    if (preloaderSvgTextarea) {
                        preloaderSvgTextarea.addEventListener('input', syncPreloaderPreview);
                        preloaderSvgTextarea.addEventListener('change', syncPreloaderPreview);
                    }
                    if (preloaderBgInput) {
                        preloaderBgInput.addEventListener('input', syncPreloaderPreview);
                        preloaderBgInput.addEventListener('change', syncPreloaderPreview);
                    }
                    if (preloaderWidthInput) {
                        preloaderWidthInput.addEventListener('input', syncPreloaderPreview);
                        preloaderWidthInput.addEventListener('change', syncPreloaderPreview);
                    }
                    if (preloaderMinInput) {
                        preloaderMinInput.addEventListener('input', syncPreloaderPreview);
                        preloaderMinInput.addEventListener('change', syncPreloaderPreview);
                    }
                    if (preloaderFadeInput) {
                        preloaderFadeInput.addEventListener('input', syncPreloaderPreview);
                        preloaderFadeInput.addEventListener('change', syncPreloaderPreview);
                    }
                    if (preloaderImageInput) {
                        preloaderImageInput.addEventListener('input', syncPreloaderPreview);
                        preloaderImageInput.addEventListener('change', syncPreloaderPreview);
                    }
                    syncPreloaderPreview();

                    var uploadEndpoint = '<?php echo esc_js(admin_url('admin-post.php')); ?>';
                    var uploadNonce = '<?php echo esc_js(wp_create_nonce('nexdirectory_upload_image_nonce')); ?>';
                    var mediaPickers = document.querySelectorAll('[data-nexdirectory-media-picker]');
                    var parseUrls = function (value) {
                        return String(value || '')
                            .split(/\r?\n|,/)
                            .map(function (row) { return String(row || '').trim(); })
                            .filter(function (row) { return /^https?:\/\//i.test(row); });
                    };
                    var uniqueUrls = function (rows) {
                        var seen = {};
                        return (rows || []).filter(function (row) {
                            var key = String(row || '').trim();
                            if (!key || seen[key]) {
                                return false;
                            }
                            seen[key] = true;
                            return true;
                        });
                    };
                    var setPickerFeedback = function (picker, text, tone) {
                        var feedback = picker ? picker.querySelector('[data-nexdirectory-media-feedback]') : null;
                        if (!feedback) {
                            return;
                        }
                        feedback.textContent = String(text || '').trim();
                        if (tone) {
                            feedback.setAttribute('data-tone', String(tone));
                        } else {
                            feedback.removeAttribute('data-tone');
                        }
                    };
                    var createTile = function (url) {
                        var tile = document.createElement('div');
                        tile.className = 'nexdirectory-media-tile';
                        tile.setAttribute('data-nexdirectory-media-url', url);
                        var img = document.createElement('img');
                        img.src = url;
                        img.alt = '<?php echo esc_js(__('Fallback image', 'nexdirectory')); ?>';
                        var remove = document.createElement('button');
                        remove.type = 'button';
                        remove.className = 'nexdirectory-media-remove';
                        remove.setAttribute('data-nexdirectory-media-remove', '1');
                        remove.setAttribute('aria-label', '<?php echo esc_js(__('Remove image', 'nexdirectory')); ?>');
                        remove.textContent = '×';
                        tile.appendChild(img);
                        tile.appendChild(remove);
                        return tile;
                    };
                    var renderPicker = function (picker) {
                        if (!picker) {
                            return;
                        }
                        var targetSelector = String(picker.getAttribute('data-nexdirectory-media-target') || '').trim();
                        var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                        var gallery = picker.querySelector('.nexdirectory-media-gallery');
                        if (!targetInput || !gallery) {
                            return;
                        }
                        var urls = uniqueUrls(parseUrls(targetInput.value));
                        gallery.innerHTML = '';
                        urls.forEach(function (url) {
                            gallery.appendChild(createTile(url));
                        });
                    };
                    var updatePickerValue = function (picker, urls) {
                        if (!picker) {
                            return;
                        }
                        var targetSelector = String(picker.getAttribute('data-nexdirectory-media-target') || '').trim();
                        var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                        if (!targetInput) {
                            return;
                        }
                        var allowMultiple = String(picker.getAttribute('data-nexdirectory-media-multiple') || '0') === '1';
                        var rows = uniqueUrls((urls || []).map(function (row) { return String(row || '').trim(); }));
                        if (!allowMultiple) {
                            rows = rows.length ? [rows[0]] : [];
                        }
                        targetInput.value = allowMultiple ? rows.join('\n') : (rows[0] || '');
                        targetInput.dispatchEvent(new Event('input', { bubbles: true }));
                        targetInput.dispatchEvent(new Event('change', { bubbles: true }));
                        markDirty();
                        renderPicker(picker);
                    };
                    var pickWithMediaModal = function (picker) {
                        if (!picker || !window.wp || !window.wp.media) {
                            return;
                        }
                        var targetSelector = String(picker.getAttribute('data-nexdirectory-media-target') || '').trim();
                        var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                        if (!targetInput) {
                            return;
                        }
                        var allowMultiple = String(picker.getAttribute('data-nexdirectory-media-multiple') || '0') === '1';
                        var frame = window.wp.media({
                            title: '<?php echo esc_js(__('Select an image', 'nexdirectory')); ?>',
                            button: { text: '<?php echo esc_js(__('Use image', 'nexdirectory')); ?>' },
                            library: { type: 'image' },
                            multiple: allowMultiple
                        });
                        frame.on('select', function () {
                            var selectionState = frame.state().get('selection');
                            if (!selectionState) {
                                return;
                            }
                            var selected = [];
                            selectionState.each(function (attachment) {
                                if (!attachment) {
                                    return;
                                }
                                var data = attachment.toJSON ? attachment.toJSON() : null;
                                if (data && data.url) {
                                    selected.push(String(data.url));
                                }
                            });
                            if (!selected.length) {
                                return;
                            }
                            var existing = parseUrls(targetInput.value);
                            var merged = allowMultiple ? existing.concat(selected) : [selected[0]];
                            updatePickerValue(picker, merged);
                            setPickerFeedback(picker, '<?php echo esc_js(__('Media selection updated.', 'nexdirectory')); ?>', 'success');
                        });
                        frame.open();
                    };
                    var uploadImageFile = function (file, target) {
                        var formData = new FormData();
                        formData.append('action', 'nexdirectory_upload_image');
                        formData.append('nexdirectory_upload_nonce', uploadNonce);
                        formData.append('nexdirectory_upload_target', target);
                        formData.append('nexdirectory_upload_kind', 'image');
                        formData.append('file', file);
                        return fetch(uploadEndpoint, {
                            method: 'POST',
                            credentials: 'same-origin',
                            body: formData
                        }).then(function (response) {
                            return response.json().catch(function () { return {}; }).then(function (payload) {
                                if (!response.ok || !payload || payload.success !== true || !payload.data || !payload.data.url) {
                                    var message = payload && payload.data && payload.data.message
                                        ? String(payload.data.message)
                                        : '<?php echo esc_js(__('Image upload failed.', 'nexdirectory')); ?>';
                                    throw new Error(message);
                                }
                                return String(payload.data.url || '').trim();
                            });
                        });
                    };
                    var handleDroppedFiles = function (picker, files) {
                        if (!picker || !files || !files.length) {
                            return;
                        }
                        var targetSelector = String(picker.getAttribute('data-nexdirectory-media-target') || '').trim();
                        var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                        if (!targetInput) {
                            return;
                        }
                        var allowMultiple = String(picker.getAttribute('data-nexdirectory-media-multiple') || '0') === '1';
                        var uploadTarget = String(picker.getAttribute('data-nexdirectory-upload-target') || (allowMultiple ? 'gallery' : 'cover')).trim();
                        var existing = parseUrls(targetInput.value);
                        var queue = Array.prototype.slice.call(files || []);
                        var uploaded = [];
                        var failures = [];
                        var chain = Promise.resolve();
                        queue.forEach(function (file) {
                            chain = chain.then(function () {
                                if (!file || String(file.type || '').indexOf('image/') !== 0) {
                                    failures.push('<?php echo esc_js(__('One file was skipped because it is not an image.', 'nexdirectory')); ?>');
                                    return;
                                }
                                return uploadImageFile(file, uploadTarget).then(function (url) {
                                    if (url) {
                                        uploaded.push(url);
                                    }
                                }).catch(function (error) {
                                    failures.push(error && error.message ? String(error.message) : '<?php echo esc_js(__('Image upload failed.', 'nexdirectory')); ?>');
                                });
                            });
                        });
                        chain.then(function () {
                            if (uploaded.length) {
                                var merged = allowMultiple ? existing.concat(uploaded) : [uploaded[uploaded.length - 1]];
                                updatePickerValue(picker, merged);
                            }
                            if (failures.length) {
                                setPickerFeedback(picker, failures[0], 'error');
                            } else if (uploaded.length) {
                                setPickerFeedback(picker, '<?php echo esc_js(__('Upload complete.', 'nexdirectory')); ?>', 'success');
                            }
                        });
                    };
                    mediaPickers.forEach(function (picker) {
                        renderPicker(picker);
                        var dropzone = picker.querySelector('[data-nexdirectory-media-open]');
                        var fileInput = picker.querySelector('[data-nexdirectory-media-file-input]');
                        if (dropzone) {
                            dropzone.addEventListener('click', function () {
                                pickWithMediaModal(picker);
                            });
                            dropzone.addEventListener('dragover', function (event) {
                                event.preventDefault();
                                dropzone.classList.add('is-dragover');
                            });
                            dropzone.addEventListener('dragleave', function () {
                                dropzone.classList.remove('is-dragover');
                            });
                            dropzone.addEventListener('drop', function (event) {
                                event.preventDefault();
                                dropzone.classList.remove('is-dragover');
                                handleDroppedFiles(picker, event.dataTransfer && event.dataTransfer.files ? event.dataTransfer.files : []);
                            });
                        }
                        if (fileInput) {
                            fileInput.addEventListener('change', function () {
                                handleDroppedFiles(picker, fileInput.files || []);
                                fileInput.value = '';
                            });
                        }
                        picker.addEventListener('click', function (event) {
                            var remove = event.target && event.target.closest ? event.target.closest('[data-nexdirectory-media-remove]') : null;
                            if (!remove) {
                                return;
                            }
                            event.preventDefault();
                            var tile = remove.closest('[data-nexdirectory-media-url]');
                            var targetSelector = String(picker.getAttribute('data-nexdirectory-media-target') || '').trim();
                            var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                            if (!tile || !targetInput) {
                                return;
                            }
                            var removeUrl = String(tile.getAttribute('data-nexdirectory-media-url') || '').trim();
                            var rows = parseUrls(targetInput.value).filter(function (row) {
                                return String(row || '').trim() !== removeUrl;
                            });
                            updatePickerValue(picker, rows);
                            setPickerFeedback(picker, '<?php echo esc_js(__('Image removed.', 'nexdirectory')); ?>', 'success');
                        });
                    });

                    var copyButtons = document.querySelectorAll('.nexdirectory-copy-shortcode');
                    copyButtons.forEach(function (button) {
                        button.addEventListener('click', function () {
                            var shortcode = String(button.getAttribute('data-shortcode') || '').trim();
                            if (!shortcode) {
                                return;
                            }
                            var restoreHtml = button.innerHTML;
                            var restoreAriaLabel = button.getAttribute('aria-label');
                            var onCopied = function () {
                                var liveStatus = button.querySelector('[data-nexdirectory-copy-status]');
                                if (liveStatus) {
                                    liveStatus.textContent = '<?php echo esc_js(__('Copied to clipboard.', 'nexdirectory')); ?>';
                                    button.setAttribute('aria-label', '<?php echo esc_js(__('App Pass copied to clipboard', 'nexdirectory')); ?>');
                                } else {
                                    button.textContent = '<?php echo esc_js(__('Copied', 'nexdirectory')); ?>';
                                }
                                window.setTimeout(function () {
                                    button.innerHTML = restoreHtml;
                                    if (restoreAriaLabel) {
                                        button.setAttribute('aria-label', restoreAriaLabel);
                                    } else {
                                        button.removeAttribute('aria-label');
                                    }
                                }, 1100);
                            };
                            var fallbackCopy = function () {
                                var fallbackInput = document.createElement('input');
                                fallbackInput.type = 'text';
                                fallbackInput.value = shortcode;
                                document.body.appendChild(fallbackInput);
                                fallbackInput.select();
                                try {
                                    document.execCommand('copy');
                                    onCopied();
                                } catch (copyError) {
                                    // no-op
                                }
                                document.body.removeChild(fallbackInput);
                            };
                            if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
                                navigator.clipboard.writeText(shortcode).then(onCopied).catch(function () {
                                    fallbackCopy();
                                });
                                return;
                            }
                            fallbackCopy();
                        });
                    });

                    var regeneratePassTrigger = document.getElementById('nexdirectory-regenerate-app-pass-trigger');
                    var regeneratePassConfirmation = document.getElementById('nexdirectory-regenerate-app-pass-confirmation');
                    var regeneratePassConfirm = document.getElementById('nexdirectory-regenerate-app-pass-confirm');
                    var regeneratePassCancel = document.getElementById('nexdirectory-regenerate-app-pass-cancel');
                    var regeneratePassForm = document.getElementById('nexdirectory-regenerate-app-pass-form');
                    var setRegeneratePassConfirmation = function (isOpen) {
                        if (!regeneratePassTrigger || !regeneratePassConfirmation) {
                            return;
                        }
                        regeneratePassConfirmation.hidden = !isOpen;
                        regeneratePassTrigger.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
                        if (isOpen && regeneratePassConfirm) {
                            regeneratePassConfirm.focus();
                        } else if (!isOpen) {
                            regeneratePassTrigger.focus();
                        }
                    };
                    if (regeneratePassTrigger && regeneratePassConfirmation) {
                        regeneratePassTrigger.addEventListener('click', function () {
                            setRegeneratePassConfirmation(regeneratePassConfirmation.hidden);
                        });
                        regeneratePassConfirmation.addEventListener('keydown', function (event) {
                            if (event.key === 'Escape') {
                                event.preventDefault();
                                setRegeneratePassConfirmation(false);
                            }
                        });
                    }
                    if (regeneratePassCancel) {
                        regeneratePassCancel.addEventListener('click', function () {
                            setRegeneratePassConfirmation(false);
                        });
                    }
                    if (regeneratePassForm && regeneratePassConfirm) {
                        regeneratePassForm.addEventListener('submit', function () {
                            regeneratePassConfirm.disabled = true;
                            regeneratePassConfirm.setAttribute('aria-busy', 'true');
                            regeneratePassConfirm.textContent = '<?php echo esc_js(__('Generating secure App Pass…', 'nexdirectory')); ?>';
                        });
                    }

                    var helpDialog = document.getElementById('nexdirectory-settings-help-dialog');
                    var helpBackdrop = document.getElementById('nexdirectory-settings-help-backdrop');
                    var helpTitle = document.getElementById('nexdirectory-settings-help-title');
                    var helpBody = document.getElementById('nexdirectory-settings-help-body');
                    var helpTriggers = [];
                    var genericHelpBody = '<?php echo esc_js(__('Configure this option based on your platform behavior, design, moderation, and submission workflow.', 'nexdirectory')); ?>';
                    var makeHelpTrigger = function (title, body) {
                        var trigger = document.createElement('button');
                        trigger.type = 'button';
                        trigger.className = 'nexdirectory-help-trigger';
                        trigger.setAttribute('data-nexdirectory-help-title', String(title || '').trim());
                        trigger.setAttribute('data-nexdirectory-help-body', String(body || '').trim());
                        trigger.setAttribute('aria-label', '<?php echo esc_js(__('Open help dialog', 'nexdirectory')); ?>');
                        var icon = document.createElement('span');
                        icon.className = 'dashicons dashicons-editor-help';
                        icon.setAttribute('aria-hidden', 'true');
                        trigger.appendChild(icon);
                        return trigger;
                    };
                    var openHelpDialog = function (title, body) {
                        if (!helpDialog || !helpBackdrop || !helpTitle || !helpBody) {
                            return;
                        }
                        helpTitle.textContent = String(title || '<?php echo esc_js(__('Settings Help', 'nexdirectory')); ?>');
                        helpBody.innerHTML = '';
                        var paragraphs = String(body || '').split(/\n{2,}/).map(function (entry) {
                            return String(entry || '').trim();
                        }).filter(function (entry) {
                            return entry.length > 0;
                        });
                        if (!paragraphs.length) {
                            paragraphs = [genericHelpBody];
                        }
                        paragraphs.forEach(function (text) {
                            var p = document.createElement('p');
                            p.textContent = text;
                            helpBody.appendChild(p);
                        });
                        helpDialog.classList.add('is-open');
                        helpBackdrop.classList.add('is-open');
                        helpDialog.setAttribute('aria-hidden', 'false');
                        var closeButton = helpDialog.querySelector('[data-nexdirectory-help-close]');
                        if (closeButton) {
                            closeButton.focus();
                        }
                    };
                    var closeHelpDialog = function () {
                        if (!helpDialog || !helpBackdrop) {
                            return;
                        }
                        helpDialog.classList.remove('is-open');
                        helpBackdrop.classList.remove('is-open');
                        helpDialog.setAttribute('aria-hidden', 'true');
                    };
                    var getFieldBodyText = function (field) {
                        var bodyParts = [];
                        var descriptionNodes = field.querySelectorAll('.description');
                        descriptionNodes.forEach(function (node) {
                            var text = String(node.textContent || '').trim();
                            if (text) {
                                bodyParts.push(text);
                            }
                        });
                        if (!bodyParts.length) {
                            var cards = field.querySelectorAll('.nexdirectory-settings-section-card p');
                            cards.forEach(function (node) {
                                var text = String(node.textContent || '').trim();
                                if (text) {
                                    bodyParts.push(text);
                                }
                            });
                        }
                        if (!bodyParts.length) {
                            bodyParts.push(genericHelpBody);
                        }
                        return bodyParts.join('\n\n');
                    };
                    var injectHelpTriggers = function () {
                        var panelHeadings = document.querySelectorAll('.nexdirectory-settings-panel > h2');
                        panelHeadings.forEach(function (heading) {
                            if (heading.querySelector('.nexdirectory-help-trigger')) {
                                return;
                            }
                            var panel = heading.closest('.nexdirectory-settings-panel');
                            if (!panel) {
                                return;
                            }
                            var summaryNode = panel.querySelector('.description, .nexdirectory-settings-subheading');
                            var summaryText = summaryNode ? String(summaryNode.textContent || '').trim() : '';
                            if (!summaryText) {
                                summaryText = genericHelpBody;
                            }
                            var title = String(heading.textContent || '').trim() || '<?php echo esc_js(__('Settings Section', 'nexdirectory')); ?>';
                            var trigger = makeHelpTrigger(title, summaryText);
                            heading.appendChild(trigger);
                            helpTriggers.push(trigger);
                        });

                        var fields = document.querySelectorAll('.nexdirectory-settings-panel .nexdirectory-settings-field');
                        fields.forEach(function (field) {
                            if (field.classList.contains('nexdirectory-no-auto-help')) {
                                return;
                            }
                            if (field.querySelector('.nexdirectory-help-trigger')) {
                                return;
                            }
                            var label = field.querySelector('label');
                            if (!label) {
                                return;
                            }
                            var labelText = String(label.textContent || '').replace(/\s+/g, ' ').trim();
                            if (!labelText) {
                                return;
                            }
                            var trigger = makeHelpTrigger(labelText, getFieldBodyText(field));
                            label.insertAdjacentElement('afterend', trigger);
                            helpTriggers.push(trigger);
                        });
                    };
                    injectHelpTriggers();

                    document.addEventListener('click', function (event) {
                        var blueprintTrigger = event.target.closest('[data-nexdirectory-blueprint-trigger]');
                        if (blueprintTrigger) {
                            event.preventDefault();
                            openBlueprintConfirmation(blueprintTrigger);
                            return;
                        }
                        var blueprintCancel = event.target.closest('[data-nexdirectory-blueprint-cancel="1"]');
                        if (blueprintCancel) {
                            event.preventDefault();
                            closeBlueprintConfirmation(true);
                            return;
                        }
                        if (event.target.closest('#nexdirectory-blueprint-confirm-submit')) {
                            event.preventDefault();
                            var targetForm = pendingBlueprintForm;
                            var confirmedInput = targetForm
                                ? targetForm.querySelector('input[name="nexdirectory_blueprint_confirmed"]')
                                : null;
                            if (!targetForm || !confirmedInput) {
                                closeBlueprintConfirmation(true);
                                return;
                            }
                            confirmedInput.value = '1';
                            if (blueprintConfirmSubmit) {
                                blueprintConfirmSubmit.disabled = true;
                                blueprintConfirmSubmit.textContent = '<?php echo esc_js(__('Applying Blueprint…', 'nexdirectory')); ?>';
                            }
                            closeBlueprintConfirmation(false);
                            if (typeof targetForm.requestSubmit === 'function') {
                                targetForm.requestSubmit();
                            } else {
                                targetForm.submit();
                            }
                        }
                    });

                    document.addEventListener('click', function (event) {
                        var closeEl = event.target.closest('[data-nexdirectory-help-close="1"]');
                        if (closeEl) {
                            event.preventDefault();
                            closeHelpDialog();
                            return;
                        }
                        var trigger = event.target.closest('[data-nexdirectory-help-title]');
                        if (!trigger) {
                            return;
                        }
                        event.preventDefault();
                        openHelpDialog(
                            String(trigger.getAttribute('data-nexdirectory-help-title') || '').trim(),
                            String(trigger.getAttribute('data-nexdirectory-help-body') || '').trim()
                        );
                    });

                    document.addEventListener('keydown', function (event) {
                        if (event.key === 'Escape') {
                            closeBlueprintConfirmation(true);
                            closeHelpDialog();
                        }
                    });

                    // Custom submission fields are now managed by creators in the frontend submit/edit form.
                })();
            <?php $this->enqueue_inline_script_asset('nexdirectory-admin-settings-page', ob_get_clean(), 'after'); ?>
        </div>
