<?php
        wp_enqueue_media();
        $settings_brand_name = $this->get_white_label_brand_name();
        $site_profile_catalog = method_exists($this, 'get_site_profile_catalog') ? (array) $this->get_site_profile_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('eep_site_profile', 'events'));
        } else {
            $site_profile_value = sanitize_key((string) get_option('eep_site_profile', 'events'));
        }
        if ($site_profile_value === '' || !isset($site_profile_catalog[$site_profile_value])) {
            $site_profile_value = 'events';
        }
        $this->sync_route_options_to_existing_pages($site_profile_value);
        $platform_mode_value = $this->sanitize_platform_mode_option((string) get_option('eep_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(
            'eep_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(
            'eep_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(
            'eep_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(
            'eep_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(
            'eep_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_boost_page_url = $this->get_platform_page_url(
            'eep_page_boost_posts_url',
            $this->get_profile_route_slugs('boost', $site_profile_value),
            $this->get_profile_route_default_url('boost', $site_profile_value)
        );
        $settings_owner_analytics_page_url = $this->get_platform_page_url(
            'eep_page_owner_analytics_url',
            $this->get_profile_route_slugs('analytics', $site_profile_value),
            $this->get_profile_route_default_url('analytics', $site_profile_value)
        );
        $settings_saved_page_url = $this->get_platform_page_url(
            'eep_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(
            'eep_page_whos_attending_url',
            $this->get_profile_route_slugs('attendees', $site_profile_value),
            $this->get_profile_route_default_url('attendees', $site_profile_value)
        );
        $settings_event_webapp_page_url = $this->get_platform_page_url(
            'eep_page_event_webapp_url',
            ['event-app'],
            home_url('/event-app/')
        );
        $settings_whats_new_page_url = $this->get_platform_page_url(
            'eep_page_whats_new_url',
            ['whats-new'],
            home_url('/whats-new/')
        );
        $settings_account_page_url = $this->get_platform_page_url(
            'eep_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(
            'eep_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(
            'eep_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(
            __('%s Settings', 'nexdirectory'),
            $settings_brand_name
        );
        $premium_unlocked = !function_exists('epw_fs') || epw_fs()->can_use_premium_code__premium_only();
        $white_label_enabled = (string) get_option('eep_white_label_enabled', '0') === '1';
        $white_label_name_value = (string) get_option('eep_white_label_plugin_name', '');
        $white_label_description_value = (string) get_option('eep_white_label_plugin_description', '');
        $white_label_author_value = (string) get_option('eep_white_label_plugin_author', '');
        $white_label_url_value = (string) get_option('eep_white_label_plugin_url', '');
        $white_label_support_url_value = (string) get_option('eep_white_label_support_url', '');
        $white_label_support_email_value = (string) get_option('eep_white_label_support_email', '');
        $white_label_menu_icon_value = (string) get_option('eep_white_label_admin_menu_icon', 'dashicons-admin-generic');
        $white_label_footer_text_value = (string) get_option('eep_white_label_admin_footer_text', '');
        $white_label_lock_enabled = (string) get_option('eep_white_label_lock_enabled', '0') === '1';
        $white_label_has_password = trim((string) get_option('eep_white_label_password_hash', '')) !== '';
        $white_label_is_unlocked = $this->is_white_label_section_unlocked();
        $white_label_unlock_token = $this->get_white_label_unlock_token_from_request();
        $white_label_force_reset_url = $this->get_white_label_force_reset_url(get_current_user_id());
        $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('eep_style_font_family', 'Inter, system-ui, -apple-system, sans-serif');
        $display_font_value = (string) get_option('eep_style_display_font_family', 'Oswald, Inter, sans-serif');
        $base_font_size_value = (string) get_option('eep_style_font_size_base', '18px');
        $h2_size_value = (string) get_option('eep_style_h2_size', '1.75rem');
        $h3_size_value = (string) get_option('eep_style_h3_size', '1.35rem');
        $body_weight_value = (string) get_option('eep_style_font_weight_body', '400');
        $heading_weight_value = (string) get_option('eep_style_font_weight_heading', '700');
        $spacing_unit_value = (string) get_option('eep_style_spacing_unit', '16px');
        $spacing_scale_value = (string) get_option('eep_style_spacing_scale', '1');
        $radius_md_value = (string) get_option('eep_style_radius_md', '12px');
        $radius_lg_value = (string) get_option('eep_style_radius_lg', '24px');
        $style_box_style_value = $this->sanitize_style_box_style_option((string) get_option('eep_style_box_style', 'default'));
        $style_button_style_value = $this->sanitize_style_button_style_option((string) get_option('eep_style_button_style', 'solid'));
        $style_button_radius_mode_value = $this->sanitize_style_button_radius_mode_option((string) get_option('eep_style_button_radius_mode', 'inherit'));
        $style_density_mode_value = $this->sanitize_style_density_mode_option((string) get_option('eep_style_density_mode', 'comfortable'));
        $style_border_mode_value = $this->sanitize_style_border_mode_option((string) get_option('eep_style_border_mode', 'subtle'));
        $style_shadow_mode_value = $this->sanitize_style_shadow_mode_option((string) get_option('eep_style_shadow_mode', 'soft'));
        $style_content_width_value = $this->sanitize_style_content_width_option((string) get_option('eep_style_content_width', 'standard'));
        $style_input_style_value = $this->sanitize_style_input_style_option((string) get_option('eep_style_input_style', 'outline'));
        $map_layout_value = sanitize_key((string) get_option('eep_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('eep_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('eep_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('eep_page_side_padding', '10%'));
        $page_side_padding_mobile_raw = (string) get_option('eep_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('eep_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('eep_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('eep_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('eep_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('eep_mapbox_style_id', 'mapbox/streets-v12'));
        $mapbox_style_options = (array) $this->get_mapbox_style_id_options();
        $thumb_fallback_raw = (string) get_option('eep_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('eep_style_fallback_hero_url', ''));
        $favicon_url = esc_url((string) get_option('eep_style_favicon_url', ''));
        $home_meta_title_value = $this->sanitize_home_meta_title_option((string) get_option('eep_home_meta_title', ''));
        $home_meta_description_value = $this->sanitize_home_meta_description_option((string) get_option('eep_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('eep_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();
        $legacy_custom_form_fields_value = trim((string) get_option('eep_custom_form_fields', '[]'));
        if ($legacy_custom_form_fields_value === '') {
            $legacy_custom_form_fields_value = '[]';
        }
        $legacy_custom_form_fields_decoded = json_decode($legacy_custom_form_fields_value, true);
        if (is_array($legacy_custom_form_fields_decoded)) {
            $legacy_custom_form_fields_pretty = wp_json_encode(
                $legacy_custom_form_fields_decoded,
                JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
            );
            if (is_string($legacy_custom_form_fields_pretty) && $legacy_custom_form_fields_pretty !== '') {
                $legacy_custom_form_fields_value = $legacy_custom_form_fields_pretty;
            }
        }

        $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('eep_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('eep_enable_pending_admin_notifications', '1');
        }
        $pending_email_toggle_value = get_option('eep_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('eep_enable_pending_admin_notifications', '1');
        }
        $extension_app_pass = $this->get_extension_app_pass();
        $extension_import_status = sanitize_key((string) get_option('eep_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('eep_extension_import_media_policy', ''));
        if (!in_array($extension_import_media_policy, ['none', 'images', 'images_video', 'video'], true)) {
            $extension_import_media_policy = 'none';
        }
        $indexnow_enabled = (string) get_option('eep_indexnow_enabled', '0') === '1';
        $indexnow_key = preg_replace('/[^A-Za-z0-9]/', '', (string) get_option('eep_indexnow_key', ''));
        if (strlen((string) $indexnow_key) < 8 && method_exists($this, 'ensure_indexnow_key')) {
            $indexnow_key = (string) $this->ensure_indexnow_key();
        }
        $indexnow_endpoint = esc_url((string) get_option('eep_indexnow_endpoint', 'https://api.indexnow.org/indexnow'));
        if ($indexnow_endpoint === '') {
            $indexnow_endpoint = 'https://api.indexnow.org/indexnow';
        }
        $indexnow_submit_updates = (string) get_option('eep_indexnow_submit_updates', '0') === '1';
        $indexnow_submit_removals = (string) get_option('eep_indexnow_submit_removals', '0') === '1';
        $indexnow_key_url = $indexnow_key !== '' ? home_url('/' . rawurlencode($indexnow_key) . '.txt') : '';
        $extension_import_content_mode = sanitize_key((string) get_option('eep_extension_import_content_mode', 'rewrite'));
        if (!in_array($extension_import_content_mode, ['rewrite', 'verbatim'], true)) {
            $extension_import_content_mode = 'rewrite';
        }
        $extension_notify_owner_default = (string) get_option('eep_extension_notify_potential_owner_default', '0') === '1';
        $extension_import_author_id = absint((int) get_option('eep_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('eep_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('eep_frontend_sticky_nav_logo_url', ''));
        $sticky_nav_logo_link_url = esc_url((string) get_option('eep_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('eep_frontend_sticky_nav_custom_links', '');
        $sticky_nav_use_wp_menus = (string) get_option('eep_frontend_sticky_nav_use_wp_menus', '0') === '1';
        $sticky_nav_wp_menu_guest = absint((int) get_option('eep_frontend_sticky_nav_wp_menu_guest', 0));
        $sticky_nav_wp_menu_member = absint((int) get_option('eep_frontend_sticky_nav_wp_menu_member', 0));
        $sticky_nav_wp_menu_admin = absint((int) get_option('eep_frontend_sticky_nav_wp_menu_admin', 0));
        $sticky_nav_wp_menu_roles = get_option('eep_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('eep_enable_frontend_footer', '1') === '1';
        $footer_show_logo = (string) get_option('eep_frontend_footer_show_logo', '1') === '1';
        $footer_logo_url = esc_url((string) get_option('eep_frontend_footer_logo_url', ''));
        $footer_logo_link_url = esc_url((string) get_option('eep_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('eep_frontend_footer_use_wp_menus', '0') === '1';
        $footer_menu_count = (int) get_option('eep_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('eep_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('eep_frontend_footer_show_privacy_link', '1') === '1';
        $footer_bottom_text = (string) get_option('eep_frontend_footer_bottom_text', '');
        $shortcodes = [
            ['code' => '[eep_listings_archive]', 'usage' => __('Filterable listings archive grid page.', 'nexdirectory')],
            ['code' => '[eep_listings_map]', 'usage' => __('Interactive map page with filters and results list.', 'nexdirectory')],
            ['code' => '[eep_listings_calendar]', 'usage' => __('Monthly calendar/timeline view for listings.', 'nexdirectory')],
            ['code' => '[eep_events_query_grid]', 'usage' => __('Elementor-friendly query grid with custom taxonomy/category filtering.', 'nexdirectory')],
            ['code' => '[eep_events_bento_grid]', 'usage' => __('Bento-style query grid with hover effects and 6 layout templates.', 'nexdirectory')],
            ['code' => '[eep_events_ajax_search]', 'usage' => __('Dynamic AJAX search widget with custom query controls and filters.', 'nexdirectory')],
            ['code' => '[eep_event_chatbot]', 'usage' => __('AI chatbot assistant powered by indexed published listings.', 'nexdirectory')],
            ['code' => '[eep_submit]', 'usage' => __('Frontend submit/edit listing form for logged-in users.', 'nexdirectory')],
            ['code' => '[eep_my_listings]', 'usage' => __('User dashboard for submitted listings and quick edits.', 'nexdirectory')],
            ['code' => '[eep_boost_posts]', 'usage' => __('Paid boost dashboard with active plans, renewals, and boost history.', 'nexdirectory')],
            ['code' => '[eep_saved_listings]', 'usage' => __('Dashboard for saved/attending listings.', 'nexdirectory')],
            ['code' => '[eep_owner_analytics]', 'usage' => __('Owner analytics dashboard with listing performance metrics and export tools.', 'nexdirectory')],
            ['code' => '[eep_account]', 'usage' => __('Account management and recommendations.', 'nexdirectory')],
            ['code' => '[eep_auth]', 'usage' => __('Custom login/sign-up experience.', 'nexdirectory')],
            ['code' => '[eep_auth_links]', 'usage' => __('Reusable Login/Signup buttons with signed-in account dropdown menu.', 'nexdirectory')],
            ['code' => '[eep_user_management]', 'usage' => __('Admin user management and listing moderation actions.', 'nexdirectory')],
            ['code' => '[eep_moderation_queue]', 'usage' => __('Admin moderation queue for pending listings and reports.', 'nexdirectory')],
            ['code' => '[eep_organizers]', 'usage' => __('Public organizer directory.', 'nexdirectory')],
            ['code' => '[eep_claim_listing]', 'usage' => __('Frontend listing claim form for imported/admin-created listings.', 'nexdirectory')],
        ];
        $shortcode_aliases = [
            ['code' => '[eep_events_archive]', 'usage' => __('Legacy alias of [eep_listings_archive].', 'nexdirectory')],
            ['code' => '[eep_events_map]', 'usage' => __('Legacy alias of [eep_listings_map].', 'nexdirectory')],
            ['code' => '[eep_events_calendar]', 'usage' => __('Legacy alias of [eep_listings_calendar].', 'nexdirectory')],
            ['code' => '[eep_submit_event]', 'usage' => __('Legacy alias of [eep_submit].', 'nexdirectory')],
            ['code' => '[eep_my_events]', 'usage' => __('Legacy alias of [eep_my_listings].', 'nexdirectory')],
            ['code' => '[eep_my_tickets]', 'usage' => __('Legacy alias of [eep_saved_listings].', 'nexdirectory')],
            ['code' => '[nexdirectory_events_archive]', 'usage' => __('Alias of [eep_listings_archive] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_events_map]', 'usage' => __('Alias of [eep_listings_map] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_events_calendar]', 'usage' => __('Alias of [eep_listings_calendar] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_events_query_grid]', 'usage' => __('Alias of [eep_events_query_grid] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_events_bento_grid]', 'usage' => __('Alias of [eep_events_bento_grid] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_events_ajax_search]', 'usage' => __('Alias of [eep_events_ajax_search] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_event_chatbot]', 'usage' => __('Alias of [eep_event_chatbot] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_submit_event]', 'usage' => __('Alias of [eep_submit] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_my_events]', 'usage' => __('Alias of [eep_my_listings] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_boost_posts]', 'usage' => __('Alias of [eep_boost_posts] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_my_tickets]', 'usage' => __('Alias of [eep_saved_listings] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_owner_analytics]', 'usage' => __('Alias of [eep_owner_analytics] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_account]', 'usage' => __('Alias of [eep_account] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_auth]', 'usage' => __('Alias of [eep_auth] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_auth_links]', 'usage' => __('Alias of [eep_auth_links] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_user_management]', 'usage' => __('Alias of [eep_user_management] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_moderation_queue]', 'usage' => __('Alias of [eep_moderation_queue] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_organizers]', 'usage' => __('Alias of [eep_organizers] for page builders/templates.', 'nexdirectory')],
            ['code' => '[nexdirectory_claim_listing]', 'usage' => __('Alias of [eep_claim_listing] for page builders/templates.', 'nexdirectory')],
        ];
        $runtime_logs = $this->get_runtime_logs(120);
        $chatbot_stats = $this->get_chatbot_index_stats();
        $settings_email_health = $this->get_settings_email_health();
        $settings_api_health = $this->get_settings_api_health($premium_unlocked);
        $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);
        $demo_limit_context = method_exists($this, 'get_demo_limit_admin_context')
            ? (array) $this->get_demo_limit_admin_context()
            : [];
        $settings_demo_mode_enabled = !empty($demo_limit_context['is_demo_mode']);
        $settings_demo_limit = max(1, (int) ($demo_limit_context['limit'] ?? 3));
        $settings_demo_used = max(0, (int) ($demo_limit_context['used'] ?? 0));
        $settings_demo_remaining = max(0, (int) ($demo_limit_context['remaining'] ?? 0));
        $settings_upgrade_url = esc_url((string) ($demo_limit_context['upgrade_url'] ?? 'https://nexdirectory.com/purchase'));
        $settings_license_url = esc_url((string) ($demo_limit_context['license_url'] ?? admin_url('admin.php?page=eep-settings#eep-tab-monetization--boost-packages')));
        $settings_license_label = sanitize_text_field((string) ($demo_limit_context['license_label'] ?? __('Activate License', 'nexdirectory')));
        ?>
        <div class="wrap eep-admin-premium eep-settings-premium">
            <?php $this->render_admin_premium_shell_styles(); ?>
            <section class="eep-admin-hero">
                <div class="eep-settings-hero-main">
                    <span class="eep-admin-hero-kicker"><?php esc_html_e('Admin Control Center', 'nexdirectory'); ?></span>
                    <h1><?php echo esc_html($settings_page_title); ?></h1>
                    <p><?php echo esc_html(sprintf(__('Configure routing, design, moderation, notifications, and AI tools for your %s experience.', 'nexdirectory'), $settings_plural_lower)); ?></p>
                    <div class="eep-settings-hero-meta">
                        <span class="eep-settings-hero-pill"><span class="dashicons dashicons-layout" aria-hidden="true"></span><?php esc_html_e('Template-Based Settings', 'nexdirectory'); ?></span>
                        <span class="eep-settings-hero-pill"><span class="dashicons dashicons-update" aria-hidden="true"></span><?php esc_html_e('Auto-Save Enabled', 'nexdirectory'); ?></span>
                    </div>
                </div>
                <div class="eep-settings-hero-tools">
                    <div class="eep-settings-search-wrap eep-settings-search-wrap-top">
                        <span class="dashicons dashicons-search" aria-hidden="true"></span>
                        <input type="search" id="eep-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="eep-settings-search-clear" id="eep-settings-search-top-clear" data-target-input="eep-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>
            <?php if ($settings_demo_mode_enabled) : ?>
                <section class="eep-settings-demo-alert" aria-label="<?php esc_attr_e('Demo mode status', 'nexdirectory'); ?>">
                    <div class="eep-settings-demo-alert-copy">
                        <h3><?php echo esc_html(sprintf(__('Demo Mode Active: %d Free Events', 'nexdirectory'), $settings_demo_limit)); ?></h3>
                        <p><?php esc_html_e('This site is currently in demo mode. Keep this visible to stakeholders so there is no surprise when the free cap is reached.', 'nexdirectory'); ?></p>
                        <span class="eep-settings-demo-alert-counter">
                            <?php
                            echo esc_html(
                                sprintf(
                                    __('Used %1$d of %2$d (Remaining: %3$d)', 'nexdirectory'),
                                    $settings_demo_used,
                                    $settings_demo_limit,
                                    $settings_demo_remaining
                                )
                            );
                            ?>
                        </span>
                    </div>
                    <div class="eep-settings-demo-alert-actions">
                        <a class="button button-primary" href="<?php echo $settings_upgrade_url; ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e('Buy / Upgrade', 'nexdirectory'); ?></a>
                        <a class="button" href="<?php echo $settings_license_url; ?>"><?php echo esc_html($settings_license_label); ?></a>
                    </div>
                </section>
            <?php endif; ?>
            <?php settings_errors(); ?>
            <section class="eep-admin-panel">
            <style>
                .eep-settings-premium .eep-admin-hero { position: relative; overflow: hidden; background: radial-gradient(circle at top right, rgba(79, 70, 229, .25), rgba(79, 70, 229, 0) 46%), radial-gradient(circle at bottom left, rgba(249, 115, 22, .2), rgba(249, 115, 22, 0) 44%), linear-gradient(135deg, #0f172a 0%, #111827 55%, #1f2937 100%); color: #fff; border-radius: 18px; padding: 24px; display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 400px); gap: 18px; align-items: center; margin-bottom: 14px; box-shadow: 0 20px 40px rgba(15, 23, 42, .28); border: 1px solid rgba(51, 65, 85, .45); }
                .eep-settings-premium .eep-admin-hero h1 { margin: 0 0 6px; font-size: 30px; font-weight: 800; color: #fff; letter-spacing: -.02em; }
                .eep-settings-premium .eep-admin-hero p { margin: 0; color: #d5ddeb; max-width: 880px; font-size: 15px; line-height: 1.5; }
                .eep-settings-premium .eep-admin-hero .eep-admin-hero-kicker { display: inline-block; margin-bottom: 8px; font-size: 10px; font-weight: 700; letter-spacing: .09em; text-transform: uppercase; color: #fdba74; background: rgba(251, 146, 60, .16); border: 1px solid rgba(251, 146, 60, .38); padding: 4px 9px; border-radius: 999px; }
                .eep-settings-hero-main { min-width: 0; }
                .eep-settings-hero-meta { margin-top: 12px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
                .eep-settings-hero-pill { display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; border-radius: 999px; border: 1px solid rgba(148, 163, 184, .45); background: rgba(15, 23, 42, .44); color: #dbeafe; font-size: 11px; font-weight: 700; letter-spacing: .02em; }
                .eep-settings-hero-pill .dashicons { width: 14px; height: 14px; font-size: 14px; }
                .eep-settings-hero-tools { display: grid; gap: 7px; align-content: start; }
                .eep-settings-search-wrap-top { margin: 0; }
                .eep-settings-search-wrap-top input { background: rgba(15, 23, 42, .45); border-color: rgba(148, 163, 184, .38); color: #0f172a; }
                .eep-settings-search-wrap-top input::placeholder { color: #9ca3af; }
                .eep-settings-search-wrap-top .dashicons-search { color: #cbd5e1; }
                .eep-settings-search-wrap-top .eep-settings-search-clear { color: #cbd5e1; }
                .eep-settings-search-wrap-top .eep-settings-search-clear:hover { background: rgba(148, 163, 184, .18); color: #fff; }
                .eep-settings-hero-tools .description { margin: 0; color: #cbd5e1; }
                .eep-settings-demo-alert {
                    margin-bottom: 14px;
                    border: 1px solid #fecaca;
                    border-radius: 14px;
                    background: linear-gradient(135deg, #fff7ed 0%, #ffedd5 100%);
                    box-shadow: 0 10px 26px rgba(249, 115, 22, .16);
                    padding: 14px 16px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    gap: 12px;
                    flex-wrap: wrap;
                }
                .eep-settings-demo-alert-copy h3 {
                    margin: 0 0 4px;
                    color: #9a3412;
                    font-size: 18px;
                    line-height: 1.25;
                }
                .eep-settings-demo-alert-copy p {
                    margin: 0;
                    color: #7c2d12;
                    font-size: 13px;
                }
                .eep-settings-demo-alert-counter {
                    display: inline-flex;
                    align-items: center;
                    margin-top: 8px;
                    padding: 4px 10px;
                    border-radius: 999px;
                    border: 1px solid #fdba74;
                    background: rgba(255, 255, 255, .62);
                    color: #9a3412;
                    font-size: 12px;
                    font-weight: 700;
                    letter-spacing: .01em;
                }
                .eep-settings-demo-alert-actions {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    flex-wrap: wrap;
                }
                .eep-settings-demo-alert-actions .button {
                    min-height: 40px;
                    font-weight: 700;
                }
                .eep-settings-tabs.nav-tab-wrapper { border-bottom: 0; margin: 18px 0 14px; padding: 0; display: flex; gap: 8px; flex-wrap: wrap; }
                .eep-settings-tabs .nav-tab { cursor: pointer; border: 1px solid #dde3ec; border-radius: 999px; padding: 7px 14px; line-height: 1.3; margin: 0; background: #fff; color: #334155; font-weight: 700; font-size: 12px; transition: all .2s ease; display: inline-flex; align-items: center; gap: 6px; }
                .eep-settings-tabs .nav-tab .dashicons { width: 14px; height: 14px; font-size: 14px; }
                .eep-settings-tabs .nav-tab:hover { border-color: #f97316; color: #f97316; background: #fff7ed; transform: translateY(-1px); }
                .eep-settings-tabs .nav-tab.nav-tab-active { border-color: #f97316; background: #f97316; color: #fff; box-shadow: 0 8px 18px rgba(249, 115, 22, .25); }
                .eep-settings-tabs .nav-tab.is-disabled { cursor: not-allowed; opacity: .58; color: #6b7280; border-color: #d1d5db; background: #f3f4f6; }
                .eep-settings-tabs .nav-tab.is-disabled:hover { border-color: #d1d5db; color: #6b7280; background: #f3f4f6; }
                .eep-settings-shell { display: grid; grid-template-columns: minmax(240px, 280px) minmax(0, 1fr); gap: 16px; align-items: start; }
                .eep-settings-sidebar { position: sticky; top: 48px; align-self: start; border: 1px solid #dce3ed; border-radius: 14px; background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%); box-shadow: 0 10px 24px rgba(15, 23, 42, .06); padding: 12px; }
                .eep-settings-sidebar-title { margin: 0 0 8px; color: #0f172a; font-size: 13px; font-weight: 700; letter-spacing: .02em; text-transform: uppercase; }
                .eep-settings-search-wrap { position: relative; margin-bottom: 10px; }
                .eep-settings-search-wrap input { width: 100%; border-radius: 10px; border: 1px solid #d8e0ec; padding: 9px 38px 9px 34px; font-size: 13px; background: #fff; }
                .eep-settings-search-wrap .dashicons-search { position: absolute; top: 9px; left: 10px; font-size: 16px; width: 16px; height: 16px; color: #64748b; pointer-events: none; }
                .eep-settings-search-clear { position: absolute; top: 4px; right: 4px; border: 0; background: transparent; color: #94a3b8; width: 28px; height: 28px; border-radius: 8px; cursor: pointer; }
                .eep-settings-search-clear:hover { background: #f1f5f9; color: #0f172a; }
                .eep-settings-search-meta { margin: 0 0 10px; font-size: 11px; color: #64748b; min-height: 16px; }
                .eep-settings-subtabs { margin: 0; display: grid; gap: 7px; border: 0; padding: 0; }
                .eep-settings-subtabs .eep-settings-subtab { display: flex; align-items: center; justify-content: flex-start; min-height: 34px; padding: 7px 10px; border: 1px solid #d7dee9; border-radius: 10px; background: #fff; color: #334155; text-decoration: none; font-weight: 600; font-size: 12px; line-height: 1.2; cursor: pointer; transition: all .2s ease; letter-spacing: .01em; }
                .eep-settings-subtabs .eep-settings-subtab:hover { border-color: #f97316; color: #f97316; background: #fff7ed; transform: translateX(1px); }
                .eep-settings-subtabs .eep-settings-subtab.is-active { background: #f97316; border-color: #f97316; color: #fff; box-shadow: 0 8px 18px rgba(249, 115, 22, .2); }
                .eep-settings-subtabs .eep-settings-subtab.is-disabled { cursor: not-allowed; opacity: .58; color: #6b7280; border-color: #d1d5db; background: #f3f4f6; transform: none; }
                .eep-settings-subtabs .eep-settings-subtab.is-disabled:hover { border-color: #d1d5db; color: #6b7280; background: #f3f4f6; transform: none; }
                .eep-settings-subtabs .eep-settings-subtab[hidden] { display: none !important; }
                .eep-settings-content { min-width: 0; }
                .eep-settings-content-header { border: 1px solid #edf0f5; border-radius: 14px; background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%); padding: 14px 16px; margin-bottom: 12px; }
                .eep-settings-content-header h2 { margin: 0; font-size: 20px; line-height: 1.25; color: #0f172a; }
                .eep-settings-content-header p { margin: 4px 0 0; font-size: 13px; color: #64748b; }
                .eep-settings-search-empty { border: 1px dashed #d7dee9; background: #fff; border-radius: 12px; padding: 12px; margin-bottom: 12px; color: #475569; font-size: 13px; }
                .eep-settings-search-empty[hidden] { display: none !important; }
                .eep-settings-panel { display: none; background: linear-gradient(180deg, #ffffff 0%, #f8faff 100%); border: 1px solid #dcdcde; border-radius: 14px; padding: 18px 20px; margin-bottom: 14px; box-shadow: 0 10px 22px rgba(16,24,40,.06); }
                .eep-settings-panel.is-active { display: block; }
                .eep-settings-panel h2 { margin-top: 0; margin-bottom: 6px; }
                .eep-settings-subheading { margin: 0 0 14px; font-size: 13px; color: #50575e; max-width: 860px; line-height: 1.5; }
                .eep-settings-section-card { border: 1px solid #ececf0; border-radius: 10px; background: #f9fafb; padding: 12px; }
                .eep-settings-section-card h3 { display: flex; align-items: center; gap: 8px; margin: 0 0 8px; font-size: 14px; }
                .eep-settings-section-card .dashicons { color: #2271b1; width: 18px; height: 18px; font-size: 18px; }
                .eep-connection-card { border-color: #dbe5f1; background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%); }
                .eep-connection-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
                .eep-connection-badge { display: inline-flex; align-items: center; justify-content: center; padding: 4px 10px; border-radius: 999px; border: 1px solid transparent; font-size: 11px; line-height: 1.1; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; }
                .eep-connection-badge.is-connected { background: #dcfce7; color: #166534; border-color: #86efac; }
                .eep-connection-badge.is-disconnected { background: #fee2e2; color: #991b1b; border-color: #fecaca; }
                .eep-connection-list { display: grid; gap: 10px; margin-top: 6px; }
                .eep-connection-row { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 8px; align-items: center; border: 1px solid #e7edf6; border-radius: 10px; background: #fff; padding: 10px; }
                .eep-connection-row strong { color: #0f172a; font-size: 13px; line-height: 1.3; }
                .eep-connection-row .description { margin: 3px 0 0; }
                .eep-connection-actions { margin-top: 10px; justify-content: flex-start; }
                .eep-settings-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 20px; }
                .eep-settings-field { background: #fff; border: 1px solid #edf0f5; border-radius: 12px; padding: 12px; }
                .eep-settings-field label { font-weight: 600; display: block; margin-bottom: 4px; }
                .eep-settings-field .description { margin-top: 4px; color: #646970; font-size: 12px; }
                .eep-settings-field input[type="text"],
                .eep-settings-field input[type="url"],
                .eep-settings-field input[type="password"],
                .eep-settings-field input[type="number"],
                .eep-settings-field select,
                .eep-settings-field textarea { width: 100%; max-width: 760px; }
                .eep-settings-field.eep-full { grid-column: 1 / -1; }
                .eep-settings-field.eep-search-hidden { display: none !important; }
                .eep-settings-field-grid { display: grid; gap: 10px; }
                .eep-settings-inline { display: flex; gap: 8px; align-items: center; }
                .eep-settings-inline input[type="text"],
                .eep-settings-inline input[type="url"],
                .eep-settings-inline input[type="number"],
                .eep-settings-inline input[type="password"],
                .eep-settings-inline textarea { flex: 1 1 auto; max-width: none; }
                .eep-settings-select-helper { margin-top: 6px; display: grid; gap: 6px; }
                .eep-settings-preset-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
                .eep-settings-preset-status { font-size: 12px; color: #166534; min-height: 18px; }
                .eep-settings-hint-list { margin: 8px 0 0 18px; color: #50575e; list-style: disc; }
                .eep-settings-hint-list li { margin-bottom: 4px; }
                .eep-settings-toggle-list { display: grid; gap: 8px; }
                .eep-settings-toggle-item { border: 1px solid #dcdcde; border-radius: 8px; background: #fff; padding: 10px 12px; }
                .eep-settings-toggle-item label { margin-bottom: 2px; }
                .eep-settings-autosave-note { margin: 0; display: inline-flex; align-items: center; gap: 6px; color: #64748b; font-size: 12px; }
                .eep-settings-autosave-note .dashicons { width: 16px; height: 16px; font-size: 16px; line-height: 1; }
                .eep-settings-autosave-status[data-tone="pending"] { color: #1d4ed8; }
                .eep-settings-autosave-status[data-tone="success"] { color: #15803d; }
                .eep-settings-autosave-status[data-tone="error"] { color: #b91c1c; }
                .eep-monetization-grid { gap: 16px; }
                .eep-monetization-card { padding: 14px; border-color: #e7ecf4; background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%); }
                .eep-monetization-repeater { display: grid; gap: 10px; }
                .eep-monetization-row { display: grid; grid-template-columns: minmax(110px, 1fr) minmax(120px, 1fr) auto; gap: 10px; padding: 10px; border: 1px solid #e8edf5; border-radius: 10px; background: #fff; }
                .eep-monetization-row-type { grid-template-columns: minmax(160px, 1fr) minmax(140px, 1fr) minmax(120px, 1fr) auto; }
                .eep-monetization-col label { font-size: 12px; font-weight: 600; color: #4b5563; margin-bottom: 5px; }
                .eep-monetization-col-actions { display: flex; align-items: flex-end; justify-content: flex-end; }
                .eep-settings-sticky-save { position: sticky; bottom: 8px; z-index: 30; margin-top: 14px; background: rgba(255,255,255,.95); border: 1px solid #dcdcde; border-radius: 12px; padding: 12px; box-shadow: 0 10px 24px rgba(15, 23, 42, .12); display: flex; align-items: center; justify-content: space-between; gap: 12px; backdrop-filter: blur(3px); }
                .eep-settings-sticky-status { display: flex; align-items: center; gap: 8px; min-width: 0; }
                .eep-settings-sticky-status p { margin: 0; color: #4b5563; font-size: 12px; }
                .eep-settings-status-dot { width: 10px; height: 10px; border-radius: 999px; background: #cbd5e1; flex: 0 0 auto; }
                .eep-settings-status-dot[data-tone="pending"] { background: #3b82f6; box-shadow: 0 0 0 4px rgba(59, 130, 246, .15); }
                .eep-settings-status-dot[data-tone="success"] { background: #10b981; box-shadow: 0 0 0 4px rgba(16, 185, 129, .15); }
                .eep-settings-status-dot[data-tone="error"] { background: #ef4444; box-shadow: 0 0 0 4px rgba(239, 68, 68, .15); }
                .eep-settings-sticky-actions { display: flex; align-items: center; gap: 8px; }
                .eep-settings-sticky-save .button-primary { min-width: 150px; }
                .eep-settings-route-grid { display: grid; gap: 10px; margin-top: 10px; }
                .eep-settings-route-row { display: grid; grid-template-columns: minmax(180px, 240px) minmax(0, 1fr) auto; gap: 8px; align-items: center; }
                .eep-settings-route-row strong { color: #111827; font-size: 13px; }
                .eep-settings-route-row .eep-shortcode-inline { width: 100%; display: flex; gap: 8px; align-items: center; }
                .eep-settings-route-row .eep-shortcode-inline input { width: 100%; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 12px; background: #f8fafc; }
                .eep-settings-route-row .button { white-space: nowrap; }
                .eep-settings-visual-options { display: grid; grid-template-columns: repeat(auto-fit, minmax(148px, 1fr)); gap: 10px; margin-top: 10px; }
                .eep-settings-visual-option { border: 1px solid #dce3ed; border-radius: 12px; padding: 10px; background: #fff; text-align: left; cursor: pointer; transition: border-color .2s ease, box-shadow .2s ease, transform .2s ease; }
                .eep-settings-visual-option:hover { border-color: #ff5e14; transform: translateY(-1px); box-shadow: 0 8px 18px rgba(15, 23, 42, .09); }
                .eep-settings-visual-option.is-active { border-color: #ff5e14; box-shadow: 0 0 0 2px rgba(255, 94, 20, .2); background: #fff7ed; }
                .eep-settings-visual-option span { display: block; font-size: 12px; color: #4b5563; margin-top: 3px; }
                .eep-design-choice-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px; margin-top: 8px; }
                .eep-design-choice-grid-compact { grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); }
                .eep-design-choice { border: 1px solid #dce3ed; border-radius: 10px; padding: 8px; background: #fff; text-align: left; cursor: pointer; display: grid; gap: 4px; transition: border-color .2s ease, box-shadow .2s ease, transform .2s ease; }
                .eep-design-choice:hover { border-color: #f97316; transform: translateY(-1px); box-shadow: 0 8px 18px rgba(15, 23, 42, .08); }
                .eep-design-choice.is-active { border-color: #f97316; box-shadow: 0 0 0 2px rgba(249, 115, 22, .2); background: #fff7ed; }
                .eep-design-choice strong { font-size: 12px; color: #111827; line-height: 1.3; }
                .eep-design-choice span { font-size: 11px; color: #64748b; line-height: 1.35; }
                .eep-design-choice-swatch { height: 26px; border-radius: 8px; border: 1px solid #d8dee9; background: #fff; display: block; }
                .eep-swatch-box-default { background: #fff; border-color: #dde3ed; box-shadow: inset 0 0 0 1px #f3f4f6; }
                .eep-swatch-box-gradient { background: linear-gradient(135deg, #fff7ed, #ffffff 42%, #fef3c7); border-color: #fdba74; }
                .eep-swatch-box-bold { background: #fff7ed; border: 2px solid #fb923c; }
                .eep-swatch-box-neumorphic { background: #f3f4f6; border-color: transparent; box-shadow: 6px 6px 12px #d5d9de, -6px -6px 12px #ffffff; }
                .eep-swatch-btn-solid { background: #f97316; border-color: #ea580c; }
                .eep-swatch-btn-outline { background: #fff; border: 2px solid #f97316; }
                .eep-swatch-btn-soft { background: #ffedd5; border-color: #fdba74; }
                .eep-swatch-btn-dark { background: #111827; border-color: #030712; }
                .eep-swatch-radius-inherit { border-radius: 10px; background: #f8fafc; }
                .eep-swatch-radius-pill { border-radius: 999px; background: #f8fafc; }
                .eep-swatch-radius-sharp { border-radius: 0; background: #f8fafc; }
                .eep-swatch-input-outline { background: #fff; border: 1px solid #d1d5db; }
                .eep-swatch-input-filled { background: #f8fafc; border: 1px solid #e2e8f0; }
                .eep-swatch-input-underlined { background: linear-gradient(to top, #f97316 0 2px, transparent 2px 100%), #fff; border: 0; border-bottom: 1px solid #d1d5db; border-radius: 0; }
                .eep-swatch-density-compact { background: linear-gradient(#e2e8f0 0 3px, transparent 3px 8px, #e2e8f0 8px 11px, transparent 11px 16px, #e2e8f0 16px 19px, transparent 19px 100%), #fff; }
                .eep-swatch-density-comfortable { background: linear-gradient(#e2e8f0 0 3px, transparent 3px 10px, #e2e8f0 10px 13px, transparent 13px 20px, #e2e8f0 20px 23px, transparent 23px 100%), #fff; }
                .eep-swatch-density-loose { background: linear-gradient(#e2e8f0 0 3px, transparent 3px 13px, #e2e8f0 13px 16px, transparent 16px 100%), #fff; }
                .eep-swatch-border-minimal { border-color: transparent; box-shadow: inset 0 0 0 1px rgba(148, 163, 184, .2); }
                .eep-swatch-border-subtle { border-color: #dbe2ec; }
                .eep-swatch-border-strong { border: 2px solid #94a3b8; }
                .eep-swatch-shadow-none { box-shadow: none; }
                .eep-swatch-shadow-soft { box-shadow: 0 4px 10px rgba(15, 23, 42, .08); }
                .eep-swatch-shadow-medium { box-shadow: 0 8px 18px rgba(15, 23, 42, .13); }
                .eep-swatch-shadow-dramatic { box-shadow: 0 16px 32px rgba(15, 23, 42, .24); }
                .eep-swatch-width-narrow { background: linear-gradient(to right, transparent 0 22%, #e2e8f0 22% 78%, transparent 78% 100%), #fff; }
                .eep-swatch-width-standard { background: linear-gradient(to right, transparent 0 14%, #e2e8f0 14% 86%, transparent 86% 100%), #fff; }
                .eep-swatch-width-wide { background: linear-gradient(to right, transparent 0 7%, #e2e8f0 7% 93%, transparent 93% 100%), #fff; }
                .eep-swatch-width-full { background: linear-gradient(to right, #e2e8f0 0 100%), #fff; }
                .eep-settings-core-title { margin: 0 0 8px; font-size: 15px; display: flex; align-items: center; gap: 8px; }
                .eep-settings-core-title .dashicons { color: #ff5e14; }
                .eep-settings-core-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
                .eep-settings-core-actions .description { margin: 0 !important; }
                .eep-preloader-preview-shell { --eep-preloader-preview-bg: #ffffff; --eep-preloader-preview-fade: 420ms; --eep-preloader-preview-width: 420px; position: relative; min-height: 220px; border: 1px solid #d9e2ee; border-radius: 14px; background: var(--eep-preloader-preview-bg); overflow: hidden; display: flex; align-items: center; justify-content: center; box-shadow: inset 0 0 0 1px rgba(255,255,255,.65), 0 8px 18px rgba(15, 23, 42, .05); opacity: 1; transform: scale(1); transition: opacity var(--eep-preloader-preview-fade) ease, transform var(--eep-preloader-preview-fade) ease; }
                .eep-preloader-preview-shell::before { content: ""; position: absolute; inset: 0; background-image: linear-gradient(to right, rgba(148,163,184,.12) 1px, transparent 1px), linear-gradient(to bottom, rgba(148,163,184,.12) 1px, transparent 1px); background-size: 24px 24px; pointer-events: none; }
                .eep-preloader-preview-shell.is-fading { opacity: 0; transform: scale(.985); }
                .eep-preloader-preview-stage { position: relative; z-index: 2; width: min(var(--eep-preloader-preview-width), 90%); max-height: 70%; display: flex; align-items: center; justify-content: center; }
                .eep-preloader-preview-stage img,
                .eep-preloader-preview-stage svg { display: block; width: 100%; height: auto; max-width: 100%; max-height: 160px; }
                .eep-preloader-preview-empty { text-align: center; color: #64748b; font-size: 12px; font-weight: 600; letter-spacing: .01em; }
                .eep-preloader-preview-meta { margin-top: 8px; font-size: 12px; color: #64748b; display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
                .eep-settings-panel input[type="checkbox"] { -webkit-appearance: none; appearance: none; width: 42px; height: 24px; border-radius: 999px; border: 1px solid #cbd5e1; background: #e5e7eb; position: relative; cursor: pointer; vertical-align: middle; margin: 0 10px 0 0; transition: background-color .2s ease, border-color .2s ease; }
                .eep-settings-panel input[type="checkbox"]::before { content: ""; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; box-shadow: 0 1px 3px rgba(15, 23, 42, .25); transition: transform .2s ease; }
                .eep-settings-panel input[type="checkbox"]:checked { background: #ff5e14; border-color: #ff5e14; }
                .eep-settings-panel input[type="checkbox"]:checked::before { transform: translateX(18px); }
                .eep-settings-panel input[type="checkbox"]:focus-visible { outline: 2px solid #1d4ed8; outline-offset: 2px; }
                .eep-settings-panel label:has(> input[type="checkbox"]) { display: flex; align-items: center; gap: 2px; line-height: 1.4; margin-bottom: 0; }
                .eep-shortcode-table code { font-size: 12px; }
                .eep-shortcode-copy-cell { width: 130px; text-align: right; }
                .eep-settings-shortcode-actions { margin-bottom: 12px; display: flex; gap: 8px; flex-wrap: wrap; }
                .eep-media-picker { display: grid; gap: 8px; }
                .eep-media-dropzone { width: 100%; border: 1px dashed #d0d7e2; border-radius: 12px; background: #f7fafc; padding: 14px; text-align: center; cursor: pointer; display: grid; gap: 4px; align-items: center; justify-items: center; }
                .eep-media-dropzone .dashicons { color: #f97316; font-size: 20px; width: 20px; height: 20px; }
                .eep-media-dropzone strong { font-size: 13px; color: #111827; }
                .eep-media-dropzone span { font-size: 12px; color: #64748b; }
                .eep-media-dropzone.is-dragover { border-color: #f97316; background: #fff7ed; }
                .eep-media-gallery { display: grid; gap: 8px; margin-top: 2px; }
                .eep-fallback-preview-grid { grid-template-columns: repeat(auto-fit, minmax(82px, 82px)); }
                .eep-fallback-preview-single { grid-template-columns: minmax(0, 260px); }
                .eep-media-tile { position: relative; border: 1px solid #dcdcde; border-radius: 10px; overflow: hidden; background: #fff; }
                .eep-media-tile img { width: 100%; height: 82px; object-fit: cover; display: block; }
                .eep-fallback-preview-single .eep-media-tile img { height: 148px; }
                .eep-media-remove { position: absolute; top: 6px; right: 6px; border: 0; border-radius: 999px; width: 22px; height: 22px; cursor: pointer; background: rgba(15, 23, 42, 0.82); color: #fff; font-size: 16px; line-height: 1; }
                .eep-media-remove:hover { background: rgba(220, 38, 38, 0.9); }
                .eep-media-feedback { min-height: 16px; margin: 0 !important; }
                .eep-media-feedback[data-tone="error"] { color: #b91c1c; }
                .eep-media-feedback[data-tone="success"] { color: #166534; }
                .eep-settings-counter { margin-top: 5px; color: #64748b; font-size: 12px; }
                .eep-seo-serp-preview { margin-top: 10px; padding: 12px; border: 1px solid #e5e7eb; border-radius: 12px; background: #fff; }
                .eep-seo-serp-url { color: #166534; font-size: 12px; margin-bottom: 5px; line-height: 1.4; word-break: break-all; }
                .eep-seo-serp-title { color: #1a0dab; font-size: 18px; line-height: 1.35; margin-bottom: 4px; font-weight: 500; }
                .eep-seo-serp-description { color: #4b5563; font-size: 13px; line-height: 1.45; }
                .eep-settings-accordion { border: 1px solid #dcdcde; border-radius: 10px; background: #fff; padding: 8px 10px; margin-top: 4px; }
                .eep-settings-accordion > summary { cursor: pointer; font-weight: 600; color: #1d2327; }
                .eep-settings-accordion[open] > summary { margin-bottom: 10px; }
                .eep-map-skin-legend { margin: 8px 0 0; padding-left: 18px; color: #50575e; }
                .eep-help-link { margin-left: 6px; text-decoration: none; }
                .eep-help-link .dashicons { font-size: 16px; width: 16px; height: 16px; vertical-align: text-bottom; }
                .eep-help-trigger { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; margin-left: 6px; border: 1px solid #dcdcde; border-radius: 50%; background: #f6f7f7; color: #2271b1; cursor: pointer; vertical-align: middle; }
                .eep-help-trigger:hover { border-color: #2271b1; background: #eef4fb; color: #135e96; }
                .eep-help-trigger .dashicons { width: 16px; height: 16px; font-size: 16px; line-height: 1; }
                .eep-help-dialog-backdrop { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.48); z-index: 99998; opacity: 0; pointer-events: none; transition: opacity .2s ease; }
                .eep-help-dialog { position: fixed; top: 50%; left: 50%; width: min(680px, calc(100vw - 34px)); max-height: calc(100vh - 48px); overflow: auto; transform: translate(-50%, -48%); z-index: 99999; background: #fff; border-radius: 14px; box-shadow: 0 18px 42px rgba(16, 24, 40, .28); border: 1px solid #dcdcde; padding: 18px 18px 16px; opacity: 0; pointer-events: none; transition: opacity .2s ease, transform .2s ease; }
                .eep-help-dialog.is-open,
                .eep-help-dialog-backdrop.is-open { opacity: 1; pointer-events: auto; }
                .eep-help-dialog.is-open { transform: translate(-50%, -50%); }
                .eep-help-dialog-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
                .eep-help-dialog-header h3 { margin: 0; font-size: 18px; line-height: 1.3; }
                .eep-help-dialog-close { border: 1px solid #dcdcde; border-radius: 50%; width: 28px; height: 28px; background: #fff; cursor: pointer; font-size: 18px; line-height: 1; color: #1d2327; }
                .eep-help-dialog-close:hover { border-color: #2271b1; color: #135e96; }
                .eep-help-dialog-body { color: #2c3338; font-size: 14px; line-height: 1.55; }
                .eep-help-dialog-body p { margin: 0 0 10px; }
                .eep-custom-fields-wrap { border: 1px solid #dcdcde; border-radius: 8px; overflow: hidden; background: #fff; }
                .eep-custom-fields-table { width: 100%; border-collapse: collapse; }
                .eep-custom-fields-table th, .eep-custom-fields-table td { padding: 8px; border-bottom: 1px solid #f0f0f1; vertical-align: top; }
                .eep-custom-fields-table th { background: #f6f7f7; text-align: left; font-weight: 600; }
                .eep-custom-fields-table input[type="text"], .eep-custom-fields-table select, .eep-custom-fields-table textarea { width: 100%; margin: 0; }
                .eep-custom-fields-table textarea { min-height: 68px; }
                .eep-custom-fields-controls { margin-top: 10px; display: flex; gap: 8px; align-items: center; }
                .eep-custom-fields-empty { padding: 10px; color: #646970; }
                @media (max-width: 900px) {
                    .eep-settings-premium .eep-admin-hero { grid-template-columns: 1fr; gap: 12px; padding: 18px; }
                    .eep-settings-premium .eep-admin-hero h1 { font-size: 24px; }
                    .eep-settings-shell { grid-template-columns: 1fr; }
                    .eep-settings-sidebar { position: static; top: auto; padding: 10px; }
                    .eep-settings-content-header { padding: 12px; }
                    .eep-settings-content-header h2 { font-size: 18px; }
                    .eep-settings-grid { grid-template-columns: 1fr; }
                    .eep-settings-subtabs { gap: 5px; grid-template-columns: 1fr; }
                    .eep-settings-subtabs .eep-settings-subtab { width: 100%; justify-content: flex-start; border-radius: 8px; min-height: 30px; padding: 6px 9px; font-size: 11px; }
                    .eep-settings-inline { flex-direction: column; align-items: stretch; }
                    .eep-monetization-row,
                    .eep-monetization-row-type { grid-template-columns: 1fr; }
                    .eep-monetization-col-actions { justify-content: flex-start; }
                    .eep-settings-route-row { grid-template-columns: 1fr; gap: 6px; }
                    .eep-connection-row { grid-template-columns: 1fr; }
                    .eep-shortcode-copy-cell { width: auto; text-align: left; }
                    .eep-fallback-preview-grid { grid-template-columns: repeat(auto-fit, minmax(64px, 64px)); }
                    .eep-media-tile img { height: 64px; }
                    .eep-fallback-preview-single { grid-template-columns: 1fr; }
                    .eep-fallback-preview-single .eep-media-tile img { height: auto; max-height: 220px; }
                    .eep-custom-fields-table th, .eep-custom-fields-table td { padding: 6px; }
                    .eep-settings-sticky-save { flex-direction: column; align-items: stretch; }
                    .eep-settings-sticky-actions { width: 100%; justify-content: stretch; }
                    .eep-settings-sticky-actions .button { width: 100%; text-align: center; }
                }
            </style>
            <form method="post" action="options.php">
                <?php settings_fields('eep_settings_group'); ?>
                <?php if ($white_label_is_unlocked && $white_label_unlock_token !== '') : ?>
                    <input type="hidden" name="eep_white_label_unlock_token" value="<?php echo esc_attr($white_label_unlock_token); ?>">
                <?php endif; ?>
                <nav class="nav-tab-wrapper eep-settings-tabs" id="eep-settings-tabs">
                    <a href="#eep-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="#eep-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="#eep-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="#eep-tab-monetization" class="nav-tab" data-tab="monetization"><span class="dashicons dashicons-money-alt" aria-hidden="true"></span><?php esc_html_e('Monetisation', 'nexdirectory'); ?></a>
                    <a href="#eep-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="#eep-tab-chatbot" class="nav-tab is-disabled" data-tab="chatbot" data-disabled="1" aria-disabled="true"><span class="dashicons dashicons-format-chat" aria-hidden="true"></span><?php esc_html_e('AI Chatbot (Coming soon)', 'nexdirectory'); ?></a>
                    <a href="#eep-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="eep-settings-shell">
                    <aside class="eep-settings-sidebar">
                        <h3 class="eep-settings-sidebar-title"><?php esc_html_e('Navigate Settings', 'nexdirectory'); ?></h3>
                        <p class="eep-settings-search-meta" id="eep-settings-search-meta"><?php esc_html_e('Search all sections and tabs.', 'nexdirectory'); ?></p>
                        <nav class="eep-settings-subtabs" id="eep-settings-subtabs" aria-label="<?php esc_attr_e('Settings sections', 'nexdirectory'); ?>">
                            <a href="#eep-tab-general--setup" class="eep-settings-subtab is-active" data-parent-tab="general" data-subtab="setup"><?php esc_html_e('Setup', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-general--routing" class="eep-settings-subtab" data-parent-tab="general" data-subtab="routing"><?php esc_html_e('Routing', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-general--navbar" class="eep-settings-subtab" data-parent-tab="general" data-subtab="navbar"><?php esc_html_e('Navbar', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-general--footer" class="eep-settings-subtab" data-parent-tab="general" data-subtab="footer"><?php esc_html_e('Footer', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-general--shortcodes" class="eep-settings-subtab" data-parent-tab="general" data-subtab="shortcodes"><?php esc_html_e('Shortcodes', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-design-maps--branding" class="eep-settings-subtab" data-parent-tab="design-maps" data-subtab="branding"><?php esc_html_e('Branding & UI', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-design-maps--heros" class="eep-settings-subtab" data-parent-tab="design-maps" data-subtab="heros"><?php esc_html_e('Heroes', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-design-maps--layouts" class="eep-settings-subtab" data-parent-tab="design-maps" data-subtab="layouts"><?php esc_html_e('Layouts', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-design-maps--maps" class="eep-settings-subtab" data-parent-tab="design-maps" data-subtab="maps"><?php esc_html_e('Maps Configuration', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-submissions--rules" class="eep-settings-subtab" data-parent-tab="submissions" data-subtab="rules"><?php esc_html_e('Rules & Moderation', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-submissions--permissions" class="eep-settings-subtab" data-parent-tab="submissions" data-subtab="permissions"><?php esc_html_e('Roles & Access', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-submissions--submission-form" class="eep-settings-subtab" data-parent-tab="submissions" data-subtab="submission-form"><?php esc_html_e('Form Setup & Limits', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-monetization--boost-packages" class="eep-settings-subtab" data-parent-tab="monetization" data-subtab="boost-packages"><?php esc_html_e('Boost Packages', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-monetization--boost-payment" class="eep-settings-subtab" data-parent-tab="monetization" data-subtab="boost-payment"><?php esc_html_e('Boost Payment', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-monetization--tickets" class="eep-settings-subtab" data-parent-tab="monetization" data-subtab="tickets"><?php esc_html_e('Tickets', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-notifications--email" class="eep-settings-subtab" data-parent-tab="notifications" data-subtab="email"><?php esc_html_e('Email', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-notifications--alerts" class="eep-settings-subtab" data-parent-tab="notifications" data-subtab="alerts"><?php esc_html_e('Alerts', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-chatbot--chatbot" class="eep-settings-subtab is-disabled" data-parent-tab="chatbot" data-subtab="chatbot" data-disabled="1" aria-disabled="true"><?php esc_html_e('Chatbot (Coming soon)', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-advanced--seo" class="eep-settings-subtab" data-parent-tab="advanced" data-subtab="seo"><?php esc_html_e('SEO', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-advanced--extension" class="eep-settings-subtab" data-parent-tab="advanced" data-subtab="extension"><?php esc_html_e('Chrome Extension', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-advanced--email" class="eep-settings-subtab" data-parent-tab="advanced" data-subtab="email"><?php esc_html_e('SMTP Email', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-advanced--apis" class="eep-settings-subtab" data-parent-tab="advanced" data-subtab="apis"><?php esc_html_e('APIs', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-advanced--display" class="eep-settings-subtab" data-parent-tab="advanced" data-subtab="display"><?php esc_html_e('Display', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-advanced--white-label" class="eep-settings-subtab" data-parent-tab="advanced" data-subtab="white-label"><?php esc_html_e('White Label', 'nexdirectory'); ?></a>
                            <a href="#eep-tab-advanced--logs" class="eep-settings-subtab" data-parent-tab="advanced" data-subtab="logs"><?php esc_html_e('Logs', 'nexdirectory'); ?></a>
                        </nav>
                    </aside>
                    <div class="eep-settings-content" id="eep-settings-content">
                        <div class="eep-settings-content-header">
                            <h2 id="eep-settings-active-section-title"><?php esc_html_e('Setup', 'nexdirectory'); ?></h2>
                            <p id="eep-settings-active-section-description"><?php esc_html_e('Manage configuration and preferences for this section.', 'nexdirectory'); ?></p>
                        </div>
                        <div class="eep-settings-search-empty" id="eep-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-monetization.php'; ?>
                <?php require __DIR__ . '/sections/tab-notifications.php'; ?>
                <?php require __DIR__ . '/sections/tab-chatbot.php'; ?>
                <?php require __DIR__ . '/sections/tab-advanced.php'; ?>
                    </div>
                </div>

                <div class="eep-settings-sticky-save">
                    <div class="eep-settings-sticky-status">
                        <span class="eep-settings-status-dot" id="eep-settings-status-dot" aria-hidden="true"></span>
                        <p id="eep-settings-autosave-status-sticky" class="eep-settings-autosave-status"><?php esc_html_e('Auto-save is active. Changes save automatically.', 'nexdirectory'); ?></p>
                    </div>
                    <div class="eep-settings-sticky-actions">
                        <button type="button" class="button" id="eep-settings-reset-button-sticky"><?php esc_html_e('Reset View', 'nexdirectory'); ?></button>
                        <button type="submit" class="button button-primary" id="eep-settings-save-button"><?php esc_html_e('Save Settings', 'nexdirectory'); ?></button>
                    </div>
                </div>
            </form>
            </section>
            <form id="eep-clear-logs-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_clear_logs">
                <?php wp_nonce_field('eep_clear_logs', 'eep_clear_logs_nonce'); ?>
            </form>
            <form id="eep-send-test-email-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_send_test_email">
                <?php wp_nonce_field('eep_send_test_email', 'eep_send_test_email_nonce'); ?>
            </form>
            <form id="eep-test-map-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_test_map_connection">
                <?php wp_nonce_field('eep_test_map_connection', 'eep_test_map_connection_nonce'); ?>
            </form>
            <form id="eep-test-captcha-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_test_captcha_connection">
                <?php wp_nonce_field('eep_test_captcha_connection', 'eep_test_captcha_connection_nonce'); ?>
            </form>
            <form id="eep-test-routing-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_test_routing_connection">
                <?php wp_nonce_field('eep_test_routing_connection', 'eep_test_routing_connection_nonce'); ?>
            </form>
            <form id="eep-reset-smooth-scroll-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_reset_smooth_scroll_defaults">
                <?php wp_nonce_field('eep_reset_smooth_scroll_defaults', 'eep_reset_smooth_scroll_defaults_nonce'); ?>
            </form>
            <form id="eep-chatbot-test-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_chatbot_test_connection">
                <?php wp_nonce_field('eep_chatbot_test_connection', 'eep_chatbot_test_connection_nonce'); ?>
            </form>
            <form id="eep-chatbot-reindex-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_chatbot_reindex_now">
                <?php wp_nonce_field('eep_chatbot_reindex_now', 'eep_chatbot_reindex_now_nonce'); ?>
            </form>
            <form id="eep-chatbot-clear-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_chatbot_clear_index">
                <?php wp_nonce_field('eep_chatbot_clear_index', 'eep_chatbot_clear_index_nonce'); ?>
            </form>
            <form id="eep-generate-pages-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_generate_pages">
                <?php wp_nonce_field('eep_generate_pages', 'eep_generate_pages_nonce'); ?>
            </form>
            <form id="eep-regenerate-app-pass-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_regenerate_extension_app_pass">
                <?php wp_nonce_field('eep_regenerate_extension_app_pass', 'eep_regenerate_extension_app_pass_nonce'); ?>
            </form>
            <form id="eep-white-label-unlock-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_white_label_unlock">
                <?php wp_nonce_field('eep_white_label_unlock', 'eep_white_label_unlock_nonce'); ?>
            </form>
            <form id="eep-white-label-lock-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_white_label_lock">
                <?php wp_nonce_field('eep_white_label_lock', 'eep_white_label_lock_nonce'); ?>
            </form>
            <form id="eep-white-label-reset-defaults-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_white_label_reset_defaults">
                <input type="hidden" name="eep_white_label_unlock_token" value="<?php echo esc_attr($white_label_unlock_token); ?>">
                <?php wp_nonce_field('eep_white_label_reset_defaults', 'eep_white_label_reset_defaults_nonce'); ?>
            </form>
            <form id="eep-white-label-force-reset-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="eep_white_label_force_reset">
                <?php wp_nonce_field('eep_white_label_force_reset', 'eep_white_label_force_reset_nonce'); ?>
            </form>
            <div class="eep-help-dialog-backdrop" id="eep-settings-help-backdrop" data-eep-help-close="1"></div>
            <div class="eep-help-dialog" id="eep-settings-help-dialog" role="dialog" aria-modal="true" aria-hidden="true" aria-labelledby="eep-settings-help-title">
                <div class="eep-help-dialog-header">
                    <h3 id="eep-settings-help-title"><?php esc_html_e('Settings Help', 'nexdirectory'); ?></h3>
                    <button type="button" class="eep-help-dialog-close" data-eep-help-close="1" aria-label="<?php esc_attr_e('Close help dialog', 'nexdirectory'); ?>">&times;</button>
                </div>
                <div class="eep-help-dialog-body" id="eep-settings-help-body">
                    <p><?php esc_html_e('Click the help icons beside each field to see guidance.', 'nexdirectory'); ?></p>
                </div>
            </div>
            <script>
                (function () {
                    var tabsRoot = document.getElementById('eep-settings-tabs');
                    if (!tabsRoot) {
                        return;
                    }
                    var tabs = tabsRoot.querySelectorAll('[data-tab]');
                    var subtabsRoot = document.getElementById('eep-settings-subtabs');
                    var subtabs = subtabsRoot ? subtabsRoot.querySelectorAll('[data-parent-tab][data-subtab]') : [];
                    var panels = document.querySelectorAll('.eep-settings-panel[data-tab][data-subtab]');
                    var settingsForm = document.querySelector('form[action="options.php"]');
                    var dirtyState = false;
                    var activeTabStorageKey = 'eepSettingsActiveTab';
                    var activeSubtabStorageKey = 'eepSettingsActiveSubtab';
                    var settingsSearchPrimaryInput = document.getElementById('eep-settings-search');
                    var settingsSearchTopInput = document.getElementById('eep-settings-search-top');
                    var settingsSearchInputs = [settingsSearchPrimaryInput, settingsSearchTopInput].filter(function (inputEl) {
                        return !!inputEl;
                    });
                    var settingsSearchPrimaryClear = document.getElementById('eep-settings-search-clear');
                    var settingsSearchTopClear = document.getElementById('eep-settings-search-top-clear');
                    var settingsSearchClearButtons = [settingsSearchPrimaryClear, settingsSearchTopClear].filter(function (buttonEl) {
                        return !!buttonEl;
                    });
                    var settingsSearchMeta = document.getElementById('eep-settings-search-meta');
                    var settingsSearchEmpty = document.getElementById('eep-settings-search-empty');
                    var settingsSaveButton = document.getElementById('eep-settings-save-button');
                    var resetViewButtonSticky = document.getElementById('eep-settings-reset-button-sticky');
                    var autosaveStatusNodes = [
                        document.getElementById('eep-settings-autosave-status-sticky')
                    ].filter(function (nodeEl) {
                        return !!nodeEl;
                    });
                    var autosaveStatusDot = document.getElementById('eep-settings-status-dot');
                    var activeSectionTitleNode = document.getElementById('eep-settings-active-section-title');
                    var activeSectionDescriptionNode = document.getElementById('eep-settings-active-section-description');
                    var autosaveDebounceMs = 900;
                    var autosaveTimer = null;
                    var autosaveInFlight = false;
                    var autosaveQueued = false;
                    var autosaveStatusTimer = null;
                    var searchCrossTabJumpInProgress = false;
                    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="eep_notify_admin_pending_badge"][type="checkbox"]');
                    var pendingEmailToggle = document.querySelector('input[name="eep_notify_admin_pending_email"][type="checkbox"]');
                    var legacyPendingToggleInput = document.getElementById('eep_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();
                            return;
                        }
                        externalForm.submit();
                    });
                    var getActivePanel = function () {
                        return document.querySelector('.eep-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-eep-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-eep-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('.eep-settings-field');
                            var panelMatches = 0;
                            panelFields.forEach(function (fieldEl) {
                                var matched = true;
                                if (query !== '') {
                                    matched = getFieldSearchText(fieldEl).indexOf(query) > -1;
                                }
                                fieldEl.classList.toggle('eep-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 = '#eep-tab-' + parentKey;
                                if (subtabKey) {
                                    hash += '--' + subtabKey;
                                }
                                window.history.replaceState({}, '', baseUrl + hash);
                            }
                        } catch (historyError) {
                            // no-op
                        }
                    };
                    var setAutosaveStatus = 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 () {
                                setAutosaveStatus('<?php echo esc_js(__('Auto-save enabled. Changes are saved automatically.', 'nexdirectory')); ?>', '', true);
                            }, 2800);
                        }
                    };
                    var runSettingsAutosave = function () {
                        if (!settingsForm || !dirtyState) {
                            return;
                        }
                        if (autosaveInFlight) {
                            autosaveQueued = true;
                            return;
                        }
                        autosaveInFlight = true;
                        autosaveQueued = false;
                        if (settingsSaveButton) {
                            settingsSaveButton.disabled = true;
                        }
                        setAutosaveStatus('<?php echo esc_js(__('Saving changes...', 'nexdirectory')); ?>', 'pending', true);
                        window.fetch(settingsForm.action, {
                            method: 'POST',
                            credentials: 'same-origin',
                            cache: 'no-store',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            body: new window.FormData(settingsForm)
                        }).then(function (response) {
                            if (!response || !response.ok) {
                                throw new Error('save_failed');
                            }
                            return response.text();
                        }).then(function () {
                            clearDirty();
                            setAutosaveStatus('<?php echo esc_js(__('All changes saved.', 'nexdirectory')); ?>', 'success');
                        }).catch(function () {
                            setAutosaveStatus('<?php echo esc_js(__('Auto-save failed. Use Save Settings.', 'nexdirectory')); ?>', 'error', true);
                        }).finally(function () {
                            autosaveInFlight = false;
                            if (settingsSaveButton) {
                                settingsSaveButton.disabled = false;
                            }
                            if (autosaveQueued) {
                                dirtyState = true;
                                scheduleSettingsAutosave(450);
                            }
                        });
                    };
                    var scheduleSettingsAutosave = function (delayMs) {
                        if (!settingsForm) {
                            return;
                        }
                        if (autosaveTimer) {
                            window.clearTimeout(autosaveTimer);
                            autosaveTimer = null;
                        }
                        autosaveTimer = window.setTimeout(function () {
                            autosaveTimer = null;
                            runSettingsAutosave();
                        }, typeof delayMs === 'number' ? delayMs : autosaveDebounceMs);
                    };
                    var markDirty = function () {
                        dirtyState = true;
                        scheduleSettingsAutosave();
                    };
                    var clearDirty = function () {
                        dirtyState = false;
                    };
                    if (settingsForm) {
                        settingsForm.querySelectorAll('input[name], select[name], textarea[name]').forEach(function (inputEl) {
                            inputEl.addEventListener('input', markDirty);
                            inputEl.addEventListener('change', markDirty);
                        });
                        settingsForm.addEventListener('submit', function () {
                            syncLegacyPendingToggle();
                            if (autosaveTimer) {
                                window.clearTimeout(autosaveTimer);
                                autosaveTimer = null;
                            }
                            clearDirty();
                        });
                    }
                    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('#eep-tab-') === 0) {
                        var hashToken = hashValue.replace('#eep-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 === '') && /^#eep-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('eep_enable_submit_autosave');
                    var autosaveField = document.getElementById('eep-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('eep_theme_override_all_plugin_pages');
                    var themeOverrideGranular = document.getElementById('eep-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-eep-preset-target]');
                    presetSelects.forEach(function (selectEl) {
                        var targetSelector = selectEl.getAttribute('data-eep-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('eep_home_meta_title');
                        var descriptionInput = document.getElementById('eep_home_meta_description');
                        var titleCount = document.getElementById('eep-home-meta-title-count');
                        var descriptionCount = document.getElementById('eep-home-meta-description-count');
                        var titleStatus = document.getElementById('eep-home-meta-title-status');
                        var descriptionStatus = document.getElementById('eep-home-meta-description-status');
                        var serpTitle = document.getElementById('eep-home-serp-title');
                        var serpDescription = document.getElementById('eep-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-eep-visual-select]');
                        selects.forEach(function (selectEl) {
                            if (!selectEl || selectEl.nextElementSibling && selectEl.nextElementSibling.classList.contains('eep-settings-visual-options')) {
                                return;
                            }
                            var wrapper = document.createElement('div');
                            wrapper.className = 'eep-settings-visual-options';
                            var syncActiveOption = function () {
                                var currentValue = String(selectEl.value || '');
                                wrapper.querySelectorAll('.eep-settings-visual-option').forEach(function (opt) {
                                    var value = String(opt.getAttribute('data-eep-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 = 'eep-settings-visual-option';
                                button.setAttribute('data-eep-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-eep-choice-grid][data-eep-select]');
                        grids.forEach(function (grid) {
                            var selectSelector = String(grid.getAttribute('data-eep-select') || '').trim();
                            if (!selectSelector) {
                                return;
                            }
                            var selectEl = document.querySelector(selectSelector);
                            if (!selectEl) {
                                return;
                            }
                            var sync = function () {
                                var currentValue = String(selectEl.value || '');
                                grid.querySelectorAll('.eep-design-choice').forEach(function (choice) {
                                    var choiceValue = String(choice.getAttribute('data-eep-choice-value') || '');
                                    choice.classList.toggle('is-active', choiceValue === currentValue);
                                });
                            };
                            grid.querySelectorAll('.eep-design-choice').forEach(function (choice) {
                                choice.addEventListener('click', function () {
                                    var nextValue = String(choice.getAttribute('data-eep-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-eep-design-preset-select]');
                        var presetApply = document.querySelector('[data-eep-design-preset-apply]');
                        var presetStatus = document.querySelector('[data-eep-design-preset-status]');
                        if (!presetSelect || !presetApply) {
                            return;
                        }
                        var presets = {
                            'launchpad-modern': {
                                label: 'Launchpad Modern',
                                values: {
                                    eep_event_hero_layout: 'cinematic',
                                    eep_event_page_layout: 'modern',
                                    eep_event_gallery_type: 'default',
                                    eep_style_box_style: 'default',
                                    eep_style_button_style: 'solid',
                                    eep_style_button_radius_mode: 'inherit',
                                    eep_style_input_style: 'outline',
                                    eep_style_density_mode: 'comfortable',
                                    eep_style_border_mode: 'subtle',
                                    eep_style_shadow_mode: 'soft',
                                    eep_style_content_width: 'standard',
                                    eep_page_side_padding: '10%',
                                    eep_page_side_padding_mobile: '2%'
                                }
                            },
                            'minimal-focus': {
                                label: 'Minimal Focus',
                                values: {
                                    eep_event_hero_layout: 'minimal',
                                    eep_event_page_layout: 'single-column',
                                    eep_event_gallery_type: 'default',
                                    eep_style_box_style: 'default',
                                    eep_style_button_style: 'outline',
                                    eep_style_button_radius_mode: 'sharp',
                                    eep_style_input_style: 'underlined',
                                    eep_style_density_mode: 'loose',
                                    eep_style_border_mode: 'minimal',
                                    eep_style_shadow_mode: 'none',
                                    eep_style_content_width: 'narrow',
                                    eep_page_side_padding: '8%',
                                    eep_page_side_padding_mobile: '4%'
                                }
                            },
                            'editorial-story': {
                                label: 'Editorial Story',
                                values: {
                                    eep_event_hero_layout: 'split',
                                    eep_event_page_layout: 'editorial',
                                    eep_event_gallery_type: 'default',
                                    eep_style_box_style: 'gradient',
                                    eep_style_button_style: 'soft',
                                    eep_style_button_radius_mode: 'inherit',
                                    eep_style_input_style: 'filled',
                                    eep_style_density_mode: 'comfortable',
                                    eep_style_border_mode: 'subtle',
                                    eep_style_shadow_mode: 'medium',
                                    eep_style_content_width: 'standard',
                                    eep_page_side_padding: '10%',
                                    eep_page_side_padding_mobile: '3%'
                                }
                            },
                            'executive-spotlight': {
                                label: 'Executive Spotlight',
                                values: {
                                    eep_event_hero_layout: 'spotlight',
                                    eep_event_page_layout: 'left-sidebar',
                                    eep_event_gallery_type: 'default',
                                    eep_style_box_style: 'bold',
                                    eep_style_button_style: 'dark',
                                    eep_style_button_radius_mode: 'sharp',
                                    eep_style_input_style: 'outline',
                                    eep_style_density_mode: 'comfortable',
                                    eep_style_border_mode: 'strong',
                                    eep_style_shadow_mode: 'medium',
                                    eep_style_content_width: 'wide',
                                    eep_page_side_padding: '8%',
                                    eep_page_side_padding_mobile: '2%'
                                }
                            },
                            'immersive-showcase': {
                                label: 'Immersive Showcase',
                                values: {
                                    eep_event_hero_layout: 'immersive',
                                    eep_event_page_layout: 'full3',
                                    eep_event_gallery_type: 'carousel',
                                    eep_style_box_style: 'gradient',
                                    eep_style_button_style: 'solid',
                                    eep_style_button_radius_mode: 'pill',
                                    eep_style_input_style: 'filled',
                                    eep_style_density_mode: 'loose',
                                    eep_style_border_mode: 'minimal',
                                    eep_style_shadow_mode: 'dramatic',
                                    eep_style_content_width: 'wide',
                                    eep_page_side_padding: '6%',
                                    eep_page_side_padding_mobile: '2%'
                                }
                            },
                            'compact-control': {
                                label: 'Compact Control',
                                values: {
                                    eep_event_hero_layout: 'compact',
                                    eep_event_page_layout: 'zig-zag',
                                    eep_event_gallery_type: 'default',
                                    eep_style_box_style: 'default',
                                    eep_style_button_style: 'outline',
                                    eep_style_button_radius_mode: 'sharp',
                                    eep_style_input_style: 'outline',
                                    eep_style_density_mode: 'compact',
                                    eep_style_border_mode: 'strong',
                                    eep_style_shadow_mode: 'soft',
                                    eep_style_content_width: 'standard',
                                    eep_page_side_padding: '7%',
                                    eep_page_side_padding_mobile: '2%'
                                }
                            },
                            'zen-clean': {
                                label: 'Zen Clean',
                                values: {
                                    eep_event_hero_layout: 'minimal',
                                    eep_event_page_layout: 'zen',
                                    eep_event_gallery_type: 'default',
                                    eep_style_box_style: 'default',
                                    eep_style_button_style: 'soft',
                                    eep_style_button_radius_mode: 'inherit',
                                    eep_style_input_style: 'underlined',
                                    eep_style_density_mode: 'loose',
                                    eep_style_border_mode: 'minimal',
                                    eep_style_shadow_mode: 'none',
                                    eep_style_content_width: 'narrow',
                                    eep_page_side_padding: '9%',
                                    eep_page_side_padding_mobile: '4%'
                                }
                            },
                            'bold-campaign': {
                                label: 'Bold Campaign',
                                values: {
                                    eep_event_hero_layout: 'cinematic',
                                    eep_event_page_layout: 'fifty-fifty',
                                    eep_event_gallery_type: 'carousel',
                                    eep_style_box_style: 'bold',
                                    eep_style_button_style: 'solid',
                                    eep_style_button_radius_mode: 'pill',
                                    eep_style_input_style: 'filled',
                                    eep_style_density_mode: 'compact',
                                    eep_style_border_mode: 'strong',
                                    eep_style_shadow_mode: 'dramatic',
                                    eep_style_content_width: 'full',
                                    eep_page_side_padding: '4%',
                                    eep_page_side_padding_mobile: '2%'
                                }
                            },
                            'gallery-plus': {
                                label: 'Gallery Plus',
                                values: {
                                    eep_event_hero_layout: 'split',
                                    eep_event_page_layout: 'full3',
                                    eep_event_gallery_type: 'wall',
                                    eep_style_box_style: 'gradient',
                                    eep_style_button_style: 'dark',
                                    eep_style_button_radius_mode: 'inherit',
                                    eep_style_input_style: 'filled',
                                    eep_style_density_mode: 'comfortable',
                                    eep_style_border_mode: 'subtle',
                                    eep_style_shadow_mode: 'medium',
                                    eep_style_content_width: 'wide',
                                    eep_page_side_padding: '6%',
                                    eep_page_side_padding_mobile: '2%'
                                }
                            },
                            'professional-default': {
                                label: 'Professional Default',
                                values: {
                                    eep_event_hero_layout: 'cinematic',
                                    eep_event_page_layout: 'modern',
                                    eep_event_gallery_type: 'default',
                                    eep_style_box_style: 'default',
                                    eep_style_button_style: 'solid',
                                    eep_style_button_radius_mode: 'inherit',
                                    eep_style_input_style: 'outline',
                                    eep_style_density_mode: 'comfortable',
                                    eep_style_border_mode: 'subtle',
                                    eep_style_shadow_mode: 'soft',
                                    eep_style_content_width: 'standard',
                                    eep_page_side_padding: '10%',
                                    eep_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('eep_map_provider');
                    var mapStyleSelect = document.getElementById('eep_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('eep_preloader_enabled');
                    var preloaderSourceSelect = document.getElementById('eep_preloader_source');
                    var preloaderSvgField = document.querySelector('[data-eep-preloader-field="svg"]');
                    var preloaderImageField = document.querySelector('[data-eep-preloader-field="image"]');
                    var preloaderResetButton = document.getElementById('eep-preloader-reset-defaults');
                    var preloaderSvgTextarea = document.getElementById('eep_preloader_svg_markup');
                    var preloaderImageInput = document.getElementById('eep_preloader_image_url');
                    var preloaderBgInput = document.getElementById('eep_preloader_background_color');
                    var preloaderWidthInput = document.getElementById('eep_preloader_logo_max_width');
                    var preloaderMinInput = document.getElementById('eep_preloader_min_duration_ms');
                    var preloaderFadeInput = document.getElementById('eep_preloader_fade_duration_ms');
                    var preloaderInitialToggle = document.querySelector('input[type="checkbox"][name="eep_preloader_show_on_initial"]');
                    var preloaderSpaToggle = document.querySelector('input[type="checkbox"][name="eep_preloader_show_on_spa"]');
                    var preloaderOnlyHomeToggle = document.querySelector('input[type="checkbox"][name="eep_preloader_show_only_home"]');
                    var preloaderShowOnceToggle = document.querySelector('input[type="checkbox"][name="eep_preloader_show_once"]');
                    var preloaderMobileToggle = document.querySelector('input[type="checkbox"][name="eep_preloader_disable_mobile"]');
                    var preloaderMotionToggle = document.querySelector('input[type="checkbox"][name="eep_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('eep-preloader-preview-shell');
                    var preloaderPreviewStage = document.getElementById('eep-preloader-preview-stage');
                    var preloaderPreviewStatus = document.getElementById('eep-preloader-preview-status');
                    var preloaderPreviewTiming = document.getElementById('eep-preloader-preview-timing');
                    var preloaderPreviewPlay = document.getElementById('eep-preloader-preview-play');
                    var preloaderPreviewStop = document.getElementById('eep-preloader-preview-stop');
                    var preloaderPreviewTimer = null;
                    var preloaderPreviewFadeTimer = null;
                    var preloaderPreviewImageCache = preloaderImageInput ? String(preloaderImageInput.value || '').trim() : '';

                    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('--eep-preloader-preview-bg', bgColor || '#FFFFFF');
                        preloaderPreviewShell.style.setProperty('--eep-preloader-preview-width', String(Math.round(artWidth)) + 'px');
                        preloaderPreviewShell.style.setProperty('--eep-preloader-preview-fade', String(Math.round(fadeMs)) + 'ms');

                        if (!enabled) {
                            preloaderPreviewStage.innerHTML = '<div class="eep-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="eep-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="eep-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('eep-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);
                        window.setInterval(function () {
                            var currentImageValue = String(preloaderImageInput.value || '').trim();
                            if (currentImageValue !== preloaderPreviewImageCache) {
                                preloaderPreviewImageCache = currentImageValue;
                                syncPreloaderPreview();
                            }
                        }, 500);
                    }
                    syncPreloaderPreview();

                    var monetizationPanels = document.querySelectorAll('.eep-settings-panel[data-tab="monetization"]');
                    var monetizationPanel = document.getElementById('eep-tab-monetization');
                    if (monetizationPanels.length) {
                        var packageRowsWrap = monetizationPanel ? monetizationPanel.querySelector('[data-eep-package-rows]') : null;
                        var typeRowsWrap = monetizationPanel ? monetizationPanel.querySelector('[data-eep-type-rows]') : null;
                        var packageHiddenInput = document.getElementById('eep_boost_duration_pricing');
                        var typeHiddenInput = document.getElementById('eep_boost_type_pricing');
                        var typePricingToggle = document.getElementById('eep_boost_type_pricing_enabled');
                        var conditionalBindings = [
                            { toggle: '#eep_boost_enabled', target: 'boost-settings' },
                            { toggle: '#eep_boost_vat_enabled', target: 'boost-vat' },
                            { toggle: '#eep_boost_auto_renew_enabled', target: 'boost-autorenew-settings' },
                            { toggle: '#eep_boost_stripe_enabled', target: 'boost-stripe' },
                            { toggle: '#eep_boost_paypal_enabled', target: 'boost-paypal' },
                            { toggle: '#eep_ticketing_enabled', target: 'ticket-settings' },
                            { toggle: '#eep_ticket_stripe_enabled', target: 'ticket-stripe' },
                            { toggle: '#eep_ticket_paypal_enabled', target: 'ticket-paypal' },
                            { toggle: '#eep_boost_show_featured_badge', target: 'boost-featured-settings' },
                            { toggle: '#eep_boost_type_pricing_enabled', target: 'boost-type-pricing' }
                        ];

                        var sanitizeInteger = function (value, min, max, fallback) {
                            var parsed = parseInt(String(value || ''), 10);
                            if (Number.isNaN(parsed)) {
                                return fallback;
                            }
                            if (typeof min === 'number' && parsed < min) {
                                parsed = min;
                            }
                            if (typeof max === 'number' && parsed > max) {
                                parsed = max;
                            }
                            return parsed;
                        };
                        var sanitizeDecimal = function (value, fallback) {
                            var normalized = String(value || '').trim().replace(',', '.');
                            var parsed = parseFloat(normalized);
                            if (!Number.isFinite(parsed)) {
                                return fallback;
                            }
                            if (parsed < 0) {
                                parsed = 0;
                            }
                            return Math.round(parsed * 100) / 100;
                        };
                        var formatMoney = function (value) {
                            var amount = sanitizeDecimal(value, 0);
                            return amount.toFixed(2);
                        };
                        var escapeHtml = function (value) {
                            return String(value || '')
                                .replace(/&/g, '&amp;')
                                .replace(/</g, '&lt;')
                                .replace(/>/g, '&gt;')
                                .replace(/"/g, '&quot;')
                                .replace(/'/g, '&#039;');
                        };
                        var getTypeOptions = function () {
                            if (!typeRowsWrap) {
                                return [];
                            }
                            var raw = String(typeRowsWrap.getAttribute('data-eep-type-options') || '').trim();
                            if (!raw) {
                                return [];
                            }
                            try {
                                var parsed = JSON.parse(raw);
                                if (!parsed || typeof parsed !== 'object') {
                                    return [];
                                }
                                return Object.keys(parsed).map(function (slug) {
                                    return {
                                        slug: String(slug || '').trim(),
                                        label: String(parsed[slug] || slug || '').trim()
                                    };
                                }).filter(function (item) {
                                    return item.slug !== '';
                                });
                            } catch (error) {
                                return [];
                            }
                        };
                        var getPackageRows = function () {
                            if (!packageRowsWrap) {
                                return [];
                            }
                            var rows = [];
                            packageRowsWrap.querySelectorAll('[data-eep-package-row]').forEach(function (rowEl) {
                                var daysEl = rowEl.querySelector('[data-eep-package-days]');
                                var priceEl = rowEl.querySelector('[data-eep-package-price]');
                                var days = sanitizeInteger(daysEl ? daysEl.value : '', 1, 3650, 0);
                                var price = sanitizeDecimal(priceEl ? priceEl.value : '', 0);
                                if (days > 0 && price > 0) {
                                    rows.push({
                                        days: days,
                                        price: price
                                    });
                                }
                            });
                            rows.sort(function (a, b) {
                                return a.days - b.days;
                            });
                            var dedup = {};
                            rows.forEach(function (row) {
                                dedup[row.days] = row;
                            });
                            return Object.keys(dedup).map(function (daysKey) {
                                return dedup[daysKey];
                            });
                        };
                        var getDurationChoices = function () {
                            var rows = getPackageRows();
                            if (!rows.length) {
                                return [7, 30, 90];
                            }
                            var unique = {};
                            rows.forEach(function (row) {
                                unique[String(row.days)] = row.days;
                            });
                            return Object.keys(unique).map(function (key) {
                                return unique[key];
                            }).sort(function (a, b) { return a - b; });
                        };
                        var serializePackageRows = function () {
                            if (!packageHiddenInput) {
                                return;
                            }
                            var rows = getPackageRows();
                            if (!rows.length) {
                                packageHiddenInput.value = '';
                                return;
                            }
                            packageHiddenInput.value = JSON.stringify(rows);
                        };
                        var normalizeTypeRows = function () {
                            if (!typeRowsWrap) {
                                return [];
                            }
                            var rows = [];
                            typeRowsWrap.querySelectorAll('[data-eep-type-row]').forEach(function (rowEl) {
                                var typeEl = rowEl.querySelector('[data-eep-type-slug]');
                                var daysEl = rowEl.querySelector('[data-eep-type-days]');
                                var priceEl = rowEl.querySelector('[data-eep-type-price]');
                                var typeSlug = String(typeEl ? typeEl.value : '').trim();
                                var days = sanitizeInteger(daysEl ? daysEl.value : '', 1, 3650, 0);
                                var price = sanitizeDecimal(priceEl ? priceEl.value : '', 0);
                                if (typeSlug !== '' && days > 0 && price > 0) {
                                    rows.push({
                                        type: typeSlug,
                                        days: days,
                                        price: price
                                    });
                                }
                            });
                            return rows;
                        };
                        var serializeTypeRows = function () {
                            if (!typeHiddenInput) {
                                return;
                            }
                            if (!typePricingToggle || !typePricingToggle.checked) {
                                typeHiddenInput.value = '';
                                return;
                            }
                            var rows = normalizeTypeRows();
                            if (!rows.length) {
                                typeHiddenInput.value = '';
                                return;
                            }
                            var grouped = {};
                            rows.forEach(function (row) {
                                if (!grouped[row.type]) {
                                    grouped[row.type] = {};
                                }
                                grouped[row.type][String(row.days)] = row.price;
                            });
                            var lines = [];
                            Object.keys(grouped).sort().forEach(function (typeSlug) {
                                var dayMap = grouped[typeSlug];
                                var parts = Object.keys(dayMap).map(function (dayKey) {
                                    return parseInt(dayKey, 10);
                                }).filter(function (dayInt) {
                                    return Number.isFinite(dayInt) && dayInt > 0;
                                }).sort(function (a, b) {
                                    return a - b;
                                }).map(function (dayInt) {
                                    return String(dayInt) + ':' + formatMoney(dayMap[String(dayInt)]);
                                });
                                if (parts.length) {
                                    lines.push(typeSlug + '|' + parts.join(','));
                                }
                            });
                            typeHiddenInput.value = lines.join('\n');
                        };
                        var renderTypeDurationOptions = function () {
                            if (!typeRowsWrap) {
                                return;
                            }
                            var choices = getDurationChoices();
                            typeRowsWrap.querySelectorAll('[data-eep-type-days]').forEach(function (selectEl) {
                                var current = sanitizeInteger(selectEl.value, 1, 3650, choices[0]);
                                var hasCurrent = choices.indexOf(current) !== -1;
                                var html = '';
                                choices.forEach(function (dayValue) {
                                    html += '<option value="' + String(dayValue) + '">' + String(dayValue) + ' <?php echo esc_js(__('days', 'nexdirectory')); ?></option>';
                                });
                                if (!hasCurrent && current > 0) {
                                    html += '<option value="' + String(current) + '">' + String(current) + ' <?php echo esc_js(__('days', 'nexdirectory')); ?></option>';
                                }
                                selectEl.innerHTML = html;
                                selectEl.value = hasCurrent ? String(current) : String(choices[0] || current);
                            });
                        };
                        var setConditionalVisibility = function (targetKey, visible) {
                            monetizationPanels.forEach(function (panelEl) {
                                panelEl.querySelectorAll('[data-eep-conditional-field="' + targetKey + '"]').forEach(function (fieldEl) {
                                    fieldEl.style.display = visible ? '' : 'none';
                                });
                            });
                        };
                        var syncConditionalFields = function () {
                            conditionalBindings.forEach(function (binding) {
                                var toggleEl = document.querySelector(binding.toggle);
                                if (!toggleEl) {
                                    return;
                                }
                                setConditionalVisibility(binding.target, !!toggleEl.checked);
                            });
                        };
                        var createPackageRow = function (days, price) {
                            var row = document.createElement('div');
                            row.className = 'eep-monetization-row';
                            row.setAttribute('data-eep-package-row', '');
                            row.innerHTML = '' +
                                '<div class="eep-monetization-col">' +
                                '<label><?php echo esc_js(__('Duration (days)', 'nexdirectory')); ?></label>' +
                                '<input type="number" min="1" max="3650" step="1" value="' + String(sanitizeInteger(days, 1, 3650, 30)) + '" data-eep-package-days>' +
                                '</div>' +
                                '<div class="eep-monetization-col">' +
                                '<label><?php echo esc_js(__('Price', 'nexdirectory')); ?></label>' +
                                '<input type="number" min="0" step="0.01" value="' + formatMoney(price) + '" data-eep-package-price>' +
                                '</div>' +
                                '<div class="eep-monetization-col eep-monetization-col-actions">' +
                                '<button type="button" class="button-link-delete" data-eep-remove-package><?php echo esc_js(__('Remove', 'nexdirectory')); ?></button>' +
                                '</div>';
                            return row;
                        };
                        var createTypeRow = function (typeSlug, days, price) {
                            var typeOptions = getTypeOptions();
                            var optionsHtml = '<option value=""><?php echo esc_js(__('Select type', 'nexdirectory')); ?></option>';
                            typeOptions.forEach(function (option) {
                                optionsHtml += '<option value="' + escapeHtml(option.slug) + '">' + escapeHtml(option.label) + '</option>';
                            });
                            var row = document.createElement('div');
                            row.className = 'eep-monetization-row eep-monetization-row-type';
                            row.setAttribute('data-eep-type-row', '');
                            row.innerHTML = '' +
                                '<div class="eep-monetization-col">' +
                                '<label><?php echo esc_js(__('Listing type', 'nexdirectory')); ?></label>' +
                                '<select data-eep-type-slug>' + optionsHtml + '</select>' +
                                '</div>' +
                                '<div class="eep-monetization-col">' +
                                '<label><?php echo esc_js(__('Duration', 'nexdirectory')); ?></label>' +
                                '<select data-eep-type-days></select>' +
                                '</div>' +
                                '<div class="eep-monetization-col">' +
                                '<label><?php echo esc_js(__('Override price', 'nexdirectory')); ?></label>' +
                                '<input type="number" min="0" step="0.01" value="' + formatMoney(price) + '" data-eep-type-price>' +
                                '</div>' +
                                '<div class="eep-monetization-col eep-monetization-col-actions">' +
                                '<button type="button" class="button-link-delete" data-eep-remove-type-row><?php echo esc_js(__('Remove', 'nexdirectory')); ?></button>' +
                                '</div>';
                            var typeSelect = row.querySelector('[data-eep-type-slug]');
                            var daysSelect = row.querySelector('[data-eep-type-days]');
                            if (typeSelect) {
                                typeSelect.value = String(typeSlug || '');
                            }
                            if (daysSelect) {
                                daysSelect.value = String(sanitizeInteger(days, 1, 3650, 30));
                            }
                            return row;
                        };
                        var ensureAtLeastOneTypeRow = function () {
                            if (!typeRowsWrap) {
                                return;
                            }
                            var rows = typeRowsWrap.querySelectorAll('[data-eep-type-row]');
                            if (rows.length > 0) {
                                return;
                            }
                            typeRowsWrap.appendChild(createTypeRow('', getDurationChoices()[0] || 30, 0));
                            renderTypeDurationOptions();
                        };
                        var syncMonetizationHiddenFields = function () {
                            serializePackageRows();
                            renderTypeDurationOptions();
                            serializeTypeRows();
                        };

                        conditionalBindings.forEach(function (binding) {
                            var toggleEl = document.querySelector(binding.toggle);
                            if (!toggleEl) {
                                return;
                            }
                            toggleEl.addEventListener('change', function () {
                                syncConditionalFields();
                                syncMonetizationHiddenFields();
                                markDirty();
                            });
                        });

                        var monetizationClickHandler = function (event) {
                            var addPackage = event.target.closest('[data-eep-add-boost-package]');
                            if (addPackage && packageRowsWrap) {
                                event.preventDefault();
                                packageRowsWrap.appendChild(createPackageRow(30, 0));
                                syncMonetizationHiddenFields();
                                markDirty();
                                return;
                            }
                            var removePackage = event.target.closest('[data-eep-remove-package]');
                            if (removePackage && packageRowsWrap) {
                                event.preventDefault();
                                var packageRow = removePackage.closest('[data-eep-package-row]');
                                if (packageRow) {
                                    packageRow.remove();
                                }
                                if (!packageRowsWrap.querySelector('[data-eep-package-row]')) {
                                    packageRowsWrap.appendChild(createPackageRow(30, 9.99));
                                }
                                syncMonetizationHiddenFields();
                                markDirty();
                                return;
                            }
                            var addTypeRow = event.target.closest('[data-eep-add-type-row]');
                            if (addTypeRow && typeRowsWrap) {
                                event.preventDefault();
                                typeRowsWrap.appendChild(createTypeRow('', getDurationChoices()[0] || 30, 0));
                                syncMonetizationHiddenFields();
                                markDirty();
                                return;
                            }
                            var removeTypeRow = event.target.closest('[data-eep-remove-type-row]');
                            if (removeTypeRow && typeRowsWrap) {
                                event.preventDefault();
                                var typeRow = removeTypeRow.closest('[data-eep-type-row]');
                                if (typeRow) {
                                    typeRow.remove();
                                }
                                ensureAtLeastOneTypeRow();
                                syncMonetizationHiddenFields();
                                markDirty();
                            }
                        };
                        var monetizationInputHandler = function (event) {
                            if (!event.target || !event.target.closest('[data-eep-package-row], [data-eep-type-row]')) {
                                return;
                            }
                            syncMonetizationHiddenFields();
                            markDirty();
                        };
                        var monetizationChangeHandler = function (event) {
                            if (!event.target || !event.target.closest('[data-eep-package-row], [data-eep-type-row], #eep_boost_type_pricing_enabled')) {
                                return;
                            }
                            syncMonetizationHiddenFields();
                            markDirty();
                        };

                        monetizationPanels.forEach(function (panelEl) {
                            panelEl.addEventListener('click', monetizationClickHandler);
                            panelEl.addEventListener('input', monetizationInputHandler);
                            panelEl.addEventListener('change', monetizationChangeHandler);
                        });

                        if (settingsForm) {
                            settingsForm.addEventListener('submit', function () {
                                syncMonetizationHiddenFields();
                            });
                        }

                        syncConditionalFields();
                        ensureAtLeastOneTypeRow();
                        syncMonetizationHiddenFields();
                    }

                    var uploadEndpoint = '<?php echo esc_js(admin_url('admin-post.php')); ?>';
                    var uploadNonce = '<?php echo esc_js(wp_create_nonce('eep_upload_image_nonce')); ?>';
                    var mediaPickers = document.querySelectorAll('[data-eep-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-eep-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 = 'eep-media-tile';
                        tile.setAttribute('data-eep-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 = 'eep-media-remove';
                        remove.setAttribute('data-eep-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-eep-media-target') || '').trim();
                        var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                        var gallery = picker.querySelector('.eep-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-eep-media-target') || '').trim();
                        var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                        if (!targetInput) {
                            return;
                        }
                        var allowMultiple = String(picker.getAttribute('data-eep-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] || '');
                        markDirty();
                        renderPicker(picker);
                    };
                    var pickWithMediaModal = function (picker) {
                        if (!picker || !window.wp || !window.wp.media) {
                            return;
                        }
                        var targetSelector = String(picker.getAttribute('data-eep-media-target') || '').trim();
                        var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                        if (!targetInput) {
                            return;
                        }
                        var allowMultiple = String(picker.getAttribute('data-eep-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', 'eep_upload_image');
                        formData.append('eep_upload_nonce', uploadNonce);
                        formData.append('eep_upload_target', target);
                        formData.append('eep_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-eep-media-target') || '').trim();
                        var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                        if (!targetInput) {
                            return;
                        }
                        var allowMultiple = String(picker.getAttribute('data-eep-media-multiple') || '0') === '1';
                        var uploadTarget = String(picker.getAttribute('data-eep-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-eep-media-open]');
                        var fileInput = picker.querySelector('[data-eep-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-eep-media-remove]') : null;
                            if (!remove) {
                                return;
                            }
                            event.preventDefault();
                            var tile = remove.closest('[data-eep-media-url]');
                            var targetSelector = String(picker.getAttribute('data-eep-media-target') || '').trim();
                            var targetInput = targetSelector ? document.querySelector(targetSelector) : null;
                            if (!tile || !targetInput) {
                                return;
                            }
                            var removeUrl = String(tile.getAttribute('data-eep-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('.eep-copy-shortcode');
                    copyButtons.forEach(function (button) {
                        button.addEventListener('click', function () {
                            var shortcode = String(button.getAttribute('data-shortcode') || '').trim();
                            if (!shortcode) {
                                return;
                            }
                            var restoreLabel = button.textContent;
                            var onCopied = function () {
                                button.textContent = '<?php echo esc_js(__('Copied', 'nexdirectory')); ?>';
                                window.setTimeout(function () {
                                    button.textContent = restoreLabel;
                                }, 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 helpDialog = document.getElementById('eep-settings-help-dialog');
                    var helpBackdrop = document.getElementById('eep-settings-help-backdrop');
                    var helpTitle = document.getElementById('eep-settings-help-title');
                    var helpBody = document.getElementById('eep-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 = 'eep-help-trigger';
                        trigger.setAttribute('data-eep-help-title', String(title || '').trim());
                        trigger.setAttribute('data-eep-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-eep-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('.eep-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('.eep-settings-panel > h2');
                        panelHeadings.forEach(function (heading) {
                            if (heading.querySelector('.eep-help-trigger')) {
                                return;
                            }
                            var panel = heading.closest('.eep-settings-panel');
                            if (!panel) {
                                return;
                            }
                            var summaryNode = panel.querySelector('.description, .eep-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('.eep-settings-panel .eep-settings-field');
                        fields.forEach(function (field) {
                            if (field.querySelector('.eep-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 closeEl = event.target.closest('[data-eep-help-close="1"]');
                        if (closeEl) {
                            event.preventDefault();
                            closeHelpDialog();
                            return;
                        }
                        var trigger = event.target.closest('[data-eep-help-title]');
                        if (!trigger) {
                            return;
                        }
                        event.preventDefault();
                        openHelpDialog(
                            String(trigger.getAttribute('data-eep-help-title') || '').trim(),
                            String(trigger.getAttribute('data-eep-help-body') || '').trim()
                        );
                    });

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

                    // Custom submission fields are now managed by creators in the frontend submit/edit form.
                })();
            </script>
        </div>
